mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-12-01 16:36:28 +08:00
fix(telegram): recover final replies after bounded 429 cooldown
Wait within a bounded budget for Telegram 429 retry_after on final sends and final streaming edits while keeping intermediate progress edits skipped immediately, resume chunked sends only from unsent chunks, propagate strict channel delivery failures back to send_message, and remove orphaned thinking placeholders on stream finalization. Refs #7630
This commit is contained in:
@@ -1028,6 +1028,73 @@ class StreamingHandler:
|
||||
if self._message_response is not None:
|
||||
await run_in_threadpool(_StreamChain().finalize_message, self._message_response)
|
||||
|
||||
def _resolve_channel_enum(self) -> Optional[NotificationChannel]:
|
||||
"""
|
||||
解析当前流式输出所属的通知渠道枚举,无法识别时返回 None。
|
||||
"""
|
||||
if not self._channel:
|
||||
return None
|
||||
try:
|
||||
return NotificationChannel(self._channel)
|
||||
except (ValueError, KeyError):
|
||||
return None
|
||||
|
||||
def _rollover_message_if_needed(
|
||||
self,
|
||||
current_text: str,
|
||||
end_offset: Optional[int],
|
||||
) -> str:
|
||||
"""
|
||||
当前消息超长时冻结旧消息并重置编辑身份,返回新消息应发送的未交付文本。
|
||||
"""
|
||||
if (
|
||||
self._message_response is None
|
||||
or not self._max_message_length
|
||||
or len(current_text) <= self._max_message_length
|
||||
):
|
||||
return current_text
|
||||
logger.debug(
|
||||
f"流式消息长度 {len(current_text)} 超过限制 {self._max_message_length},启用新消息"
|
||||
)
|
||||
with self._lock:
|
||||
unsent_text = self._unsent_text_locked(current_text)
|
||||
self._msg_start_offset += len(current_text) - len(unsent_text)
|
||||
next_text = self._buffer[self._msg_start_offset : end_offset]
|
||||
self._message_response = None
|
||||
self._sent_text = ""
|
||||
self._sent_thinking_status = ""
|
||||
return next_text
|
||||
|
||||
def _build_direct_stream_message(self, text: str) -> Message:
|
||||
"""
|
||||
构造流式首条或分段直发消息体。
|
||||
"""
|
||||
return Message.model_validate({
|
||||
"channel": self._channel,
|
||||
"source": self._source,
|
||||
"mtype": MessageType.Agent,
|
||||
"userid": self._user_id,
|
||||
"username": self._username,
|
||||
"original_message_id": self._original_message_id,
|
||||
"original_chat_id": self._original_chat_id,
|
||||
"title": self._title,
|
||||
"text": text,
|
||||
"rich_message": self._get_rich_message(text),
|
||||
"save_history": False,
|
||||
})
|
||||
|
||||
def _should_clear_thinking_placeholder_locked(self, current_text: str, final: bool) -> bool:
|
||||
"""
|
||||
判断收尾时是否需要删除仅含思考占位且无后续正文的渠道消息。
|
||||
"""
|
||||
return (
|
||||
final
|
||||
and not current_text
|
||||
and self._message_response is not None
|
||||
and bool(self._sent_thinking_status)
|
||||
and self._sent_text == self._sent_thinking_status
|
||||
)
|
||||
|
||||
async def _flush(
|
||||
self,
|
||||
end_offset: Optional[int] = None,
|
||||
@@ -1046,7 +1113,10 @@ class StreamingHandler:
|
||||
# 当前消息的文本 = buffer 中从 _msg_start_offset 开始的部分
|
||||
current_text = self._buffer[self._msg_start_offset : end_offset]
|
||||
thinking_status = self._thinking_status_text
|
||||
if not current_text or current_text == self._sent_text:
|
||||
should_clear_placeholder = self._should_clear_thinking_placeholder_locked(
|
||||
current_text, final
|
||||
)
|
||||
if (not current_text or current_text == self._sent_text) and not should_clear_placeholder:
|
||||
# 没有新内容需要刷新
|
||||
return
|
||||
if (not self._channel or not self._source) and not self._allow_dispatch_without_context:
|
||||
@@ -1056,97 +1126,66 @@ class StreamingHandler:
|
||||
chain = _StreamChain()
|
||||
|
||||
try:
|
||||
if should_clear_placeholder:
|
||||
channel_enum = self._resolve_channel_enum()
|
||||
response = self._message_response
|
||||
if channel_enum is not None and response is not None and response.message_id:
|
||||
deleted = await run_in_threadpool(
|
||||
chain.delete_message,
|
||||
channel=channel_enum,
|
||||
source=response.source or self._source or "",
|
||||
message_id=response.message_id,
|
||||
chat_id=response.chat_id,
|
||||
)
|
||||
if deleted:
|
||||
with self._lock:
|
||||
self._message_response = None
|
||||
self._sent_text = ""
|
||||
self._sent_thinking_status = ""
|
||||
return
|
||||
|
||||
current_text = self._rollover_message_if_needed(current_text, end_offset)
|
||||
if self._message_response is None:
|
||||
# 第一次发送:发送新消息并获取 message_id
|
||||
if not current_text:
|
||||
return
|
||||
# 首次发送或超长分段:发送新消息并获取 message_id
|
||||
response = await run_in_threadpool(
|
||||
chain.send_direct_message,
|
||||
Message.model_validate({
|
||||
"channel": self._channel,
|
||||
"source": self._source,
|
||||
"mtype": MessageType.Agent,
|
||||
"userid": self._user_id,
|
||||
"username": self._username,
|
||||
"original_message_id": self._original_message_id,
|
||||
"original_chat_id": self._original_chat_id,
|
||||
"title": self._title,
|
||||
"text": current_text,
|
||||
"rich_message": self._get_rich_message(current_text),
|
||||
"save_history": False,
|
||||
}),
|
||||
self._build_direct_stream_message(current_text),
|
||||
)
|
||||
if response and response.success and response.message_id:
|
||||
self._message_response = response
|
||||
self._record_sent_text(current_text, thinking_status)
|
||||
logger.debug(f"流式输出初始消息已发送: message_id={response.message_id}")
|
||||
logger.debug(f"流式输出消息已发送: message_id={response.message_id}")
|
||||
else:
|
||||
logger.debug("流式输出初始消息发送失败或未返回message_id,降级为非流式输出")
|
||||
logger.debug("流式输出消息发送失败或未返回message_id,降级为非流式输出")
|
||||
self._streaming_enabled = False
|
||||
return
|
||||
|
||||
# 后续更新:编辑已有消息
|
||||
channel_enum = self._resolve_channel_enum()
|
||||
if channel_enum is None:
|
||||
return
|
||||
metadata = dict(self._message_response.metadata or {})
|
||||
rich_message = self._get_rich_message(current_text)
|
||||
if rich_message:
|
||||
# 通用编辑接口不增加渠道专属参数,通过元数据交给 Telegram 模块消费。
|
||||
metadata["telegram_rich_message"] = rich_message
|
||||
metadata["telegram_wait_for_edit_interval"] = final
|
||||
success = await run_in_threadpool(
|
||||
chain.edit_message,
|
||||
channel=channel_enum,
|
||||
source=self._message_response.source,
|
||||
message_id=self._message_response.message_id,
|
||||
chat_id=self._message_response.chat_id,
|
||||
text=current_text,
|
||||
title=self._title,
|
||||
metadata=metadata,
|
||||
)
|
||||
if success:
|
||||
self._record_sent_text(current_text, thinking_status)
|
||||
else:
|
||||
# 检查当前消息内容是否超过长度限制
|
||||
if self._max_message_length and len(current_text) > self._max_message_length:
|
||||
# 消息过长,冻结当前消息(保持最后一次成功编辑的内容)
|
||||
# 将 offset 移动到已发送文本之后,开启新消息
|
||||
logger.debug(f"流式消息长度 {len(current_text)} 超过限制 {self._max_message_length},启用新消息")
|
||||
with self._lock:
|
||||
unsent_text = self._unsent_text_locked(current_text)
|
||||
self._msg_start_offset += len(current_text) - len(unsent_text)
|
||||
current_text = self._buffer[self._msg_start_offset : end_offset]
|
||||
self._message_response = None
|
||||
self._sent_text = ""
|
||||
self._sent_thinking_status = ""
|
||||
|
||||
# 如果偏移后还有新内容,立即发送为新消息
|
||||
if current_text:
|
||||
response = await run_in_threadpool(
|
||||
chain.send_direct_message,
|
||||
Message.model_validate({
|
||||
"channel": self._channel,
|
||||
"source": self._source,
|
||||
"mtype": MessageType.Agent,
|
||||
"userid": self._user_id,
|
||||
"username": self._username,
|
||||
"original_message_id": self._original_message_id,
|
||||
"original_chat_id": self._original_chat_id,
|
||||
"title": self._title,
|
||||
"text": current_text,
|
||||
"rich_message": self._get_rich_message(current_text),
|
||||
"save_history": False,
|
||||
}),
|
||||
)
|
||||
if response and response.success and response.message_id:
|
||||
self._message_response = response
|
||||
self._record_sent_text(current_text, thinking_status)
|
||||
logger.debug(f"流式输出新消息已发送: message_id={response.message_id}")
|
||||
else:
|
||||
logger.debug("流式输出新消息发送失败,降级为非流式输出")
|
||||
self._streaming_enabled = False
|
||||
else:
|
||||
# 后续更新:编辑已有消息
|
||||
try:
|
||||
channel_enum = NotificationChannel(self._channel)
|
||||
except (ValueError, KeyError):
|
||||
return
|
||||
|
||||
metadata = dict(self._message_response.metadata or {})
|
||||
rich_message = self._get_rich_message(current_text)
|
||||
if rich_message:
|
||||
# 通用编辑接口不增加渠道专属参数,通过元数据交给 Telegram 模块消费。
|
||||
metadata["telegram_rich_message"] = rich_message
|
||||
metadata["telegram_wait_for_edit_interval"] = final
|
||||
success = await run_in_threadpool(
|
||||
chain.edit_message,
|
||||
channel=channel_enum,
|
||||
source=self._message_response.source,
|
||||
message_id=self._message_response.message_id,
|
||||
chat_id=self._message_response.chat_id,
|
||||
text=current_text,
|
||||
title=self._title,
|
||||
metadata=metadata,
|
||||
)
|
||||
if success:
|
||||
self._record_sent_text(current_text, thinking_status)
|
||||
else:
|
||||
logger.debug("流式输出消息编辑失败")
|
||||
logger.debug("流式输出消息编辑失败")
|
||||
except Exception as e:
|
||||
logger.error(f"流式输出刷新失败: {e}")
|
||||
|
||||
|
||||
@@ -1086,13 +1086,21 @@ class MoviePilotTool(BaseTool, metaclass=ABCMeta):
|
||||
|
||||
return False
|
||||
|
||||
async def send_message(self, message: Message) -> None:
|
||||
async def send_message(
|
||||
self,
|
||||
message: Message,
|
||||
*,
|
||||
strict_delivery: bool = False,
|
||||
) -> None:
|
||||
"""
|
||||
发送工具消息。
|
||||
|
||||
WebAgent 渠道没有后端模块实例,前端流式面板通过 Agent 上下文中的
|
||||
回调直接接收消息;无渠道的后台任务清空渠道侧定位信息后交由消息链广播,
|
||||
其它渠道继续走统一消息链。
|
||||
|
||||
:param message: 待发送的通知消息
|
||||
:param strict_delivery: 交互渠道发送时是否透传模块投递未确认异常
|
||||
"""
|
||||
callback = self._agent_context.get("message_callback")
|
||||
if (
|
||||
@@ -1128,6 +1136,10 @@ class MoviePilotTool(BaseTool, metaclass=ABCMeta):
|
||||
update={"original_chat_id": original_chat_id}
|
||||
)
|
||||
|
||||
if strict_delivery and self._channel and self._source:
|
||||
await ToolChain().async_post_message(message, _strict_delivery=True)
|
||||
return
|
||||
|
||||
await ToolChain().async_post_message(message)
|
||||
|
||||
async def send_tool_message(
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
发送消息工具
|
||||
"""
|
||||
|
||||
import json
|
||||
from typing import Any, Optional, Type
|
||||
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
@@ -148,11 +149,20 @@ class SendMessageTool(MoviePilotTool):
|
||||
"image": image_url,
|
||||
"rich_message": rich_message,
|
||||
"save_history": False,
|
||||
})
|
||||
}),
|
||||
strict_delivery=bool(self._channel and self._source),
|
||||
)
|
||||
self._agent_context["user_reply_sent"] = True
|
||||
self._agent_context["reply_mode"] = "send_message"
|
||||
return "消息已发送"
|
||||
except Exception as e:
|
||||
logger.error(f"发送消息失败: {e}")
|
||||
return f"发送消息时发生错误: {str(e)}"
|
||||
return json.dumps(
|
||||
{
|
||||
"success": False,
|
||||
"execution_outcome": "failed",
|
||||
"tool": self.name,
|
||||
"error": f"发送消息失败: {e}",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
@@ -1280,7 +1280,7 @@ class MessageQueueManager(metaclass=SingletonClass):
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
"""
|
||||
调用一条消息携带的发送回调并隔离渠道异常。
|
||||
调用一条消息携带的发送回调;未显式要求抛错时隔离渠道异常。
|
||||
"""
|
||||
if send_callback:
|
||||
try:
|
||||
@@ -1288,6 +1288,8 @@ class MessageQueueManager(metaclass=SingletonClass):
|
||||
send_callback(*args, **kwargs)
|
||||
except Exception as e:
|
||||
logger.error(f"发送消息错误:{str(e)}")
|
||||
if kwargs.get("raise_exception"):
|
||||
raise
|
||||
|
||||
def _monitor_loop(self) -> None:
|
||||
"""
|
||||
|
||||
@@ -526,6 +526,7 @@ class NotificationMixin:
|
||||
:param transferinfo: 文件整理信息
|
||||
:param kwargs: 其他参数(覆盖业务对象属性值)
|
||||
"""
|
||||
strict_delivery = bool(kwargs.pop("_strict_delivery", False))
|
||||
message = _render_notification_message(
|
||||
message=message,
|
||||
meta=meta,
|
||||
@@ -542,6 +543,7 @@ class NotificationMixin:
|
||||
dispatch_message = self._normalize_notification_for_dispatch(message)
|
||||
await self._async_dispatch_notification_steps(
|
||||
dispatch_message,
|
||||
strict_delivery=strict_delivery,
|
||||
kwargs=kwargs,
|
||||
)
|
||||
|
||||
@@ -549,6 +551,7 @@ class NotificationMixin:
|
||||
self,
|
||||
message: Message,
|
||||
*,
|
||||
strict_delivery: bool = False,
|
||||
kwargs: dict[str, object],
|
||||
) -> None:
|
||||
"""
|
||||
@@ -580,11 +583,14 @@ class NotificationMixin:
|
||||
etype=EventType.NoticeMessage,
|
||||
data=self._build_notice_message_data(step.message),
|
||||
)
|
||||
delivery_kwargs = dict(kwargs)
|
||||
if strict_delivery:
|
||||
delivery_kwargs["raise_exception"] = True
|
||||
await self.messagequeue.async_send_message(
|
||||
"post_message",
|
||||
message=step.message,
|
||||
immediately=step.immediately,
|
||||
**kwargs,
|
||||
immediately=True if strict_delivery else step.immediately,
|
||||
**delivery_kwargs,
|
||||
)
|
||||
try:
|
||||
step = steps.send(lookup_result)
|
||||
|
||||
@@ -638,7 +638,7 @@ class TelegramModule(_MessageChannelModuleBase[Telegram]):
|
||||
:param text: 新的消息内容
|
||||
:param title: 消息标题
|
||||
:param buttons: 新的按钮列表
|
||||
:param metadata: telegram_rich_message 为流式富文本;telegram_wait_for_edit_interval 表示等待编辑间隔收尾
|
||||
:param metadata: telegram_rich_message 为流式富文本;telegram_wait_for_edit_interval 表示收尾编辑等待间隔及有上限的 429 冷却
|
||||
:param parse_mode: Telegram 消息格式类型,默认 MarkdownV2,可传 HTML
|
||||
:return: 编辑是否成功
|
||||
"""
|
||||
|
||||
@@ -49,6 +49,11 @@ TELEGRAM_PARSE_MODE_PLAIN = ""
|
||||
TELEGRAM_EDIT_MIN_INTERVAL_SECONDS = 2.0
|
||||
# 服务端未给出重试时间时使用的默认冷却秒数
|
||||
TELEGRAM_RATE_LIMIT_DEFAULT_SECONDS = 60.0
|
||||
# 最终正文与收尾编辑在 429 冷却期内允许等待的累计上限,单位为秒;
|
||||
# 超过上限时直接失败,避免在超长 retry_after 下无界阻塞会话。
|
||||
TELEGRAM_RATE_LIMIT_MAX_WAIT_SECONDS = 60.0
|
||||
# 单次最终发送或收尾编辑在等待预算内最多因 429 重试的次数
|
||||
TELEGRAM_RATE_LIMIT_MAX_RETRIES = 2
|
||||
# 持续限流期间日志输出间隔,单位为秒
|
||||
TELEGRAM_RATE_LIMIT_LOG_INTERVAL_SECONDS = 60.0
|
||||
_TELEGRAM_RETRY_AFTER_PATTERN = re.compile(r"retry\s+after\s+(\d+)", re.IGNORECASE)
|
||||
@@ -175,6 +180,14 @@ class NonRetryableTelegramError(ImmediateException):
|
||||
pass
|
||||
|
||||
|
||||
class _TelegramRateLimitError(NonRetryableTelegramError):
|
||||
"""
|
||||
Telegram 返回 429 限流响应,须立即终止通用重试并交由冷却等待策略处理。
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
def _is_non_retryable_api_error(err: Exception) -> bool:
|
||||
"""
|
||||
判断 Bot API 错误是否为重试无意义的 4xx。
|
||||
@@ -408,23 +421,120 @@ class Telegram:
|
||||
)
|
||||
return True
|
||||
|
||||
def _has_active_rate_limit(self, chat_id: Union[str, int]) -> bool:
|
||||
"""
|
||||
只读检查聊天当前是否处于未过期的 429 冷却期,不累计跳过次数。
|
||||
|
||||
:param chat_id: 目标会话标识
|
||||
:return: 仍在冷却期返回 True,否则返回 False
|
||||
"""
|
||||
self._ensure_edit_state()
|
||||
chat_key = str(chat_id)
|
||||
with self._edit_state_lock:
|
||||
return self._chat_rate_limit_until.get(chat_key, 0.0) > time.monotonic()
|
||||
|
||||
def _wait_for_rate_limit(
|
||||
self,
|
||||
chat_id: Union[str, int],
|
||||
*,
|
||||
operation: str = "编辑",
|
||||
remaining_budget: float = 0.0,
|
||||
) -> tuple[bool, float]:
|
||||
"""
|
||||
在剩余预算内等待聊天 429 冷却结束;超预算或未开启等待时立即返回不可发送。
|
||||
|
||||
等待在锁外执行,醒来后重新核对冷却状态和客户端存活状态,避免并发请求延长冷却
|
||||
或客户端已停止后继续外发。
|
||||
|
||||
:param chat_id: 目标会话标识
|
||||
:param operation: 日志中展示的操作名称,例如发送、编辑或删除
|
||||
:param remaining_budget: 本次调用剩余可等待秒数,小于等于 0 时不等待
|
||||
:return: 二元组 ``(是否可继续投递, 剩余等待预算秒数)``
|
||||
"""
|
||||
self._ensure_edit_state()
|
||||
budget = max(0.0, float(remaining_budget))
|
||||
if budget <= 0:
|
||||
return (not self._is_chat_rate_limited(chat_id, operation=operation)), 0.0
|
||||
|
||||
chat_key = str(chat_id)
|
||||
had_bot = self._bot is not None
|
||||
waits = 0
|
||||
while True:
|
||||
now = time.monotonic()
|
||||
with self._edit_state_lock:
|
||||
cooldown_until = self._chat_rate_limit_until.get(chat_key, 0.0)
|
||||
if cooldown_until <= now:
|
||||
if chat_key in self._chat_rate_limit_until:
|
||||
skipped = self._chat_rate_limit_skipped.pop(chat_key, 0)
|
||||
self._chat_rate_limit_until.pop(chat_key, None)
|
||||
self._chat_rate_limit_last_log.pop(chat_key, None)
|
||||
if skipped:
|
||||
logger.info(
|
||||
"Telegram%s限流冷却结束,chat_id=%s,期间跳过%s次请求",
|
||||
operation,
|
||||
chat_id,
|
||||
skipped,
|
||||
)
|
||||
return True, budget
|
||||
remaining = cooldown_until - now
|
||||
|
||||
if remaining > budget:
|
||||
logger.warning(
|
||||
"Telegram%s处于429冷却,剩余约%s秒超出等待上限(剩余预算%.1f秒),放弃补发:chat_id=%s",
|
||||
operation,
|
||||
max(1, int(remaining)),
|
||||
budget,
|
||||
chat_id,
|
||||
)
|
||||
self._is_chat_rate_limited(chat_id, operation=operation)
|
||||
return False, budget
|
||||
if waits >= TELEGRAM_RATE_LIMIT_MAX_RETRIES:
|
||||
logger.warning(
|
||||
"Telegram%s持续处于429冷却,已达单次等待重试上限(剩余约%s秒),放弃补发:chat_id=%s",
|
||||
operation,
|
||||
max(1, int(remaining)),
|
||||
chat_id,
|
||||
)
|
||||
self._is_chat_rate_limited(chat_id, operation=operation)
|
||||
return False, budget
|
||||
|
||||
logger.info(
|
||||
"Telegram%s处于429冷却,等待%.1f秒后继续投递:chat_id=%s",
|
||||
operation,
|
||||
remaining,
|
||||
chat_id,
|
||||
)
|
||||
time.sleep(remaining)
|
||||
budget = max(0.0, budget - remaining)
|
||||
waits += 1
|
||||
if had_bot and self._bot is None:
|
||||
return False, budget
|
||||
|
||||
def _reserve_edit(
|
||||
self,
|
||||
chat_id: Union[str, int],
|
||||
message_id: Union[str, int],
|
||||
wait_for_interval: bool = False,
|
||||
) -> bool:
|
||||
rate_limit_budget: float = 0.0,
|
||||
) -> tuple[bool, float]:
|
||||
"""
|
||||
原子预留一次消息编辑,执行聊天冷却和消息级最小间隔检查。
|
||||
原子预留一次消息编辑,执行聊天 429 冷却和消息级最小间隔检查。
|
||||
|
||||
:param chat_id: 编辑目标会话标识
|
||||
:param message_id: 编辑目标消息标识
|
||||
:param wait_for_interval: 是否等待一次消息级间隔,最长两秒;聊天 429 冷却不会等待
|
||||
:return: 成功预留编辑时返回 True,否则返回 False
|
||||
:param wait_for_interval: 是否等待消息级间隔,最长两秒;收尾编辑同时在预算内等待 429 冷却
|
||||
:param rate_limit_budget: 本次编辑允许等待 429 冷却的剩余秒数,小于等于 0 时不等待
|
||||
:return: 二元组 ``(成功预留状态, 剩余冷却等待预算秒数)``
|
||||
"""
|
||||
self._ensure_edit_state()
|
||||
if self._is_chat_rate_limited(chat_id):
|
||||
return False
|
||||
budget = max(0.0, float(rate_limit_budget)) if wait_for_interval else 0.0
|
||||
allowed, budget = self._wait_for_rate_limit(
|
||||
chat_id,
|
||||
operation="编辑",
|
||||
remaining_budget=budget,
|
||||
)
|
||||
if not allowed:
|
||||
return False, budget
|
||||
key = (str(chat_id), int(message_id))
|
||||
if wait_for_interval:
|
||||
with self._edit_state_lock:
|
||||
@@ -432,14 +542,19 @@ class Telegram:
|
||||
if remaining > 0:
|
||||
# 调用方在线程池内收尾;不占用事件循环,也不持锁等待或无限追赶并发编辑。
|
||||
time.sleep(min(remaining, TELEGRAM_EDIT_MIN_INTERVAL_SECONDS))
|
||||
if self._is_chat_rate_limited(chat_id):
|
||||
return False
|
||||
allowed, budget = self._wait_for_rate_limit(
|
||||
chat_id,
|
||||
operation="编辑",
|
||||
remaining_budget=budget,
|
||||
)
|
||||
if not allowed:
|
||||
return False, budget
|
||||
now = time.monotonic()
|
||||
with self._edit_state_lock:
|
||||
if self._edit_next_allowed.get(key, 0.0) > now:
|
||||
return False
|
||||
return False, budget
|
||||
self._edit_next_allowed[key] = now + TELEGRAM_EDIT_MIN_INTERVAL_SECONDS
|
||||
return True
|
||||
return True, budget
|
||||
|
||||
def _mark_edit_succeeded(
|
||||
self, chat_id: Union[str, int], message_id: Union[str, int]
|
||||
@@ -1015,6 +1130,7 @@ class Telegram:
|
||||
parse_mode: Optional[str] = None,
|
||||
rich_message: Optional[str] = None,
|
||||
private_delivery: bool = False,
|
||||
wait_for_rate_limit: bool = True,
|
||||
) -> Optional[JsonDict]:
|
||||
"""
|
||||
发送文本、图文或富文本,并兼容原消息编辑和强制回复。
|
||||
@@ -1033,7 +1149,8 @@ class Telegram:
|
||||
:param parse_mode: 消息格式,默认 MarkdownV2;支持 HTML 和 plain 纯文本
|
||||
:param rich_message: 完整富文本正文;非空时替代普通图文内容
|
||||
:param private_delivery: 有用户标识时是否绕过最近会话映射直接投递私聊
|
||||
:return: 含 success 和消息引用的结果;配置缺失返回 None,限流、空内容或发送失败返回 success 为 False 的字典
|
||||
:param wait_for_rate_limit: 命中 429 冷却时是否在上限内等待并补发未送达内容,默认 True
|
||||
:return: 含 success 和消息引用的结果;配置缺失返回 None,限流超上限、空内容或发送失败返回 success 为 False 的字典
|
||||
"""
|
||||
if not self._telegram_token or not self._telegram_chat_id:
|
||||
return None
|
||||
@@ -1045,7 +1162,13 @@ class Telegram:
|
||||
original_chat_id,
|
||||
private_delivery=private_delivery,
|
||||
)
|
||||
if self._is_chat_rate_limited(chat_id, operation="发送"):
|
||||
wait_budget = TELEGRAM_RATE_LIMIT_MAX_WAIT_SECONDS if wait_for_rate_limit else 0.0
|
||||
allowed, wait_budget = self._wait_for_rate_limit(
|
||||
chat_id,
|
||||
operation="发送",
|
||||
remaining_budget=wait_budget,
|
||||
)
|
||||
if not allowed:
|
||||
self._stop_typing_if_needed(chat_id, stop_typing)
|
||||
return {"success": False}
|
||||
if not title and not text and not rich_message:
|
||||
@@ -1084,6 +1207,8 @@ class Telegram:
|
||||
stop_typing=stop_typing,
|
||||
rich_message=rich_message,
|
||||
reply_markup=reply_markup,
|
||||
wait_for_rate_limit=wait_for_rate_limit,
|
||||
rate_limit_budget=wait_budget,
|
||||
)
|
||||
|
||||
if original_message_id and original_chat_id:
|
||||
@@ -1096,18 +1221,22 @@ class Telegram:
|
||||
disable_web_page_preview=disable_web_page_preview,
|
||||
parse_mode=parse_mode,
|
||||
reply_to_message_id=original_message_id,
|
||||
wait_for_rate_limit=wait_for_rate_limit,
|
||||
rate_limit_budget=wait_budget,
|
||||
)
|
||||
self._remember_sent_message(sent, original_chat_id)
|
||||
self._stop_typing_if_needed(chat_id, stop_typing)
|
||||
return self._sent_result(sent, chat_id)
|
||||
result = self.__edit_message(
|
||||
original_chat_id,
|
||||
original_message_id,
|
||||
caption,
|
||||
buttons,
|
||||
image,
|
||||
result = self._edit_with_rate_limit(
|
||||
chat_id=original_chat_id,
|
||||
message_id=original_message_id,
|
||||
text=caption,
|
||||
buttons=buttons,
|
||||
image=image,
|
||||
disable_web_page_preview=disable_web_page_preview,
|
||||
parse_mode=parse_mode,
|
||||
wait_for_rate_limit=wait_for_rate_limit,
|
||||
rate_limit_budget=wait_budget,
|
||||
)
|
||||
self._stop_typing_if_needed(chat_id, stop_typing)
|
||||
return {
|
||||
@@ -1123,6 +1252,8 @@ class Telegram:
|
||||
reply_markup=reply_markup,
|
||||
disable_web_page_preview=disable_web_page_preview,
|
||||
parse_mode=parse_mode,
|
||||
wait_for_rate_limit=wait_for_rate_limit,
|
||||
rate_limit_budget=wait_budget,
|
||||
)
|
||||
self._remember_sent_message(sent, chat_id)
|
||||
self._stop_typing_if_needed(chat_id, stop_typing)
|
||||
@@ -1133,6 +1264,45 @@ class Telegram:
|
||||
self._stop_typing_if_needed(chat_id, stop_typing)
|
||||
return {"success": False}
|
||||
|
||||
def _edit_with_rate_limit(
|
||||
self,
|
||||
*,
|
||||
chat_id: str,
|
||||
message_id: int,
|
||||
text: str,
|
||||
buttons: Optional[List[List[dict[str, Any]]]] = None,
|
||||
image: Optional[str] = None,
|
||||
disable_web_page_preview: Optional[bool] = None,
|
||||
parse_mode: Optional[str] = None,
|
||||
wait_for_rate_limit: bool = True,
|
||||
rate_limit_budget: float = 0.0,
|
||||
) -> Optional[bool]:
|
||||
"""
|
||||
编辑交互消息;在允许预算内遇到 429 时等待冷却后重试,非限流错误不重试。
|
||||
"""
|
||||
retries_left = TELEGRAM_RATE_LIMIT_MAX_RETRIES if wait_for_rate_limit else 0
|
||||
budget = rate_limit_budget if wait_for_rate_limit else 0.0
|
||||
while True:
|
||||
result = self.__edit_message(
|
||||
chat_id,
|
||||
message_id,
|
||||
text,
|
||||
buttons,
|
||||
image,
|
||||
disable_web_page_preview=disable_web_page_preview,
|
||||
parse_mode=parse_mode,
|
||||
)
|
||||
if result or retries_left <= 0 or not self._has_active_rate_limit(chat_id):
|
||||
return result
|
||||
allowed, budget = self._wait_for_rate_limit(
|
||||
chat_id,
|
||||
operation="编辑",
|
||||
remaining_budget=budget,
|
||||
)
|
||||
if not allowed:
|
||||
return False
|
||||
retries_left -= 1
|
||||
|
||||
def _send_rich_message(
|
||||
self,
|
||||
*,
|
||||
@@ -1145,9 +1315,11 @@ class Telegram:
|
||||
stop_typing: bool,
|
||||
rich_message: str,
|
||||
reply_markup: Optional[JsonDict],
|
||||
wait_for_rate_limit: bool = True,
|
||||
rate_limit_budget: float = 0.0,
|
||||
) -> JsonDict:
|
||||
"""
|
||||
发送或编辑 Rich Message,并在限流时隔离后续输出请求。
|
||||
发送或编辑 Rich Message;限流时在预算内仅补发未送达分块,非限流错误降级纯文本。
|
||||
"""
|
||||
if original_message_id and original_chat_id and not force_reply:
|
||||
result = self.edit_msg(
|
||||
@@ -1157,6 +1329,7 @@ class Telegram:
|
||||
rich_message=rich_message,
|
||||
buttons=buttons,
|
||||
stop_typing=stop_typing,
|
||||
wait_for_interval=wait_for_rate_limit,
|
||||
)
|
||||
return {
|
||||
"success": bool(result),
|
||||
@@ -1165,18 +1338,41 @@ class Telegram:
|
||||
}
|
||||
|
||||
target_chat_id = original_chat_id if force_reply and original_chat_id else chat_id
|
||||
try:
|
||||
sent = self.__send_rich_message(
|
||||
chat_id=target_chat_id,
|
||||
rich_message=rich_message,
|
||||
reply_markup=reply_markup,
|
||||
reply_to_message_id=original_message_id if force_reply else None,
|
||||
)
|
||||
except Exception as rich_err:
|
||||
if self._is_rate_limit_error(rich_err):
|
||||
self._mark_rate_limit(target_chat_id, rich_err, operation="发送")
|
||||
sent = None
|
||||
else:
|
||||
sent_idx: set[int] = set()
|
||||
retries_left = TELEGRAM_RATE_LIMIT_MAX_RETRIES if wait_for_rate_limit else 0
|
||||
budget = rate_limit_budget if wait_for_rate_limit else 0.0
|
||||
sent = None
|
||||
while True:
|
||||
try:
|
||||
sent = self.__send_rich_message(
|
||||
chat_id=target_chat_id,
|
||||
rich_message=rich_message,
|
||||
reply_markup=reply_markup,
|
||||
reply_to_message_id=original_message_id if force_reply else None,
|
||||
sent_idx=sent_idx,
|
||||
)
|
||||
break
|
||||
except Exception as rich_err:
|
||||
if self._is_rate_limit_error(rich_err):
|
||||
self._mark_rate_limit(target_chat_id, rich_err, operation="发送")
|
||||
if retries_left > 0:
|
||||
allowed, budget = self._wait_for_rate_limit(
|
||||
target_chat_id,
|
||||
operation="发送",
|
||||
remaining_budget=budget,
|
||||
)
|
||||
if allowed:
|
||||
retries_left -= 1
|
||||
continue
|
||||
sent = None
|
||||
break
|
||||
if sent_idx:
|
||||
logger.warning(
|
||||
"Telegram Rich Message 后续分块发送失败,避免重复发送已送达分块:%s",
|
||||
rich_err,
|
||||
)
|
||||
sent = None
|
||||
break
|
||||
# Rich Message 发送失败不再等同于通知丢失,降级为纯文本重发一次。
|
||||
logger.warning(
|
||||
f"Telegram Rich Message 发送失败,降级为纯文本:{rich_err}"
|
||||
@@ -1185,7 +1381,10 @@ class Telegram:
|
||||
chat_id=target_chat_id,
|
||||
rich_message=rich_message,
|
||||
reply_markup=reply_markup,
|
||||
remaining_budget=budget if wait_for_rate_limit else 0.0,
|
||||
retries_left=retries_left,
|
||||
)
|
||||
break
|
||||
self._remember_sent_message(sent, target_chat_id)
|
||||
self._stop_typing_if_needed(chat_id, stop_typing)
|
||||
return self._sent_result(sent, chat_id)
|
||||
@@ -1269,7 +1468,7 @@ class Telegram:
|
||||
def send_image(self, image: str, title: Optional[str] = None, text: Optional[str] = None,
|
||||
userid: Optional[str] = None, original_chat_id: Optional[str] = None,
|
||||
parse_mode: Optional[str] = None, buttons: Optional[List[List[dict[str, Any]]]] = None,
|
||||
private_delivery: bool = False) -> Optional[JsonDict]:
|
||||
private_delivery: bool = False, wait_for_rate_limit: bool = True) -> Optional[JsonDict]:
|
||||
"""
|
||||
上传统一来源的完整原图,复用长正文拆分并保留会话、话题、按钮和私聊约束。
|
||||
|
||||
@@ -1281,12 +1480,19 @@ class Telegram:
|
||||
:param parse_mode: 说明文字格式,沿用普通通知约定
|
||||
:param buttons: 图片下方的统一交互按钮
|
||||
:param private_delivery: 有用户标识时是否必须发送私聊
|
||||
:param wait_for_rate_limit: 命中 429 冷却时是否在上限内等待并补发,默认 True
|
||||
:return: 图片发送结果;读取失败时 success 为 False
|
||||
"""
|
||||
if not self._telegram_token or not self._telegram_chat_id:
|
||||
return None
|
||||
chat_id = self._determine_target_chat_id(userid, original_chat_id, private_delivery=private_delivery)
|
||||
if self._is_chat_rate_limited(chat_id, operation="发送"):
|
||||
wait_budget = TELEGRAM_RATE_LIMIT_MAX_WAIT_SECONDS if wait_for_rate_limit else 0.0
|
||||
allowed, wait_budget = self._wait_for_rate_limit(
|
||||
chat_id,
|
||||
operation="发送",
|
||||
remaining_budget=wait_budget,
|
||||
)
|
||||
if not allowed:
|
||||
return {"success": False}
|
||||
loaded = load_image(image)
|
||||
if loaded is None:
|
||||
@@ -1297,6 +1503,8 @@ class Telegram:
|
||||
sent = self.__send_request(
|
||||
userid=chat_id, image=loaded[0], caption=caption, parse_mode=mode,
|
||||
reply_markup=self._create_inline_keyboard(buttons) if buttons else None,
|
||||
wait_for_rate_limit=wait_for_rate_limit,
|
||||
rate_limit_budget=wait_budget,
|
||||
)
|
||||
self._remember_sent_message(sent, chat_id)
|
||||
return self._sent_result(sent, chat_id)
|
||||
@@ -1660,41 +1868,55 @@ class Telegram:
|
||||
return False
|
||||
|
||||
def delete_msg(
|
||||
self, message_id: int, chat_id: Optional[int] = None
|
||||
self,
|
||||
message_id: int,
|
||||
chat_id: Optional[int] = None,
|
||||
wait_for_rate_limit: bool = True,
|
||||
) -> Optional[bool]:
|
||||
"""
|
||||
删除指定会话或默认会话中的消息。
|
||||
|
||||
:param message_id: 原消息标识
|
||||
:param chat_id: 目标会话;为空时使用默认会话
|
||||
:param wait_for_rate_limit: 处于 429 冷却时是否在上限内等待后删除,默认 True
|
||||
:return: 删除成功返回 True,失败返回 False;配置缺失返回 None
|
||||
"""
|
||||
if not self._telegram_token or not self._telegram_chat_id:
|
||||
return None
|
||||
|
||||
target_chat_id: Union[str, int]
|
||||
try:
|
||||
if chat_id:
|
||||
target_chat_id = chat_id
|
||||
else:
|
||||
target_chat_id = self._telegram_chat_id
|
||||
|
||||
result = self._api.delete_message(
|
||||
chat_id=target_chat_id, message_id=int(message_id)
|
||||
target_chat_id: Union[str, int] = chat_id if chat_id else self._telegram_chat_id
|
||||
retries_left = TELEGRAM_RATE_LIMIT_MAX_RETRIES if wait_for_rate_limit else 0
|
||||
budget = TELEGRAM_RATE_LIMIT_MAX_WAIT_SECONDS if wait_for_rate_limit else 0.0
|
||||
while True:
|
||||
allowed, budget = self._wait_for_rate_limit(
|
||||
target_chat_id,
|
||||
operation="删除",
|
||||
remaining_budget=budget,
|
||||
)
|
||||
if result:
|
||||
logger.info(
|
||||
f"成功删除Telegram消息: chat_id={target_chat_id}, message_id={message_id}"
|
||||
if not allowed:
|
||||
return False
|
||||
try:
|
||||
result = self._api.delete_message(
|
||||
chat_id=target_chat_id, message_id=int(message_id)
|
||||
)
|
||||
return True
|
||||
else:
|
||||
if result:
|
||||
logger.info(
|
||||
f"成功删除Telegram消息: chat_id={target_chat_id}, message_id={message_id}"
|
||||
)
|
||||
return True
|
||||
logger.error(
|
||||
f"删除Telegram消息失败: chat_id={target_chat_id}, message_id={message_id}"
|
||||
)
|
||||
return False
|
||||
except Exception as e:
|
||||
logger.error(f"删除Telegram消息异常: {str(e)}")
|
||||
return False
|
||||
except Exception as e:
|
||||
if self._is_rate_limit_error(e):
|
||||
self._mark_rate_limit(target_chat_id, e, operation="删除")
|
||||
if retries_left > 0:
|
||||
retries_left -= 1
|
||||
continue
|
||||
return False
|
||||
logger.error(f"删除Telegram消息异常: {str(e)}")
|
||||
return False
|
||||
|
||||
def edit_msg(
|
||||
self,
|
||||
@@ -1711,6 +1933,10 @@ class Telegram:
|
||||
"""
|
||||
限频更新原消息,富文本失败时尝试纯文本回退。
|
||||
|
||||
中间进度编辑(``wait_for_interval=False``)在 429 冷却或最小间隔内立即跳过;
|
||||
收尾编辑(``wait_for_interval=True``)在等待预算内等待 429 冷却与消息间隔后补发,
|
||||
超预算时直接返回 False,不无界阻塞调用方。
|
||||
|
||||
:param chat_id: 原会话标识
|
||||
:param message_id: 原消息标识
|
||||
:param text: 完整的新正文
|
||||
@@ -1719,64 +1945,56 @@ class Telegram:
|
||||
:param stop_typing: 是否在操作收尾时请求停止输入状态,默认 False
|
||||
:param parse_mode: 消息格式,默认 MarkdownV2;支持 HTML 和 plain 纯文本
|
||||
:param rich_message: 可选富文本正文;非空时覆盖普通标题和正文
|
||||
:param wait_for_interval: 是否等待消息级编辑间隔后再发送;429 冷却不会等待
|
||||
:return: 更新成功或内容未变化返回 True;限流、空内容或失败返回 False;客户端缺失返回 None
|
||||
:param wait_for_interval: 是否作为收尾编辑等待消息级间隔及有上限的 429 冷却
|
||||
:return: 更新成功或内容未变化返回 True;限流超预算、空内容或失败返回 False;客户端缺失返回 None
|
||||
"""
|
||||
if not self._bot:
|
||||
return None
|
||||
|
||||
if not self._reserve_edit(chat_id, message_id, wait_for_interval=wait_for_interval):
|
||||
return False
|
||||
|
||||
parse_mode = self._normalize_parse_mode(parse_mode)
|
||||
try:
|
||||
if rich_message:
|
||||
reply_markup = (
|
||||
self._create_inline_keyboard(buttons) if buttons else None
|
||||
)
|
||||
result = self.__edit_rich_message(
|
||||
chat_id=chat_id,
|
||||
message_id=message_id,
|
||||
rich_message=rich_message,
|
||||
reply_markup=reply_markup,
|
||||
)
|
||||
if result:
|
||||
self._mark_edit_succeeded(chat_id, message_id)
|
||||
return True
|
||||
if self._is_chat_rate_limited(chat_id):
|
||||
return False
|
||||
# Rich Message 编辑失败时降级为纯文本覆盖,避免回复停留在旧内容。
|
||||
logger.warning(
|
||||
f"Telegram Rich Message 编辑失败,降级为纯文本:chat_id={chat_id}"
|
||||
)
|
||||
fallback_result = self.__edit_plain_fallback(
|
||||
chat_id=str(chat_id),
|
||||
message_id=int(message_id),
|
||||
rich_message=rich_message,
|
||||
reply_markup=reply_markup,
|
||||
)
|
||||
if fallback_result:
|
||||
self._mark_edit_succeeded(chat_id, message_id)
|
||||
return fallback_result
|
||||
|
||||
budget = TELEGRAM_RATE_LIMIT_MAX_WAIT_SECONDS if wait_for_interval else 0.0
|
||||
retries_left = TELEGRAM_RATE_LIMIT_MAX_RETRIES if wait_for_interval else 0
|
||||
use_plain_fallback = False
|
||||
reply_markup = self._create_inline_keyboard(buttons) if (rich_message and buttons) else None
|
||||
caption = ""
|
||||
if not rich_message:
|
||||
if title:
|
||||
bold_title = self._format_title(title, parse_mode)
|
||||
caption = f"{bold_title}\n{text}" if text else (bold_title or "")
|
||||
elif text:
|
||||
caption = text
|
||||
else:
|
||||
self._stop_typing_if_needed(chat_id, stop_typing)
|
||||
return False
|
||||
|
||||
edit_result = self.__edit_message(
|
||||
chat_id=str(chat_id),
|
||||
message_id=int(message_id),
|
||||
text=caption,
|
||||
buttons=buttons,
|
||||
parse_mode=parse_mode,
|
||||
)
|
||||
if edit_result:
|
||||
self._mark_edit_succeeded(chat_id, message_id)
|
||||
return edit_result
|
||||
try:
|
||||
while True:
|
||||
reserved, budget = self._reserve_edit(
|
||||
chat_id,
|
||||
message_id,
|
||||
wait_for_interval=wait_for_interval,
|
||||
rate_limit_budget=budget,
|
||||
)
|
||||
if not reserved:
|
||||
return False
|
||||
|
||||
succeeded, rate_limited, use_plain_fallback = self._attempt_edit_once(
|
||||
chat_id=chat_id,
|
||||
message_id=message_id,
|
||||
caption=caption,
|
||||
buttons=buttons,
|
||||
parse_mode=parse_mode,
|
||||
rich_message=rich_message,
|
||||
reply_markup=reply_markup,
|
||||
use_plain_fallback=use_plain_fallback,
|
||||
)
|
||||
if succeeded:
|
||||
self._mark_edit_succeeded(chat_id, message_id)
|
||||
return True
|
||||
if rate_limited and wait_for_interval and retries_left > 0:
|
||||
retries_left -= 1
|
||||
continue
|
||||
return False
|
||||
except Exception as e:
|
||||
if self._is_rate_limit_error(e):
|
||||
self._mark_rate_limit(chat_id, e)
|
||||
@@ -1785,6 +2003,59 @@ class Telegram:
|
||||
finally:
|
||||
self._stop_typing_if_needed(chat_id, stop_typing)
|
||||
|
||||
def _attempt_edit_once(
|
||||
self,
|
||||
*,
|
||||
chat_id: Union[str, int],
|
||||
message_id: Union[str, int],
|
||||
caption: str,
|
||||
buttons: Optional[List[List[dict[str, Any]]]],
|
||||
parse_mode: str,
|
||||
rich_message: Optional[str],
|
||||
reply_markup: Optional[JsonDict],
|
||||
use_plain_fallback: bool,
|
||||
) -> tuple[bool, bool, bool]:
|
||||
"""
|
||||
执行单次编辑尝试,返回 ``(是否成功, 是否命中429, 下次是否仅走纯文本降级)``。
|
||||
"""
|
||||
if rich_message:
|
||||
if not use_plain_fallback:
|
||||
result = self.__edit_rich_message(
|
||||
chat_id=chat_id,
|
||||
message_id=message_id,
|
||||
rich_message=rich_message,
|
||||
reply_markup=reply_markup,
|
||||
)
|
||||
if result:
|
||||
return True, False, False
|
||||
if self._has_active_rate_limit(chat_id):
|
||||
return False, True, False
|
||||
# Rich Message 非限流编辑失败时降级为纯文本覆盖,避免回复停留在旧内容。
|
||||
logger.warning(
|
||||
f"Telegram Rich Message 编辑失败,降级为纯文本:chat_id={chat_id}"
|
||||
)
|
||||
use_plain_fallback = True
|
||||
fallback_result = self.__edit_plain_fallback(
|
||||
chat_id=str(chat_id),
|
||||
message_id=int(message_id),
|
||||
rich_message=rich_message,
|
||||
reply_markup=reply_markup,
|
||||
)
|
||||
if fallback_result:
|
||||
return True, False, True
|
||||
return False, self._has_active_rate_limit(chat_id), True
|
||||
|
||||
edit_result = self.__edit_message(
|
||||
chat_id=str(chat_id),
|
||||
message_id=int(message_id),
|
||||
text=caption,
|
||||
buttons=buttons,
|
||||
parse_mode=parse_mode,
|
||||
)
|
||||
if edit_result:
|
||||
return True, False, False
|
||||
return False, self._has_active_rate_limit(chat_id), False
|
||||
|
||||
@staticmethod
|
||||
def __is_no_text_edit_error(err: Exception) -> bool:
|
||||
"""
|
||||
@@ -2039,19 +2310,22 @@ class Telegram:
|
||||
rich_message: str,
|
||||
reply_markup: Optional[JsonDict] = None,
|
||||
reply_to_message_id: Optional[Union[str, int]] = None,
|
||||
sent_idx: Optional[set[int]] = None,
|
||||
) -> Any:
|
||||
"""
|
||||
发送 Telegram Rich Message,超限内容自动拆分为多条。
|
||||
发送 Telegram Rich Message,超限内容自动拆分为多条并跳过已送达分块。
|
||||
|
||||
:param chat_id: 目标聊天 ID
|
||||
:param rich_message: 完整的 Rich Markdown 正文
|
||||
:param reply_markup: 首条消息携带的键盘
|
||||
:param reply_to_message_id: 首条消息回复的原消息 ID
|
||||
:param sent_idx: 已送达分块下标集合,会原地更新用于冷却后补发去重
|
||||
:return: 最后一条已发送的 Telegram 消息
|
||||
:raises NonRetryableTelegramError: Telegram 以 400 拒绝该内容,不做退避重试
|
||||
:raises NonRetryableTelegramError: Telegram 以 400 或 429 拒绝该内容,不做通用退避重试
|
||||
:raises RetryException: 网络异常或 5xx,可重试
|
||||
"""
|
||||
chunks = self._build_rich_message_chunks(rich_message)
|
||||
delivered = sent_idx if sent_idx is not None else set()
|
||||
reply_parameters = (
|
||||
{"message_id": int(reply_to_message_id)}
|
||||
if reply_to_message_id is not None
|
||||
@@ -2060,6 +2334,8 @@ class Telegram:
|
||||
sent = None
|
||||
try:
|
||||
for index, chunk in enumerate(chunks):
|
||||
if index in delivered:
|
||||
continue
|
||||
sent = self._api.send_rich_message(
|
||||
chat_id=chat_id,
|
||||
rich_message=chunk,
|
||||
@@ -2067,6 +2343,7 @@ class Telegram:
|
||||
reply_parameters=reply_parameters if index == 0 else None,
|
||||
**self._topic_kwargs(chat_id),
|
||||
)
|
||||
delivered.add(index)
|
||||
return sent
|
||||
except Exception as err:
|
||||
# 保留 Telegram 返回的原始描述(错误码、description),否则日志只剩
|
||||
@@ -2074,6 +2351,9 @@ class Telegram:
|
||||
if _is_non_retryable_api_error(err):
|
||||
if self._is_rate_limit_error(err):
|
||||
self._mark_rate_limit(chat_id, err, operation="发送")
|
||||
raise _TelegramRateLimitError(
|
||||
f"发送 Telegram Rich Message 被限流:{err}"
|
||||
) from err
|
||||
raise NonRetryableTelegramError(
|
||||
f"发送 Telegram Rich Message 失败:{err}"
|
||||
) from err
|
||||
@@ -2086,6 +2366,8 @@ class Telegram:
|
||||
chat_id: Union[str, int],
|
||||
rich_message: str,
|
||||
reply_markup: Optional[JsonDict] = None,
|
||||
remaining_budget: float = 0.0,
|
||||
retries_left: int = 0,
|
||||
) -> Any:
|
||||
"""
|
||||
Rich Message 发送失败后的降级出口,用纯文本重发同一条内容。
|
||||
@@ -2100,25 +2382,39 @@ class Telegram:
|
||||
:param chat_id: 目标聊天 ID
|
||||
:param rich_message: 原始 Rich Markdown 正文
|
||||
:param reply_markup: 内联键盘
|
||||
:param remaining_budget: 降级路径命中 429 时允许继续等待的预算秒数
|
||||
:param retries_left: 降级路径允许因 429 重试的剩余次数
|
||||
:return: 降级发送的结果,失败返回 None
|
||||
"""
|
||||
# ``_topic_kwargs`` 只可能产出 message_thread_id,显式传参而不是 ** 展开:
|
||||
# ** 展开到 send_message 会被 mypy 匹配到第 5 个形参(disable_web_page_preview,
|
||||
# Optional[bool]),把 dict[str, int] 判为类型不兼容。
|
||||
topic_kwargs = self._topic_kwargs(chat_id)
|
||||
try:
|
||||
return self._api.send_message(
|
||||
chat_id=chat_id,
|
||||
text=rich_message,
|
||||
parse_mode=TELEGRAM_PARSE_MODE_PLAIN,
|
||||
reply_markup=reply_markup,
|
||||
message_thread_id=topic_kwargs.get("message_thread_id"),
|
||||
)
|
||||
except Exception as err:
|
||||
if self._is_rate_limit_error(err):
|
||||
self._mark_rate_limit(chat_id, err, operation="发送")
|
||||
logger.error(f"Telegram Rich Message 降级为纯文本发送仍失败:{err}")
|
||||
return None
|
||||
budget = max(0.0, float(remaining_budget))
|
||||
attempts_left = max(0, int(retries_left))
|
||||
while True:
|
||||
try:
|
||||
return self._api.send_message(
|
||||
chat_id=chat_id,
|
||||
text=rich_message,
|
||||
parse_mode=TELEGRAM_PARSE_MODE_PLAIN,
|
||||
reply_markup=reply_markup,
|
||||
message_thread_id=topic_kwargs.get("message_thread_id"),
|
||||
)
|
||||
except Exception as err:
|
||||
if self._is_rate_limit_error(err):
|
||||
self._mark_rate_limit(chat_id, err, operation="发送")
|
||||
if attempts_left > 0:
|
||||
allowed, budget = self._wait_for_rate_limit(
|
||||
chat_id,
|
||||
operation="发送",
|
||||
remaining_budget=budget,
|
||||
)
|
||||
if allowed:
|
||||
attempts_left -= 1
|
||||
continue
|
||||
logger.error(f"Telegram Rich Message 降级为纯文本发送仍失败:{err}")
|
||||
return None
|
||||
|
||||
def __send_request(
|
||||
self,
|
||||
@@ -2129,6 +2425,8 @@ class Telegram:
|
||||
disable_web_page_preview: Optional[bool] = None,
|
||||
parse_mode: Optional[str] = None,
|
||||
reply_to_message_id: Optional[int] = None,
|
||||
wait_for_rate_limit: bool = False,
|
||||
rate_limit_budget: float = 0.0,
|
||||
) -> Optional[JsonDict]:
|
||||
"""
|
||||
按内容长度和媒体类型拆分并发送普通消息。
|
||||
@@ -2140,11 +2438,14 @@ class Telegram:
|
||||
:param disable_web_page_preview: 是否禁用文本链接预览
|
||||
:param parse_mode: 消息格式,默认 MarkdownV2;支持 HTML 和 plain 纯文本
|
||||
:param reply_to_message_id: 发送消息回复的原消息标识
|
||||
:param wait_for_rate_limit: 命中 429 时是否在预算内等待冷却并补发剩余分块
|
||||
:param rate_limit_budget: 允许等待 429 冷却的剩余秒数
|
||||
:return: 最后一条发送的 Bot API 消息;失败返回 None,已发送的分块不会撤回
|
||||
"""
|
||||
parse_mode = self._normalize_parse_mode(parse_mode)
|
||||
target_chat_id = userid or self._telegram_chat_id or ""
|
||||
kwargs: Dict[str, Any] = {
|
||||
"chat_id": userid or self._telegram_chat_id,
|
||||
"chat_id": target_chat_id,
|
||||
"parse_mode": parse_mode,
|
||||
"reply_markup": reply_markup,
|
||||
}
|
||||
@@ -2153,34 +2454,56 @@ class Telegram:
|
||||
kwargs["reply_to_message_id"] = reply_to_message_id
|
||||
image_bytes = self.__process_image(image)
|
||||
|
||||
try:
|
||||
# 图片消息的标题长度限制为1024,文本消息为4096
|
||||
caption_limit = 1024 if image_bytes else 4096
|
||||
if len(caption) < caption_limit:
|
||||
ret = self.__send_short_message(image_bytes, caption,
|
||||
disable_web_page_preview=disable_web_page_preview,
|
||||
**kwargs)
|
||||
elif (
|
||||
self._is_plain_parse_mode(parse_mode)
|
||||
or self._is_html_parse_mode(parse_mode)
|
||||
):
|
||||
ret = self.__send_long_plain_message(
|
||||
image_bytes,
|
||||
caption,
|
||||
caption_limit,
|
||||
disable_web_page_preview=disable_web_page_preview,
|
||||
**kwargs,
|
||||
)
|
||||
else:
|
||||
sent_idx: set[int] = set()
|
||||
ret = self.__send_long_message(image_bytes, caption, sent_idx,
|
||||
disable_web_page_preview=disable_web_page_preview,
|
||||
**kwargs)
|
||||
|
||||
return ret
|
||||
except Exception as e:
|
||||
logger.error(f"发送Telegram消息失败: {e}")
|
||||
return None
|
||||
# 图片消息的标题长度限制为1024,文本消息为4096
|
||||
caption_limit = 1024 if image_bytes else 4096
|
||||
sent_idx: set[int] = set()
|
||||
retries_left = TELEGRAM_RATE_LIMIT_MAX_RETRIES if wait_for_rate_limit else 0
|
||||
budget = rate_limit_budget if wait_for_rate_limit else 0.0
|
||||
while True:
|
||||
try:
|
||||
if len(caption) < caption_limit:
|
||||
ret = self.__send_short_message(
|
||||
image_bytes,
|
||||
caption,
|
||||
disable_web_page_preview=disable_web_page_preview,
|
||||
**kwargs,
|
||||
)
|
||||
elif (
|
||||
self._is_plain_parse_mode(parse_mode)
|
||||
or self._is_html_parse_mode(parse_mode)
|
||||
):
|
||||
ret = self.__send_long_plain_message(
|
||||
image_bytes,
|
||||
caption,
|
||||
caption_limit,
|
||||
sent_idx=sent_idx,
|
||||
disable_web_page_preview=disable_web_page_preview,
|
||||
**kwargs,
|
||||
)
|
||||
else:
|
||||
ret = self.__send_long_message(
|
||||
image_bytes,
|
||||
caption,
|
||||
sent_idx,
|
||||
disable_web_page_preview=disable_web_page_preview,
|
||||
**kwargs,
|
||||
)
|
||||
return ret
|
||||
except _TelegramRateLimitError as e:
|
||||
if retries_left > 0:
|
||||
allowed, budget = self._wait_for_rate_limit(
|
||||
target_chat_id,
|
||||
operation="发送",
|
||||
remaining_budget=budget,
|
||||
)
|
||||
if allowed:
|
||||
retries_left -= 1
|
||||
continue
|
||||
logger.error(f"发送Telegram消息失败: {e}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error(f"发送Telegram消息失败: {e}")
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def __process_image(image_url: Optional[Union[str, bytes]]) -> Optional[bytes]:
|
||||
@@ -2221,7 +2544,7 @@ class Telegram:
|
||||
if self._is_rate_limit_error(err):
|
||||
chat_id = kwargs.get("chat_id") or self._telegram_chat_id or ""
|
||||
self._mark_rate_limit(chat_id, err, operation="发送")
|
||||
raise NonRetryableTelegramError(
|
||||
raise _TelegramRateLimitError(
|
||||
f"发送 Telegram {'图片' if image else '文本'}消息被限流:{err}"
|
||||
) from err
|
||||
raise RetryException(f"发送{'图片' if image else '文本'}消息失败:{err}") from err
|
||||
@@ -2271,18 +2594,20 @@ class Telegram:
|
||||
image: Optional[bytes],
|
||||
caption: str,
|
||||
caption_limit: int,
|
||||
sent_idx: Optional[set[int]] = None,
|
||||
disable_web_page_preview: Optional[bool] = None,
|
||||
**kwargs: Any,
|
||||
) -> Optional[JsonDict]:
|
||||
"""
|
||||
按可见长度拆分普通或HTML正文并发送各分块,HTML保持实体和标签完整。
|
||||
按可见长度拆分普通或HTML正文并发送未送达分块,HTML保持实体和标签完整。
|
||||
|
||||
键盘仅附在第一块。非限流异常由装饰器重试整个方法,已成功的分块可能再次发送;
|
||||
键盘仅附在第一块。已成功发送的分块会写入 ``sent_idx``,在重试或 429 冷却后补发时跳过;
|
||||
限流时记录会话冷却并停止立即重试。
|
||||
|
||||
:param image: 可选图片字节,仅用于第一块
|
||||
:param caption: 完整正文,HTML分块关闭并重新打开跨块标签
|
||||
:param caption_limit: 每块字符上限;图片说明通常为 1024,纯文本为 4096
|
||||
:param sent_idx: 已送达分块下标集合,会原地更新用于去重
|
||||
:param disable_web_page_preview: 是否关闭文本分块的链接预览
|
||||
:param kwargs: 目标会话、解析格式、话题、回复和键盘参数
|
||||
:return: 最后一条发送的 Bot API 消息
|
||||
@@ -2294,9 +2619,12 @@ class Telegram:
|
||||
chunks = splitter.finish()
|
||||
else:
|
||||
chunks = self._split_plain_text(caption, caption_limit)
|
||||
delivered = sent_idx if sent_idx is not None else set()
|
||||
ret = None
|
||||
try:
|
||||
for index, chunk in enumerate(chunks):
|
||||
if index in delivered:
|
||||
continue
|
||||
current_reply_markup = reply_markup if index == 0 else None
|
||||
if image and index == 0:
|
||||
ret = self.__send_photo_or_text(
|
||||
@@ -2306,6 +2634,7 @@ class Telegram:
|
||||
reply_markup=current_reply_markup,
|
||||
disable_web_page_preview=disable_web_page_preview,
|
||||
)
|
||||
delivered.add(index)
|
||||
continue
|
||||
msg_kwargs = dict(**kwargs)
|
||||
if disable_web_page_preview is not None:
|
||||
@@ -2315,12 +2644,13 @@ class Telegram:
|
||||
text=chunk,
|
||||
reply_markup=current_reply_markup,
|
||||
)
|
||||
delivered.add(index)
|
||||
return ret
|
||||
except Exception as err:
|
||||
if self._is_rate_limit_error(err):
|
||||
chat_id = kwargs.get("chat_id") or self._telegram_chat_id or ""
|
||||
self._mark_rate_limit(chat_id, err, operation="发送")
|
||||
raise NonRetryableTelegramError(
|
||||
raise _TelegramRateLimitError(
|
||||
f"发送 Telegram 长消息被限流:{err}"
|
||||
) from err
|
||||
raise RetryException("长消息发送失败") from err
|
||||
@@ -2396,7 +2726,7 @@ class Telegram:
|
||||
if self._is_rate_limit_error(e):
|
||||
chat_id = kwargs.get("chat_id") or self._telegram_chat_id or ""
|
||||
self._mark_rate_limit(chat_id, e, operation="发送")
|
||||
raise NonRetryableTelegramError(
|
||||
raise _TelegramRateLimitError(
|
||||
f"发送 Telegram 消息被限流:{e}"
|
||||
) from e
|
||||
try:
|
||||
|
||||
@@ -700,3 +700,22 @@ async def test_agent_fallback_does_not_repeat_answer_in_output_or_history(
|
||||
agent.send_agent_message.assert_awaited_once_with(fallback)
|
||||
assert agent._streamed_output == delivered_prefix + answer
|
||||
save_display.assert_awaited_once_with(delivered_prefix + answer)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stop_streaming_deletes_orphaned_thinking_placeholder(channel_stream) -> None:
|
||||
"""
|
||||
仅发送过思考占位且通过工具直接完成回复时,收尾应删除占位消息避免停留在思考中。
|
||||
"""
|
||||
handler, calls, messages, _ = channel_stream
|
||||
handler.thinking_started()
|
||||
await handler._flush_messages()
|
||||
assert messages == {"1": "🤔 思考中 · 已用时 0 秒"}
|
||||
|
||||
all_sent, final_text = await handler.stop_streaming()
|
||||
|
||||
assert all_sent is False
|
||||
assert final_text == ""
|
||||
assert [call[0] for call in calls] == ["send_direct_message", "delete_message"]
|
||||
assert calls[1][2]["message_id"] == "1"
|
||||
assert await handler.take() == ""
|
||||
|
||||
@@ -3,13 +3,19 @@ Agent Telegram Rich Message 契约测试。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app.agent.orchestrator import MoviePilotAgent
|
||||
from app.agent.policy.contracts import ExecutionOutcome
|
||||
from app.agent.prompt import prompt_manager
|
||||
from app.agent.tools.impl.send_message import SendMessageInput, SendMessageTool
|
||||
from app.agent.tools.result import inspect_tool_result
|
||||
from app.chain.agent import AgentChain
|
||||
from app.schemas.types import NotificationChannel
|
||||
from app.schemas.message import Message
|
||||
from app.schemas.types import MessageType, NotificationChannel
|
||||
|
||||
|
||||
def test_send_message_input_accepts_rich_message_only() -> None:
|
||||
@@ -90,3 +96,91 @@ def test_agent_direct_telegram_reply_uses_rich_message() -> None:
|
||||
|
||||
assert message.text == "# 结果\n\n- **完成**"
|
||||
assert message.rich_message == "# 结果\n\n- **完成**"
|
||||
|
||||
|
||||
def test_send_message_tool_reports_failed_when_channel_delivery_unconfirmed() -> None:
|
||||
"""
|
||||
交互渠道发送未确认时,send_message 必须返回失败状态且不得标记已回复。
|
||||
"""
|
||||
|
||||
async def _run():
|
||||
tool = SendMessageTool(session_id="session-1", user_id="10001")
|
||||
tool.set_message_attr(
|
||||
channel=NotificationChannel.Telegram.value,
|
||||
source="telegram-test",
|
||||
username="tester",
|
||||
)
|
||||
agent_context: dict[str, object] = {}
|
||||
tool.set_agent_context(agent_context=agent_context)
|
||||
with patch(
|
||||
"app.agent.tools.base.ToolChain.async_post_message",
|
||||
new_callable=AsyncMock,
|
||||
side_effect=RuntimeError("Telegram 通知发送未确认:Telegram"),
|
||||
) as async_post_message:
|
||||
result = await tool.run(rich_message="# 最终回复")
|
||||
return result, agent_context, async_post_message
|
||||
|
||||
result, agent_context, async_post_message = asyncio.run(_run())
|
||||
payload = json.loads(result)
|
||||
|
||||
assert async_post_message.await_args.kwargs == {"_strict_delivery": True}
|
||||
assert inspect_tool_result(result) is ExecutionOutcome.FAILED
|
||||
assert payload["success"] is False
|
||||
assert payload["execution_outcome"] == "failed"
|
||||
assert "Telegram 通知发送未确认" in payload["error"]
|
||||
assert agent_context.get("user_reply_sent") is None
|
||||
|
||||
|
||||
def test_async_post_message_strict_delivery_propagates_module_error() -> None:
|
||||
"""
|
||||
异步通知在严格投递模式下应透传模块发送未确认异常,普通模式仍隔离错误。
|
||||
"""
|
||||
chain = AgentChain()
|
||||
message = Message(
|
||||
channel=NotificationChannel.Telegram,
|
||||
source="telegram-test",
|
||||
mtype=MessageType.Other,
|
||||
userid="10001",
|
||||
text="最终正文",
|
||||
save_history=False,
|
||||
)
|
||||
|
||||
class _FailingTelegramModule:
|
||||
"""
|
||||
模拟发送未确认的 Telegram 通知模块。
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def get_priority() -> int:
|
||||
"""
|
||||
返回模块调度优先级。
|
||||
"""
|
||||
return 0
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
"""
|
||||
返回模块展示名称。
|
||||
"""
|
||||
return "Telegram"
|
||||
|
||||
@staticmethod
|
||||
def post_message(message: Message, **_kwargs: object) -> None:
|
||||
"""
|
||||
模拟 Telegram 模块未确认投递并抛错。
|
||||
"""
|
||||
del message
|
||||
raise RuntimeError("Telegram 通知发送未确认:Telegram")
|
||||
|
||||
with (
|
||||
patch.object(chain.eventmanager, "async_send_event", new_callable=AsyncMock),
|
||||
patch.object(
|
||||
chain._module_dispatcher._module_catalog,
|
||||
"get_running_modules",
|
||||
return_value=[_FailingTelegramModule()],
|
||||
),
|
||||
):
|
||||
with pytest.raises(RuntimeError, match="Telegram 通知发送未确认"):
|
||||
asyncio.run(chain.async_post_message(message, _strict_delivery=True))
|
||||
# 普通通知路径保持原有异常隔离语义,不影响其他后台通知调用方。
|
||||
asyncio.run(chain.async_post_message(message))
|
||||
|
||||
@@ -135,6 +135,85 @@ async def test_agent_final_edit_waits_during_telegram_edit_interval(
|
||||
assert "思考中" not in final_text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_agent_final_edit_recovers_after_telegram_429_cooldown(telegram, monkeypatch):
|
||||
"""
|
||||
进度编辑触发 429 冷却后,中间刷新跳过,收尾编辑应等待剩余冷却并覆盖思考中消息。
|
||||
"""
|
||||
now = [100.0]
|
||||
waits = []
|
||||
monkeypatch.setattr("app.modules.telegram.telegram.time.monotonic", lambda: now[0])
|
||||
|
||||
def advance(seconds):
|
||||
"""
|
||||
记录并推进 Telegram 429 冷却等待,保持用例离线。
|
||||
|
||||
:param seconds: 等待秒数
|
||||
"""
|
||||
waits.append(seconds)
|
||||
now[0] += seconds
|
||||
|
||||
monkeypatch.setattr("app.modules.telegram.telegram.time.sleep", advance)
|
||||
telegram.bot.send_rich_message.return_value = {
|
||||
"message_id": 101, "chat": {"id": "fake_chat_id"},
|
||||
}
|
||||
telegram.bot.edit_message_text.side_effect = [
|
||||
TelegramApiError("editMessageText", "Too Many Requests", 429, {"retry_after": 13}),
|
||||
{"message_id": 101, "chat": {"id": "fake_chat_id"}},
|
||||
]
|
||||
handler = StreamingHandler()
|
||||
handler._channel = NotificationChannel.Telegram.value
|
||||
handler._source = "bot"
|
||||
handler._streaming_enabled = True
|
||||
handler._original_message_id = "question"
|
||||
module = TelegramModule()
|
||||
module._channel = NotificationChannel.Telegram
|
||||
monkeypatch.setattr(module, "get_configs", lambda: {"bot": SimpleNamespace(name="bot")})
|
||||
monkeypatch.setattr(module, "get_instance", lambda _name: telegram)
|
||||
monkeypatch.setattr(module, "check_message", lambda *_args: True)
|
||||
monkeypatch.setattr(module, "get_notification_targets", lambda _message: None)
|
||||
|
||||
async def dispatch(func, *args, **kwargs):
|
||||
"""
|
||||
保留真实 Telegram 发送与编辑冷却逻辑,仅隔离模块调度边界。
|
||||
"""
|
||||
if func.__name__ == "send_direct_message":
|
||||
return module.send_direct_message(args[0])
|
||||
if func.__name__ == "edit_message":
|
||||
return module.edit_message(**kwargs)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr("app.agent.callback.run_in_threadpool", dispatch)
|
||||
handler.thinking_started()
|
||||
await handler._flush_messages()
|
||||
|
||||
now[0] += 2.0
|
||||
handler.record_tool_call("execute_command", tool_kwargs={"command": "inspect"})
|
||||
await handler._flush_messages()
|
||||
assert telegram.bot.edit_message_text.call_count == 1
|
||||
|
||||
# 冷却期内中间进度编辑直接跳过,不等待也不触碰 Bot API。
|
||||
now[0] += 3.0
|
||||
handler.record_tool_call("read_file", tool_kwargs={"file_path": "a.py"})
|
||||
await handler._flush_messages()
|
||||
assert telegram.bot.edit_message_text.call_count == 1
|
||||
assert waits == []
|
||||
|
||||
# 冷却结束前 4 秒收到最终答案,收尾编辑应等待剩余 4 秒并覆盖原消息。
|
||||
now[0] += 6.0
|
||||
handler.emit("任务已完成,这是最终结论。")
|
||||
all_sent, final_text = await handler.stop_streaming()
|
||||
|
||||
assert all_sent is True
|
||||
assert waits == [4.0]
|
||||
assert await handler.take() == ""
|
||||
assert telegram.bot.edit_message_text.call_count == 2
|
||||
rich_html = telegram.bot.edit_message_text.call_args.kwargs["rich_message"]["html"]
|
||||
assert "任务已完成,这是最终结论。" in rich_html
|
||||
assert "思考中" not in rich_html
|
||||
assert "任务已完成,这是最终结论。" in final_text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", [None, "", " ", 123, False])
|
||||
@pytest.mark.parametrize("callback_data", [None, "", 123, "history"])
|
||||
def test_inline_keyboard_filters_invalid_actions(url, callback_data):
|
||||
@@ -614,10 +693,10 @@ def test_photo_retry_stops_when_telegram_rejects_image(telegram, telegram_retry_
|
||||
@pytest.mark.parametrize("failures", [0, 1, 2])
|
||||
def test_photo_rate_limit_does_not_send_fallback_or_retry(telegram, telegram_retry_sleep, failures):
|
||||
"""
|
||||
429 必须尊重冷却期,不再用文本请求加重限流。
|
||||
超出等待上限的 429 必须尊重冷却期,不再等待、重试或用文本请求加重限流。
|
||||
"""
|
||||
rate_limit = TelegramApiError(
|
||||
"sendPhoto", "Too Many Requests", 429, {"retry_after": 17},
|
||||
"sendPhoto", "Too Many Requests", 429, {"retry_after": 120},
|
||||
)
|
||||
telegram.bot.send_photo.side_effect = [TelegramNetworkError("sendPhoto", "timeout")] * failures + [rate_limit]
|
||||
result = telegram.send_msg(title="通知", image="https://example.com/poster.jpg")
|
||||
|
||||
@@ -9,6 +9,7 @@ import pytest
|
||||
from app.modules.telegram.botapi import TelegramApiError, TelegramNetworkError
|
||||
from app.modules.telegram.telegram import (
|
||||
TELEGRAM_EDIT_MIN_INTERVAL_SECONDS,
|
||||
TELEGRAM_RATE_LIMIT_MAX_WAIT_SECONDS,
|
||||
NonRetryableTelegramError,
|
||||
RetryException,
|
||||
Telegram,
|
||||
@@ -186,17 +187,18 @@ class TestSendMsgFallsBackToPlainText:
|
||||
|
||||
assert result["success"] is False
|
||||
|
||||
def test_send_429_skips_fallback_and_retry(self):
|
||||
def test_send_429_over_cap_skips_fallback_and_retry(self):
|
||||
"""
|
||||
Rich 发送收到 429 时应立即返回失败,不再重试或发送纯文本。
|
||||
Rich 发送收到超出等待上限的 429 时应立即返回失败,不再等待、重试或降级纯文本。
|
||||
"""
|
||||
client = _make_client()
|
||||
over_cap = int(TELEGRAM_RATE_LIMIT_MAX_WAIT_SECONDS) + 30
|
||||
client._api.send_rich_message.side_effect = TelegramApiError(
|
||||
"sendRichMessage", "Too Many Requests: retry after 17", 429,
|
||||
{"retry_after": 17},
|
||||
"sendRichMessage", f"Too Many Requests: retry after {over_cap}", 429,
|
||||
{"retry_after": over_cap},
|
||||
)
|
||||
|
||||
with patch("time.sleep") as sleep_mock:
|
||||
with patch("app.modules.telegram.telegram.time.sleep") as sleep_mock:
|
||||
result = client.send_msg(title="结果", text="正文", rich_message="# 结果")
|
||||
|
||||
assert result["success"] is False
|
||||
@@ -204,23 +206,165 @@ class TestSendMsgFallsBackToPlainText:
|
||||
client._api.send_message.assert_not_called()
|
||||
sleep_mock.assert_not_called()
|
||||
|
||||
def test_plain_send_429_skips_retry(self):
|
||||
def test_plain_send_429_over_cap_skips_retry(self):
|
||||
"""
|
||||
普通发送收到 429 时也应隔离输出失败,不能阻塞 Agent。
|
||||
普通发送收到超出等待上限的 429 时应立即隔离失败,不无界阻塞 Agent。
|
||||
"""
|
||||
client = _make_client()
|
||||
over_cap = int(TELEGRAM_RATE_LIMIT_MAX_WAIT_SECONDS) + 30
|
||||
client._api.send_message.side_effect = TelegramApiError(
|
||||
"sendMessage", "Too Many Requests: retry after 17", 429,
|
||||
{"retry_after": 17},
|
||||
"sendMessage", f"Too Many Requests: retry after {over_cap}", 429,
|
||||
{"retry_after": over_cap},
|
||||
)
|
||||
|
||||
with patch("time.sleep") as sleep_mock:
|
||||
with patch("app.modules.telegram.telegram.time.sleep") as sleep_mock:
|
||||
result = client.send_msg(title="结果", text="正文")
|
||||
|
||||
assert result["success"] is False
|
||||
client._api.send_message.assert_called_once()
|
||||
sleep_mock.assert_not_called()
|
||||
|
||||
def test_send_msg_waits_for_existing_429_cooldown_within_cap(self, monkeypatch):
|
||||
"""
|
||||
已有 429 冷却剩余时间在上限内时,最终正文应等待冷却结束后补发成功。
|
||||
"""
|
||||
client = _make_client()
|
||||
client._telegram_chat_id = "-1001"
|
||||
now = [100.0]
|
||||
waits = []
|
||||
monkeypatch.setattr("app.modules.telegram.telegram.time.monotonic", lambda: now[0])
|
||||
|
||||
def advance(seconds):
|
||||
"""
|
||||
用虚拟时钟推进冷却等待,避免测试真实休眠。
|
||||
|
||||
:param seconds: 等待秒数
|
||||
"""
|
||||
waits.append(seconds)
|
||||
now[0] += seconds
|
||||
|
||||
monkeypatch.setattr("app.modules.telegram.telegram.time.sleep", advance)
|
||||
client._mark_rate_limit(
|
||||
"-1001",
|
||||
TelegramApiError("editMessageText", "Too Many Requests", 429, {"retry_after": 13}),
|
||||
)
|
||||
now[0] += 9.0
|
||||
client._api.send_rich_message.return_value = {"message_id": 201, "chat": {"id": "-1001"}}
|
||||
|
||||
result = client.send_msg(None, text="final answer", rich_message="final answer")
|
||||
|
||||
assert result == {"success": True, "message_id": 201, "chat_id": "-1001"}
|
||||
assert waits == [4.0]
|
||||
client._api.send_rich_message.assert_called_once()
|
||||
client._api.send_message.assert_not_called()
|
||||
|
||||
def test_rich_chunked_send_429_only_retries_unsent_chunks(self, monkeypatch):
|
||||
"""
|
||||
富文本多分块发送中途命中 429 时,冷却后只补发尚未送达的分块,不重发首块。
|
||||
"""
|
||||
client = _make_client()
|
||||
now = [200.0]
|
||||
waits = []
|
||||
monkeypatch.setattr("app.modules.telegram.telegram.time.monotonic", lambda: now[0])
|
||||
|
||||
def advance(seconds):
|
||||
"""
|
||||
记录并推进虚拟冷却等待。
|
||||
|
||||
:param seconds: 等待秒数
|
||||
"""
|
||||
waits.append(seconds)
|
||||
now[0] += seconds
|
||||
|
||||
monkeypatch.setattr("app.modules.telegram.telegram.time.sleep", advance)
|
||||
chunks = [{"html": "<b>第一块</b>"}, {"html": "<b>第二块</b>"}, {"html": "<b>第三块</b>"}]
|
||||
monkeypatch.setattr(client, "_build_rich_message_chunks", lambda _text: chunks)
|
||||
client._api.send_rich_message.side_effect = [
|
||||
{"message_id": 1, "chat": {"id": "chat"}},
|
||||
TelegramApiError("sendRichMessage", "Too Many Requests", 429, {"retry_after": 5}),
|
||||
{"message_id": 2, "chat": {"id": "chat"}},
|
||||
{"message_id": 3, "chat": {"id": "chat"}},
|
||||
]
|
||||
|
||||
result = client.send_msg(None, text="正文", rich_message="第一块\n第二块\n第三块")
|
||||
|
||||
assert result == {"success": True, "message_id": 3, "chat_id": "chat"}
|
||||
assert waits == [5.0]
|
||||
sent_payloads = [
|
||||
call.kwargs["rich_message"]["html"]
|
||||
for call in client._api.send_rich_message.call_args_list
|
||||
]
|
||||
assert sent_payloads == ["<b>第一块</b>", "<b>第二块</b>", "<b>第二块</b>", "<b>第三块</b>"]
|
||||
client._api.send_message.assert_not_called()
|
||||
|
||||
@pytest.mark.parametrize("parse_mode", ["plain", "HTML", "MarkdownV2"])
|
||||
def test_long_message_429_only_retries_unsent_chunks(self, monkeypatch, parse_mode):
|
||||
"""
|
||||
普通、HTML 和 MarkdownV2 长消息分块遇到 429 时,只补发未送达分块。
|
||||
"""
|
||||
client = _make_client()
|
||||
now = [300.0]
|
||||
waits = []
|
||||
monkeypatch.setattr("app.modules.telegram.telegram.time.monotonic", lambda: now[0])
|
||||
|
||||
def advance(seconds):
|
||||
"""
|
||||
推进虚拟时钟模拟等待 429 冷却。
|
||||
|
||||
:param seconds: 等待秒数
|
||||
"""
|
||||
waits.append(seconds)
|
||||
now[0] += seconds
|
||||
|
||||
monkeypatch.setattr("app.modules.telegram.telegram.time.sleep", advance)
|
||||
client._api.send_message.side_effect = [
|
||||
{"message_id": 11, "chat": {"id": "chat"}},
|
||||
TelegramApiError("sendMessage", "Too Many Requests", 429, {"retry_after": 6}),
|
||||
{"message_id": 12, "chat": {"id": "chat"}},
|
||||
]
|
||||
body = ("第一段内容" * 700) + "\n" + ("第二段内容" * 700)
|
||||
|
||||
result = client.send_msg(title="", text=body, parse_mode=parse_mode)
|
||||
|
||||
assert result == {"success": True, "message_id": 12, "chat_id": "chat"}
|
||||
assert waits == [6.0]
|
||||
sent_texts = [call.kwargs["text"] for call in client._api.send_message.call_args_list]
|
||||
assert len(sent_texts) == 3
|
||||
assert sent_texts[0] != sent_texts[1]
|
||||
assert sent_texts[1] == sent_texts[2]
|
||||
|
||||
def test_repeated_429_stops_at_wait_budget_cap(self, monkeypatch):
|
||||
"""
|
||||
连续 429 累计等待不得超过等待上限,超预算时立即放弃补发。
|
||||
"""
|
||||
client = _make_client()
|
||||
now = [400.0]
|
||||
waits = []
|
||||
monkeypatch.setattr("app.modules.telegram.telegram.time.monotonic", lambda: now[0])
|
||||
|
||||
def advance(seconds):
|
||||
"""
|
||||
记录每次虚拟等待时长并推进时钟。
|
||||
|
||||
:param seconds: 等待秒数
|
||||
"""
|
||||
waits.append(seconds)
|
||||
now[0] += seconds
|
||||
|
||||
monkeypatch.setattr("app.modules.telegram.telegram.time.sleep", advance)
|
||||
client._api.send_rich_message.side_effect = [
|
||||
TelegramApiError("sendRichMessage", "Too Many Requests", 429, {"retry_after": 35}),
|
||||
TelegramApiError("sendRichMessage", "Too Many Requests", 429, {"retry_after": 35}),
|
||||
]
|
||||
|
||||
result = client.send_msg(None, text="正文", rich_message="# 正文")
|
||||
|
||||
assert result == {"success": False}
|
||||
assert waits == [35.0]
|
||||
assert sum(waits) <= TELEGRAM_RATE_LIMIT_MAX_WAIT_SECONDS
|
||||
assert client._api.send_rich_message.call_count == 2
|
||||
client._api.send_message.assert_not_called()
|
||||
|
||||
|
||||
class TestEditMsgFallsBackToPlainText:
|
||||
"""
|
||||
@@ -279,10 +423,9 @@ class TestEditMsgFallsBackToPlainText:
|
||||
assert result is False
|
||||
client._api.edit_message_text.assert_called_once()
|
||||
|
||||
@pytest.mark.parametrize("wait_for_interval", [False, True])
|
||||
def test_429_cooldown_skips_follow_up_edits(self, monkeypatch, wait_for_interval):
|
||||
def test_429_cooldown_skips_intermediate_edits(self, monkeypatch):
|
||||
"""
|
||||
同一聊天的冷却期内后续编辑不应再触碰 Bot API。
|
||||
中间进度编辑在聊天 429 冷却期内应立即跳过,不触碰 Bot API 也不等待。
|
||||
"""
|
||||
client = _make_client()
|
||||
now = [100.0]
|
||||
@@ -297,7 +440,7 @@ class TestEditMsgFallsBackToPlainText:
|
||||
with patch("app.modules.telegram.telegram.time.sleep") as sleep_mock:
|
||||
assert client.edit_msg(
|
||||
chat_id="chat", message_id=5, text="更新", rich_message="# 更新",
|
||||
wait_for_interval=wait_for_interval,
|
||||
wait_for_interval=False,
|
||||
) is False
|
||||
sleep_mock.assert_not_called()
|
||||
assert client._api.edit_message_text.call_count == 1
|
||||
@@ -307,10 +450,91 @@ class TestEditMsgFallsBackToPlainText:
|
||||
assert client.edit_msg(chat_id="chat", message_id=5, text="更新", rich_message="# 更新") is True
|
||||
assert client._api.edit_message_text.call_count == 2
|
||||
|
||||
@pytest.mark.parametrize("interruption", ["429", "edit"])
|
||||
def test_final_edit_waits_for_429_cooldown_within_cap_and_skips_over_cap(self, monkeypatch):
|
||||
"""
|
||||
收尾编辑在 429 剩余冷却未超上限时应等待并送达,超出上限时立即放弃不阻塞。
|
||||
"""
|
||||
client = _make_client()
|
||||
now = [100.0]
|
||||
waits = []
|
||||
monkeypatch.setattr("app.modules.telegram.telegram.time.monotonic", lambda: now[0])
|
||||
|
||||
def advance(seconds):
|
||||
"""
|
||||
推进虚拟时钟并记录等待时长。
|
||||
|
||||
:param seconds: 等待秒数
|
||||
"""
|
||||
waits.append(seconds)
|
||||
now[0] += seconds
|
||||
|
||||
monkeypatch.setattr("app.modules.telegram.telegram.time.sleep", advance)
|
||||
client._mark_rate_limit(
|
||||
"chat",
|
||||
TelegramApiError("editMessageText", "Too Many Requests", 429, {"retry_after": 13}),
|
||||
)
|
||||
now[0] += 9.0
|
||||
client._api.edit_message_text.return_value = {"message_id": 10}
|
||||
|
||||
assert client.edit_msg(
|
||||
chat_id="chat", message_id=10, text="finished", rich_message="finished",
|
||||
wait_for_interval=True,
|
||||
) is True
|
||||
assert waits == [4.0]
|
||||
assert client._api.edit_message_text.call_count == 1
|
||||
|
||||
waits.clear()
|
||||
over_cap = int(TELEGRAM_RATE_LIMIT_MAX_WAIT_SECONDS) + 60
|
||||
client._mark_rate_limit(
|
||||
"chat",
|
||||
TelegramApiError("editMessageText", "Too Many Requests", 429, {"retry_after": over_cap}),
|
||||
)
|
||||
assert client.edit_msg(
|
||||
chat_id="chat", message_id=10, text="too-long", rich_message="too-long",
|
||||
wait_for_interval=True,
|
||||
) is False
|
||||
assert waits == []
|
||||
assert client._api.edit_message_text.call_count == 1
|
||||
|
||||
def test_final_edit_retries_after_fresh_429_without_plain_fallback(self, monkeypatch):
|
||||
"""
|
||||
收尾编辑本身命中短 429 时,应在冷却后重试富文本编辑而不降级纯文本。
|
||||
"""
|
||||
client = _make_client()
|
||||
now = [100.0]
|
||||
waits = []
|
||||
monkeypatch.setattr("app.modules.telegram.telegram.time.monotonic", lambda: now[0])
|
||||
|
||||
def advance(seconds):
|
||||
"""
|
||||
用虚拟时钟推进 429 冷却等待。
|
||||
|
||||
:param seconds: 等待秒数
|
||||
"""
|
||||
waits.append(seconds)
|
||||
now[0] += seconds
|
||||
|
||||
monkeypatch.setattr("app.modules.telegram.telegram.time.sleep", advance)
|
||||
client._api.edit_message_text.side_effect = [
|
||||
TelegramApiError("editMessageText", "Too Many Requests", 429, {"retry_after": 5}),
|
||||
{"message_id": 5},
|
||||
]
|
||||
|
||||
assert client.edit_msg(
|
||||
chat_id="chat", message_id=5, text="完整正文", rich_message="# 完整正文",
|
||||
wait_for_interval=True,
|
||||
) is True
|
||||
assert waits == [5.0]
|
||||
assert client._api.edit_message_text.call_count == 2
|
||||
assert all(
|
||||
call.kwargs.get("rich_message") is not None
|
||||
for call in client._api.edit_message_text.call_args_list
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize("interruption", ["429_over_cap", "edit"])
|
||||
def test_final_edit_rechecks_cooldown_and_interval_after_one_wait(self, monkeypatch, interruption):
|
||||
"""
|
||||
等待期间出现聊天冷却或同消息并发编辑时,不追加请求或无限延长等待。
|
||||
等待期间出现超上限 429 冷却或同消息并发编辑时,不追加请求或无限延长等待。
|
||||
"""
|
||||
client = _make_client()
|
||||
now = [100.0]
|
||||
@@ -327,9 +551,11 @@ class TestEditMsgFallsBackToPlainText:
|
||||
"""
|
||||
waits.append(seconds)
|
||||
now[0] += seconds
|
||||
if interruption == "429":
|
||||
if interruption == "429_over_cap":
|
||||
over_cap = int(TELEGRAM_RATE_LIMIT_MAX_WAIT_SECONDS) + 30
|
||||
client._mark_rate_limit(
|
||||
"chat", TelegramApiError("editMessageText", "Too Many Requests", 429, {"retry_after": 17}),
|
||||
"chat",
|
||||
TelegramApiError("editMessageText", "Too Many Requests", 429, {"retry_after": over_cap}),
|
||||
)
|
||||
else:
|
||||
assert client.edit_msg(chat_id="chat", message_id=5, text="并发编辑") is True
|
||||
@@ -340,7 +566,7 @@ class TestEditMsgFallsBackToPlainText:
|
||||
wait_for_interval=True,
|
||||
) is False
|
||||
assert waits == [TELEGRAM_EDIT_MIN_INTERVAL_SECONDS]
|
||||
assert client._api.edit_message_text.call_count == (1 if interruption == "429" else 2)
|
||||
assert client._api.edit_message_text.call_count == (1 if interruption == "429_over_cap" else 2)
|
||||
|
||||
def test_successful_edits_are_throttled_and_latest_text_wins(self, monkeypatch):
|
||||
"""
|
||||
|
||||
Reference in New Issue
Block a user