如何通过Telegram Bot API获取投票结果、用户选择及非匿名投票中特定用户的具体选项?
Hey there! Glad you've already nailed retrieving vote counts—let's break down how to track exactly which option a specific user chose in a non-anonymous poll using the Telegram Bot API.
Key Background
First off: Yes, you absolutely can get individual users' voting choices for non-anonymous polls—but it relies on listening for a specific type of update from Telegram, and storing that data yourself. Here's how it works:
How to Capture User Votes
Listen for
poll_answerUpdates
Whenever a user submits their vote in a non-anonymous poll, Telegram sends your bot apoll_answerupdate. This update includes all the info you need:poll_id: Unique ID of the poll (to link it to the poll you created)user: Full details of the voting user (ID, username, first/last name)option_ids: An array of IDs corresponding to the option(s) the user selected (single ID for single-choice polls, multiple for multi-select)
Set Up Your Bot to Receive These Updates
Make sure your bot is configured to fetch updates either viagetUpdatesor a webhook, and that you're not filtering outpoll_answerevents. Most bot libraries have built-in handlers for this.
Example Code (Python with python-telegram-bot)
Here's a quick example to show you how to capture and log these votes:
from telegram import Update from telegram.ext import ApplicationBuilder, PollAnswerHandler, ContextTypes async def log_user_vote(update: Update, context: ContextTypes.DEFAULT_TYPE): poll_response = update.poll_answer # Extract key details poll_id = poll_response.poll_id voting_user = poll_response.user selected_option_ids = poll_response.option_ids # If you stored the original poll's options (e.g., ["Pizza", "Burgers", "Tacos"]), # you can map the IDs to actual option text: # original_options = context.bot_data.get(poll_id, []) # selected_options = [original_options[id] for id in selected_option_ids] print(f"User {voting_user.id} (@{voting_user.username}) voted for option IDs: {selected_option_ids}") if __name__ == "__main__": app = ApplicationBuilder().token("YOUR_BOT_TOKEN_HERE").build() app.add_handler(PollAnswerHandler(log_user_vote)) app.run_polling()
Important Notes
- No Historical Data: Telegram only sends the
poll_answerupdate when the user votes—you won't get a backlog of past votes retroactively. You need to store these responses (e.g., in a database) as they come in if you want to look up a user's choice later. - Anonymous Polls Don't Work: For anonymous polls, the
poll_answerupdate won't include any user information—this is intentional to preserve anonymity. - Permissions: As long as your bot can create polls, it has permission to receive
poll_answerupdates—no extra permissions needed.
So to recap: By listening for poll_answer updates and storing the user + option data, you can easily look up exactly what any specific user voted for in a non-anonymous poll.
内容的提问来源于stack exchange,提问作者Gello

