feat(officialaccount): add eba adapter

This commit is contained in:
WangCham
2026-05-28 16:59:26 +08:00
parent 4b9aa20985
commit 8a42fd8b21
16 changed files with 1099 additions and 4 deletions

View File

@@ -93,15 +93,30 @@ class OAClient:
raise Exception('msg_signature不在请求体中')
if req.method == 'GET':
# 校验签名
if msg_signature:
wxcpt = WXBizMsgCrypt(self.token, self.aes, self.appid)
ret, reply_echo = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr)
if ret == 0:
return reply_echo
await self.logger.error(
'OfficialAccount encrypted URL verification failed: '
f'ret={ret}, timestamp_present={bool(timestamp)}, nonce_present={bool(nonce)}, '
f'echostr_present={bool(echostr)}'
)
# Plaintext callback verification.
check_str = ''.join(sorted([self.token, timestamp, nonce]))
check_signature = hashlib.sha1(check_str.encode('utf-8')).hexdigest()
if check_signature == signature:
return echostr # 验证成功返回echostr
else:
await self.logger.error('拒绝请求')
raise Exception('拒绝请求')
await self.logger.error(
'OfficialAccount plaintext URL verification failed: '
f'signature_present={bool(signature)}, timestamp_present={bool(timestamp)}, '
f'nonce_present={bool(nonce)}, echostr_present={bool(echostr)}'
)
return 'signature verification failed', 403
elif req.method == 'POST':
encryt_msg = await req.data
wxcpt = WXBizMsgCrypt(self.token, self.aes, self.appid)
@@ -279,9 +294,27 @@ class OAClientForLongerResponse:
raise Exception('msg_signature不在请求体中')
if req.method == 'GET':
if msg_signature:
wxcpt = WXBizMsgCrypt(self.token, self.aes, self.appid)
ret, reply_echo = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr)
if ret == 0:
return reply_echo
await self.logger.error(
'OfficialAccount encrypted URL verification failed: '
f'ret={ret}, timestamp_present={bool(timestamp)}, nonce_present={bool(nonce)}, '
f'echostr_present={bool(echostr)}'
)
check_str = ''.join(sorted([self.token, timestamp, nonce]))
check_signature = hashlib.sha1(check_str.encode('utf-8')).hexdigest()
return echostr if check_signature == signature else '拒绝请求'
if check_signature == signature:
return echostr
await self.logger.error(
'OfficialAccount plaintext URL verification failed: '
f'signature_present={bool(signature)}, timestamp_present={bool(timestamp)}, '
f'nonce_present={bool(nonce)}, echostr_present={bool(echostr)}'
)
return 'signature verification failed', 403
elif req.method == 'POST':
encryt_msg = await req.data

View File

@@ -0,0 +1,5 @@
from __future__ import annotations
from langbot.pkg.platform.adapters.officialaccount.adapter import OfficialAccountAdapter
__all__ = ['OfficialAccountAdapter']

View File

@@ -0,0 +1,195 @@
from __future__ import annotations
import asyncio
import traceback
import typing
import pydantic
from langbot.libs.official_account_api.api import OAClient, OAClientForLongerResponse
from langbot.libs.official_account_api.oaevent import OAEvent
from langbot.pkg.platform.adapters.officialaccount.api_impl import OfficialAccountAPIMixin
from langbot.pkg.platform.adapters.officialaccount.event_converter import OfficialAccountEventConverter
from langbot.pkg.platform.adapters.officialaccount.errors import NotSupportedError
from langbot.pkg.platform.adapters.officialaccount.message_converter import OfficialAccountMessageConverter
from langbot.pkg.platform.adapters.officialaccount.platform_api import PLATFORM_API_MAP
import langbot_plugin.api.definition.abstract.platform.adapter as abstract_platform_adapter
import langbot_plugin.api.definition.abstract.platform.event_logger as abstract_platform_logger
from langbot_plugin.api.entities.builtin.platform import entities as platform_entities
from langbot_plugin.api.entities.builtin.platform import events as platform_events
from langbot_plugin.api.entities.builtin.platform import message as platform_message
class OfficialAccountAdapter(OfficialAccountAPIMixin, abstract_platform_adapter.AbstractPlatformAdapter):
bot: typing.Any = pydantic.Field(exclude=True)
message_converter: OfficialAccountMessageConverter = OfficialAccountMessageConverter()
event_converter: OfficialAccountEventConverter = OfficialAccountEventConverter()
config: dict
bot_uuid: str | None = None
listeners: dict[
typing.Type[platform_events.Event],
typing.Callable[[platform_events.Event, abstract_platform_adapter.AbstractMessagePlatformAdapter], None],
] = {}
_message_cache: dict[str, platform_events.MessageReceivedEvent] = {}
_user_cache: dict[str, platform_entities.User] = {}
class Config:
arbitrary_types_allowed = True
def __init__(self, config: dict, logger: abstract_platform_logger.AbstractEventLogger):
required_keys = ['token', 'EncodingAESKey', 'AppSecret', 'AppID', 'Mode']
missing_keys = [key for key in required_keys if not config.get(key)]
if missing_keys:
raise Exception(f'OfficialAccount EBA adapter missing config: {missing_keys}')
mode = config['Mode']
common_kwargs = {
'token': config['token'],
'EncodingAESKey': config['EncodingAESKey'],
'Appsecret': config['AppSecret'],
'AppID': config['AppID'],
'logger': logger,
'unified_mode': True,
'api_base_url': config.get('api_base_url', 'https://api.weixin.qq.com'),
}
if mode == 'drop':
bot = OAClient(**common_kwargs)
elif mode == 'passive':
bot = OAClientForLongerResponse(
**common_kwargs,
LoadingMessage=config.get('LoadingMessage', ''),
)
else:
raise KeyError('OfficialAccount Mode must be "drop" or "passive"')
super().__init__(
config=config,
logger=logger,
bot=bot,
bot_account_id=config.get('AppID', ''),
bot_uuid=None,
listeners={},
_message_cache={},
_user_cache={},
)
self._register_native_handlers()
def set_bot_uuid(self, bot_uuid: str):
self.bot_uuid = bot_uuid
def get_supported_events(self) -> list[str]:
return [
'message.received',
'platform.specific',
]
def get_supported_apis(self) -> list[str]:
return [
'reply_message',
'get_message',
'get_user_info',
'get_friend_list',
'call_platform_api',
]
async def send_message(
self,
target_type: str,
target_id: str,
message: platform_message.MessageChain,
) -> platform_events.MessageResult:
raise NotSupportedError('send_message:official_account_requires_inbound_webhook_reply')
async def reply_message(
self,
message_source: platform_events.MessageEvent,
message: platform_message.MessageChain,
quote_origin: bool = False,
) -> platform_events.MessageResult:
source = await OfficialAccountEventConverter.yiri2target(message_source)
if not isinstance(source, OAEvent):
raise ValueError('OfficialAccount reply_message requires an OAEvent source object')
content = await OfficialAccountMessageConverter.yiri2target(message)
if self.config.get('Mode') == 'passive':
await self.bot.set_message(source.user_id, source.message_id, content)
else:
await self.bot.set_message(source.message_id, content)
return platform_events.MessageResult(message_id=source.message_id, raw={'queued': True})
async def call_platform_api(self, action: str, params: dict = {}) -> dict:
handler = PLATFORM_API_MAP.get(action)
if handler is None:
raise NotSupportedError(f'call_platform_api:{action}')
params = dict(params or {})
params.setdefault('mode', self.config.get('Mode'))
return await handler(self.bot, params)
def register_listener(
self,
event_type: typing.Type[platform_events.Event],
callback: typing.Callable[
[platform_events.Event, abstract_platform_adapter.AbstractMessagePlatformAdapter], None
],
):
self.listeners[event_type] = callback
def unregister_listener(
self,
event_type: typing.Type[platform_events.Event],
callback: typing.Callable[
[platform_events.Event, abstract_platform_adapter.AbstractMessagePlatformAdapter], None
],
):
registered = self.listeners.get(event_type)
if registered is callback:
self.listeners.pop(event_type, None)
async def handle_unified_webhook(self, bot_uuid: str, path: str, request):
return await self.bot.handle_unified_webhook(request)
async def run_async(self):
async def keep_alive():
while True:
await asyncio.sleep(1)
await self.logger.info('OfficialAccount EBA adapter running in unified webhook mode')
await keep_alive()
async def kill(self) -> bool:
return True
async def is_muted(self, group_id: int | None = None) -> bool:
return False
def _register_native_handlers(self):
for msg_type in ('text', 'image', 'voice', 'event'):
self.bot.on_message(msg_type)(self._handle_native_event)
async def _handle_native_event(self, event: OAEvent):
self.bot_account_id = event.receiver_id or self.bot_account_id
try:
if platform_events.FriendMessage in self.listeners:
legacy_event = await self.event_converter.target2legacy(event)
if legacy_event and platform_events.FriendMessage in self.listeners:
await self.listeners[platform_events.FriendMessage](legacy_event, self)
eba_event = await self.event_converter.target2yiri(event)
if eba_event:
self._cache_event(eba_event)
await self._dispatch_eba_event(eba_event)
except Exception:
await self.logger.error(f'Error in officialaccount native event: {traceback.format_exc()}')
async def _dispatch_eba_event(self, event: platform_events.EBAEvent):
for event_type in (type(event), platform_events.EBAEvent, platform_events.Event):
callback = self.listeners.get(event_type)
if callback:
await callback(event, self)
return
def _cache_event(self, event: platform_events.Event):
if isinstance(event, platform_events.MessageReceivedEvent):
self._message_cache[str(event.message_id)] = event
self._user_cache[str(event.sender.id)] = event.sender

View File

@@ -0,0 +1,85 @@
from __future__ import annotations
import typing
from langbot_plugin.api.entities.builtin.platform import entities as platform_entities
from langbot_plugin.api.entities.builtin.platform import events as platform_events
from langbot_plugin.api.entities.builtin.platform import message as platform_message
from langbot.pkg.platform.adapters.officialaccount.errors import NotSupportedError
class OfficialAccountAPIMixin:
_message_cache: dict[str, platform_events.MessageReceivedEvent]
_user_cache: dict[str, platform_entities.User]
async def get_message(
self,
chat_type: str,
chat_id: typing.Union[int, str],
message_id: typing.Union[int, str],
) -> platform_events.MessageReceivedEvent:
event = self._message_cache.get(str(message_id))
if event is None:
raise NotSupportedError('get_message:message_not_cached')
return event
async def get_user_info(self, user_id: typing.Union[int, str]) -> platform_entities.User:
user = self._user_cache.get(str(user_id))
if user is None:
raise NotSupportedError('get_user_info:not_cached')
return user
async def get_friend_list(self) -> list[platform_entities.User]:
return list(self._user_cache.values())
async def edit_message(
self,
chat_type: str,
chat_id: typing.Union[int, str],
message_id: typing.Union[int, str],
new_content: platform_message.MessageChain,
) -> None:
raise NotSupportedError('edit_message')
async def delete_message(
self,
chat_type: str,
chat_id: typing.Union[int, str],
message_id: typing.Union[int, str],
) -> None:
raise NotSupportedError('delete_message')
async def forward_message(
self,
from_chat_type: str,
from_chat_id: typing.Union[int, str],
message_id: typing.Union[int, str],
to_chat_type: str,
to_chat_id: typing.Union[int, str],
) -> platform_events.MessageResult:
raise NotSupportedError('forward_message')
async def upload_file(self, file_data: bytes, filename: str) -> str:
raise NotSupportedError('upload_file')
async def get_file_url(self, file_id: str) -> str:
raise NotSupportedError('get_file_url')
async def get_group_info(self, group_id: typing.Union[int, str]) -> platform_entities.UserGroup:
raise NotSupportedError('get_group_info')
async def get_group_list(self) -> list[platform_entities.UserGroup]:
raise NotSupportedError('get_group_list')
async def get_group_member_list(
self,
group_id: typing.Union[int, str],
) -> list[platform_entities.UserGroupMember]:
raise NotSupportedError('get_group_member_list')
async def get_group_member_info(
self,
group_id: typing.Union[int, str],
user_id: typing.Union[int, str],
) -> platform_entities.UserGroupMember:
raise NotSupportedError('get_group_member_info')

View File

@@ -0,0 +1,10 @@
from __future__ import annotations
try:
from langbot_plugin.api.entities.builtin.platform.errors import NotSupportedError
except ModuleNotFoundError:
class NotSupportedError(Exception):
def __init__(self, api_name: str, *args):
super().__init__(f"API '{api_name}' is not supported by this adapter", *args)
self.api_name = api_name

View File

@@ -0,0 +1,66 @@
from __future__ import annotations
import time
import typing
from langbot.libs.official_account_api.oaevent import OAEvent
from langbot.pkg.platform.adapters.officialaccount.message_converter import OfficialAccountMessageConverter
from langbot.pkg.platform.adapters.officialaccount.types import ADAPTER_NAME
import langbot_plugin.api.definition.abstract.platform.adapter as abstract_platform_adapter
from langbot_plugin.api.entities.builtin.platform import entities as platform_entities
from langbot_plugin.api.entities.builtin.platform import events as platform_events
class OfficialAccountEventConverter(abstract_platform_adapter.AbstractEventConverter):
@staticmethod
async def yiri2target(event: platform_events.Event) -> typing.Any:
return getattr(event, 'source_platform_object', None)
async def target2legacy(self, event: OAEvent) -> platform_events.FriendMessage | None:
eba_event = await self.target2yiri(event)
if not isinstance(eba_event, platform_events.MessageReceivedEvent):
return None
return platform_events.FriendMessage(
sender=platform_entities.Friend(
id=eba_event.sender.id,
nickname=eba_event.sender.nickname,
remark='',
),
message_chain=eba_event.message_chain,
time=eba_event.timestamp,
source_platform_object=event,
)
async def target2yiri(self, event: OAEvent) -> platform_events.Event | None:
if event.type in {'text', 'image', 'voice'}:
return await self.message_to_eba(event)
return self.platform_specific(event, f'officialaccount.{event.detail_type or event.type or "unknown"}')
async def message_to_eba(self, event: OAEvent) -> platform_events.MessageReceivedEvent:
sender_id = event.user_id or ''
timestamp = float(event.timestamp or time.time())
return platform_events.MessageReceivedEvent(
type='message.received',
adapter_name=ADAPTER_NAME,
message_id=event.message_id or f'{sender_id}:{int(timestamp)}',
message_chain=await OfficialAccountMessageConverter.target2yiri(event),
sender=platform_entities.User(
id=sender_id,
nickname=sender_id,
),
chat_type=platform_entities.ChatType.PRIVATE,
chat_id=sender_id,
timestamp=timestamp,
source_platform_object=event,
)
@staticmethod
def platform_specific(event: OAEvent, action: str) -> platform_events.PlatformSpecificEvent:
return platform_events.PlatformSpecificEvent(
type='platform.specific',
adapter_name=ADAPTER_NAME,
action=action,
data=dict(event),
timestamp=float(event.timestamp or time.time()),
source_platform_object=event,
)

View File

@@ -0,0 +1,123 @@
apiVersion: v1
kind: MessagePlatformAdapter
metadata:
name: officialaccount-eba
label:
en_US: Official Account (EBA)
zh_Hans: 微信公众号 (EBA)
zh_Hant: 微信公眾號 (EBA)
description:
en_US: WeChat Official Account adapter with Event-Based Agents support
zh_Hans: 微信公众号适配器EBA 架构版本),通过统一 Webhook 接收公众号消息
zh_Hant: 微信公眾號適配器EBA 架構版本),透過統一 Webhook 接收公眾號訊息
icon: officialaccount.png
spec:
categories:
- china
help_links:
zh: https://link.langbot.app/zh/platforms/officialaccount
en: https://link.langbot.app/en/platforms/officialaccount
ja: https://link.langbot.app/ja/platforms/officialaccount
config:
- name: webhook_url
label:
en_US: Webhook Callback URL
zh_Hans: Webhook 回调地址
zh_Hant: Webhook 回調地址
description:
en_US: Copy this URL and paste it into your Official Account webhook configuration.
zh_Hans: 复制此地址并粘贴到微信公众号的 Webhook 配置中。
zh_Hant: 複製此地址並貼到微信公眾號的 Webhook 設定中。
type: webhook-url
required: false
default: ""
- name: token
label:
en_US: Token
zh_Hans: 令牌
zh_Hant: 令牌
type: string
required: true
default: ""
- name: EncodingAESKey
label:
en_US: EncodingAESKey
zh_Hans: 消息加解密密钥
zh_Hant: 訊息加解密密鑰
type: string
required: true
default: ""
- name: AppID
label:
en_US: App ID
zh_Hans: 应用 ID
zh_Hant: 應用 ID
type: string
required: true
default: ""
- name: AppSecret
label:
en_US: App Secret
zh_Hans: 应用密钥
zh_Hant: 應用密鑰
type: string
required: true
default: ""
- name: Mode
label:
en_US: Mode
zh_Hans: 接入模式
zh_Hant: 接入模式
description:
en_US: "drop replies within the current callback; passive returns a loading message first and queues the real reply for the user's next message."
zh_Hans: "drop 会在当前回调内等待回复passive 会先返回加载提示,并将真实回复排队到用户下一条消息。"
zh_Hant: "drop 會在目前回調內等待回覆passive 會先回傳載入提示,並將真實回覆排隊到使用者下一則訊息。"
type: string
required: true
default: "drop"
- name: LoadingMessage
label:
en_US: Loading Message
zh_Hans: 加载消息
zh_Hant: 載入訊息
type: string
required: false
default: "AI正在思考中请发送任意内容获取回复。"
- name: api_base_url
label:
en_US: API Base URL
zh_Hans: API 基础 URL
zh_Hant: API 基礎 URL
description:
en_US: Optional Official Account API base URL, useful when routing through a reverse proxy.
zh_Hans: 可选,若通过反向代理访问微信公众号 API可修改此项。
zh_Hant: 可選,若透過反向代理存取微信公眾號 API可修改此項。
type: string
required: false
default: "https://api.weixin.qq.com"
supported_events:
- message.received
- platform.specific
supported_apis:
required:
- reply_message
optional:
- get_message
- get_user_info
- get_friend_list
- call_platform_api
platform_specific_apis:
- action: get_mode
description: { en_US: "Return the configured Official Account reply mode", zh_Hans: "返回当前微信公众号回复模式" }
- action: get_cached_response_status
description: { en_US: "Inspect cached passive/drop reply state for diagnostics", zh_Hans: "查看被动回复缓存状态,用于诊断" }
execution:
python:
path: ./adapter.py
attr: OfficialAccountAdapter

View File

@@ -0,0 +1,72 @@
from __future__ import annotations
import datetime
from langbot.libs.official_account_api.oaevent import OAEvent
import langbot_plugin.api.definition.abstract.platform.adapter as abstract_platform_adapter
from langbot_plugin.api.entities.builtin.platform import message as platform_message
class OfficialAccountMessageConverter(abstract_platform_adapter.AbstractMessageConverter):
@staticmethod
async def yiri2target(message_chain: platform_message.MessageChain) -> str:
content_parts: list[str] = []
for component in message_chain:
if isinstance(component, platform_message.Source):
continue
if isinstance(component, platform_message.Plain):
content_parts.append(component.text)
elif isinstance(component, platform_message.At):
content_parts.append(f'@{component.display or component.target}')
elif isinstance(component, platform_message.AtAll):
content_parts.append('@all')
elif isinstance(component, platform_message.Image):
content_parts.append('[Image]')
elif isinstance(component, platform_message.Voice):
content_parts.append('[Voice]')
elif isinstance(component, platform_message.File):
content_parts.append(f'[File: {component.name or component.id or component.url or "file"}]')
elif isinstance(component, platform_message.Quote):
if component.id is not None:
content_parts.append(f'[Quote {component.id}]')
if component.origin:
content_parts.append(await OfficialAccountMessageConverter.yiri2target(component.origin))
elif isinstance(component, platform_message.Forward):
for node in component.node_list:
if node.message_chain:
content_parts.append(await OfficialAccountMessageConverter.yiri2target(node.message_chain))
else:
content_parts.append(str(component))
return '\n'.join(part for part in content_parts if part)
@staticmethod
async def target2yiri(event: OAEvent) -> platform_message.MessageChain:
timestamp = event.timestamp or int(datetime.datetime.now().timestamp())
components: list[platform_message.MessageComponent] = [
platform_message.Source(
id=event.message_id or f'{event.user_id}:{timestamp}',
time=datetime.datetime.fromtimestamp(timestamp),
)
]
if event.type == 'text' and event.message:
components.append(platform_message.Plain(text=event.message))
elif event.type == 'image':
image_kwargs = {}
if event.picurl:
image_kwargs['url'] = event.picurl
if event.media_id:
image_kwargs['image_id'] = event.media_id
if image_kwargs:
components.append(platform_message.Image(**image_kwargs))
elif event.type == 'voice':
if event.media_id:
components.append(platform_message.Voice(voice_id=event.media_id))
else:
components.append(platform_message.Unknown(text='[officialaccount voice message without media id]'))
elif event.type == 'event':
components.append(platform_message.Unknown(text=f'[officialaccount event: {event.detail_type or "unknown"}]'))
else:
components.append(platform_message.Unknown(text=f'[unsupported officialaccount msgtype: {event.type or "unknown"}]'))
return platform_message.MessageChain(components)

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

View File

@@ -0,0 +1,27 @@
from __future__ import annotations
import typing
async def get_mode(bot, params: dict) -> dict:
return {
'mode': params.get('mode') or ('passive' if hasattr(bot, 'msg_queue') else 'drop'),
'longer_response': hasattr(bot, 'msg_queue'),
}
async def get_cached_response_status(bot, params: dict) -> dict:
message_id = params.get('message_id') or params.get('msg_id')
user_id = params.get('user_id') or params.get('from_user')
if hasattr(bot, 'generated_content'):
return {'pending': str(message_id) in {str(key) for key in bot.generated_content}}
if hasattr(bot, 'msg_queue'):
queue = bot.msg_queue.get(str(user_id), []) if user_id is not None else []
return {'queued': len(queue)}
return {'pending': False}
PLATFORM_API_MAP: dict[str, typing.Callable[[typing.Any, dict], typing.Awaitable[dict]]] = {
'get_mode': get_mode,
'get_cached_response_status': get_cached_response_status,
}

View File

@@ -0,0 +1,3 @@
from __future__ import annotations
ADAPTER_NAME = 'officialaccount-eba'