使用Python发送电报键盘

时间:2018-09-03 12:07:26

标签: python python-2.7 python-requests telegram telegram-bot

我正在尝试将带有机器人的电报键盘发送到我的帐户。我已按照TelegramAPI文档进行操作,但无法执行。我正在使用Python 2.7。

到目前为止,这是我尝试过的:

import requests

bot_token = 'xxxxxxxxxxxxxxxxxxxxxxxx'
chat_id = 'xxxxxxxxxxxx'
text = "Choose:"
reply_markup={"keyboard":[["Yes","No"],["Maybe"],["1","2","3"]],"one_time_keyboard":True}
data = {'chat_id': chat_id, 'text': text, 'reply_markup': reply_markup}
url ="https://api.telegram.org/bot" + bot_token + "/sendMessage"

r = requests.get(url, data = data)
results = r.json()
print (results)

Python不会崩溃,但是我从Telegram API收到失败响应,我也不知道为什么:

  

{u'error_code':400,u'ok':False,u'description':u”错误请求:   无法解析回复键盘标记JSON对象“}

任何想法或建议都受到高度赞赏。

谢谢安德。

1 个答案:

答案 0 :(得分:1)

利用json库,您可以转储键盘对象:

import requests, json

bot_token = 'xxxxxxxxxxxxxxxxxxxxxxxx'
chat_id = 'xxxxxxxxxxxx'
text = "Choose:"
reply_markup={"keyboard":[["Yes","No"],["Maybe"],["1","2","3"]],"one_time_keyboard":True}
data = {'chat_id': chat_id, 'text': text, 'reply_markup': json.dumps(reply_markup)}
url ="https://api.telegram.org/bot" + bot_token + "/sendMessage"

r = requests.get(url, data = data)
results = r.json()
print (results)