ForcePilot/backend/package/yuxi/channels/adapters/synologychat/webhook_send.py
Kris 69f4319023 feat(synologychat): 完成Synology Chat适配器的多维度优化
此提交对Synology Chat适配器进行了全面改进:
1. 新增消息去重、分布式轮询租约、bot名称配置等功能
2. 优化URL提取逻辑,自动清理尾部标点符号
3. 重构发送逻辑,提取通用重试工具函数并优化SID缓存
4. 完善文档提示与配置项,新增轮询租约类型支持
5. 修复认证API路径硬编码问题,调整交互组件提示文案
6. 增加Webhook模式下的DSM客户端兜底初始化
7. 优化导入顺序与代码结构,清理冗余空行
2026-05-13 16:15:22 +08:00

79 lines
2.8 KiB
Python

"""Incoming Webhook sender for Synology Chat.
Provides an alternative send path via Synology Chat's Incoming Webhook URL,
as a lighter-weight alternative to the DSM API direct connection.
"""
from __future__ import annotations
import asyncio
from typing import Any
import httpx
from yuxi.channels.adapters.synologychat.send import assert_safe_media_url
from yuxi.channels.models import DeliveryResult
async def send_via_incoming_webhook(
webhook_url: str,
text: str,
file_url: str | None = None,
timeout: float = 30.0,
client: httpx.AsyncClient | None = None,
max_retries: int = 3,
) -> DeliveryResult:
if not webhook_url:
return DeliveryResult(success=False, error="Incoming webhook URL not configured")
try:
await assert_safe_media_url(webhook_url)
except Exception as e:
return DeliveryResult(success=False, error=f"SSRF check failed: {e}")
payload: dict[str, Any] = {"text": text}
if file_url:
payload["file_url"] = file_url
async def _do_send(http_client: httpx.AsyncClient) -> DeliveryResult:
response = await http_client.post(webhook_url, data=payload)
response.raise_for_status()
result = response.json()
if result.get("success"):
return DeliveryResult(success=True, message_id=result.get("data", {}).get("message_id"))
return DeliveryResult(
success=False,
error=f"Webhook send failed: {result.get('error', {})}",
)
last_error = None
for attempt in range(max_retries):
try:
if client:
result = await _do_send(client)
else:
async with httpx.AsyncClient(timeout=httpx.Timeout(timeout)) as new_client:
result = await _do_send(new_client)
if result.success:
return result
last_error = result.error
except httpx.TimeoutException:
last_error = "Incoming webhook request timed out"
except httpx.HTTPStatusError as e:
if e.response.status_code < 500:
return DeliveryResult(success=False, error=f"Incoming webhook HTTP {e.response.status_code}")
last_error = f"Incoming webhook HTTP {e.response.status_code}"
except Exception as e:
last_error = str(e)
if attempt < max_retries - 1:
await asyncio.sleep(1.0 * (2**attempt))
return DeliveryResult(success=False, error=last_error or "Webhook send failed after retries")
def build_webhook_url(dsm_url: str, webhook_token: str) -> str:
"""Build a Synology Chat Incoming Webhook URL from DSM URL and token."""
base = dsm_url.rstrip("/")
return f"{base}/webapi/entry.cgi?api=SYNO.Chat.External&method=incoming&version=1&token={webhook_token}"