File size: 2,271 Bytes
6a1a0a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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}")