"""
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"
"👍 React to appreciate\n"
"💬 Share with friends\n"
"🔗 " + s['main_channel_name'] + " | 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."
)