refactor(gateway): migrate wecom + wecom_callback adapters to bundled plugin

Completes #41112 — the last unclaimed chat-platform channels. WeCom Smart
Robot (wecom) and callback-mode self-built apps (wecom_callback), sharing the
wecom_crypto satellite, relocated to plugins/platforms/wecom/ (adapter.py +
callback_adapter.py + wecom_crypto.py, internal crypto import rewritten).
register() exposes BOTH platforms via the registry with standalone_sender_fn
(wecom WebSocket send), setup_fn (QR/manual wizard), is_connected (bot_id /
corp_id). Core touchpoints stripped: run.py 2 factory elifs, config.py 2
_PLATFORM_CONNECTED_CHECKERS entries, gateway.py 2 static dicts + _setup_wecom
+ setup-map entry, send_message_tool _send_wecom (now registry dispatch).
Env->PlatformConfig seeding stays in core. 191 wecom-related tests pass.
This commit is contained in:
teknium1 2026-06-07 06:17:20 -07:00
parent d532c67292
commit f2a7adba54
No known key found for this signature in database
14 changed files with 360 additions and 336 deletions

View file

@ -433,10 +433,6 @@ _PLATFORM_CONNECTED_CHECKERS: dict[Platform, Callable[[PlatformConfig], bool]] =
Platform.MSGRAPH_WEBHOOK: lambda cfg: bool(
str(cfg.extra.get("client_state") or "").strip()
),
Platform.WECOM: lambda cfg: bool(cfg.extra.get("bot_id")),
Platform.WECOM_CALLBACK: lambda cfg: bool(
cfg.extra.get("corp_id") or cfg.extra.get("apps")
),
Platform.BLUEBUBBLES: lambda cfg: bool(
cfg.extra.get("server_url") and cfg.extra.get("password")
),

View file

@ -6892,23 +6892,6 @@ class GatewayRunner:
return None
return SmsAdapter(config)
elif platform == Platform.WECOM_CALLBACK:
from gateway.platforms.wecom_callback import (
WecomCallbackAdapter,
check_wecom_callback_requirements,
)
if not check_wecom_callback_requirements():
logger.warning("WeComCallback: aiohttp/httpx/defusedxml not installed")
return None
return WecomCallbackAdapter(config)
elif platform == Platform.WECOM:
from gateway.platforms.wecom import WeComAdapter, check_wecom_requirements
if not check_wecom_requirements():
logger.warning("WeCom: aiohttp not installed or WECOM_BOT_ID/SECRET not set")
return None
return WeComAdapter(config)
elif platform == Platform.WEIXIN:
from gateway.platforms.weixin import WeixinAdapter, check_weixin_requirements
if not check_weixin_requirements():

View file

@ -4006,105 +4006,9 @@ _PLATFORMS = [
# Feishu moved to plugins/platforms/feishu/ — setup metadata discovered
# dynamically via the platform registry entry registered by
# plugins/platforms/feishu/adapter.py::register(). #41112.
{
"key": "wecom",
"label": "WeCom (Enterprise WeChat)",
"emoji": "💬",
"token_var": "WECOM_BOT_ID",
"setup_instructions": [
"1. Go to WeCom Admin Console → Applications → Create AI Bot",
"2. Copy the Bot ID and Secret from the bot's credentials page",
"3. The bot connects via WebSocket — no public endpoint needed",
"4. Add the bot to a group chat or message it directly in WeCom",
"5. Restrict access with WECOM_ALLOWED_USERS for production use",
],
"vars": [
{
"name": "WECOM_BOT_ID",
"prompt": "Bot ID",
"password": False,
"help": "The Bot ID from your WeCom AI Bot.",
},
{
"name": "WECOM_SECRET",
"prompt": "Secret",
"password": True,
"help": "The secret from your WeCom AI Bot.",
},
{
"name": "WECOM_ALLOWED_USERS",
"prompt": "Allowed user IDs (comma-separated, or empty)",
"password": False,
"is_allowlist": True,
"help": "Restrict which WeCom users can interact with the bot.",
},
{
"name": "WECOM_HOME_CHANNEL",
"prompt": "Home chat ID (optional, for cron/notifications)",
"password": False,
"help": "Chat ID for scheduled results and notifications.",
},
],
},
{
"key": "wecom_callback",
"label": "WeCom Callback (Self-Built App)",
"emoji": "💬",
"token_var": "WECOM_CALLBACK_CORP_ID",
"setup_instructions": [
"1. Go to WeCom Admin Console → Applications → Create Self-Built App",
"2. Note the Corp ID (top of admin console) and create a Corp Secret",
"3. Under Receive Messages, configure the callback URL to point to your server",
"4. Copy the Token and EncodingAESKey from the callback configuration",
"5. The adapter runs an HTTP server — ensure the port is reachable from WeCom",
"6. Restrict access with WECOM_CALLBACK_ALLOWED_USERS for production use",
],
"vars": [
{
"name": "WECOM_CALLBACK_CORP_ID",
"prompt": "Corp ID",
"password": False,
"help": "Your WeCom enterprise Corp ID.",
},
{
"name": "WECOM_CALLBACK_CORP_SECRET",
"prompt": "Corp Secret",
"password": True,
"help": "The secret for your self-built application.",
},
{
"name": "WECOM_CALLBACK_AGENT_ID",
"prompt": "Agent ID",
"password": False,
"help": "The Agent ID of your self-built application.",
},
{
"name": "WECOM_CALLBACK_TOKEN",
"prompt": "Callback Token",
"password": True,
"help": "The Token from your WeCom callback configuration.",
},
{
"name": "WECOM_CALLBACK_ENCODING_AES_KEY",
"prompt": "Encoding AES Key",
"password": True,
"help": "The EncodingAESKey from your WeCom callback configuration.",
},
{
"name": "WECOM_CALLBACK_PORT",
"prompt": "Callback server port (default: 8645)",
"password": False,
"help": "Port for the HTTP callback server.",
},
{
"name": "WECOM_CALLBACK_ALLOWED_USERS",
"prompt": "Allowed user IDs (comma-separated, or empty)",
"password": False,
"is_allowlist": True,
"help": "Restrict which WeCom users can interact with the app.",
},
],
},
# WeCom (wecom + wecom_callback) moved to plugins/platforms/wecom/ —
# setup metadata discovered dynamically via the platform registry
# entries registered by plugins/platforms/wecom/adapter.py::register(). #41112.
{
"key": "weixin",
"label": "Weixin / WeChat",
@ -4567,129 +4471,8 @@ def _setup_standard_platform(platform: dict):
# (registered via setup_fn, dispatched through the plugin path). #41112.
def _setup_wecom():
"""Interactive setup for WeCom — scan QR code or manual credential input."""
print()
print(color(" ─── 💬 WeCom (Enterprise WeChat) Setup ───", Colors.CYAN))
existing_bot_id = get_env_value("WECOM_BOT_ID")
existing_secret = get_env_value("WECOM_SECRET")
if existing_bot_id and existing_secret:
print()
print_success("WeCom is already configured.")
if not prompt_yes_no(" Reconfigure WeCom?", False):
return
# ── Choose setup method ──
print()
method_choices = [
"Scan QR code to obtain Bot ID and Secret automatically (recommended)",
"Enter existing Bot ID and Secret manually",
]
method_idx = prompt_choice(
" How would you like to set up WeCom?", method_choices, 0
)
bot_id = None
secret = None
if method_idx == 0:
# ── QR scan flow ──
try:
from gateway.platforms.wecom import qr_scan_for_bot_info
except Exception as exc:
print_error(f" WeCom QR scan import failed: {exc}")
qr_scan_for_bot_info = None
if qr_scan_for_bot_info is not None:
try:
credentials = qr_scan_for_bot_info()
except KeyboardInterrupt:
print()
print_warning(" WeCom setup cancelled.")
return
except Exception as exc:
print_warning(f" QR scan failed: {exc}")
credentials = None
if credentials:
bot_id = credentials.get("bot_id", "")
secret = credentials.get("secret", "")
print_success(" ✔ QR scan successful! Bot ID and Secret obtained.")
if not bot_id or not secret:
print_info(" QR scan did not complete. Continuing with manual input.")
bot_id = None
secret = None
# ── Manual credential input ──
if not bot_id or not secret:
print()
print_info(
" 1. Go to WeCom Application → Workspace → Smart Robot -> Create smart robots"
)
print_info(" 2. Select API Mode")
print_info(" 3. Copy the Bot ID and Secret from the bot's credentials info")
print_info(" 4. The bot connects via WebSocket — no public endpoint needed")
print()
bot_id = prompt(" Bot ID", password=False)
if not bot_id:
print_warning(" Skipped — WeCom won't work without a Bot ID.")
return
secret = prompt(" Secret", password=True)
if not secret:
print_warning(" Skipped — WeCom won't work without a Secret.")
return
# ── Save core credentials ──
save_env_value("WECOM_BOT_ID", bot_id)
save_env_value("WECOM_SECRET", secret)
# ── Allowed users (deny-by-default security) ──
print()
print_info(" The gateway DENIES all users by default for security.")
print_info(" Enter user IDs to create an allowlist, or leave empty.")
allowed = prompt(" Allowed user IDs (comma-separated, or empty)", password=False)
if allowed:
cleaned = allowed.replace(" ", "")
save_env_value("WECOM_ALLOWED_USERS", cleaned)
print_success(" Saved — only these users can interact with the bot.")
else:
print()
access_choices = [
"Enable open access (anyone can message the bot)",
"Use DM pairing (unknown users request access, you approve with 'hermes pairing approve')",
"Disable direct messages",
"Skip for now (bot will deny all users until configured)",
]
access_idx = prompt_choice(
" How should unauthorized users be handled?", access_choices, 1
)
if access_idx == 0:
save_env_value("WECOM_DM_POLICY", "open")
save_env_value("GATEWAY_ALLOW_ALL_USERS", "true")
print_warning(" Open access enabled — anyone can use your bot!")
elif access_idx == 1:
save_env_value("WECOM_DM_POLICY", "pairing")
print_success(
" DM pairing mode — users will receive a code to request access."
)
print_info(" Approve with: hermes pairing approve <platform> <code>")
elif access_idx == 2:
save_env_value("WECOM_DM_POLICY", "disabled")
print_warning(" Direct messages disabled.")
else:
print_info(" Skipped — configure later with 'hermes gateway setup'")
# ── Home channel (optional) ──
print()
print_info(" Chat ID for scheduled results and notifications.")
home = prompt(" Home chat ID (optional, for cron/notifications)", password=False)
if home:
save_env_value("WECOM_HOME_CHANNEL", home)
print_success(f" Home channel set to {home}")
print()
print_success("💬 WeCom configured!")
# _setup_wecom moved to plugins/platforms/wecom/adapter.py::interactive_setup
# (registered via setup_fn, dispatched through the plugin path). #41112.
def _is_service_installed() -> bool:
@ -5223,7 +5006,8 @@ def _builtin_setup_fn(key: str):
"weixin": _setup_weixin,
# feishu moved into the plugin: setup_fn registered by
# plugins/platforms/feishu/adapter.py::register(). #41112.
"wecom": _setup_wecom,
# wecom moved into the plugin: setup_fn registered by
# plugins/platforms/wecom/adapter.py::register(). #41112.
"qqbot": _setup_qqbot,
}.get(key)

View file

@ -0,0 +1,3 @@
from .adapter import register
__all__ = ["register"]

View file

@ -1633,3 +1633,232 @@ def qr_scan_for_bot_info(
print() # newline after dots
print(f" QR scan timed out ({timeout_seconds // 60} minutes). Please try again.")
return None
# ──────────────────────────────────────────────────────────────────────────
# Plugin migration glue (#41112 / #3823)
#
# Added when the WeCom adapters (wecom + wecom_callback, sharing the
# wecom_crypto satellite) moved from gateway/platforms/ into this bundled
# plugin. register() exposes BOTH platforms via the registry, replacing the
# Platform.WECOM / Platform.WECOM_CALLBACK elifs in gateway/run.py, the
# _PLATFORM_CONNECTED_CHECKERS entries in gateway/config.py, the _setup_wecom
# wizard + _PLATFORMS["wecom"] static dict in hermes_cli/gateway.py, and the
# _send_wecom dispatch in tools/send_message_tool.py. Env→PlatformConfig
# seeding stays in core, same as prior migrations.
# ──────────────────────────────────────────────────────────────────────────
async def _standalone_send(
pconfig,
chat_id,
message,
*,
thread_id=None,
media_files=None,
force_document=False,
):
"""Out-of-process WeCom delivery via the adapter's WebSocket send pipeline.
Implements the standalone_sender_fn contract so deliver=wecom cron jobs
succeed when cron runs separately from the gateway. Opens an ephemeral
WeComAdapter, connects, sends, and disconnects. Replaces the legacy
_send_wecom helper.
"""
if not check_wecom_requirements():
return {"error": "WeCom requirements not met. Need aiohttp + WECOM_BOT_ID/SECRET."}
try:
adapter = WeComAdapter(pconfig)
connected = await adapter.connect()
if not connected:
return {"error": f"WeCom: failed to connect - {getattr(adapter, 'fatal_error_message', None) or 'unknown error'}"}
try:
result = await adapter.send(chat_id, message)
if not result.success:
return {"error": f"WeCom send failed: {result.error}"}
return {
"success": True,
"platform": "wecom",
"chat_id": chat_id,
"message_id": result.message_id,
}
finally:
await adapter.disconnect()
except Exception as e:
return {"error": f"WeCom send failed: {e}"}
def interactive_setup() -> None:
"""Interactive setup for WeCom — QR scan or manual credential input.
Replaces hermes_cli/gateway.py::_setup_wecom and the static
_PLATFORMS["wecom"] dict. CLI helpers are lazy-imported.
"""
from hermes_cli.config import get_env_value, save_env_value
from hermes_cli.setup import prompt_choice
from hermes_cli.cli_output import (
prompt,
prompt_yes_no,
print_header,
print_info,
print_success,
print_warning,
print_error,
)
print_header("WeCom (Enterprise WeChat)")
existing_bot_id = get_env_value("WECOM_BOT_ID")
existing_secret = get_env_value("WECOM_SECRET")
if existing_bot_id and existing_secret:
print_success("WeCom is already configured.")
if not prompt_yes_no("Reconfigure WeCom?", False):
return
method_idx = prompt_choice(
"How would you like to set up WeCom?",
[
"Scan QR code to obtain Bot ID and Secret automatically (recommended)",
"Enter existing Bot ID and Secret manually",
],
0,
)
bot_id = None
secret = None
if method_idx == 0:
try:
credentials = qr_scan_for_bot_info()
except KeyboardInterrupt:
print_warning("WeCom setup cancelled.")
return
except Exception as exc:
print_warning(f"QR scan failed: {exc}")
credentials = None
if credentials:
bot_id = credentials.get("bot_id", "")
secret = credentials.get("secret", "")
print_success("✔ QR scan successful! Bot ID and Secret obtained.")
if not bot_id or not secret:
print_info("QR scan did not complete. Continuing with manual input.")
bot_id = None
secret = None
if not bot_id or not secret:
print_info("1. Go to WeCom Application → Workspace → Smart Robot -> Create smart robots")
print_info("2. Select API Mode")
print_info("3. Copy the Bot ID and Secret from the bot's credentials info")
print_info("4. The bot connects via WebSocket — no public endpoint needed")
bot_id = prompt("Bot ID", password=False)
if not bot_id:
print_warning("Skipped — WeCom won't work without a Bot ID.")
return
secret = prompt("Secret", password=True)
if not secret:
print_warning("Skipped — WeCom won't work without a Secret.")
return
save_env_value("WECOM_BOT_ID", bot_id)
save_env_value("WECOM_SECRET", secret)
print_info("The gateway DENIES all users by default for security.")
print_info("Enter user IDs to create an allowlist, or leave empty.")
allowed = prompt("Allowed user IDs (comma-separated, or empty)", password=False)
if allowed:
save_env_value("WECOM_ALLOWED_USERS", allowed.replace(" ", ""))
print_success("Saved — only these users can interact with the bot.")
else:
access_idx = prompt_choice(
"How should unauthorized users be handled?",
[
"Enable open access (anyone can message the bot)",
"Use DM pairing (unknown users request access, you approve with 'hermes pairing approve')",
"Disable direct messages",
"Skip for now (bot will deny all users until configured)",
],
1,
)
if access_idx == 0:
save_env_value("WECOM_DM_POLICY", "open")
save_env_value("GATEWAY_ALLOW_ALL_USERS", "true")
print_warning("Open access enabled — anyone can use your bot!")
elif access_idx == 1:
save_env_value("WECOM_DM_POLICY", "pairing")
print_success("DM pairing mode — users will receive a code to request access.")
print_info("Approve with: hermes pairing approve <platform> <code>")
elif access_idx == 2:
save_env_value("WECOM_DM_POLICY", "disabled")
print_warning("Direct messages disabled.")
else:
print_info("Skipped — configure later with 'hermes gateway setup'")
home = prompt("Home chat ID (optional, for cron/notifications)", password=False)
if home:
save_env_value("WECOM_HOME_CHANNEL", home)
print_success(f"Home channel set to {home}")
print_success("💬 WeCom configured!")
def _is_connected(config) -> bool:
"""WeCom (Smart Robot) is connected when a bot_id is configured. Mirrors the
legacy _PLATFORM_CONNECTED_CHECKERS[Platform.WECOM] entry."""
extra = getattr(config, "extra", {}) or {}
return bool(extra.get("bot_id"))
def _callback_is_connected(config) -> bool:
"""WeCom callback mode is connected when corp_id (or a multi-app `apps`
block) is configured. Mirrors the legacy
_PLATFORM_CONNECTED_CHECKERS[Platform.WECOM_CALLBACK] entry."""
extra = getattr(config, "extra", {}) or {}
return bool(extra.get("corp_id") or extra.get("apps"))
def _build_adapter(config):
"""Factory wrapper that constructs WeComAdapter from a PlatformConfig."""
return WeComAdapter(config)
def _build_callback_adapter(config):
"""Factory wrapper that constructs WecomCallbackAdapter from a PlatformConfig."""
from plugins.platforms.wecom.callback_adapter import WecomCallbackAdapter
return WecomCallbackAdapter(config)
def register(ctx) -> None:
"""Plugin entry point — registers both WeCom platforms."""
ctx.register_platform(
name="wecom",
label="WeCom (Enterprise WeChat)",
adapter_factory=_build_adapter,
check_fn=check_wecom_requirements,
is_connected=_is_connected,
validate_config=_is_connected,
required_env=["WECOM_BOT_ID", "WECOM_SECRET"],
install_hint="pip install 'hermes-agent[wecom]'",
setup_fn=interactive_setup,
allowed_users_env="WECOM_ALLOWED_USERS",
allow_all_env="WECOM_ALLOW_ALL_USERS",
cron_deliver_env_var="WECOM_HOME_CHANNEL",
standalone_sender_fn=_standalone_send,
max_message_length=4000,
emoji="💼",
allow_update_command=True,
)
from plugins.platforms.wecom.callback_adapter import check_wecom_callback_requirements
ctx.register_platform(
name="wecom_callback",
label="WeCom Callback (self-built apps)",
adapter_factory=_build_callback_adapter,
check_fn=check_wecom_callback_requirements,
is_connected=_callback_is_connected,
validate_config=_callback_is_connected,
required_env=["WECOM_CALLBACK_CORP_ID", "WECOM_CALLBACK_CORP_SECRET"],
install_hint="pip install 'hermes-agent[wecom]'",
allowed_users_env="WECOM_CALLBACK_ALLOWED_USERS",
allow_all_env="WECOM_CALLBACK_ALLOW_ALL_USERS",
emoji="💼",
allow_update_command=True,
)

View file

@ -47,7 +47,7 @@ except ImportError:
from gateway.config import Platform, PlatformConfig
from gateway.platforms.base import BasePlatformAdapter, MessageEvent, MessageType, SendResult
from gateway.platforms.wecom_crypto import WXBizMsgCrypt, WeComCryptoError
from plugins.platforms.wecom.wecom_crypto import WXBizMsgCrypt, WeComCryptoError
logger = logging.getLogger(__name__)

View file

@ -0,0 +1,52 @@
name: wecom-platform
label: WeCom (Enterprise WeChat)
kind: platform
version: 1.0.0
description: >
WeCom / Enterprise WeChat gateway adapter for Hermes Agent. Registers two
platforms: ``wecom`` (Smart Robot over WebSocket) and ``wecom_callback``
(self-built apps over an HTTP callback endpoint with AES message crypto).
Relays messages between WeCom chats and the Hermes agent.
author: NousResearch
requires_env:
- name: WECOM_BOT_ID
description: "WeCom Smart Robot bot ID"
prompt: "WeCom bot ID"
password: false
- name: WECOM_SECRET
description: "WeCom Smart Robot secret"
prompt: "WeCom secret"
password: true
optional_env:
- name: WECOM_WEBSOCKET_URL
description: "WeCom Smart Robot WebSocket URL"
prompt: "WeCom WebSocket URL"
password: false
- name: WECOM_HOME_CHANNEL
description: "Default chat ID for cron / notification delivery"
prompt: "Home channel ID"
password: false
- name: WECOM_ALLOWED_USERS
description: "Comma-separated WeCom user IDs allowed to talk to the bot"
prompt: "Allowed users (comma-separated)"
password: false
- name: WECOM_CALLBACK_CORP_ID
description: "WeCom callback-mode corp ID (self-built apps)"
prompt: "WeCom callback corp ID"
password: false
- name: WECOM_CALLBACK_CORP_SECRET
description: "WeCom callback-mode corp secret"
prompt: "WeCom callback corp secret"
password: true
- name: WECOM_CALLBACK_AGENT_ID
description: "WeCom callback-mode agent ID"
prompt: "WeCom callback agent ID"
password: false
- name: WECOM_CALLBACK_TOKEN
description: "WeCom callback verification token"
prompt: "WeCom callback token"
password: true
- name: WECOM_CALLBACK_ENCODING_AES_KEY
description: "WeCom callback EncodingAESKey for message crypto"
prompt: "WeCom callback EncodingAESKey"
password: true

View file

@ -103,7 +103,7 @@ def test_base_adapter_defaults_to_not_owning_access_policy():
@pytest.mark.parametrize(
"module_path, class_name",
[
("gateway.platforms.wecom", "WeComAdapter"),
("plugins.platforms.wecom.adapter", "WeComAdapter"),
("gateway.platforms.weixin", "WeixinAdapter"),
("gateway.platforms.yuanbao", "YuanbaoAdapter"),
("gateway.platforms.qqbot.adapter", "QQAdapter"),

View file

@ -77,11 +77,11 @@ def test_helper_is_importable_from_every_platform_that_uses_it():
the regression shows up as a runtime adapter-startup crash."""
# Just importing exercises the helper's import path for each adapter.
import gateway.platforms.qqbot.adapter # noqa: F401
import gateway.platforms.wecom # noqa: F401
import plugins.platforms.wecom.adapter # noqa: F401
import plugins.platforms.dingtalk.adapter # noqa: F401
import gateway.platforms.signal # noqa: F401
import gateway.platforms.bluebubbles # noqa: F401
import gateway.platforms.wecom_callback # noqa: F401
import plugins.platforms.wecom.callback_adapter # noqa: F401
class TestWhatsappTypingLeakFix:

View file

@ -303,7 +303,7 @@ class TestMatrixTextBatching:
def _make_wecom_adapter():
"""Create a minimal WeComAdapter for testing text batching."""
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
config = PlatformConfig(enabled=True, token="test-token")
adapter = object.__new__(WeComAdapter)

View file

@ -15,35 +15,35 @@ from gateway.platforms.base import SendResult
class TestWeComRequirements:
def test_returns_false_without_aiohttp(self, monkeypatch):
monkeypatch.setattr("gateway.platforms.wecom.AIOHTTP_AVAILABLE", False)
monkeypatch.setattr("gateway.platforms.wecom.HTTPX_AVAILABLE", True)
from gateway.platforms.wecom import check_wecom_requirements
monkeypatch.setattr("plugins.platforms.wecom.adapter.AIOHTTP_AVAILABLE", False)
monkeypatch.setattr("plugins.platforms.wecom.adapter.HTTPX_AVAILABLE", True)
from plugins.platforms.wecom.adapter import check_wecom_requirements
assert check_wecom_requirements() is False
def test_returns_false_without_httpx(self, monkeypatch):
monkeypatch.setattr("gateway.platforms.wecom.AIOHTTP_AVAILABLE", True)
monkeypatch.setattr("gateway.platforms.wecom.HTTPX_AVAILABLE", False)
from gateway.platforms.wecom import check_wecom_requirements
monkeypatch.setattr("plugins.platforms.wecom.adapter.AIOHTTP_AVAILABLE", True)
monkeypatch.setattr("plugins.platforms.wecom.adapter.HTTPX_AVAILABLE", False)
from plugins.platforms.wecom.adapter import check_wecom_requirements
assert check_wecom_requirements() is False
def test_returns_true_when_available(self, monkeypatch):
monkeypatch.setattr("gateway.platforms.wecom.AIOHTTP_AVAILABLE", True)
monkeypatch.setattr("gateway.platforms.wecom.HTTPX_AVAILABLE", True)
from gateway.platforms.wecom import check_wecom_requirements
monkeypatch.setattr("plugins.platforms.wecom.adapter.AIOHTTP_AVAILABLE", True)
monkeypatch.setattr("plugins.platforms.wecom.adapter.HTTPX_AVAILABLE", True)
from plugins.platforms.wecom.adapter import check_wecom_requirements
assert check_wecom_requirements() is True
class TestWeComAdapterInit:
def test_declares_non_editable_message_capability(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
assert WeComAdapter.SUPPORTS_MESSAGE_EDITING is False
def test_reads_config_from_extra(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
config = PlatformConfig(
enabled=True,
@ -67,7 +67,7 @@ class TestWeComAdapterInit:
monkeypatch.setenv("WECOM_BOT_ID", "env-bot")
monkeypatch.setenv("WECOM_SECRET", "env-secret")
monkeypatch.setenv("WECOM_WEBSOCKET_URL", "wss://env.example/ws")
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
assert adapter._bot_id == "env-bot"
@ -78,8 +78,8 @@ class TestWeComAdapterInit:
class TestWeComConnect:
@pytest.mark.asyncio
async def test_connect_records_missing_credentials(self, monkeypatch):
import gateway.platforms.wecom as wecom_module
from gateway.platforms.wecom import WeComAdapter
import plugins.platforms.wecom.adapter as wecom_module
from plugins.platforms.wecom.adapter import WeComAdapter
monkeypatch.setattr(wecom_module, "AIOHTTP_AVAILABLE", True)
monkeypatch.setattr(wecom_module, "HTTPX_AVAILABLE", True)
@ -95,8 +95,8 @@ class TestWeComConnect:
@pytest.mark.asyncio
async def test_connect_records_handshake_failure_details(self, monkeypatch):
import gateway.platforms.wecom as wecom_module
from gateway.platforms.wecom import WeComAdapter
import plugins.platforms.wecom.adapter as wecom_module
from plugins.platforms.wecom.adapter import WeComAdapter
class DummyClient:
async def aclose(self):
@ -124,9 +124,9 @@ class TestWeComConnect:
class TestWeComQrScan:
@patch("gateway.platforms.wecom.time")
@patch("gateway.platforms.wecom.json.loads")
@patch("gateway.platforms.wecom.logger")
@patch("plugins.platforms.wecom.adapter.time")
@patch("plugins.platforms.wecom.adapter.json.loads")
@patch("plugins.platforms.wecom.adapter.logger")
@patch("urllib.request.urlopen")
@patch("urllib.request.Request")
def test_qr_scan_timeout_uses_monotonic_clock(
@ -137,7 +137,7 @@ class TestWeComQrScan:
mock_json_loads,
mock_time,
):
from gateway.platforms.wecom import qr_scan_for_bot_info
from plugins.platforms.wecom.adapter import qr_scan_for_bot_info
generate_resp = MagicMock()
generate_resp.read.return_value = b'{"data":{"scode":"abc","auth_url":"https://example.com/qr"}}'
@ -168,7 +168,7 @@ class TestWeComQrScan:
class TestWeComReplyMode:
@pytest.mark.asyncio
async def test_send_uses_passive_reply_markdown_when_reply_context_exists(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
adapter._reply_req_ids["msg-1"] = "req-1"
@ -189,7 +189,7 @@ class TestWeComReplyMode:
@pytest.mark.asyncio
async def test_send_image_file_uses_passive_reply_media_when_reply_context_exists(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
adapter._reply_req_ids["msg-1"] = "req-1"
@ -222,7 +222,7 @@ class TestWeComReplyMode:
class TestExtractText:
def test_extracts_plain_text(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
body = {
"msgtype": "text",
@ -233,7 +233,7 @@ class TestExtractText:
assert reply_text is None
def test_extracts_mixed_text(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
body = {
"msgtype": "mixed",
@ -249,7 +249,7 @@ class TestExtractText:
assert text == "part1\npart2"
def test_extracts_voice_and_quote(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
body = {
"msgtype": "voice",
@ -265,7 +265,7 @@ class TestCallbackDispatch:
@pytest.mark.asyncio
@pytest.mark.parametrize("cmd", ["aibot_msg_callback", "aibot_callback"])
async def test_dispatch_accepts_new_and_legacy_callback_cmds(self, cmd):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
adapter._on_message = AsyncMock()
@ -277,7 +277,7 @@ class TestCallbackDispatch:
class TestPolicyHelpers:
def test_dm_allowlist(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(
PlatformConfig(enabled=True, extra={"dm_policy": "allowlist", "allow_from": ["user-1"]})
@ -290,7 +290,7 @@ class TestPolicyHelpers:
``extra``) must populate the DM allowlist. Otherwise ``dm_policy:
allowlist`` runs with an empty allowlist and drops every listed user
at intake — the documented env vars become no-ops."""
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
monkeypatch.setenv("WECOM_DM_POLICY", "allowlist")
monkeypatch.setenv("WECOM_ALLOWED_USERS", "user-1, user-2")
@ -306,7 +306,7 @@ class TestPolicyHelpers:
def test_dm_allowlist_extra_takes_precedence_over_env(self, monkeypatch):
"""Config ``extra`` wins over the env fallback, so an explicit
allowlist is never silently widened by a stray WECOM_ALLOWED_USERS."""
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
monkeypatch.setenv("WECOM_ALLOWED_USERS", "env-user")
@ -319,7 +319,7 @@ class TestPolicyHelpers:
assert adapter._is_dm_allowed("env-user") is False
def test_group_allowlist_and_per_group_sender_allowlist(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(
PlatformConfig(
@ -339,7 +339,7 @@ class TestPolicyHelpers:
class TestMediaHelpers:
def test_detect_wecom_media_type(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
assert WeComAdapter._detect_wecom_media_type("image/png") == "image"
assert WeComAdapter._detect_wecom_media_type("video/mp4") == "video"
@ -347,7 +347,7 @@ class TestMediaHelpers:
assert WeComAdapter._detect_wecom_media_type("application/pdf") == "file"
def test_voice_non_amr_downgrades_to_file(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
result = WeComAdapter._apply_file_size_limits(128, "voice", "audio/mpeg")
@ -356,7 +356,7 @@ class TestMediaHelpers:
assert "AMR" in (result["downgrade_note"] or "")
def test_oversized_file_is_rejected(self):
from gateway.platforms.wecom import ABSOLUTE_MAX_BYTES, WeComAdapter
from plugins.platforms.wecom.adapter import ABSOLUTE_MAX_BYTES, WeComAdapter
result = WeComAdapter._apply_file_size_limits(ABSOLUTE_MAX_BYTES + 1, "file", "application/pdf")
@ -365,7 +365,7 @@ class TestMediaHelpers:
def test_decrypt_file_bytes_round_trip(self):
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
plaintext = b"wecom-secret"
key = os.urandom(32)
@ -380,7 +380,7 @@ class TestMediaHelpers:
@pytest.mark.asyncio
async def test_load_outbound_media_rejects_placeholder_path(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
@ -391,8 +391,8 @@ class TestMediaHelpers:
class TestMediaUpload:
@pytest.mark.asyncio
async def test_upload_media_bytes_uses_sdk_sequence(self, monkeypatch):
import gateway.platforms.wecom as wecom_module
from gateway.platforms.wecom import (
import plugins.platforms.wecom.adapter as wecom_module
from plugins.platforms.wecom.adapter import (
APP_CMD_UPLOAD_MEDIA_CHUNK,
APP_CMD_UPLOAD_MEDIA_FINISH,
APP_CMD_UPLOAD_MEDIA_INIT,
@ -439,7 +439,7 @@ class TestMediaUpload:
@pytest.mark.asyncio
@patch("tools.url_safety.is_safe_url", return_value=True)
async def test_download_remote_bytes_rejects_large_content_length(self, _mock_safe):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
class FakeResponse:
headers = {"content-length": "10"}
@ -468,7 +468,7 @@ class TestMediaUpload:
@pytest.mark.asyncio
async def test_cache_media_decrypts_url_payload_before_writing(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
plaintext = b"secret document bytes"
@ -507,7 +507,7 @@ class TestMediaUpload:
class TestSend:
@pytest.mark.asyncio
async def test_send_uses_proactive_payload(self):
from gateway.platforms.wecom import APP_CMD_SEND, WeComAdapter
from plugins.platforms.wecom.adapter import APP_CMD_SEND, WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
adapter._send_request = AsyncMock(return_value={"headers": {"req_id": "req-1"}, "errcode": 0})
@ -526,7 +526,7 @@ class TestSend:
@pytest.mark.asyncio
async def test_send_reports_wecom_errors(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
adapter._send_request = AsyncMock(return_value={"errcode": 40001, "errmsg": "bad request"})
@ -538,7 +538,7 @@ class TestSend:
@pytest.mark.asyncio
async def test_send_image_falls_back_to_text_for_remote_url(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
adapter._send_media_source = AsyncMock(return_value=SendResult(success=False, error="upload failed"))
@ -551,7 +551,7 @@ class TestSend:
@pytest.mark.asyncio
async def test_send_voice_sends_caption_and_downgrade_note(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
adapter._prepare_outbound_media = AsyncMock(
@ -587,7 +587,7 @@ class TestSend:
class TestInboundMessages:
@pytest.mark.asyncio
async def test_on_message_builds_event(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
adapter._text_batch_delay_seconds = 0 # disable batching for tests
@ -619,7 +619,7 @@ class TestInboundMessages:
@pytest.mark.asyncio
async def test_on_message_preserves_quote_context(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
adapter._text_batch_delay_seconds = 0 # disable batching for tests
@ -648,7 +648,7 @@ class TestInboundMessages:
@pytest.mark.asyncio
async def test_on_message_respects_group_policy(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(
PlatformConfig(
@ -680,7 +680,7 @@ class TestWeComZombieSessionFix:
"""Tests for PR #11572 — device_id, markdown reply, group req_id fallback."""
def test_adapter_generates_stable_device_id_per_instance(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
assert isinstance(adapter._device_id, str)
@ -691,7 +691,7 @@ class TestWeComZombieSessionFix:
assert adapter._device_id == adapter._device_id
def test_different_adapter_instances_get_distinct_device_ids(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
a = WeComAdapter(PlatformConfig(enabled=True))
b = WeComAdapter(PlatformConfig(enabled=True))
@ -699,7 +699,7 @@ class TestWeComZombieSessionFix:
@pytest.mark.asyncio
async def test_open_connection_includes_device_id_in_subscribe(self):
from gateway.platforms.wecom import APP_CMD_SUBSCRIBE, WeComAdapter
from plugins.platforms.wecom.adapter import APP_CMD_SUBSCRIBE, WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
adapter._bot_id = "test-bot"
@ -735,7 +735,7 @@ class TestWeComZombieSessionFix:
adapter._cleanup_ws = _fake_cleanup
adapter._wait_for_handshake = _fake_handshake
with patch("gateway.platforms.wecom.aiohttp.ClientSession", _FakeSession):
with patch("plugins.platforms.wecom.adapter.aiohttp.ClientSession", _FakeSession):
await adapter._open_connection()
assert len(sent_payloads) == 1
@ -747,7 +747,7 @@ class TestWeComZombieSessionFix:
@pytest.mark.asyncio
async def test_on_message_caches_last_req_id_per_chat(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
adapter._text_batch_delay_seconds = 0
@ -773,7 +773,7 @@ class TestWeComZombieSessionFix:
@pytest.mark.asyncio
async def test_on_message_does_not_cache_blocked_sender_req_id(self):
"""Blocked chats shouldn't populate the proactive-send fallback cache."""
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(
PlatformConfig(
@ -802,7 +802,7 @@ class TestWeComZombieSessionFix:
assert "group-blocked" not in adapter._last_chat_req_ids
def test_remember_chat_req_id_is_bounded(self):
from gateway.platforms.wecom import DEDUP_MAX_SIZE, WeComAdapter
from plugins.platforms.wecom.adapter import DEDUP_MAX_SIZE, WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
for i in range(DEDUP_MAX_SIZE + 50):
@ -813,7 +813,7 @@ class TestWeComZombieSessionFix:
assert adapter._last_chat_req_ids[latest] == f"req-{DEDUP_MAX_SIZE + 49}"
def test_remember_chat_req_id_ignores_empty_values(self):
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
adapter._remember_chat_req_id("", "req-1")
@ -826,7 +826,7 @@ class TestWeComZombieSessionFix:
"""Sending into a group without reply_to should use the last cached
req_id via APP_CMD_RESPONSE — WeCom AI Bots cannot initiate APP_CMD_SEND
in group chats (errcode 600039)."""
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
adapter._last_chat_req_ids["group-1"] = "inbound-req-42"
@ -851,7 +851,7 @@ class TestWeComZombieSessionFix:
@pytest.mark.asyncio
async def test_proactive_send_without_cached_req_id_uses_app_cmd_send(self):
"""When we have no prior req_id (fresh DM target), APP_CMD_SEND is used."""
from gateway.platforms.wecom import APP_CMD_SEND, WeComAdapter
from plugins.platforms.wecom.adapter import APP_CMD_SEND, WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
adapter._send_request = AsyncMock(
@ -884,7 +884,7 @@ class TestTextBatchFlushRace:
"""A flush task that has been superseded must leave the event in the
batch dict for the new task to handle."""
from gateway.platforms.base import MessageEvent, MessageType
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
adapter._text_batch_delay_seconds = 0
@ -927,7 +927,7 @@ class TestTextBatchFlushRace:
async def test_active_task_processes_event_normally(self):
"""When the task is not superseded it must still process the event."""
from gateway.platforms.base import MessageEvent, MessageType
from gateway.platforms.wecom import WeComAdapter
from plugins.platforms.wecom.adapter import WeComAdapter
adapter = WeComAdapter(PlatformConfig(enabled=True))
adapter._text_batch_delay_seconds = 0

View file

@ -6,8 +6,8 @@ from xml.etree import ElementTree as ET
import pytest
from gateway.config import PlatformConfig
from gateway.platforms.wecom_callback import WecomCallbackAdapter
from gateway.platforms.wecom_crypto import WXBizMsgCrypt
from plugins.platforms.wecom.callback_adapter import WecomCallbackAdapter
from plugins.platforms.wecom.wecom_crypto import WXBizMsgCrypt
def _app(name="test-app", corp_id="ww1234567890", agent_id="1000002"):
@ -49,7 +49,7 @@ class TestWecomCrypto:
crypt = WXBizMsgCrypt(app["token"], app["encoding_aes_key"], app["corp_id"])
encrypted_xml = crypt.encrypt("<xml/>", nonce="n", timestamp="1")
root = ET.fromstring(encrypted_xml)
from gateway.platforms.wecom_crypto import SignatureError
from plugins.platforms.wecom.wecom_crypto import SignatureError
with pytest.raises(SignatureError):
crypt.decrypt("bad-sig", "1", "n", root.findtext("Encrypt", default=""))

View file

@ -795,7 +795,7 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None,
elif platform == Platform.FEISHU:
result = await _registry_standalone_send("feishu", pconfig, chat_id, chunk, thread_id)
elif platform == Platform.WECOM:
result = await _send_wecom(pconfig.extra, chat_id, chunk)
result = await _registry_standalone_send("wecom", pconfig, chat_id, chunk, thread_id)
elif platform == Platform.BLUEBUBBLES:
result = await _send_bluebubbles(pconfig.extra, chat_id, chunk)
elif platform == Platform.QQBOT:
@ -1443,31 +1443,8 @@ async def _send_matrix_via_adapter(pconfig, chat_id, message, media_files=None,
# wired via standalone_sender_fn and reached through _registry_standalone_send. #41112.
async def _send_wecom(extra, chat_id, message):
"""Send via WeCom using the adapter's WebSocket send pipeline."""
try:
from gateway.platforms.wecom import WeComAdapter, check_wecom_requirements
if not check_wecom_requirements():
return {"error": "WeCom requirements not met. Need aiohttp + WECOM_BOT_ID/SECRET."}
except ImportError:
return {"error": "WeCom adapter not available."}
try:
from gateway.config import PlatformConfig
pconfig = PlatformConfig(extra=extra)
adapter = WeComAdapter(pconfig)
connected = await adapter.connect()
if not connected:
return _error(f"WeCom: failed to connect - {adapter.fatal_error_message or 'unknown error'}")
try:
result = await adapter.send(chat_id, message)
if not result.success:
return _error(f"WeCom send failed: {result.error}")
return {"success": True, "platform": "wecom", "chat_id": chat_id, "message_id": result.message_id}
finally:
await adapter.disconnect()
except Exception as e:
return _error(f"WeCom send failed: {e}")
# _send_wecom moved to plugins/platforms/wecom/adapter.py::_standalone_send,
# wired via standalone_sender_fn and reached through _registry_standalone_send. #41112.
async def _send_weixin(pconfig, chat_id, message, media_files=None):