File size: 4,155 Bytes
fa22010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
764f6e8
fa22010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
764f6e8
fa22010
 
 
764f6e8
fa22010
 
 
8559de8
 
 
 
 
 
 
 
fa22010
 
 
764f6e8
fa22010
 
 
 
 
 
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
"""

AI Doubt Solver

Explains any JEE/NEET question, MCQ, or topic forwarded to the bot.

Works for: DM messages, group @mentions, replies-to-bot messages.

"""

import logging
import re

logger = logging.getLogger(__name__)

# System prompt that makes the bot act as a JEE/NEET tutor
_SYSTEM_PROMPT = (
    "You are an expert JEE and NEET tutor named 'CrazyBot'. "
    "Your job is to explain concepts, solve MCQs, and clear doubts for students preparing for JEE Main, "
    "JEE Advanced, and NEET-UG. "
    "When given a question or MCQ, you MUST:\n"
    "1. Identify the topic/concept\n"
    "2. Explain the core concept clearly in simple language\n"
    "3. Show step-by-step solution if it's a numerical\n"
    "4. State the correct answer with full reasoning\n"
    "5. Give 1 exam tip related to this concept\n\n"
    "Keep responses concise (max 400 words). Use Unicode math symbols (Β², √, Ο€, ΞΌ, Ξ”, ΞΈ). "
    "No LaTeX. Format with emojis for readability on Telegram."
)

_DOUBT_PROMPT_TEMPLATE = """A JEE/NEET student has a doubt. Here is what they sent:



---

{content}

---



Please explain this clearly. If it's an MCQ, solve it step-by-step and reveal the correct answer.

If it's a concept question, explain it with an example and a JEE/NEET exam tip."""


def _extract_text(message) -> str:
    """

    Extract meaningful text from a Telegram message object.

    Handles: plain text, forwarded text, poll questions, captions.

    """
    parts = []

    # Forwarded message context
    if message.forward_origin or message.forward_date:
        parts.append("[Forwarded content]")

    # Poll forwarded
    if message.poll:
        poll = message.poll
        parts.append(f"MCQ: {poll.question}")
        for i, opt in enumerate(poll.options):
            label = chr(65 + i)  # A, B, C, D
            parts.append(f"({label}) {opt.text}")
        return "\n".join(parts)

    # Regular text or caption
    text = message.text or message.caption or ""

    # Strip bot mention (@BotName) from group messages
    text = re.sub(r'@\w+', '', text).strip()

    if text:
        parts.append(text)

    return "\n".join(parts).strip() if parts else ""


async def solve_doubt(user_question: str) -> str:
    """

    Call LLM to explain/solve the student's question.

    Returns formatted response string.

    """
    if not user_question or len(user_question.strip()) < 5:
        return (
            "πŸ€” *I need a question to answer!*\n\n"
            "Please:\n"
            "β€’ Type your doubt directly\n"
            "β€’ Forward any MCQ or question to me\n"
            "β€’ Reply to a question in the group mentioning me\n\n"
            "Example: `What is Bernoulli's principle?`"
        )

    prompt = _DOUBT_PROMPT_TEMPLATE.format(content=user_question[:2000])

    try:
        from content.config_manager import config_manager
        from content.generator import _call_llm, _clean_markdown
        s = config_manager.settings
        system_prompt = _SYSTEM_PROMPT.replace("CrazyBot", s['bot_name'])
        
        answer = await _call_llm(prompt, system_prompt=system_prompt)
        if not answer:
            return "⚠️ I couldn't generate a response right now. Please try again."

        # Add helpful footer with engagement CTAs
        engagement = (
            "\n\n━━━━━━━━━━━━━━━━━━\n"
            "πŸ‘ <b>React to appreciate</b>\n"
            "πŸ’¬ <b>Share with friends</b>\n"
            "πŸ”— <a href=\"" + s['main_channel_url'] + "\"><b>" + s['main_channel_name'] + "</b></a> | Ask more doubts anytime!"
        )
        answer += engagement
        return answer

    except Exception as e:
        logger.error(f"[DoubtSolver] API error: {e}")
        from content.config_manager import config_manager
        s = config_manager.settings
        return (
            "⚠️ *Doubt solver is temporarily unavailable.*\n"
            f"Please try again in a moment, or check [{s['main_channel_name']}]({s['main_channel_url']}) for help."
        )