2015-07-18 89 views
1

我寫了一個電報機器人。一切進展順利,運作良好。但是當我想要使用ReplyKeyboardMarkup,因爲它在document中提到,它不起作用!我的意思是鍵盤沒有顯示出來。ReplyKeyboardMarkup不工作python?

此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() 

回答

2

你必須序列reply_markup到JSON字符串分別,就像在這個答案中一樣Telegram bot custom keyboard in PHP

+0

是的,我昨晚意識到它,但我忘了刪除我的問題! +1爲你的答案:) – Hadi

2

因爲它仍然花了我一些嘗試和錯誤,甚至在Python中進入正確在閱讀由Kostya鏈接的PHP答案後,這裏是一個適用的Python代碼(您只需添加您的bot的令牌和聊天ID來發送消息)。

請注意,我還必須更新我的電報客戶端到最新版本(當前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() 
+0

你是一個救星:) – neo

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

0

下面的代碼片段將工作纔剛剛開始:

reply_markup = { 
    "keyboard": [[{"text":"1"}], [{"text":"2"}]], 
    "resize_keyboard": True, 
    "one_time_keyboard": True 
}