File size: 3,107 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"""

Doubt Handler

Listens for:

  1. Any private (DM) message to the bot

  2. Group messages that mention the bot (@BotName)

  3. Replies to the bot's messages in a group



Registers users and calls the AI Doubt Solver.

"""

import logging
from telegram import Update
from telegram.ext import ContextTypes, MessageHandler, filters
from content.doubt_solver import solve_doubt, _extract_text
from content.user_registry import register_user

logger = logging.getLogger(__name__)


async def handle_doubt(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Core handler β€” called for all qualifying doubt messages."""
    message = update.message or update.edited_message
    if not message:
        return

    user = message.from_user
    if not user:
        return

    # Register the user automatically (for broadcast, stats, etc.)
    register_user(user.id, user.first_name, user.username)

    chat_type = message.chat.type  # 'private', 'group', 'supergroup'

    # ── Group: only respond to @mentions or replies-to-bot ──
    if chat_type in ("group", "supergroup"):
        # Cache bot username to avoid API call on every message
        if "bot_username" not in context.bot_data:
            me = await context.bot.get_me()
            context.bot_data["bot_username"] = me.username
        bot_username = context.bot_data["bot_username"]

        is_mention  = bot_username and f"@{bot_username}" in (message.text or message.caption or "")
        is_reply_to_bot = (
            message.reply_to_message
            and message.reply_to_message.from_user
            and message.reply_to_message.from_user.id == context.bot.id
        )

        if not is_mention and not is_reply_to_bot:
            return  # Ignore regular group messages

    # ── Extract the question content ──
    question = _extract_text(message)

    # If it's a reply in a group, also include the parent message
    if message.reply_to_message and not message.poll:
        parent = message.reply_to_message
        parent_text = parent.text or parent.caption or ""
        if parent_text and parent_text not in question:
            question = f"{parent_text}\n\nStudent's doubt: {question}"

    # Show "typing..." indicator
    await context.bot.send_chat_action(chat_id=message.chat_id, action="typing")

    # Call AI
    answer = await solve_doubt(question)

    await message.reply_text(
        answer,
        parse_mode="MarkdownV2",
        reply_to_message_id=message.message_id
    )

    logger.info(
        f"[Doubt] Answered for {user.first_name} ({user.id}) "
        f"in {'DM' if chat_type == 'private' else f'group {message.chat_id}'}"
    )


# ── Filter: private DMs (any text/forward/poll) ──
private_doubt_handler = MessageHandler(
    filters.ChatType.PRIVATE & ~filters.COMMAND,
    handle_doubt
)

# ── Filter: group messages with mention OR reply-to-bot ──
group_doubt_handler = MessageHandler(
    filters.ChatType.GROUPS & ~filters.COMMAND,
    handle_doubt
)