Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Telegram Bad Request: can't parse entities #1546

Merged
merged 2 commits into from
Dec 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading