You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Telegram API MarkdownV2转义字符问题求助(Google App Script环境)

Telegram Bot MarkdownV2转义问题(Google App Script)

我是开发新手,正在用Google App Script开发对接Google Sheets的Telegram机器人,遇到了MarkdownV2转义的问题:

按照Telegram文档要求,我用单个\转义!:

'!'必须用前置字符\进行转义

var send = url + "/sendMessage?chat_id=" + id + "&text=" + "Hey\! New item" + "&parse_mode=MarkdownV2";

运行后返回400错误,提示需要用两个\\:

Exception: Request failed for https://api.telegram.org returned code 400. Truncated server response: {"ok":false,"error_code":400,"description":"Bad Request: can't parse entities: Character '!' is reserved and must be escaped with the preceding '\\'"} (use muteHttpExceptions option to examine full response)

改用两个\\后仍报错:

Exception: Invalid argument: https://api.telegram.org/botxyz:abc/sendMessage?chat_id=xyz&text=Hey\!%20New%20item&parse_mode=MarkdownV2

但直接访问编码后的链接https://api.telegram.org/botxyz:abc/sendMessage?chat_id=xyz&text=Hey%5C!%20New%20item&parse_mode=MarkdownV2却能正常工作。


问题根源

  1. JavaScript字符串转义规则:在JS中,单个\是转义字符,要表示一个实际的\必须写两个\\。你第一次写的Hey\!会被JS解析成Hey!,等于没做转义,所以Telegram返回400错误。
  2. URL编码缺失:即使写了\\得到\!,直接拼到URL里时,\没有被URL编码(应转为%5C),导致Telegram无法识别有效转义,触发参数无效错误。

两种解决方法

方法1:手动编码文本参数

先构造符合MarkdownV2要求的文本(用\\转义特殊字符),再用encodeURIComponent()对文本做URL编码:

// 1. 构造MarkdownV2格式文本,JS里用\\表示一个\
var markdownText = "Hey\\! New item";
// 2. 对文本进行URL编码
var encodedText = encodeURIComponent(markdownText);
// 3. 拼接并发起请求
var sendUrl = url + "/sendMessage?chat_id=" + id + "&text=" + encodedText + "&parse_mode=MarkdownV2";
UrlFetchApp.fetch(sendUrl);

生成的URL中text参数会被编码为Hey%5C!%20New%20item,和你手动访问的有效链接一致。

方法2:用POST请求传递Payload(推荐)

避免手动拼接URL,直接通过POST请求的payload传递参数,Google App Script会自动处理编码逻辑:

var payload = {
  chat_id: id,
  text: "Hey\\! New item", // 直接写MarkdownV2要求的转义格式
  parse_mode: "MarkdownV2"
};

var options = {
  method: "post",
  payload: payload
};

UrlFetchApp.fetch(url + "/sendMessage", options);

这种方式更简洁,也能避免手动编码时的遗漏,适合处理包含多个特殊字符的文本内容。


内容的提问来源于stack exchange,提问作者Rex Nguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 08:24:18