From 23294c1f93f22f9a9a4bb7a423fc6d039fbe01ea Mon Sep 17 00:00:00 2001 From: xboard Date: Sat, 28 Mar 2026 09:10:54 +0800 Subject: [PATCH] fix: escape Telegram Markdown special characters (fix #450) --- app/Services/TelegramService.php | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/app/Services/TelegramService.php b/app/Services/TelegramService.php index 83f52c7..ffd9797 100644 --- a/app/Services/TelegramService.php +++ b/app/Services/TelegramService.php @@ -29,7 +29,9 @@ class TelegramService public function sendMessage(int $chatId, string $text, string $parseMode = ''): void { - $text = $parseMode === 'markdown' ? str_replace('_', '\_', $text) : $text; + if ($parseMode === 'markdown') { + $text = $this->escapeMarkdown($text); + } $this->request('sendMessage', [ 'chat_id' => $chatId, @@ -38,6 +40,26 @@ class TelegramService ]); } + /** + * 转义 Telegram Markdown 特殊字符 + */ + protected function escapeMarkdown(string $text): string + { + $escapeChars = ['_', '*', '`', '[']; + $escapedText = ''; + + for ($i = 0; $i < strlen($text); $i++) { + $char = $text[$i]; + if (in_array($char, $escapeChars, true)) { + $escapedText .= '\\' . $char; + } else { + $escapedText .= $char; + } + } + + return $escapedText; + } + public function approveChatJoinRequest(int $chatId, int $userId): void { $this->request('approveChatJoinRequest', [