fix: escape Telegram Markdown special characters (fix #450)

This commit is contained in:
xboard
2026-03-28 09:10:54 +08:00
parent 130f7c82a8
commit 23294c1f93

View File

@@ -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', [