mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-06-09 23:36:02 +00:00
feat(officialaccount): add eba adapter
This commit is contained in:
158
tests/e2e/live_officialaccount_eba_probe.py
Normal file
158
tests/e2e/live_officialaccount_eba_probe.py
Normal file
@@ -0,0 +1,158 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from quart import Quart, request
|
||||
|
||||
from langbot.pkg.platform.adapters.officialaccount.adapter import OfficialAccountAdapter
|
||||
from langbot_plugin.api.definition.abstract.platform.event_logger import AbstractEventLogger
|
||||
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 ProbeLogger(AbstractEventLogger):
|
||||
async def info(self, text, images=None, message_session_id=None, no_throw=True):
|
||||
print(f'[info] {text}')
|
||||
|
||||
async def debug(self, text, images=None, message_session_id=None, no_throw=True):
|
||||
print(f'[debug] {text}')
|
||||
|
||||
async def warning(self, text, images=None, message_session_id=None, no_throw=True):
|
||||
print(f'[warning] {text}')
|
||||
|
||||
async def error(self, text, images=None, message_session_id=None, no_throw=True):
|
||||
print(f'[error] {text}')
|
||||
|
||||
|
||||
def redact(value: Any) -> Any:
|
||||
if isinstance(value, dict):
|
||||
return {
|
||||
key: '<redacted>' if key.lower() in {'secret', 'token', 'encodingaeskey', 'encrypt', 'appsecret'} else redact(item)
|
||||
for key, item in value.items()
|
||||
}
|
||||
if isinstance(value, list):
|
||||
return [redact(item) for item in value]
|
||||
return value
|
||||
|
||||
|
||||
def summarize_event(event: platform_events.EBAEvent) -> dict:
|
||||
data = {
|
||||
'type': event.type,
|
||||
'adapter_name': event.adapter_name,
|
||||
'timestamp': event.timestamp,
|
||||
}
|
||||
for field in ('message_id', 'chat_id', 'chat_type', 'action', 'data'):
|
||||
if hasattr(event, field):
|
||||
value = getattr(event, field)
|
||||
if hasattr(value, 'value'):
|
||||
value = value.value
|
||||
data[field] = redact(value)
|
||||
if hasattr(event, 'sender') and event.sender is not None:
|
||||
data['sender'] = event.sender.model_dump()
|
||||
if hasattr(event, 'message_chain') and event.message_chain is not None:
|
||||
data['message_chain'] = event.message_chain.model_dump()
|
||||
return data
|
||||
|
||||
|
||||
def record_api(results: list[dict[str, Any]], name: str, ok: bool, result: Any = None, error: Exception | None = None):
|
||||
entry = {'name': name, 'ok': ok}
|
||||
if result is not None:
|
||||
entry['result'] = redact(result)
|
||||
if error is not None:
|
||||
entry['error'] = repr(error)
|
||||
results.append(entry)
|
||||
print('OFFICIALACCOUNT_EBA_API', json.dumps(entry, ensure_ascii=False, default=str))
|
||||
|
||||
|
||||
async def run_api(results: list[dict[str, Any]], name: str, func):
|
||||
try:
|
||||
result = await func()
|
||||
record_api(results, name, True, result)
|
||||
return result
|
||||
except Exception as exc:
|
||||
record_api(results, name, False, error=exc)
|
||||
return None
|
||||
|
||||
|
||||
def config_from_env() -> dict:
|
||||
config = {
|
||||
'token': os.getenv('OFFICIALACCOUNT_TOKEN', ''),
|
||||
'EncodingAESKey': os.getenv('OFFICIALACCOUNT_ENCODING_AES_KEY', ''),
|
||||
'AppSecret': os.getenv('OFFICIALACCOUNT_APP_SECRET', ''),
|
||||
'AppID': os.getenv('OFFICIALACCOUNT_APP_ID', ''),
|
||||
'Mode': os.getenv('OFFICIALACCOUNT_MODE', 'drop'),
|
||||
'LoadingMessage': os.getenv('OFFICIALACCOUNT_LOADING_MESSAGE', 'AI正在思考中,请发送任意内容获取回复。'),
|
||||
'api_base_url': os.getenv('OFFICIALACCOUNT_API_BASE_URL', 'https://api.weixin.qq.com'),
|
||||
}
|
||||
missing = [key for key in ('token', 'EncodingAESKey', 'AppSecret', 'AppID', 'Mode') if not config.get(key)]
|
||||
if missing:
|
||||
raise RuntimeError(f'Missing required OfficialAccount env vars for fields: {missing}')
|
||||
return config
|
||||
|
||||
|
||||
async def run_probe(args: argparse.Namespace):
|
||||
adapter = OfficialAccountAdapter(config_from_env(), ProbeLogger())
|
||||
events: list[platform_events.EBAEvent] = []
|
||||
api_results: list[dict[str, Any]] = []
|
||||
first_message = asyncio.Event()
|
||||
log_path = Path(args.log)
|
||||
log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
async def listener(event, adapter):
|
||||
events.append(event)
|
||||
with log_path.open('a', encoding='utf-8') as fp:
|
||||
fp.write(json.dumps(summarize_event(event), ensure_ascii=False, default=str) + '\n')
|
||||
print('OFFICIALACCOUNT_EBA_EVENT', json.dumps(summarize_event(event), ensure_ascii=False, default=str))
|
||||
if isinstance(event, platform_events.MessageReceivedEvent):
|
||||
first_message.set()
|
||||
|
||||
adapter.register_listener(platform_events.EBAEvent, listener)
|
||||
|
||||
app = Quart(__name__)
|
||||
|
||||
@app.route('/callback', methods=['GET', 'POST'])
|
||||
async def callback():
|
||||
return await adapter.handle_unified_webhook('probe', '', request)
|
||||
|
||||
server_task = asyncio.create_task(app.run_task(host=args.host, port=args.port))
|
||||
try:
|
||||
await asyncio.wait_for(first_message.wait(), timeout=args.timeout)
|
||||
first = next(event for event in events if isinstance(event, platform_events.MessageReceivedEvent))
|
||||
await run_api(api_results, 'reply_message', lambda: adapter.reply_message(first, platform_message.MessageChain([platform_message.Plain(text=args.reply_text)])))
|
||||
await run_api(api_results, 'get_message', lambda: adapter.get_message(first.chat_type.value, first.chat_id, first.message_id))
|
||||
await run_api(api_results, 'get_user_info', lambda: adapter.get_user_info(first.sender.id))
|
||||
await run_api(api_results, 'get_friend_list', adapter.get_friend_list)
|
||||
await run_api(api_results, 'call_platform_api.get_mode', lambda: adapter.call_platform_api('get_mode', {}))
|
||||
finally:
|
||||
server_task.cancel()
|
||||
try:
|
||||
await server_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
summary = {
|
||||
'events': [event.type for event in events],
|
||||
'api_results': api_results,
|
||||
'log': str(log_path),
|
||||
}
|
||||
print('OFFICIALACCOUNT_EBA_SUMMARY', json.dumps(summary, ensure_ascii=False, default=str))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Live OfficialAccount EBA adapter probe')
|
||||
parser.add_argument('--host', default='127.0.0.1')
|
||||
parser.add_argument('--port', type=int, default=5311)
|
||||
parser.add_argument('--timeout', type=float, default=300)
|
||||
parser.add_argument('--log', default='data/temp/officialaccount_eba_probe.jsonl')
|
||||
parser.add_argument('--reply-text', default='OfficialAccount EBA probe reply')
|
||||
args = parser.parse_args()
|
||||
asyncio.run(run_probe(args))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
213
tests/unit_tests/platform/test_officialaccount_eba_adapter.py
Normal file
213
tests/unit_tests/platform/test_officialaccount_eba_adapter.py
Normal file
@@ -0,0 +1,213 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from langbot.libs.official_account_api.oaevent import OAEvent
|
||||
from langbot.pkg.platform.adapters.officialaccount.adapter import OfficialAccountAdapter
|
||||
from langbot.pkg.platform.adapters.officialaccount.errors import NotSupportedError
|
||||
from langbot.pkg.platform.adapters.officialaccount.event_converter import OfficialAccountEventConverter
|
||||
from langbot.pkg.platform.adapters.officialaccount.message_converter import OfficialAccountMessageConverter
|
||||
from langbot.pkg.platform.adapters.officialaccount.platform_api import PLATFORM_API_MAP
|
||||
from langbot_plugin.api.definition.abstract.platform.event_logger import AbstractEventLogger
|
||||
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 DummyLogger(AbstractEventLogger):
|
||||
async def info(self, text, images=None, message_session_id=None, no_throw=True):
|
||||
pass
|
||||
|
||||
async def debug(self, text, images=None, message_session_id=None, no_throw=True):
|
||||
pass
|
||||
|
||||
async def warning(self, text, images=None, message_session_id=None, no_throw=True):
|
||||
pass
|
||||
|
||||
async def error(self, text, images=None, message_session_id=None, no_throw=True):
|
||||
pass
|
||||
|
||||
|
||||
class DummyOAClient:
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.token = kwargs['token']
|
||||
self.aes = kwargs['EncodingAESKey']
|
||||
self.appid = kwargs['AppID']
|
||||
self.appsecret = kwargs['Appsecret']
|
||||
self.base_url = kwargs.get('api_base_url')
|
||||
self._message_handlers = {}
|
||||
self.generated_content = {}
|
||||
self.handle_unified_webhook = AsyncMock(return_value='success')
|
||||
self.set_message = AsyncMock(return_value=None)
|
||||
|
||||
def on_message(self, msg_type: str):
|
||||
def decorator(func):
|
||||
self._message_handlers.setdefault(msg_type, []).append(func)
|
||||
return func
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
class DummyLongerOAClient(DummyOAClient):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.loading_message = kwargs['LoadingMessage']
|
||||
self.msg_queue = {}
|
||||
|
||||
|
||||
def manifest() -> dict:
|
||||
manifest_path = (
|
||||
pathlib.Path(__file__).parents[3]
|
||||
/ 'src'
|
||||
/ 'langbot'
|
||||
/ 'pkg'
|
||||
/ 'platform'
|
||||
/ 'adapters'
|
||||
/ 'officialaccount'
|
||||
/ 'manifest.yaml'
|
||||
)
|
||||
return yaml.safe_load(manifest_path.read_text())
|
||||
|
||||
|
||||
def make_adapter(mode: str = 'drop') -> OfficialAccountAdapter:
|
||||
config = {
|
||||
'token': 'token',
|
||||
'EncodingAESKey': 'encoding-key',
|
||||
'AppSecret': 'secret',
|
||||
'AppID': 'app-id',
|
||||
'Mode': mode,
|
||||
'LoadingMessage': 'loading',
|
||||
}
|
||||
with (
|
||||
patch('langbot.pkg.platform.adapters.officialaccount.adapter.OAClient', DummyOAClient),
|
||||
patch('langbot.pkg.platform.adapters.officialaccount.adapter.OAClientForLongerResponse', DummyLongerOAClient),
|
||||
):
|
||||
return OfficialAccountAdapter(config, DummyLogger())
|
||||
|
||||
|
||||
def oa_event(**overrides) -> OAEvent:
|
||||
payload = {
|
||||
'ToUserName': overrides.get('to_user', 'gh_app'),
|
||||
'FromUserName': overrides.get('from_user', 'openid-1'),
|
||||
'CreateTime': overrides.get('timestamp', 1710000000),
|
||||
'MsgType': overrides.get('msgtype', 'text'),
|
||||
'Content': overrides.get('content', 'hello'),
|
||||
'MsgId': overrides.get('message_id', 123),
|
||||
}
|
||||
if payload['MsgType'] == 'image':
|
||||
payload.update({'PicUrl': 'https://example.test/a.jpg', 'MediaId': 'media-1', 'Content': None})
|
||||
if payload['MsgType'] == 'voice':
|
||||
payload.update({'MediaId': 'voice-1', 'Content': None})
|
||||
if payload['MsgType'] == 'event':
|
||||
payload.update({'Event': overrides.get('event', 'subscribe'), 'EventKey': 'qrscene_1', 'Content': None})
|
||||
return OAEvent(payload)
|
||||
|
||||
|
||||
def test_officialaccount_supported_events_match_manifest():
|
||||
assert make_adapter().get_supported_events() == manifest()['spec']['supported_events']
|
||||
|
||||
|
||||
def test_officialaccount_supported_apis_match_manifest():
|
||||
supported_apis = make_adapter().get_supported_apis()
|
||||
manifest_apis = manifest()['spec']['supported_apis']
|
||||
|
||||
assert supported_apis == manifest_apis['required'] + manifest_apis['optional']
|
||||
|
||||
|
||||
def test_officialaccount_platform_api_map_matches_manifest():
|
||||
manifest_actions = {item['action'] for item in manifest()['spec']['platform_specific_apis']}
|
||||
|
||||
assert set(PLATFORM_API_MAP) == manifest_actions
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_officialaccount_message_converter_maps_components_to_passive_text():
|
||||
content = await OfficialAccountMessageConverter.yiri2target(
|
||||
platform_message.MessageChain(
|
||||
[
|
||||
platform_message.Plain(text='hi'),
|
||||
platform_message.Image(url='https://example.test/a.png'),
|
||||
platform_message.File(name='a.txt', url='https://example.test/a.txt'),
|
||||
platform_message.Quote(origin=platform_message.MessageChain([platform_message.Plain(text='quoted')])),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
assert 'hi' in content
|
||||
assert '[Image]' in content
|
||||
assert '[File: a.txt]' in content
|
||||
assert 'quoted' in content
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_officialaccount_event_converter_maps_text_image_voice_and_platform_event():
|
||||
text_event = await OfficialAccountEventConverter().target2yiri(oa_event(content='hello'))
|
||||
image_event = await OfficialAccountEventConverter().target2yiri(oa_event(msgtype='image'))
|
||||
voice_event = await OfficialAccountEventConverter().target2yiri(oa_event(msgtype='voice'))
|
||||
subscribe_event = await OfficialAccountEventConverter().target2yiri(oa_event(msgtype='event', event='subscribe'))
|
||||
|
||||
assert isinstance(text_event, platform_events.MessageReceivedEvent)
|
||||
assert text_event.adapter_name == 'officialaccount-eba'
|
||||
assert text_event.chat_type == platform_entities.ChatType.PRIVATE
|
||||
assert text_event.chat_id == 'openid-1'
|
||||
assert str(text_event.message_chain) == 'hello'
|
||||
|
||||
assert isinstance(image_event.message_chain[1], platform_message.Image)
|
||||
assert image_event.message_chain[1].image_id == 'media-1'
|
||||
assert isinstance(voice_event.message_chain[1], platform_message.Voice)
|
||||
assert voice_event.message_chain[1].voice_id == 'voice-1'
|
||||
assert isinstance(subscribe_event, platform_events.PlatformSpecificEvent)
|
||||
assert subscribe_event.action == 'officialaccount.subscribe'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_officialaccount_adapter_dispatches_eba_and_legacy_and_caches_message_event():
|
||||
adapter = make_adapter()
|
||||
eba_calls: list[platform_events.Event] = []
|
||||
legacy_calls: list[platform_events.Event] = []
|
||||
|
||||
async def eba_listener(event, adapter):
|
||||
eba_calls.append(event)
|
||||
|
||||
async def legacy_listener(event, adapter):
|
||||
legacy_calls.append(event)
|
||||
|
||||
adapter.register_listener(platform_events.MessageReceivedEvent, eba_listener)
|
||||
adapter.register_listener(platform_events.FriendMessage, legacy_listener)
|
||||
await adapter._handle_native_event(oa_event())
|
||||
|
||||
assert len(eba_calls) == 1
|
||||
assert len(legacy_calls) == 1
|
||||
received = eba_calls[0]
|
||||
assert isinstance(received, platform_events.MessageReceivedEvent)
|
||||
assert await adapter.get_message('private', 'openid-1', 123) == received
|
||||
assert (await adapter.get_user_info('openid-1')).nickname == 'openid-1'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_officialaccount_reply_platform_api_and_unsupported_send():
|
||||
adapter = make_adapter()
|
||||
source_event = await OfficialAccountEventConverter().target2yiri(oa_event())
|
||||
message = platform_message.MessageChain([platform_message.Plain(text='reply')])
|
||||
|
||||
await adapter.reply_message(source_event, message)
|
||||
adapter.bot.set_message.assert_awaited_once_with(123, 'reply')
|
||||
|
||||
assert await adapter.call_platform_api('get_mode', {}) == {'mode': 'drop', 'longer_response': False}
|
||||
|
||||
with pytest.raises(NotSupportedError):
|
||||
await adapter.send_message('person', 'openid-1', message)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_officialaccount_passive_mode_reply_queues_by_user():
|
||||
adapter = make_adapter(mode='passive')
|
||||
source_event = await OfficialAccountEventConverter().target2yiri(oa_event())
|
||||
|
||||
await adapter.reply_message(source_event, platform_message.MessageChain([platform_message.Plain(text='reply')]))
|
||||
|
||||
adapter.bot.set_message.assert_awaited_once_with('openid-1', 123, 'reply')
|
||||
Reference in New Issue
Block a user