Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions astrbot/core/platform/sources/telegram/tg_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -1106,6 +1107,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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Telegram replies fail during rebuild

When a reply or streamed edit overlaps polling recovery, especially during shutdown or across multiple awaited API calls, get_client() can return the old self.client while the application is shutting down, and send() passes a single resolved client to send_with_client, which retains it across awaits. Later requests then use the closing or closed bot, and the reply fails or is incomplete.

Make get_client() provide a usable client during recovery and have each Telegram API call resolve the client when it is made instead of retaining a snapshot across awaits.

Also at astrbot/core/platform/sources/telegram/tg_event.py:94-96.

)

async def handle_msg(self, message: AstrBotMessage) -> None:
Expand Down
102 changes: 64 additions & 38 deletions astrbot/core/platform/sources/telegram/tg_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down Expand Up @@ -116,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:
Expand All @@ -130,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),
Expand All @@ -139,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(
Expand Down Expand Up @@ -215,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,
Expand All @@ -228,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],
*,
Expand All @@ -263,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.
Expand All @@ -286,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),
Expand Down Expand Up @@ -329,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)]
Expand Down Expand Up @@ -363,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 = {
Expand All @@ -380,34 +402,34 @@ 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,
use_media_action=False,
)
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),
Expand All @@ -425,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(
Expand Down Expand Up @@ -619,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),
Expand All @@ -637,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,
Expand All @@ -648,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,
Expand All @@ -659,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),
Expand All @@ -671,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
Expand Down
68 changes: 68 additions & 0 deletions tests/test_telegram_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Loading