Implemented the escaping function for the Markdown2.

This commit is contained in:
Andrey Parhomenko 2023-10-05 17:51:24 +03:00
parent 223f8a5b29
commit 84419940e3
2 changed files with 28 additions and 1 deletions

View file

@ -38,7 +38,10 @@ func (w *MutateMessageWidget) Serve(c *tg.Context) {
} }
for u := range c.Input() { for u := range c.Input() {
text := u.Message.Text 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.NewKeyboard().Row(
tg.NewButton("Upper case").Go("upper-case"), tg.NewButton("Upper case").Go("upper-case"),
tg.NewButton("Lower case").Go("lower-case"), tg.NewButton("Lower case").Go("lower-case"),
tg.NewButton("Escape chars").Go("escape"),
).Row( ).Row(
backButton, backButton,
).Reply(), ).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( tg.NewNode(

View file

@ -3,6 +3,7 @@ package tg
import ( import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
//"strings" //"strings"
re "regexp"
) )
type Message = tgbotapi.Message type Message = tgbotapi.Message
@ -13,6 +14,16 @@ type MessageCompo struct {
Text string 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) { func (compo *MessageCompo) SetMessage(msg *Message) {
compo.Message = msg compo.Message = msg
} }