Search code examples
pythontelegramchatbotpython-telegram-bot

Telegram Bot Poll payload without chat data


When receiving plain messages (MessageHandler) or callback queries (CallbackQueryHandler) the update payload includes the chat object (id, type, etc..)

{'update_id': 696992165, 
    'message': {'message_id': 1267, 'date': 1589968391, 
       'chat': {'id': 931365322, 'type': 'private', 

In case of Poll (PollHandler) this is not the case (only the question, answers, and info related to the poll question)

{'update_id': 696992167, 
  'poll': {'id': '5920521737891479577', 'question': 'What is the capital of Ukraine?', 
   'options': [{'text': 'Rabat', 'voter_count': 0}, 
               {'text': 'Kyiv', 'voter_count': 1}, 
               {'text': 'Luxembourg', 'voter_count': 0}], 
       'total_voter_count': 1, 'is_closed': False, 'is_anonymous': True, 
     'type': 'quiz', 'allows_multiple_answers': False, 'correct_option_id': 1, 
     'explanation_entities': [], 'close_date': None}}

Is there a way to include the chat_data which the Poll belongs to?


Solution

  • When the bot creates a poll (using Polling, I can't speak about webhooks yet) it updates its bot_data with {poll_id: {'chat_id': chat_id, 'message_id': message_id}} and when your bot process an answer, you can get the poll_id from update.poll.id and then use it on context.bot_data to get the chat_id

    def poll_answer_handler(update, context):
        chatId = context.bot_data[update.poll.id]['chat_id']
    

    It's important to do not stop/restart the bot at any point between the creation of the poll and requesting the chat_id, otherwise the bot_data will be empty. Solution? Having persistence makes the bot_data persistent.

    PS: This goes for Python-Telegram-Bot 12.6