From bd112939460b737d45e5ffd3166ada5efa75b182 Mon Sep 17 00:00:00 2001 From: azep-ninja Date: Sat, 28 Dec 2024 13:53:50 -0700 Subject: [PATCH] fix tg markdown issue. --- .../client-telegram/src/messageManager.ts | 4 ++-- packages/client-telegram/src/utils.ts | 23 +++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/packages/client-telegram/src/messageManager.ts b/packages/client-telegram/src/messageManager.ts index 3450ca853fc..bbf597232d5 100644 --- a/packages/client-telegram/src/messageManager.ts +++ b/packages/client-telegram/src/messageManager.ts @@ -18,7 +18,7 @@ import { stringToUuid } from "@elizaos/core"; import { generateMessageResponse, generateShouldRespond } from "@elizaos/core"; import { messageCompletionFooter, shouldRespondFooter } from "@elizaos/core"; -import { cosineSimilarity } from "./utils"; +import { cosineSimilarity, escapeMarkdown } from "./utils"; import { MESSAGE_CONSTANTS, TIMING_CONSTANTS, @@ -692,7 +692,7 @@ export class MessageManager { const sentMessages: Message.TextMessage[] = []; for (let i = 0; i < chunks.length; i++) { - const chunk = chunks[i]; + const chunk = escapeMarkdown(chunks[i]); const sentMessage = (await ctx.telegram.sendMessage( ctx.chat.id, chunk, diff --git a/packages/client-telegram/src/utils.ts b/packages/client-telegram/src/utils.ts index 86f0278f0e3..bbd80433499 100644 --- a/packages/client-telegram/src/utils.ts +++ b/packages/client-telegram/src/utils.ts @@ -75,6 +75,29 @@ export function cosineSimilarity(text1: string, text2: string, text3?: string): return dotProduct / maxMagnitude; } +export function escapeMarkdown(text: string): string { + // Don't escape if it's a code block + if (text.startsWith('```') && text.endsWith('```')) { + return text; + } + + // Split the text by code blocks + const parts = text.split(/(```[\s\S]*?```)/g); + + return parts.map((part, index) => { + // If it's a code block (odd indices in the split result will be code blocks) + if (index % 2 === 1) { + return part; + } + // For regular text, only escape characters that need escaping in Markdown + return part + // First preserve any intended inline code spans + .replace(/`.*?`/g, match => match) + // Then only escape the minimal set of special characters that need escaping in Markdown mode + .replace(/([*_`\\])/g, '\\$1'); + }).join(''); +} + /** * Splits a message into chunks that fit within Telegram's message length limit */