如何用JavaScript向Telegram群组发送Inline Keyboard?
修复Telegram Bot内嵌键盘发送问题
问题描述
通过JavaScript调用Telegram Bot API的sendMessage接口发送消息,原GET请求代码如下:
const url = `https://api.telegram.org/bot<bot_token>/sendMessage?chat_id=${chat_id}&text=${message}` const data = await fetch(url).then(resp => resp.json())
尝试添加内嵌键盘时,构造的参数字符串出现错误:
const message='{"reply_markup":{{\"inline_keyboard\": [[{ \text\" : \" Press here\", \"callback_data\" : \"TEST\" }]]}}}'
发送后得到的错误JSON:
{"reply_markup":{{"inline_keyboard": [[{ ext" : " Press here", "callback_data" : "TEST" }]]}}}
错误原因
- 转义错误:
\text\"里的\t会被解析为制表符,导致最终变成ext",正确键名应为"text",转义方式错误。 - 多余大括号:
reply_markup的值是单个对象,不需要嵌套双大括号{{}},单大括号{}即可。 - GET请求局限性:GET请求传递复杂JSON参数时,转义处理易出错且有长度限制,不适合传递带键盘的消息。
解决方案
方案1:修复GET请求的参数转义
若坚持使用GET请求,需正确构造JSON字符串并做URL编码:
// 构造键盘配置对象 const inlineKeyboard = { reply_markup: { inline_keyboard: [ [{ text: "Press here", callback_data: "TEST" }] ] } }; // 转成JSON字符串后做URL编码 const encodedReplyMarkup = encodeURIComponent(JSON.stringify(inlineKeyboard.reply_markup)); // 消息文本也需单独编码避免转义问题 const text = "消息内容"; const url = `https://api.telegram.org/bot<bot_token>/sendMessage?chat_id=${chat_id}&text=${encodeURIComponent(text)}&reply_markup=${encodedReplyMarkup}`; const data = await fetch(url).then(resp => resp.json());
方案2:使用POST请求(推荐)
Telegram Bot API推荐用POST请求发送带复杂参数的消息,彻底避免转义麻烦:
const url = `https://api.telegram.org/bot<bot_token>/sendMessage`; const payload = { chat_id: chat_id, text: "消息内容", reply_markup: { inline_keyboard: [ [{ text: "Press here", callback_data: "TEST" }] ] } }; const data = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) }).then(resp => resp.json());
说明
- POST请求直接传递JSON格式请求体,无需手动处理转义,稳定性更高。
- 需将代码中的
<bot_token>和chat_id替换为实际有效的值。
内容的提问来源于stack exchange,提问作者vtable
相关产品推荐
相关产品推荐

