Skip to content

Commit

Permalink
Merge pull request elizaOS#1546 from azep-ninja/fix--Telegram-Markdow…
Browse files Browse the repository at this point in the history
…n-issues

fix: Telegram Bad Request: can't parse entities
  • Loading branch information
monilpat authored Dec 28, 2024
2 parents a155dd1 + cbbd2ff commit 9cff4e1
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
4 changes: 2 additions & 2 deletions packages/client-telegram/src/messageManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
23 changes: 23 additions & 0 deletions packages/client-telegram/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down

0 comments on commit 9cff4e1

Please sign in to comment.