2016-11-24 7 views
-1

У меня есть следующая часть кода, которая работает очень хорошо, пока пользователь не нажмет кнопку inline_keyboard.Как реагировать, если кнопка inline_keyboard нажата в боксе Telegram? 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'] 
     message = body['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'] 
     try: 
      callback_query = body['callback_query'] 
      data = callback_query.get('data') 
     except: 
      pass 
     b0 = u'\U0001F4FD'+' Intro' 
     b1 = u'\U0001F4D6'+' Start the play!' 
     b2 = u'\U0001F4D5'+' Scene 1' 
     keym = 'keyboard' 
     json_keyboard = json.dumps({keym: [[b0]], 'resize_keyboard': True,}) 

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

     def reply(msg=None, img=None, vid=None, aud=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': 'false', 
        'parse_mode': 'markdown', 
        #'reply_to_message_id': str(message_id), 
        'reply_markup': json_keyboard, 
       })).read() 
      elif img: 
       resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [ 
        ('chat_id', str(chat_id)), 
        ('reply_markup', json_keyboard), 
       ], [ 
        ('photo', 'image.jpg', img), 
       ]) 
      elif vid: 
       resp = multipart.post_multipart(BASE_URL + 'sendVideo', [ 
        ('chat_id', str(chat_id)), 
        ('reply_markup', json_keyboard), 
       ], [ 
        ('video', 'vid.mp4', vid), 
       ]) 
      elif aud: 
       resp = multipart.post_multipart(BASE_URL + 'sendAudio', [ 
        ('chat_id', str(chat_id)), 
        #('caption', 'Music in the park'), 
        ('reply_markup', json_keyboard), 
       ], [ 
        ('audio', 'Play', aud), 
       ]) 
      else: 
       logging.error('no msg or img specified') 
       resp = None 

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

     try: 
      if data == '1': 
       b2 = u'\U000025FC'+' Next' 
       keym = 'inline_keyboard' 
       json_keyboard = json.dumps({keym: [[{'text': b2, 'callback_data': '2'}]]}) 
       line1 = linecache.getline('stattxt/sc1-1.txt', 6) 
       line2 = linecache.getline('stattxt/sc1-1.txt', 7) 
       line3 = linecache.getline('stattxt/sc1-1.txt', 8) 
       line4 = linecache.getline('stattxt/sc1-1.txt', 9) 
       line5 = linecache.getline('stattxt/sc1-1.txt', 10) 
       reply(u'\U000025FC'+line1+'\n'+line2+'\n'+line3+'\n'+line4+'\n'+line5) 

     except: 
      if text.startswith('/'): 
       if text == '/start': 
        setEnabled(chat_id, True) 
        img = Image.open('statimg/zeroimg.jpg') 
        output = StringIO.StringIO() 
        img.save(output, 'JPEG') 
        reply(img=output.getvalue()) 

       elif text == '/stop': 
        reply('Bot disabled') 
        setEnabled(chat_id, False) 

       else: 
        reply('It\'s not time for this') 

      elif text == u'\U0001F4FD'+' Intro': 
       json_keyboard = json.dumps({keym: [[b1]], 'resize_keyboard': True, 'one_time_keyboard': False, 'hide_keyboard': False}) 
       reply(vid=urllib.urlopen('statimg/vid1.mp4').read()) 

      elif text == u'\U0001F4D6'+' Start the play!': 
       json_keyboard = json.dumps({keym: [[b2]], 'resize_keyboard': True, 'one_time_keyboard': False}) 
       img = Image.open('statimg/firstf.jpg') 
       output = StringIO.StringIO() 
       img.save(output, 'JPEG') 
       reply(img=output.getvalue()) 

      elif text == u'\U0001F4D5'+' Scene 1': 
       b2 = u'\U000025FC'+' Next' 
       keym = 'inline_keyboard' 
       json_keyboard = json.dumps({keym: [[{'text': b2, 'callback_data': '1'}]]}) 
       line1 = linecache.getline('stattxt/sc1-1.txt', 1) 
       line2 = linecache.getline('stattxt/sc1-1.txt', 2) 
       line3 = linecache.getline('stattxt/sc1-1.txt', 3) 
       line4 = linecache.getline('stattxt/sc1-1.txt', 4) 

мне нужна помощь, чтобы понять, что я делаю неправильно. Я хочу иметь resopnse, который описан в if data == '1', когда пользователь нажимает кнопку встроенной клавиатуры u'\U000025FC'+' Next. Прямо сейчас, когда пользователь нажимает эту кнопку, ничего не происходит.

Я действительно понимаю, что я должен отслеживать какой-то запрос обратного вызова, но я не могу понять, как это сделать надлежащим образом с данной архитектурой.

Пожалуйста, советую!

ответ

0

На второй мысли я решить это сам, изменяя эту часть кода:

try: 
    message = body['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'] 
except: 
    callback_query = body['callback_query'] 
    data = callback_query['data'] 
    message = callback_query['message'] 
    date = callback_query['message'].get('date') 
    text = callback_query['message'].get('text') 
    fr = callback_query['message'].get('from') 
    chat = callback_query['message'].get('chat') 
    chat_id = chat['id'] 

 Смежные вопросы

  • Нет связанных вопросов^_^