so add the ghost mode for bot

This commit is contained in:
timka123 committed 2026-11-07 23:49:10 +03:00
1 parent aa8b044905
commit 1809661f27
7 files changed
+584 -7

No files matched your search

+288 -4
View File
@@ -1,13 +1,21 @@
"""Message and command handlers for HomeAgent Telegram bot with strict Rich Messages support."""
"""Message and command handlers for HomeAgent Telegram bot with strict Rich Messages and Ghost Bot (Guest Mode) support."""
import asyncio
import logging
import re
from typing import Optional
import uuid
from aiogram import Router
from aiogram.enums import ChatAction
from aiogram import Bot, Router
from aiogram.enums import ChatAction, ParseMode
from aiogram.filters import Command
from aiogram.types import InputRichMessage, Message
from aiogram.types import (
InlineQueryResultArticle,
InputRichMessage,
InputRichMessageContent,
InputTextMessageContent,
Message,
)
from homeagent.agent.base import BaseAgent
from homeagent.bot.progress import ProgressReporter
@@ -20,6 +28,22 @@ from homeagent.tools.registry import ToolRegistry
logger = logging.getLogger(__name__)
def _clean_bot_mention(text: str, bot_username: Optional[str] = None) -> str:
"""Remove bot mention and command suffixes like /cmd@bot from the input text."""
if not text:
return ""
cleaned = text
if bot_username:
# Strip specific @bot_username mention (case-insensitive)
cleaned = re.sub(rf"@{re.escape(bot_username)}\b", "", cleaned, flags=re.IGNORECASE)
else:
# Strip generic @...bot mention
cleaned = re.sub(r"@\w+bot\b", "", cleaned, flags=re.IGNORECASE)
# Strip /cmd@botname -> /cmd
cleaned = re.sub(r"(/[a-zA-Z0-9_]+)@\w+", r"\1", cleaned)
return cleaned.strip()
def create_bot_router(
settings: Settings,
agent: BaseAgent,
@@ -146,6 +170,176 @@ def create_bot_router(
for chunk in chunks:
await _send_reply(message, chunk)
@router.guest_message()
async def handle_guest_message(message: Message, bot: Optional[Bot] = None) -> None:
"""Handle guest messages when HomeAgent acts as a Ghost Bot in chats it hasn't joined."""
active_bot = message.bot or bot
if not active_bot:
logger.error("No Bot instance available for handling guest_message")
return
if not settings.GHOST_MODE_ENABLED:
logger.info("Ghost mode disabled by config, ignoring guest_message (query_id=%s)", message.guest_query_id)
return
guest_query_id = message.guest_query_id
if not guest_query_id:
logger.warning("Received guest_message without guest_query_id: %s", message)
return
chat_id = message.chat.id
thread_id = message.message_thread_id
user = message.from_user
user_info = f"{user.id} (@{user.username})" if user else "unknown"
logger.info(
"Processing ghost bot guest_message from %s in chat=%s, thread=%s, query_id=%s",
user_info,
chat_id,
thread_id,
guest_query_id,
)
# Retrieve bot username to cleanly strip @bot_username
bot_username = None
try:
me = await active_bot.get_me()
bot_username = me.username
except Exception as e:
logger.debug("Could not fetch bot username via get_me: %s", e)
raw_text = message.text or message.caption or ""
cleaned_text = _clean_bot_mention(raw_text, bot_username)
# Context extraction from reply_to_message if the user invoked the bot in reply to another message
reply_context = ""
if message.reply_to_message:
author = (
message.reply_to_message.from_user.full_name
if message.reply_to_message.from_user
else "Собеседник"
)
reply_body = (
message.reply_to_message.text
or message.reply_to_message.caption
or ""
)
if reply_body:
reply_context = (
f"[Контекст сообщения от {author}, на которое отвечает пользователь]:\n"
f"{reply_body}\n\n"
)
# 1. Quick commands in ghost mode
cmd_lower = cleaned_text.lower()
if cmd_lower in ("/start", "/help", "help", "старт", "помощь"):
skills = skill_manager.list_skills()
tools = tool_registry.list_tools()
bot_tag = f"@{bot_username}" if bot_username else "@bot"
help_msg = (
f"👻 **HomeAgent — Ghost Bot (Гостевой режим)**\n\n"
f"Я отвечаю в чатах без необходимости добавления меня в участники!\n\n"
f"⚙️ **Текущий статус:**\n"
f"- LLM Провайдер: `{settings.get_active_provider_name()}`\n"
f"- Главная модель: `{settings.get_active_model()}`\n"
f"- Доступно скиллов: **{len(skills)}** (`/skills`)\n"
f"- Доступно инструментов: **{len(tools)}**\n\n"
f"💡 **Как меня использовать:**\n"
f"• Упомяните `{bot_tag} <ваш вопрос>` с любой задачей или вопросом.\n"
f"• Ответьте тегом `{bot_tag}` на любое сообщение, чтобы я проанализировал или объяснил его.\n"
f"• Команды: `/skills`, `/memory`, `/reset`."
)
await _send_guest_reply(active_bot, guest_query_id, help_msg)
return
if cmd_lower == "/skills":
skills = skill_manager.list_skills()
if not skills:
await _send_guest_reply(
active_bot,
guest_query_id,
"В папке `skills/` пока нет скиллов.",
)
return
lines = ["🎯 **Доступные скиллы (Ghost Mode):**\n"]
for s in skills:
triggers_str = ", ".join([f"`{t}`" for t in s.triggers]) if s.triggers else f"`/skill {s.name}`"
lines.append(f"• **{s.title}** (`{s.name}`)\n _{s.description}_\n Запуск: {triggers_str}\n")
lines.append("\n_Упомяните меня с названием скилла или триггером для запуска._")
await _send_guest_reply(active_bot, guest_query_id, "\n".join(lines))
return
if cmd_lower == "/memory":
memory = get_global_memory()
items = memory.list_facts()
if not items:
await _send_guest_reply(
active_bot,
guest_query_id,
"Глобальная память пуста.",
)
return
lines = [f"🧠 **Глобальная память ({len(items)} фактов):**\n"]
for item in items:
lines.append(f"- `[{item.id}]` ({item.category}): {item.fact}")
await _send_guest_reply(active_bot, guest_query_id, "\n".join(lines))
return
if cmd_lower == "/reset":
agent.conversation_manager.clear(chat_id, thread_id)
topic_info = f"в топике #{thread_id}" if thread_id else "в этом чате"
await _send_guest_reply(
active_bot,
guest_query_id,
f"🧹 Контекст диалога {topic_info} успешно очищен.",
)
return
# If empty text and no reply context
if not cleaned_text and not reply_context:
bot_tag = f"@{bot_username}" if bot_username else "@bot"
welcome_msg = (
f"👋 **Привет! Я персональный AI-ассистент HomeAgent (Ghost Mode).**\n\n"
f"Я отвечаю в чатах без необходимости добавления в участники.\n"
f"Напишите `{bot_tag} <вопрос>` или ответьте моим тегом на любое сообщение!"
)
await _send_guest_reply(active_bot, guest_query_id, welcome_msg)
return
# 2. Check if the message triggers a skill
matched = skill_manager.match_trigger(cleaned_text)
if matched:
skill, extra_args = matched
prompt_to_run = skill.render(extra_instructions=extra_args)
logger.info("Executing skill '%s' via ghost mode for chat=%d, thread=%s", skill.name, chat_id, thread_id)
else:
if reply_context:
if cleaned_text:
prompt_to_run = f"{reply_context}[Запрос/вопрос пользователя]:\n{cleaned_text}"
else:
prompt_to_run = (
f"{reply_context}\n"
f"Пользователь упомянул тебя в ответ на это сообщение без дополнительного текста. "
f"Пожалуйста, проанализируй это сообщение, объясни его суть или дай полезный ответ по контексту."
)
else:
prompt_to_run = cleaned_text
# 3. Process with AI agent
typing_task = asyncio.create_task(_keep_typing(message))
try:
response_text = await agent.chat(
chat_id=chat_id,
thread_id=thread_id,
user_message=prompt_to_run,
on_progress=None,
)
finally:
typing_task.cancel()
# 4. Send reply via answerGuestQuery
await _send_guest_reply(active_bot, guest_query_id, response_text)
return router
@@ -183,6 +377,96 @@ async def _send_reply(message: Message, text: str) -> None:
logger.error("Failed sending message completely: %s", final_err)
async def _send_guest_reply(bot: Bot, guest_query_id: str, text: str) -> None:
"""Send reply to a guest message strictly using Telegram answerGuestQuery API with InputRichMessage."""
query_result_id = uuid.uuid4().hex
# Telegram Rich Messages limit is up to 32,768 characters
truncated_rich = text
if len(truncated_rich) > 32000:
truncated_rich = truncated_rich[:32000] + "\n\n_...[ответ сокращен из-за лимита Telegram]_"
rich_content = InputRichMessageContent(
rich_message=InputRichMessage(markdown=truncated_rich)
)
result = InlineQueryResultArticle(
id=query_result_id,
title="HomeAgent",
input_message_content=rich_content,
)
try:
await bot.answer_guest_query(
guest_query_id=guest_query_id,
result=result,
)
logger.info("Successfully replied to guest query %s with markdown InputRichMessage", guest_query_id)
return
except Exception as e:
logger.warning("Failed sending guest reply with markdown InputRichMessage: %s", e)
# Fallback 1: HTML InputRichMessage (in case of markdown parsing issue)
try:
html_content = InputRichMessageContent(
rich_message=InputRichMessage(html=truncated_rich)
)
html_result = InlineQueryResultArticle(
id=query_result_id,
title="HomeAgent",
input_message_content=html_content,
)
await bot.answer_guest_query(
guest_query_id=guest_query_id,
result=html_result,
)
logger.info("Successfully replied to guest query %s with html InputRichMessage fallback", guest_query_id)
return
except Exception as e2:
logger.warning("Failed sending guest reply with HTML InputRichMessage: %s", e2)
# Fallback 2: InputTextMessageContent with standard Markdown (truncated to 4000)
truncated_text = text
if len(truncated_text) > 4000:
truncated_text = truncated_text[:4000] + "\n\n_...[сокращено]_"
try:
plain_md_content = InputTextMessageContent(
message_text=truncated_text,
parse_mode=ParseMode.MARKDOWN,
)
plain_md_result = InlineQueryResultArticle(
id=query_result_id,
title="HomeAgent",
input_message_content=plain_md_content,
)
await bot.answer_guest_query(
guest_query_id=guest_query_id,
result=plain_md_result,
)
logger.info("Successfully replied to guest query %s with InputTextMessageContent Markdown", guest_query_id)
return
except Exception as e3:
logger.warning("Failed sending guest reply with InputTextMessageContent Markdown: %s", e3)
# Fallback 3: Plain text without parse_mode
try:
plain_text_content = InputTextMessageContent(
message_text=truncated_text,
parse_mode=None,
)
plain_text_result = InlineQueryResultArticle(
id=query_result_id,
title="HomeAgent",
input_message_content=plain_text_content,
)
await bot.answer_guest_query(
guest_query_id=guest_query_id,
result=plain_text_result,
)
logger.info("Successfully replied to guest query %s with plain text fallback", guest_query_id)
except Exception as final_err:
logger.error("Failed sending guest query reply completely for query %s: %s", guest_query_id, final_err)
async def _keep_typing(message: Message) -> None:
"""Send typing action periodically while agent executes."""
try:
+5 -2
View File
@@ -89,6 +89,7 @@ class TelegramAgentApp:
logger.info("Starting HomeAgent Telegram Bot...")
logger.info("Allowed User IDs: %s", self.settings.ALLOWED_TELEGRAM_USER_IDS)
logger.info("Ghost Bot Mode: %s", "Enabled (Bot API 10.0+ guest_message)" if self.settings.GHOST_MODE_ENABLED else "Disabled")
logger.info("LLM Provider: %s", self.settings.get_active_provider_name())
logger.info("Orchestrator Model: %s", self.settings.get_active_model())
logger.info("Subagent Model: %s", self.settings.get_active_subagent_model())
@@ -98,8 +99,10 @@ class TelegramAgentApp:
await self._setup_commands()
try:
# Delete any webhooks and start polling
# Delete any webhooks and start polling with automatically resolved update types (including guest_message)
await self.bot.delete_webhook(drop_pending_updates=True)
await self.dp.start_polling(self.bot)
allowed_updates = self.dp.resolve_used_update_types()
logger.info("Polling with allowed_updates: %s", allowed_updates)
await self.dp.start_polling(self.bot, allowed_updates=allowed_updates)
finally:
await self.bot.session.close()