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

如何用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" }]]}}}

错误原因

  1. 转义错误:\text\"里的\t会被解析为制表符,导致最终变成ext",正确键名应为"text",转义方式错误。
  2. 多余大括号:reply_markup的值是单个对象,不需要嵌套双大括号{{}},单大括号{}即可。
  3. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 01:45:34