so add the ghost mode for bot

This commit is contained in:
timka123 committed 2026-11-08 00:01:48 +03:00
1 parent 1809661f27
commit 34a43c953e
6 files changed
+69 -10

No files matched your search

+1 -1
View File
@@ -13,7 +13,7 @@
- 💬 **Telegram Форумы и Топики**: Полная поддержка тем (`message_thread_id`). Контекст диалога изолирован внутри каждого топика (топик задач не путается с топиком календаря). - 💬 **Telegram Форумы и Топики**: Полная поддержка тем (`message_thread_id`). Контекст диалога изолирован внутри каждого топика (топик задач не путается с топиком календаря).
- 📜 **Telegram Rich Messages**: Строгая отправка через нативный метод Telegram Bot API `send_rich_message` с объектом `InputRichMessage(markdown=...)` и лимитом до 32 768 символов. - 📜 **Telegram Rich Messages**: Строгая отправка через нативный метод Telegram Bot API `send_rich_message` с объектом `InputRichMessage(markdown=...)` и лимитом до 32 768 символов.
- 👻 **Ghost-боты (Telegram Bot API 10.0+ Guest Mode)**: Бот может отвечать в любых чатах, группах и супергруппах через `@-упоминания` (`guest_message` и `answerGuestQuery`), **даже не будучи добавленным в чат**. Поддерживается контекстный анализ сообщений через ответы (`reply_to_message`). - 👻 **Ghost-боты (Telegram Bot API 10.0+ Guest Mode)**: Бот может отвечать в любых чатах, группах и супергруппах через `@-упоминания` (`guest_message` и `answerGuestQuery`), **даже не будучи добавленным в чат**. Поддерживается контекстный анализ сообщений через ответы (`reply_to_message`).
- 🔒 **Строгий вайтлист в ЛС и группах**: В стандартных чатах бот отвечает **только вам** (`ALLOWED_TELEGRAM_USER_IDS`). Сообщения от посторонних тихо игнорируются. - 🔒 **Строгий вайтлист (Ghost- и Chat-фильтр)**: Бот отвечает **только вам** (`ALLOWED_TELEGRAM_USER_IDS`) как в личных/групповых сообщениях, так и в Ghost-режиме. Сообщения от посторонних тихо игнорируются без ответа.
- 🌐 **Глобальная общая память (Global Shared Memory)**: Хранилище фактов, заметок и предпочтений, общее для всех топиков форума (`/memory`, `remember_fact`, `recall_facts`). - 🌐 **Глобальная общая память (Global Shared Memory)**: Хранилище фактов, заметок и предпочтений, общее для всех топиков форума (`/memory`, `remember_fact`, `recall_facts`).
- 🦊 **Интеграция с Gitea / Forgejo (`https://git.timka.su`)**: Поиск и просмотр репозиториев, чтение файлов и директорий, «вайбкодинг» (создание и обновление файлов с автоматическими коммитами), создание веток, управление Issues и создание Pull Requests. - 🦊 **Интеграция с Gitea / Forgejo (`https://git.timka.su`)**: Поиск и просмотр репозиториев, чтение файлов и директорий, «вайбкодинг» (создание и обновление файлов с автоматическими коммитами), создание веток, управление Issues и создание Pull Requests.
- 🎟️ **Интеграция с Jira**: Полноценная поддержка Jira Cloud v3 enhanced search (`POST /rest/api/3/search/jql`) и Server/Data Center, просмотр задач с десериализацией ADF, создание тикетов, добавление комментариев, смена статусов, редактирование любых стандартных и кастомных полей (`jira_update_issue`), получение схемы полей (`jira_get_editable_fields`), поиск пользователей (`jira_search_users`) и фильтр задач по `statusCategory`. - 🎟️ **Интеграция с Jira**: Полноценная поддержка Jira Cloud v3 enhanced search (`POST /rest/api/3/search/jql`) и Server/Data Center, просмотр задач с десериализацией ADF, создание тикетов, добавление комментариев, смена статусов, редактирование любых стандартных и кастомных полей (`jira_update_issue`), получение схемы полей (`jira_get_editable_fields`), поиск пользователей (`jira_search_users`) и фильтр задач по `statusCategory`.
+2 -1
View File
@@ -45,9 +45,10 @@ Ghost-режим позволяет вашему боту отвечать в л
2. Запустите Mini App BotFather командой `/mybots` и выберите вашего бота. 2. Запустите Mini App BotFather командой `/mybots` и выберите вашего бота.
3. Перейдите в **Bot Settings** -> **Guest Mode**. 3. Перейдите в **Bot Settings** -> **Guest Mode**.
4. Нажмите **Enable** (включить гостевой режим). 4. Нажмите **Enable** (включить гостевой режим).
5. Теперь любой пользователь может призвать бота в любом чате: 5. Теперь авторизованный пользователь (`ALLOWED_TELEGRAM_USER_IDS`) может призвать бота в любом чате:
- `@имя_бота <вопрос>` — бот ответит прямо в чат через `answerGuestQuery`. - `@имя_бота <вопрос>` — бот ответит прямо в чат через `answerGuestQuery`.
- Если ответить тегом `@имя_бота` на чужое сообщение, бот автоматически получит его контекст и проанализирует/переведёт/ответит по нему. - Если ответить тегом `@имя_бота` на чужое сообщение, бот автоматически получит его контекст и проанализирует/переведёт/ответит по нему.
- Запросы от неавторизованных пользователей тихо игнорируются.
6. В файле `.env` режим включен по умолчанию (`GHOST_MODE_ENABLED=true`). При необходимости его можно отключить (`false`). 6. В файле `.env` режим включен по умолчанию (`GHOST_MODE_ENABLED=true`). При необходимости его можно отключить (`false`).
--- ---
+13
View File
@@ -199,6 +199,19 @@ def create_bot_router(
guest_query_id, guest_query_id,
) )
# Enforce strict user whitelist check for ghost bot messages
caller = message.guest_bot_caller_user or message.from_user
allowed_ids = settings.ALLOWED_TELEGRAM_USER_IDS
if not allowed_ids or not caller or caller.id not in allowed_ids:
caller_id = caller.id if caller else 0
caller_uname = caller.username if caller else "none"
logger.warning(
"Unauthorized ghost message attempt blocked: user_id=%s, username=@%s",
caller_id,
caller_uname,
)
return
# Retrieve bot username to cleanly strip @bot_username # Retrieve bot username to cleanly strip @bot_username
bot_username = None bot_username = None
try: try:
+5
View File
@@ -28,6 +28,11 @@ class WhitelistMiddleware(BaseMiddleware):
data: Dict[str, Any], data: Dict[str, Any],
) -> Any: ) -> Any:
user: User | None = data.get("event_from_user") user: User | None = data.get("event_from_user")
if not user and hasattr(event, "guest_bot_caller_user") and event.guest_bot_caller_user:
user = event.guest_bot_caller_user
elif not user and hasattr(event, "from_user") and event.from_user:
user = event.from_user
if not user: if not user:
# Events without a user (e.g. system status updates) are ignored # Events without a user (e.g. system status updates) are ignored
return None return None
+4 -2
View File
@@ -53,8 +53,10 @@ class TelegramAgentApp:
except Exception as e: except Exception as e:
logger.warning("Could not initialize Telegram Bot with provided token: %s", e) logger.warning("Could not initialize Telegram Bot with provided token: %s", e)
# Enforce strict whitelist middleware on all message events # Enforce strict whitelist middleware on message and ghost/guest events
self.dp.message.middleware(WhitelistMiddleware(self.settings)) whitelist_middleware = WhitelistMiddleware(self.settings)
self.dp.message.middleware(whitelist_middleware)
self.dp.guest_message.middleware(whitelist_middleware)
# Register router # Register router
router = create_bot_router( router = create_bot_router(
+44 -6
View File
@@ -89,7 +89,7 @@ async def test_send_guest_reply_truncates_oversized_text():
async def test_guest_message_handling_general_query(tmp_path): async def test_guest_message_handling_general_query(tmp_path):
settings = Settings( settings = Settings(
GHOST_MODE_ENABLED=True, GHOST_MODE_ENABLED=True,
ALLOWED_TELEGRAM_USER_IDS=[111], # Whitelist with only 111 ALLOWED_TELEGRAM_USER_IDS=[111], # Authorized user 111
) )
agent = MagicMock() agent = MagicMock()
agent.chat = AsyncMock(return_value="Answer from Ghost Agent!") agent.chat = AsyncMock(return_value="Answer from Ghost Agent!")
@@ -105,8 +105,8 @@ async def test_guest_message_handling_general_query(tmp_path):
bot.answer_guest_query = AsyncMock() bot.answer_guest_query = AsyncMock()
bot.send_chat_action = AsyncMock() bot.send_chat_action = AsyncMock()
# User 999 is NOT in whitelist! Should still be allowed in ghost mode per user instructions. # User 111 is in whitelist
caller_user = User(id=999, is_bot=False, first_name="Stranger", username="stranger") caller_user = User(id=111, is_bot=False, first_name="Owner", username="owner")
chat = Chat(id=-100123456, type="supergroup", title="External Group") chat = Chat(id=-100123456, type="supergroup", title="External Group")
guest_msg = Message( guest_msg = Message(
message_id=1, message_id=1,
@@ -136,9 +136,47 @@ async def test_guest_message_handling_general_query(tmp_path):
assert result.input_message_content.rich_message.markdown == "Answer from Ghost Agent!" assert result.input_message_content.rich_message.markdown == "Answer from Ghost Agent!"
@pytest.mark.asyncio
async def test_guest_message_blocks_unauthorized_user(tmp_path):
settings = Settings(
GHOST_MODE_ENABLED=True,
ALLOWED_TELEGRAM_USER_IDS=[111], # Only 111 is allowed
)
agent = MagicMock()
skill_manager = SkillManager(tmp_path / "skills")
tool_registry = ToolRegistry()
router = create_bot_router(settings, agent, skill_manager, tool_registry)
dp = Dispatcher()
dp.include_router(router)
bot = MagicMock(spec=Bot)
bot.answer_guest_query = AsyncMock()
# Unauthorized user 999
unauthorized_user = User(id=999, is_bot=False, first_name="Stranger", username="stranger")
chat = Chat(id=-100123456, type="supergroup", title="External Group")
guest_msg = Message(
message_id=2,
date=datetime.now(),
chat=chat,
from_user=unauthorized_user,
text="@homeagent_bot привет",
guest_query_id="gq_unauthorized",
guest_bot_caller_user=unauthorized_user,
)
guest_msg._bot = bot
upd = Update(update_id=101, guest_message=guest_msg)
await dp.feed_update(bot, upd)
agent.chat.assert_not_called()
bot.answer_guest_query.assert_not_called()
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_guest_message_handling_with_reply_to_message(tmp_path): async def test_guest_message_handling_with_reply_to_message(tmp_path):
settings = Settings(GHOST_MODE_ENABLED=True) settings = Settings(GHOST_MODE_ENABLED=True, ALLOWED_TELEGRAM_USER_IDS=[777])
agent = MagicMock() agent = MagicMock()
agent.chat = AsyncMock(return_value="Analysis of the replied message") agent.chat = AsyncMock(return_value="Analysis of the replied message")
skill_manager = SkillManager(tmp_path / "skills") skill_manager = SkillManager(tmp_path / "skills")
@@ -174,7 +212,7 @@ async def test_guest_message_handling_with_reply_to_message(tmp_path):
) )
guest_msg._bot = bot guest_msg._bot = bot
upd = Update(update_id=101, guest_message=guest_msg) upd = Update(update_id=102, guest_message=guest_msg)
await dp.feed_update(bot, upd) await dp.feed_update(bot, upd)
agent.chat.assert_awaited_once() agent.chat.assert_awaited_once()
@@ -189,7 +227,7 @@ async def test_guest_message_handling_with_reply_to_message(tmp_path):
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_guest_message_commands(tmp_path): async def test_guest_message_commands(tmp_path):
settings = Settings(GHOST_MODE_ENABLED=True) settings = Settings(GHOST_MODE_ENABLED=True, ALLOWED_TELEGRAM_USER_IDS=[1])
agent = MagicMock() agent = MagicMock()
skill_manager = SkillManager(tmp_path / "skills") skill_manager = SkillManager(tmp_path / "skills")
tool_registry = ToolRegistry() tool_registry = ToolRegistry()