import logging from telegram import Update, Poll from telegram.ext import ContextTypes from content.database import get_poll_data logger = logging.getLogger(__name__) async def poll_handler(update: Update, context: ContextTypes.DEFAULT_TYPE): """ Handle poll updates to show Difficulty Labels. Runs when the poll object itself changes (voter count increases). """ poll: Poll = update.poll poll_id = poll.id # Check if we track this poll res = get_poll_data(poll_id) if not res: return channel_id, message_id, correct_index = res total_votes = poll.total_voter_count # We only update difficulty after a certain number of votes to be statistically significant # Or every 10 votes for live updates if total_votes < 5: return # Calculate percentage of correct answers correct_votes = poll.options[correct_index].voter_count accuracy = (correct_votes / total_votes) * 100 if total_votes > 0 else 0 difficulty = "🔥 Hard" if accuracy > 75: difficulty = "✅ Easy" elif accuracy > 40: difficulty = "🟠 Medium" # Post a difficulty update as a reply to the poll # We use a unique key in bot_data to avoid spamming the same poll last_update_key = f"diff_upd_{poll_id}" last_votes = context.bot_data.get(last_update_key, 0) # Update every 10 votes or once at 5 votes if total_votes >= 5 and last_votes == 0: pass # allow first update elif total_votes - last_votes < 10: return context.bot_data[last_update_key] = total_votes try: text = ( f"📊 *Live Difficulty Update*\n" f"━━━━━━━━━━━━━━━━━━\n" f"Level: *{difficulty}*\n" f"Accuracy: *{accuracy:.1f}%* get it right\n" f"Total Voters: *{total_votes}*" ) await context.bot.send_message( chat_id=channel_id, text=text, reply_to_message_id=message_id, parse_mode="MarkdownV2" ) except Exception as e: logger.warning(f"Failed to send difficulty update: {e}")