feat: handle plain text messages without /ask prefix
This commit is contained in:
@@ -219,6 +219,57 @@ async def upload_doc(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
)
|
||||
|
||||
|
||||
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
user_data = db.get_user(update.effective_user.id)
|
||||
if not user_data:
|
||||
await update.message.reply_text("⛔ Belum terdaftar. Gunakan /start TOKEN untuk registrasi.")
|
||||
return
|
||||
|
||||
question = update.message.text.strip()
|
||||
if not question:
|
||||
return
|
||||
|
||||
await update.message.chat.send_action("typing")
|
||||
|
||||
if not await is_academic_topic(question, _client, DEEPSEEK_MODEL):
|
||||
await update.message.reply_text(REJECT_MESSAGE)
|
||||
return
|
||||
|
||||
relevant = await rag.search(user_data["id"], question, n_results=5)
|
||||
context_text = ""
|
||||
if relevant:
|
||||
context_text = "\n\nKonteks dari Second Brain pengguna:\n" + "\n".join(
|
||||
f"[{'Global' if r['scope'] == 'global' else 'Pribadi'}] {r['content']}"
|
||||
for r in relevant
|
||||
)
|
||||
|
||||
history = db.get_conversation_history(user_data["id"])
|
||||
system_prompt = (
|
||||
f"{ACADEMIC_SYSTEM_PROMPT}\n\n"
|
||||
f"Nama dosen: {user_data['full_name']}"
|
||||
f"{context_text}"
|
||||
)
|
||||
|
||||
messages = [{"role": "system", "content": system_prompt}]
|
||||
messages.extend(history)
|
||||
messages.append({"role": "user", "content": question})
|
||||
|
||||
try:
|
||||
response = await _client.chat.completions.create(
|
||||
model=DEEPSEEK_MODEL,
|
||||
messages=messages,
|
||||
max_tokens=1500,
|
||||
)
|
||||
answer = response.choices[0].message.content
|
||||
except Exception as e:
|
||||
await update.message.reply_text(f"❌ Gagal menghubungi AI: {str(e)[:100]}")
|
||||
return
|
||||
|
||||
db.save_conversation(user_data["id"], "user", question)
|
||||
db.save_conversation(user_data["id"], "assistant", answer)
|
||||
await update.message.reply_text(answer)
|
||||
|
||||
|
||||
async def clear_chat(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
user_data = db.get_user(update.effective_user.id)
|
||||
if not user_data:
|
||||
|
||||
@@ -50,6 +50,9 @@ def main():
|
||||
))
|
||||
app.add_handler(MessageHandler(filters.Document.ALL, user_handler.upload_doc))
|
||||
|
||||
# Plain text → langsung tanya AI tanpa perlu /ask
|
||||
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, user_handler.handle_message))
|
||||
|
||||
print("🤖 Second Brain Bot is running...")
|
||||
app.run_polling()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user