How to Retrieve Poll Results from a Telegram Bot Using Python

I am working on a Python script for a Telegram bot designed to conduct polls in a group chat. I want to find out how to capture the final results from the bot that uses the send_poll functionality. Although the results are displayed in the group chat, I would like to store them for future reference and use. Ideally, I would like the output formatted to indicate whether the choice was option ‘a’ or ‘b’.

def start_poll(bot, update):
    choices = ['a', 'b']
    bot.send_poll(update.message.chat_id, 'Please select either option a or b:', choices)

updater.dispatcher.add_handler(CommandHandler('initiate', start_poll))
updater.start_polling()

To capture and store the poll results, you can utilize the poll_answer handler that the Telegram Bot API offers. This involves listening for responses and extracting data as users cast their votes. Here’s how you might adapt your existing setup:

Firstly, you need a function to handle the poll answers which will look something like this:

from telegram import Update
from telegram.ext import Updater, CommandHandler, PollAnswerHandler, CallbackContext

poll_answers = {}

# Function to handle poll answers
def receive_poll_answer(update: Update, context: CallbackContext):
    user_id = update.poll_answer.user.id
    poll_id = update.poll_answer.poll_id
    option_ids = update.poll_answer.option_ids

    answer = [context.bot_data[poll_id]['options'][option_id] for option_id in option_ids]
    poll_answers[user_id] = answer
    print(f'User {user_id} voted for {answer}')

# Add the handler to your bot
updater.dispatcher.add_handler(PollAnswerHandler(receive_poll_answer))

You need to ensure that when you send the poll, you store the poll’s ID and the options so that they can be referenced when processing responses. When a user answers, you capture their user ID and the chosen options to store them accordingly, thus allowing you to retrieve and format the results as you need later on.