如果在 Telegram 机器人中按下 inline_keyboard 按钮,如何响应? Python

How to response if inline_keyboard button pressed in Telegram bot? Python

我有下一部分代码,在用户按下 inline_keyboard 按钮之前它工作得很好。

代码如下:

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)

我需要一些帮助来弄清楚我做错了什么。当用户按下内联键盘按钮 u'\U000025FC'+' Next 时,我想要在 if data == '1' 中描述的响应。现在当用户按下这个按钮时没有任何反应。

我知道我应该以某种方式跟踪回调查询,但我不知道如何使用给定的体系结构以正确的方式执行此操作。

请指教!

转念一想,我通过更改这部分代码自己解决了这个问题:

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']