Telegram Bot使用reply_markup发送消息失败求助(Heroku+Express)
问题:Telegram Bot无法发送带reply_markup的消息
我用Express+Request在Heroku上部署了Telegram Bot,目前能正常回复文本消息,但发送带reply_markup的消息失败,排查两天没解决,代码如下:
app.post("/",async(req,final)=>{ const body=req.body console.log(JSON.stringify(body)) if(body.message){ const form={ text:req.body.message.text, msgid:req.body.message.message_id, uid:req.body.message.from.id, chatid:req.body.message.chat.id } if(form.text.indexOf("/start")!=-1){ sendMessage(form.chatid,form.msgid,"Welcome") }else{ let reply_markup={} reply_markup.inline_keyboard=[] let inlineRow=[] inlineRow.push({ text:"one", callback_data:"/one:"+body.message.text }) inlineRow.push({ text:"two", callback_data:"/two:"+body.message.text }) let inlineRow1=[] inlineRow1.push({ text:"three", callback_data:"/three:"+body.message.text }) inlineRow1.push({ text:"four", callback_data:"/four:"+body.message.text }) reply_markup.inline_keyboard.push(inlineRow) reply_markup.inline_keyboard.push(inlineRow1) sendMsgButton(form.chatid,"Click a button",reply_markup) } } final.send("SUCCESS") }) function sendMsgButton(chat_id,text,reply_markup){ request({ url:"https://api.telegram.org/botAPITOken/", method:"POST", form:{ "method": "sendMessage", "chat_id": chat_id, "parse_mode":"Markdown", "reply_markup":reply_markup, "text":text } },(err,res,body)=>{ console.log("SendMessage",body) }) }
解决方案
问题出在两个核心点:
reply_markup未序列化为JSON字符串
Telegram API要求reply_markup参数必须是JSON格式的字符串,你直接传入JavaScript对象后,Request的form字段会把它转成表单编码的键值对,导致Telegram无法解析。API请求路径错误
你当前的请求URL是https://api.telegram.org/botAPITOken/,正确的路径应该直接指向sendMessage接口:https://api.telegram.org/bot<你的Token>/sendMessage,不需要在form里指定method字段。
修复后的代码
推荐使用Request的json字段自动处理序列化:
function sendMsgButton(chat_id,text,reply_markup){ request({ url:"https://api.telegram.org/botAPITOken/sendMessage", method:"POST", json: true, // 自动将body对象转为JSON格式 body:{ "chat_id": chat_id, "parse_mode":"Markdown", "reply_markup": reply_markup, "text":text } },(err,res,body)=>{ console.log("SendMessage",body) }) }
如果坚持用form字段,需手动序列化reply_markup:
function sendMsgButton(chat_id,text,reply_markup){ request({ url:"https://api.telegram.org/botAPITOken/sendMessage", method:"POST", form:{ "chat_id": chat_id, "parse_mode":"Markdown", "reply_markup": JSON.stringify(reply_markup), "text":text } },(err,res,body)=>{ console.log("SendMessage",body) }) }
额外提示
- 确认
APITOken已替换为你的真实Bot Token - 查看Heroku日志中的
SendMessage输出,Telegram API会返回具体错误信息,帮助快速定位问题
内容的提问来源于stack exchange,提问作者LimLex
相关产品推荐
相关产品推荐

