2016-07-03 155 views
1

我已經從GitHub下載了這個用Python編寫的這個open-source code(我對它很新穎),我想讓我的機器人有一個自定義鍵盤而不是讓它用戶說他們想要的。例如,如果用戶開始與我的機器人聊天,他們會自動發送/start,當發生這種情況時,我希望我的機器人在鍵盤上給他們兩個到三個選項['Option One'], [Option Two],,當他們選擇其中一個選項時,我想要有完全不同的選項(例如['Plan A'], ['Plan B'],)。再次,當他們選擇其中一個時,他們在鍵盤上得到不同的選擇,等等。Telegram Bot:自定義鍵盤[Python]

class WebhookHandler(webapp2.RequestHandler): 
def post(self): 
    urlfetch.set_default_fetch_deadline(60) 
    body = json.loads(self.request.body) 
    logging.info('request body:') 
    logging.info(body) 
    self.response.write(json.dumps(body)) 

    update_id = body['update_id'] 
    try: 
     message = body['message'] 
    except: 
     message = body['edited_message'] 
    message_id = message.get('message_id') 
    date = message.get('date') 
    text = message.get('text') 
    fr = message.get('from') 
    chat = message['chat'] 
    chat_id = chat['id'] 

    if not text: 
     logging.info('no text') 
     return 

    def reply(msg=None, img=None): 
     if msg: 
      resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({ 
       'chat_id': str(chat_id), 
       'text': msg.encode('utf-8'), 
       'disable_web_page_preview': 'true', 
      })).read() 

     else: 
      logging.error('no msg or img specified') 
      resp = None 

     logging.info('send response:') 
     logging.info(resp) 

    if text.startswith('/'): 
     if text == '/start': 
      reply('Bot enabled') 
      setEnabled(chat_id, True) 
     elif text == '/stop': 
      reply('Bot disabled') 
      setEnabled(chat_id, False) 

     else: 
      reply('That ain\'t been coded yet.') 

正如我所說的,我處女Pyhton,並且我會很感激,如果你應用你的代碼,這就是本文上面的代碼,而不是給我的想法(我不知道如何使用它們,並完成工作!)。

回答

2

首先,我建議你使用一些模塊來處理它。由於您是新手,python-telegram-bot可以幫助您。

好吧,假設你會使用它,你有兩個選擇:

  1. 您可以創建一個鍵盤在選項命令。

    def start(bot, update): 
        kb = [[telegram.KeyboardButton('/command1')], 
          [telegram.KeyboardButton('/command2')]] 
        kb_markup = telegram.ReplyKeyboardMarkup(kb) 
        bot.send_message(chat_id=update.message.chat_id, 
            text="your message", 
            reply_markup=kb_markup) 
    
    start_handler = CommandHandler('start', start) 
    dispatcher.add_handler(start_handler) 
    
  2. 創建文本選項並使用正則表達式來過濾它們。

    def start(bot, update): 
        kb = [[telegram.KeyboardButton("Option 1")], 
          [telegram.KeyboardButton("Option 2")]] 
        kb_markup = telegram(chat_id=update.message.chat_id, 
             text="your message", 
             reply_markup=kb_markup) 
    
    start_handler = RegexHandler('some-regex-here', start) 
    dispatcher.add_handler(start_handler) 
    

但是,你不能阻止用戶發送任何他想要的其它消息。您只能忽略這些消息並只回覆命令或鍵盤響應。