I’m working on a Telegram bot using Python and having trouble with inline keyboard callbacks. When users click my inline buttons, nothing happens even though I have callback handling code.
class BotRequestHandler(webapp2.RequestHandler):
def post(self):
urlfetch.set_default_fetch_deadline(45)
request_data = json.loads(self.request.body)
logging.info('incoming data:')
logging.info(request_data)
self.response.write(json.dumps(request_data))
update_number = request_data['update_id']
msg = request_data.get('message', {})
msg_id = msg.get('message_id')
timestamp = msg.get('date')
user_text = msg.get('text')
sender = msg.get('from')
conversation = msg.get('chat', {})
conv_id = conversation.get('id')
try:
query_callback = request_data['callback_query']
button_data = query_callback.get('data')
except:
button_data = None
btn1 = u'\U0001F680' + ' Welcome'
btn2 = u'\U0001F4DA' + ' Begin Game'
btn3 = u'\U0001F4DC' + ' Chapter 1'
keyboard_type = 'keyboard'
menu_keyboard = json.dumps({keyboard_type: [[btn1]], 'resize_keyboard': True})
def send_response(text_msg=None, photo=None, video=None):
if text_msg:
response = urllib2.urlopen(API_URL + 'sendMessage', urllib.urlencode({
'chat_id': str(conv_id),
'text': text_msg.encode('utf-8'),
'parse_mode': 'markdown',
'reply_markup': menu_keyboard,
})).read()
elif photo:
response = multipart.post_multipart(API_URL + 'sendPhoto', [
('chat_id': str(conv_id)),
('reply_markup': menu_keyboard),
], [
('photo', 'pic.jpg', photo),
])
return response
try:
if button_data == 'next_step':
next_btn = u'\U000026A1' + ' Continue'
keyboard_type = 'inline_keyboard'
menu_keyboard = json.dumps({keyboard_type: [[{'text': next_btn, 'callback_data': 'step_2'}]]})
story_text = 'Chapter content goes here...'
send_response(u'\U000026A1' + story_text)
except:
if user_text and user_text.startswith('/'):
if user_text == '/start':
welcome_img = Image.open('assets/welcome.jpg')
img_buffer = StringIO.StringIO()
welcome_img.save(img_buffer, 'JPEG')
send_response(photo=img_buffer.getvalue())
The issue is that when users press my inline keyboard button, the callback isn’t being processed properly. I have the callback_query handling code but it seems like I’m missing something in the flow. How should I structure this to properly catch and respond to inline button presses?