from __future__ import annotations import asyncio import logging from yuxi.channel.extensions.telegram.format import split_telegram_html_chunks logger = logging.getLogger(__name__) class TelegramDelivery: def __init__(self, outbound): self._outbound = outbound async def deliver_chunks( self, target_id: str, html_chunks: list[str], *, reply_to_id: str | None = None, thread_id: str | None = None, account_id: str | None = None, ) -> list[str]: msg_ids: list[str] = [] for chunk in html_chunks: msg_id = await self._outbound.send_text_raw( target_id, chunk, reply_to_id=reply_to_id, thread_id=thread_id, account_id=account_id, ) if msg_id: msg_ids.append(msg_id) if len(html_chunks) > 1: await asyncio.sleep(0.3) return msg_ids async def deliver_single( self, target_id: str, html: str, *, reply_to_id: str | None = None, thread_id: str | None = None, account_id: str | None = None, chunk_limit: int = 4096, ) -> list[str]: chunks = split_telegram_html_chunks(html, chunk_limit) return await self.deliver_chunks( target_id, chunks, reply_to_id=reply_to_id, thread_id=thread_id, account_id=account_id, ) async def deliver_placeholder_edit( self, target_id: str, html: str, *, reply_to_id: str | None = None, thread_id: str | None = None, account_id: str | None = None, chunk_limit: int = 4096, placeholder_text: str = "⏳ 正在生成回复...", ) -> list[str]: chunks = split_telegram_html_chunks(html, chunk_limit) if len(chunks) <= 1: return await self.deliver_single( target_id, html, reply_to_id=reply_to_id, thread_id=thread_id, account_id=account_id, chunk_limit=chunk_limit, ) placeholder_id = await self._outbound.send_text_raw( target_id, placeholder_text, reply_to_id=reply_to_id, thread_id=thread_id, account_id=account_id, ) if not placeholder_id: return await self.deliver_chunks( target_id, chunks, reply_to_id=reply_to_id, thread_id=thread_id, account_id=account_id, ) msg_ids = [placeholder_id] accumulated = "" for chunk in chunks: accumulated += chunk if len(accumulated) > chunk_limit: accumulated = accumulated[:chunk_limit] await self._outbound.edit_message( target_id, placeholder_id, accumulated, thread_id=thread_id, account_id=account_id, ) if len(chunks) > 1: await asyncio.sleep(0.5) return msg_ids