diff --git a/cmd/test/main.go b/cmd/test/main.go index 06a8fa0..8cbb01a 100644 --- a/cmd/test/main.go +++ b/cmd/test/main.go @@ -38,7 +38,10 @@ func (w *MutateMessageWidget) Serve(c *tg.Context) { } for u := range c.Input() { text := u.Message.Text - c.Sendf("%s", w.Mutate(text)) + _, err := c.Sendf2("%s", w.Mutate(text)) + if err != nil { + c.Sendf("debug: %q", err) + } } } @@ -132,6 +135,7 @@ WithInitFunc(func(c *tg.Context) { tg.NewKeyboard().Row( tg.NewButton("Upper case").Go("upper-case"), tg.NewButton("Lower case").Go("lower-case"), + tg.NewButton("Escape chars").Go("escape"), ).Row( backButton, ).Reply(), @@ -162,6 +166,18 @@ WithInitFunc(func(c *tg.Context) { } }), ), + tg.NewNode( + "escape", tg.RenderFunc(func(c *tg.Context) tg.UI { + return tg.UI{ + tg.NewMessage( + "Type a string and the bot will escape characters in it", + ).Reply( + backKeyboard.Reply(), + ), + NewMutateMessageWidget(tg.Escape2), + } + }), + ), ), tg.NewNode( diff --git a/tg/message.go b/tg/message.go index 4197ecd..5bda431 100644 --- a/tg/message.go +++ b/tg/message.go @@ -3,6 +3,7 @@ package tg import ( tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" //"strings" + re "regexp" ) type Message = tgbotapi.Message @@ -13,6 +14,16 @@ type MessageCompo struct { Text string } +var ( + escapeRe = re.MustCompile(`([_*\[\]()~`+"`"+`>#+-=|{}.!])`) +) + +// Escape special characters in Markdown 2 and return the +// resulting string. +func Escape2(str string) string { + return string(escapeRe.ReplaceAll([]byte(str), []byte("\\$1"))) +} + func (compo *MessageCompo) SetMessage(msg *Message) { compo.Message = msg }