2

我写了一个电报机器人。一切都很顺利,而且运作良好。但是当我想ReplyKeyboardMarkup按照它的文档中提到的那样使用时,它没有用!我的意思是键盘不显示。

这个 JSON 对象有一个键keyboard,根据它的文档,它的值是:

类型:字符串数组。

描述:按钮行数组,每行由一个字符串数组表示

这是我发送请求的代码:

reply_markup = {'keyboard': [['1'],['2']], 'resize_keyboard': True, 'one_time_keyboard': True}
params = urllib.urlencode({
      'chat_id': str(chat_id),
      'text': msg.encode('utf-8'),
      'reply_markup': reply_markup,
      'disable_web_page_preview': 'true',
      # 'reply_to_message_id': str(message_id),
})
resp = urllib2.urlopen(BASE_URL + 'sendMessage', params).read()
4

4 回答 4

3

您必须单独将 reply_markup 序列化为 JSON 字符串,就像在这个答案Telegram bot custom keyboard in PHP

于 2015-07-19T07:53:21.063 回答
3

因为即使在阅读了 Kostya 链接的 PHP 答案之后,我仍然需要进行一些试验和错误才能正确使用 Python,所以这是一个适用的 Python 代码(您只需要添加您的机器人的令牌和聊天 ID将消息发送到)。

请注意,我还必须将 Telegram 客户端更新到最新版本(当前为 3.1)才能看到结果。

import urllib
import urllib2
import json


TOKEN = "<your bot token>"
chat_id = <your chat id>


msg = "some string"
BASE_URL = "https://api.telegram.org/bot{}/".format(TOKEN)

reply_markup = {'keyboard': [['1'],['2']], 'resize_keyboard': True, 'one_time_keyboard': True}
reply_markup = json.dumps(reply_markup)
params = urllib.urlencode({
      'chat_id': str(chat_id),
      'text': msg.encode('utf-8'),
      'reply_markup': reply_markup,
      'disable_web_page_preview': 'true',
      # 'reply_to_message_id': str(message_id),
})
resp = urllib2.urlopen(BASE_URL + 'sendMessage', params).read()
于 2015-07-26T17:20:14.483 回答
1

如果你喜欢你可以试试这个方法

import telegram
from telegram.ext import Updater

updater = Updater(token='BOT_TOKEN')
dispatcher = updater.dispatcher
updater.start_polling()
def test(bot, update):
    results = bot.sendMessage(chat_id=update.message.chat_id, text="Test", reply_markup={"keyboard":[["Test1"], ["Test2"], ["Test3"], ["Test4"]})
    print results
dispatcher.addTelegramCommandHandler('test', test)

这个导入让事情变得更简短,我今天才开始使用它python-telegram-bot 3.4

于 2016-03-28T22:06:45.380 回答
0

以下代码段将起作用:

reply_markup = {
    "keyboard": [[{"text":"1"}], [{"text":"2"}]], 
    "resize_keyboard": True, 
    "one_time_keyboard": True
}
于 2016-05-26T15:51:44.843 回答