Hey everyone! I’m building a Telegram bot for my chat group. It’s supposed to make polls and keep track of the votes. I’ve got the poll creation part working fine using the API. The bot saves the message ID and poll ID after creating a poll.
But now I’m stuck. I can’t figure out how to get the actual votes from these polls. Does anyone know how to do this? I’ve looked through the docs but can’t find anything helpful. Any tips or tricks would be super useful!
Here’s a quick example of what I’ve done so far:
def create_poll(chat_id, question, options):
result = bot.send_poll(chat_id=chat_id, question=question, options=options)
poll_id = result.poll.id
message_id = result.message_id
save_poll_info(poll_id, message_id)
return poll_id
# But how do I get the votes?
Thanks in advance for any help!
hey jackwolf, i’ve dealt with this before. you gotta use the getpoll method to fetch updated poll data. it returns a Poll object with vote info. just pass the saved poll_id to it like this:
updated_poll = bot.get_poll(poll_id)
votes = updated_poll.total_voter_count
hope that helps! let me know if u need anything else
I’ve implemented something similar in my Telegram bot projects. One approach that worked well for me was using the poll_answer
handler to capture votes in real-time. Here’s a basic example:
@bot.poll_answer_handler()
def handle_poll_answer(poll_answer):
poll_id = poll_answer.poll_id
user_id = poll_answer.user.id
option_ids = poll_answer.option_ids
# Process and store the vote data
update_vote_counts(poll_id, option_ids)
This way, you’ll get updates as soon as users vote. You can then store these votes in a database or memory, depending on your needs. Remember to set up proper error handling and consider scalability if you’re dealing with large groups or multiple polls.
For retrieving final results, the getPoll method mentioned earlier is indeed useful. Combine both approaches for a robust solution.