ForcePilot/backend/package/yuxi/channel/extensions/zalo/gateway.py
Kris 5946478772 feat(channel): 添加小红书、XMPP、元宝和 Zalo 渠道扩展
新增小红书、XMPP、元宝、Zalo 四个渠道扩展。

小红书渠道扩展主要模块:config, gateway, webhook, outbound, streaming, pairing, security, dedupe, media, status, window

XMPP 渠道扩展主要模块:plugin, config, gateway, outbound, streaming, pairing, security, dedupe, accounts, commands, muc, rate_limiter, stanza_utils, status, monitor

元宝渠道扩展主要模块:plugin, client, config_schema, gateway, outbound(chunk/queue/transport), inbound(dispatcher), streaming, pairing, security, accounts, actions, commands, codec(biz/conn), session, shared, utils

Zalo 渠道扩展主要模块:api, config, gateway, webhook, outbound, pairing, security, session, polling, monitor, status
2026-05-21 12:04:05 +08:00

130 lines
4.8 KiB
Python

import asyncio
import time
import logging
from yuxi.channel.extensions.zalo.config import ZaloConfigAdapter
from yuxi.channel.extensions.zalo.monitor import parse_update_to_unified
from yuxi.channel.extensions.zalo.types import ZaloAccount
logger = logging.getLogger(__name__)
class ZaloGateway:
def __init__(self, config_adapter: ZaloConfigAdapter | None = None):
self._running = False
self._tasks: list[asyncio.Task] = []
self._account: ZaloAccount | None = None
self._message_queue: asyncio.Queue | None = None
self._last_message_at: float | None = None
self._config_adapter = config_adapter or ZaloConfigAdapter()
@property
def message_queue(self) -> asyncio.Queue | None:
return self._message_queue
@property
def last_message_at(self) -> float | None:
return self._last_message_at
async def start(self, ctx) -> object:
account = self._resolve_account(ctx)
if not account.is_configured():
logger.warning("Zalo account %s not configured, skipping start", account.account_id)
return {"running": False, "reason": "not-configured"}
await self._probe_bot(account)
self._message_queue = asyncio.Queue(maxsize=1000)
self._running = True
self._account = account
if account.webhook_url:
await self._start_webhook(account)
task = asyncio.create_task(self._webhook_wait_loop(account))
else:
from yuxi.channel.extensions.zalo.polling import start_polling_loop
task = asyncio.create_task(start_polling_loop(account, asyncio.Event(), self))
self._tasks.append(task)
logger.info(
"Zalo gateway started for account %s (mode=%s)",
account.account_id,
"webhook" if account.webhook_url else "polling",
)
return {"running": True, "account_id": account.account_id}
async def stop(self, ctx) -> None:
self._running = False
for task in self._tasks:
task.cancel()
self._tasks.clear()
if self._account and self._account.webhook_url:
await self._stop_webhook(self._account)
self._message_queue = None
logger.info("Zalo gateway stopped")
async def _webhook_wait_loop(self, account: ZaloAccount):
abort = asyncio.Event()
try:
while not abort.is_set() and self._running:
await asyncio.sleep(1.0)
except asyncio.CancelledError:
abort.set()
async def process_update(self, update: dict, account: ZaloAccount | dict) -> None:
unified = parse_update_to_unified(update, account)
if unified is None:
return
if self._message_queue is not None:
self._last_message_at = time.monotonic()
await self._message_queue.put(unified)
logger.debug("Zalo message enqueued: sender=%s", unified.get("sender", {}).get("id"))
def _resolve_account(self, ctx) -> ZaloAccount:
config = getattr(ctx, "config", {}) if ctx else {}
accounts = config.get("accounts", {})
account_id = getattr(ctx, "account_id", "default")
raw = accounts.get(account_id, {})
account_dict = self._config_adapter.build_account(account_id, raw)
field_names = {f.name for f in ZaloAccount.__dataclass_fields__.values()}
return ZaloAccount(**{k: v for k, v in account_dict.items() if k in field_names})
async def _probe_bot(self, account: ZaloAccount) -> None:
from yuxi.channel.extensions.zalo.api import ZaloBotApi
api = ZaloBotApi(account.bot_token, proxy=account.proxy)
try:
result = await api.get_me()
bot_info = result.get("result", {})
logger.info("Zalo bot probe ok: id=%s name=%s", bot_info.get("id", ""), bot_info.get("name", ""))
except Exception as e:
logger.warning("Zalo bot probe failed (non-fatal): %s", e)
finally:
await api.close()
async def _start_webhook(self, account: ZaloAccount) -> None:
from yuxi.channel.extensions.zalo.webhook import register_webhook
account_dict = {
"bot_token": account.bot_token,
"webhook_url": account.webhook_url,
"webhook_secret": account.webhook_secret,
"proxy": account.proxy,
}
ok = await register_webhook(account_dict)
if not ok:
logger.warning("Zalo webhook registration failed for account %s", account.account_id)
async def _stop_webhook(self, account: ZaloAccount) -> None:
from yuxi.channel.extensions.zalo.webhook import unregister_webhook
account_dict = {"bot_token": account.bot_token, "proxy": account.proxy}
await unregister_webhook(account_dict)