From 04f5273f4cccfa08a9486ab0e77d253e0247d076 Mon Sep 17 00:00:00 2001 From: wcqqq1214 Date: Fri, 4 Dec 2026 05:01:46 +0800 Subject: [PATCH 1/2] fix: use the active Telegram client for in-flight replies --- .../platform/sources/telegram/tg_adapter.py | 1 + .../platform/sources/telegram/tg_event.py | 13 +++- tests/test_telegram_adapter.py | 68 +++++++++++++++++++ 3 files changed, 81 insertions(+), 1 deletion(-) diff --git a/astrbot/core/platform/sources/telegram/tg_adapter.py b/astrbot/core/platform/sources/telegram/tg_adapter.py index 2a44e45a351..45b67c8782c 100644 --- a/astrbot/core/platform/sources/telegram/tg_adapter.py +++ b/astrbot/core/platform/sources/telegram/tg_adapter.py @@ -1106,6 +1106,7 @@ def create_event(self, message: AstrBotMessage) -> TelegramPlatformEvent: platform_meta=self.meta(), session_id=message.session_id, client=self.client, + get_client=self.get_client, ) async def handle_msg(self, message: AstrBotMessage) -> None: diff --git a/astrbot/core/platform/sources/telegram/tg_event.py b/astrbot/core/platform/sources/telegram/tg_event.py index cc2fbed9113..46391d4b458 100644 --- a/astrbot/core/platform/sources/telegram/tg_event.py +++ b/astrbot/core/platform/sources/telegram/tg_event.py @@ -84,9 +84,20 @@ def __init__( platform_meta: PlatformMetadata, session_id: str, client: ExtBot, + *, + get_client: Callable[[], ExtBot] | None = None, ) -> None: super().__init__(message_str, message_obj, platform_meta, session_id) - self.client = client + self._get_client = get_client or (lambda: client) + + @property + def client(self) -> ExtBot: + """Return the active bot, including after a polling client rebuild.""" + return self._get_client() + + @client.setter + def client(self, client: ExtBot) -> None: + self._get_client = lambda: client @classmethod def _split_message(cls, text: str) -> list[str]: diff --git a/tests/test_telegram_adapter.py b/tests/test_telegram_adapter.py index eaa67f33f70..b2837d2603e 100644 --- a/tests/test_telegram_adapter.py +++ b/tests/test_telegram_adapter.py @@ -1614,3 +1614,71 @@ async def receive(update, context): await asyncio.wait_for(task, timeout=5) assert len(polling_requests) == 2 assert all(client.is_closed for client in clients) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streaming", [False, True], ids=["plain", "streaming-edit"]) +async def test_existing_event_replies_after_client_rebuild(monkeypatch, streaming): + replies = [] + results = { + "getMe": { + "id": 123, + "is_bot": True, + "first_name": "Bot", + "username": "test_bot", + }, + "sendChatAction": True, + "sendMessage": { + "message_id": 17, + "date": 0, + "chat": {"id": -123, "type": "group"}, + }, + "editMessageText": True, + } + + def respond(request): + method = request.url.path.rsplit("/", 1)[-1] + if method in ("sendMessage", "editMessageText"): + params = httpx.QueryParams(request.content) + replies.append((method, params["text"].strip(), params.get("message_id"))) + return httpx.Response(200, json={"ok": True, "result": results[method]}) + + monkeypatch.setattr( + HTTPXRequest, + "_build_client", + lambda self: httpx.AsyncClient(transport=httpx.MockTransport(respond)), + ) + monkeypatch.setattr("astrbot.core.utils.metrics.Metric.upload", AsyncMock()) + queue = asyncio.Queue() + adapter = RealTelegramPlatformAdapter( + make_platform_config( + "telegram", telegram_token="123:TEST", telegram_command_register=False + ), + {}, + queue, + ) + await adapter._start_application() + try: + update = create_mock_update(chat_type="group", chat_id=-123) + await adapter.message_handler(update, _build_context()) + event = queue.get_nowait() + if streaming: + + async def chunks(): + yield MessageChain([Comp.Plain("first")]) + await adapter._recreate_application() + await adapter._start_application() + yield MessageChain([Comp.Plain(" second")]) + + await event.send_streaming(chunks()) + assert replies == [ + ("sendMessage", "first", None), + ("editMessageText", "first second", "17"), + ] + else: + await adapter._recreate_application() + await adapter._start_application() + await event.send(MessageChain([Comp.Plain("reply")])) + assert replies == [("sendMessage", "reply", None)] + finally: + await adapter.terminate() From 8d3efcd34914fc5a8d6a7385d585179536c74fe1 Mon Sep 17 00:00:00 2001 From: wcqqq1214 Date: Fri, 4 Dec 2026 05:15:44 +0800 Subject: [PATCH 2/2] fix: resolve the Telegram client for each reply request --- .../platform/sources/telegram/tg_adapter.py | 1 + .../platform/sources/telegram/tg_event.py | 89 +++++++++++-------- 2 files changed, 53 insertions(+), 37 deletions(-) diff --git a/astrbot/core/platform/sources/telegram/tg_adapter.py b/astrbot/core/platform/sources/telegram/tg_adapter.py index 45b67c8782c..b28157fc52a 100644 --- a/astrbot/core/platform/sources/telegram/tg_adapter.py +++ b/astrbot/core/platform/sources/telegram/tg_adapter.py @@ -300,6 +300,7 @@ async def send_by_session( self.client, message_chain, from_username, + get_client=self.get_client, ) await super().send_by_session(session, message_chain) diff --git a/astrbot/core/platform/sources/telegram/tg_event.py b/astrbot/core/platform/sources/telegram/tg_event.py index 46391d4b458..58a5873b9c0 100644 --- a/astrbot/core/platform/sources/telegram/tg_event.py +++ b/astrbot/core/platform/sources/telegram/tg_event.py @@ -127,7 +127,7 @@ def _split_message(cls, text: str) -> list[str]: @classmethod async def _send_text_chunks( cls, - client: ExtBot, + get_client: Callable[[], ExtBot], text: str, payload: dict[str, Any], ) -> None: @@ -141,7 +141,7 @@ async def _send_text_chunks( markdown_text = telegramify_markdown.markdownify( chunk, ) - await client.send_message( + await get_client().send_message( text=markdown_text, parse_mode="MarkdownV2", **cast(Any, chunk_payload), @@ -150,7 +150,7 @@ async def _send_text_chunks( logger.warning( f"Failed to convert message to Markdown,using normal text: {e!s}" ) - await client.send_message(text=chunk, **cast(Any, chunk_payload)) + await get_client().send_message(text=chunk, **cast(Any, chunk_payload)) @classmethod def _build_inline_keyboard( @@ -226,9 +226,9 @@ def _get_chat_action_for_chain(cls, chain: list[Any]) -> ChatAction | str: @classmethod async def _send_media_with_action( cls, - client: ExtBot, + get_client: Callable[[], ExtBot], upload_action: ChatAction | str, - send_coro, + send_method: str, *, user_name: str, message_thread_id: str | None = None, @@ -239,20 +239,20 @@ async def _send_media_with_action( str | None, payload.get("message_thread_id") ) await cls._send_chat_action( - client, user_name, upload_action, effective_thread_id + get_client(), user_name, upload_action, effective_thread_id ) send_payload = dict(payload) if effective_thread_id and "message_thread_id" not in send_payload: send_payload["message_thread_id"] = effective_thread_id - await send_coro(**send_payload) + await getattr(get_client(), send_method)(**send_payload) await cls._send_chat_action( - client, user_name, ChatAction.TYPING, effective_thread_id + get_client(), user_name, ChatAction.TYPING, effective_thread_id ) @classmethod async def _send_voice_with_fallback( cls, - client: ExtBot, + get_client: Callable[[], ExtBot], path: str, payload: dict[str, Any], *, @@ -274,15 +274,15 @@ async def _send_voice_with_fallback( if message_thread_id and "message_thread_id" not in media_payload: media_payload["message_thread_id"] = message_thread_id await cls._send_media_with_action( - client, + get_client, ChatAction.UPLOAD_VOICE, - client.send_voice, + "send_voice", user_name=user_name, voice=path, **cast(Any, media_payload), ) else: - await client.send_voice(voice=path, **cast(Any, payload)) + await get_client().send_voice(voice=path, **cast(Any, payload)) except BadRequest as e: # python-telegram-bot raises BadRequest for Voice_messages_forbidden; # distinguish the voice-privacy case via the API error message. @@ -297,16 +297,16 @@ async def _send_voice_with_fallback( if message_thread_id and "message_thread_id" not in media_payload: media_payload["message_thread_id"] = message_thread_id await cls._send_media_with_action( - client, + get_client, ChatAction.UPLOAD_DOCUMENT, - client.send_document, + "send_document", user_name=user_name, document=path, caption=caption, **cast(Any, media_payload), ) else: - await client.send_document( + await get_client().send_document( document=path, caption=caption, **cast(Any, payload), @@ -340,7 +340,18 @@ async def send_with_client( client: ExtBot, message: MessageChain, user_name: str, + *, + get_client: Callable[[], ExtBot] | None = None, ) -> None: + """Send a reply using the current bot for each Telegram request. + + Args: + client: Bot used when no client getter is supplied. + message: Message components to send. + user_name: Telegram chat ID, optionally followed by a topic ID. + get_client: Returns the adapter's current bot after a rebuild. + """ + get_client = get_client or (lambda: client) image_path = None action_rows = [i for i in message.chain if isinstance(i, ActionRow)] @@ -374,7 +385,7 @@ async def send_with_client( # 根据消息链确定合适的 chat action 并发送 action = cls._get_chat_action_for_chain(message.chain) - await cls._send_chat_action(client, user_name, action, message_thread_id) + await cls._send_chat_action(get_client(), user_name, action, message_thread_id) for index, i in enumerate(message.chain): payload = { @@ -391,26 +402,26 @@ async def send_with_client( if at_user_id and not at_flag: i.text = f"@{at_user_id} {i.text}" at_flag = True - await cls._send_text_chunks(client, i.text, payload) + await cls._send_text_chunks(get_client, i.text, payload) elif isinstance(i, Image): image_path = await i.convert_to_file_path() if _is_gif(image_path): - send_coro = client.send_animation + send_coro = get_client().send_animation media_kwarg = {"animation": image_path} else: - send_coro = client.send_photo + send_coro = get_client().send_photo media_kwarg = {"photo": image_path} await send_coro(**media_kwarg, **cast(Any, payload)) elif isinstance(i, File): path = await i.get_file() name = i.name or os.path.basename(path) - await client.send_document( + await get_client().send_document( document=path, filename=name, **cast(Any, payload) ) elif isinstance(i, Record): path = await i.convert_to_file_path() await cls._send_voice_with_fallback( - client, + get_client, path, payload, caption=i.text or None, @@ -418,7 +429,7 @@ async def send_with_client( ) elif isinstance(i, Video): path = await i.convert_to_file_path() - await client.send_video( + await get_client().send_video( video=path, caption=getattr(i, "text", None) or None, **cast(Any, payload), @@ -436,13 +447,17 @@ async def send_with_client( payload["reply_to_message_id"] = str(reply_message_id) if message_thread_id: payload["message_thread_id"] = message_thread_id - await cls._send_text_chunks(client, fallback_text, payload) + await cls._send_text_chunks(get_client, fallback_text, payload) async def send(self, message: MessageChain) -> None: - if self.get_message_type() == MessageType.GROUP_MESSAGE: - await self.send_with_client(self.client, message, self.message_obj.group_id) - else: - await self.send_with_client(self.client, message, self.get_sender_id()) + chat_id = ( + self.message_obj.group_id + if self.get_message_type() == MessageType.GROUP_MESSAGE + else self.get_sender_id() + ) + await self.send_with_client( + self.client, message, chat_id, get_client=self._get_client + ) await super().send(message) async def get_group( @@ -630,16 +645,16 @@ async def _process_chain_items( image_path = await i.convert_to_file_path() if _is_gif(image_path): action = ChatAction.UPLOAD_VIDEO - send_coro = self.client.send_animation + send_method = "send_animation" media_kwarg = {"animation": image_path} else: action = ChatAction.UPLOAD_PHOTO - send_coro = self.client.send_photo + send_method = "send_photo" media_kwarg = {"photo": image_path} await self._send_media_with_action( - self.client, + self._get_client, action, - send_coro, + send_method, user_name=user_name, **media_kwarg, **cast(Any, payload), @@ -648,9 +663,9 @@ async def _process_chain_items( path = await i.get_file() name = i.name or os.path.basename(path) await self._send_media_with_action( - self.client, + self._get_client, ChatAction.UPLOAD_DOCUMENT, - self.client.send_document, + "send_document", user_name=user_name, document=path, filename=name, @@ -659,7 +674,7 @@ async def _process_chain_items( elif isinstance(i, Record): path = await i.convert_to_file_path() await self._send_voice_with_fallback( - self.client, + self._get_client, path, payload, caption=i.text or None, @@ -670,9 +685,9 @@ async def _process_chain_items( elif isinstance(i, Video): path = await i.convert_to_file_path() await self._send_media_with_action( - self.client, + self._get_client, ChatAction.UPLOAD_VIDEO, - self.client.send_video, + "send_video", user_name=user_name, video=path, **cast(Any, payload), @@ -682,7 +697,7 @@ async def _process_chain_items( async def _send_final_segment(self, delta: str, payload: dict[str, Any]) -> None: """将累积文本作为 MarkdownV2 真实消息发送,失败时回退到纯文本。""" - await self._send_text_chunks(self.client, delta, payload) + await self._send_text_chunks(self._get_client, delta, payload) async def send_streaming(self, generator, use_fallback: bool = False): message_thread_id = None