该提交实现了支持企业微信、微信公众号、个人微信桥接三种模式的完整微信渠道适配器,包含以下核心模块: 1. 基础认证与配置相关:auth_adapter、config_reload、setup_contract等 2. 消息处理与格式转换:format、attachment_adapter、outbound_adapter等 3. 多模式客户端支持:wecom/mp子模块,包含加解密、消息收发能力 4. 辅助能力:限速器、防抖、会话绑定、事件映射、模板渲染等 5. 扩展能力:二维码登录、消息读取、特权用户、心跳监控等 实现了完整的微信生态对接能力,支持消息收发、事件处理、API调用限流、配置热重载等功能。
79 lines
2.3 KiB
Python
79 lines
2.3 KiB
Python
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
from yuxi.channels.models import ChatType, EventType
|
|
|
|
WECHAT_TO_UNIFIED_MESSAGE_TYPE: dict[str, str] = {
|
|
"text": "text",
|
|
"image": "image",
|
|
"voice": "voice",
|
|
"video": "video",
|
|
"file": "file",
|
|
"link": "link",
|
|
"location": "location",
|
|
"event": "event",
|
|
"news": "news",
|
|
}
|
|
|
|
WECHAT_TO_UNIFIED_EVENT_TYPE: dict[str, str] = {
|
|
"subscribe": "subscribe",
|
|
"unsubscribe": "unsubscribe",
|
|
"CLICK": "click",
|
|
"VIEW": "view",
|
|
"LOCATION": "location_event",
|
|
"scancode_push": "scancode",
|
|
"scancode_waitmsg": "scancode",
|
|
"enter_agent": "enter_agent",
|
|
}
|
|
|
|
WECHAT_MODE_LABEL: dict[str, str] = {
|
|
"wecom": "WeCom",
|
|
"mp": "Official Account",
|
|
"personal": "Personal Bridge",
|
|
}
|
|
|
|
|
|
def map_message_type(wechat_msg_type: str) -> str:
|
|
return WECHAT_TO_UNIFIED_MESSAGE_TYPE.get(wechat_msg_type, wechat_msg_type)
|
|
|
|
|
|
def map_event_type(wechat_event_type: str) -> str:
|
|
return WECHAT_TO_UNIFIED_EVENT_TYPE.get(wechat_event_type, wechat_event_type)
|
|
|
|
|
|
def map_chat_type(from_user: str, to_user: str, chat_id: str = "") -> ChatType:
|
|
if chat_id and chat_id != from_user:
|
|
return ChatType.GROUP
|
|
return ChatType.DIRECT
|
|
|
|
|
|
def map_event(wechat_event_type: str) -> EventType | None:
|
|
mapping: dict[str, EventType] = {
|
|
"subscribe": EventType.USER_JOIN,
|
|
"unsubscribe": EventType.USER_LEAVE,
|
|
"CLICK": EventType.MESSAGE,
|
|
"enter_agent": EventType.MESSAGE,
|
|
}
|
|
return mapping.get(wechat_event_type)
|
|
|
|
|
|
def map_wechat_error(errcode: int, errmsg: str) -> dict[str, Any]:
|
|
error_map: dict[int, tuple[str, str]] = {
|
|
40001: ("invalid_credential", "Invalid access token"),
|
|
40014: ("invalid_token", "Invalid access token"),
|
|
41001: ("access_token_missing", "Access token missing"),
|
|
42001: ("token_expired", "Access token expired"),
|
|
48001: ("api_unauthorized", "API not authorized"),
|
|
}
|
|
code, message = error_map.get(errcode, ("unknown", errmsg))
|
|
return {"code": code, "message": message}
|
|
|
|
|
|
def build_channel_identity(mode: str, from_user: str, chat_id: str) -> dict[str, Any]:
|
|
return {
|
|
"channel_user_id": f"wx:{from_user}",
|
|
"channel_chat_id": f"wx:{chat_id}" if chat_id else f"wx:{from_user}",
|
|
"wechat_mode": mode,
|
|
}
|