使用Telegram API能否实现点击自定义文本触发带参数Bot命令?
问题解答
结论:直接通过bot_command实体实现你要的功能不可行,原因如下:
- Telegram的
bot_command实体要求文本必须以/开头,且仅会识别/到第一个空格(或文本结尾)的部分为命令,点击后只会发送这个基础命令,无法携带参数。 - 非
/开头的文本无法被标记为bot_command实体,自然无法触发命令跳转。
可行替代方案
方案1:使用内联键盘按钮(推荐)
将需要点击的文本做成内联按钮,点击后可快速填充带参数的命令到输入框,用户一键发送即可。示例请求:
curl --location --request POST 'https://api.telegram.org/bot{bot_code}/sendMessage' \ --header 'Content-Type: application/json' \ --data-raw '{ "chat_id": 1, "text": "Some message, another text.", "reply_markup": { "inline_keyboard": [ [ { "text": "some_text_for_command", "switch_inline_query_current_chat": "/some_command with_text" } ] ] } }'
效果:用户点击按钮后,聊天输入框会自动填入/some_command with_text,只需按下发送键即可完成命令发送。
如果需要自动发送(由bot代为发送该命令消息),可以改用callback_data,在bot收到回调请求后主动发送命令:
# 第一步:发送带回调按钮的消息 curl --location --request POST 'https://api.telegram.org/bot{bot_code}/sendMessage' \ --header 'Content-Type: application/json' \ --data-raw '{ "chat_id": 1, "text": "Some message, another text.", "reply_markup": { "inline_keyboard": [ [ { "text": "some_text_for_command", "callback_data": "send_some_command" } ] ] } }' # 第二步:bot收到callback_query后,调用sendMessage发送命令 curl --location --request POST 'https://api.telegram.org/bot{bot_code}/sendMessage' \ --header 'Content-Type: application/json' \ --data-raw '{ "chat_id": 1, "text": "/some_command with_text" }'
方案2:自定义链接跳转(不推荐)
使用text_link实体将文本链接到你的后端接口,后端收到请求后调用Telegram API发送命令。但这种方式需要用户授权,流程繁琐,不如内联按钮直观。
内容的提问来源于stack exchange,提问作者Pavel
相关产品推荐
相关产品推荐

