From d3c0bc28f10bec9da66eb2b070ea5bf96a3e3b4e Mon Sep 17 00:00:00 2001 From: Alexey Skobkin Date: Tue, 12 Mar 2024 23:01:05 +0300 Subject: [PATCH] Fix #18. Escaping underscore symbols to avoid Telegram's Bot API "Markdown" (v1) parser errors. --- bot/bot.go | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/bot/bot.go b/bot/bot.go index c187d2f..c12c070 100644 --- a/bot/bot.go +++ b/bot/bot.go @@ -24,6 +24,8 @@ type Bot struct { llm *llm.LlmConnector extractor *extractor.Extractor stats *stats.Stats + + markdownV1Replacer *strings.Replacer } func NewBot(api *telego.Bot, llm *llm.LlmConnector, extractor *extractor.Extractor) *Bot { @@ -32,6 +34,14 @@ func NewBot(api *telego.Bot, llm *llm.LlmConnector, extractor *extractor.Extract llm: llm, extractor: extractor, stats: stats.NewStats(), + + markdownV1Replacer: strings.NewReplacer( + // https://core.telegram.org/bots/api#markdown-style + "_", "\\_", + //"*", "\\*", + //"`", "\\`", + //"[", "\\[", + ), } } @@ -110,7 +120,7 @@ func (b *Bot) heyHandler(bot *telego.Bot, update telego.Update) { message := tu.Message( chatID, - llmReply, + b.escapeMarkdownV1Symbols(llmReply), ).WithParseMode("Markdown") _, err = bot.SendMessage(b.reply(update.Message, message)) @@ -176,7 +186,7 @@ func (b *Bot) summarizeHandler(bot *telego.Bot, update telego.Update) { message := tu.Message( chatID, - llmReply, + b.escapeMarkdownV1Symbols(llmReply), ).WithParseMode("Markdown") _, err = bot.SendMessage(b.reply(update.Message, message)) @@ -282,6 +292,10 @@ func (b *Bot) createLlmRequestContext(update telego.Update) llm.RequestContext { return rc } +func (b *Bot) escapeMarkdownV1Symbols(input string) string { + return b.markdownV1Replacer.Replace(input) +} + func (b *Bot) reply(originalMessage *telego.Message, newMessage *telego.SendMessageParams) *telego.SendMessageParams { return newMessage.WithReplyParameters(&telego.ReplyParameters{ MessageID: originalMessage.MessageID,