mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-06-08 23:06:03 +00:00
feat(platform): add slack eba adapter
This commit is contained in:
161
tests/e2e/live_slack_eba_probe.py
Normal file
161
tests/e2e/live_slack_eba_probe.py
Normal file
@@ -0,0 +1,161 @@
|
||||
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.slack.adapter import SlackAdapter
|
||||
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):
|
||||
secret_keys = {'token', 'signing_secret', 'authorization', 'access_token'}
|
||||
return {key: '<redacted>' if key.lower() in secret_keys 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, 'group') and event.group is not None:
|
||||
data['group'] = event.group.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('SLACK_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 = {
|
||||
'bot_token': os.getenv('SLACK_BOT_TOKEN', ''),
|
||||
'signing_secret': os.getenv('SLACK_SIGNING_SECRET', ''),
|
||||
'bot_user_id': os.getenv('SLACK_BOT_USER_ID', ''),
|
||||
}
|
||||
missing = [key for key in ('bot_token', 'signing_secret') if not config.get(key)]
|
||||
if missing:
|
||||
raise RuntimeError(f'Missing required Slack env vars for fields: {missing}')
|
||||
return config
|
||||
|
||||
|
||||
async def run_probe(args: argparse.Namespace):
|
||||
adapter = SlackAdapter(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)
|
||||
summary = summarize_event(event)
|
||||
with log_path.open('a', encoding='utf-8') as fp:
|
||||
fp.write(json.dumps(summary, ensure_ascii=False, default=str) + '\n')
|
||||
print('SLACK_EBA_EVENT', json.dumps(summary, 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)
|
||||
if getattr(first, 'group', None):
|
||||
await run_api(api_results, 'get_group_info', lambda: adapter.get_group_info(first.group.id))
|
||||
await run_api(api_results, 'get_group_member_info', lambda: adapter.get_group_member_info(first.group.id, first.sender.id))
|
||||
await run_api(api_results, 'get_group_member_list', lambda: adapter.get_group_member_list(first.group.id))
|
||||
await run_api(api_results, 'call_platform_api.get_mode', lambda: adapter.call_platform_api('get_mode', {}))
|
||||
await run_api(api_results, 'call_platform_api.auth_test', lambda: adapter.call_platform_api('auth_test', {}))
|
||||
finally:
|
||||
server_task.cancel()
|
||||
try:
|
||||
await server_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
await adapter.kill()
|
||||
|
||||
summary = {
|
||||
'events': [event.type for event in events],
|
||||
'api_results': api_results,
|
||||
'log': str(log_path),
|
||||
}
|
||||
print('SLACK_EBA_SUMMARY', json.dumps(summary, ensure_ascii=False, default=str))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Live Slack EBA adapter probe')
|
||||
parser.add_argument('--host', default='127.0.0.1')
|
||||
parser.add_argument('--port', type=int, default=5313)
|
||||
parser.add_argument('--timeout', type=float, default=300)
|
||||
parser.add_argument('--log', default='data/temp/slack_eba_probe.jsonl')
|
||||
parser.add_argument('--reply-text', default='Slack EBA probe reply')
|
||||
args = parser.parse_args()
|
||||
asyncio.run(run_probe(args))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
239
tests/unit_tests/platform/test_slack_eba_adapter.py
Normal file
239
tests/unit_tests/platform/test_slack_eba_adapter.py
Normal file
@@ -0,0 +1,239 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import pathlib
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from langbot.libs.slack_api.slackevent import SlackEvent
|
||||
from langbot.pkg.platform.adapters.slack.adapter import SlackAdapter
|
||||
from langbot.pkg.platform.adapters.slack.errors import NotSupportedError
|
||||
from langbot.pkg.platform.adapters.slack.event_converter import SlackEventConverter
|
||||
from langbot.pkg.platform.adapters.slack.message_converter import SlackMessageConverter
|
||||
from langbot.pkg.platform.adapters.slack.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 DummySlackWebClient:
|
||||
async def auth_test(self):
|
||||
return {'ok': True, 'user_id': 'B-1'}
|
||||
|
||||
|
||||
class DummySlackClient:
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.bot_token = kwargs['bot_token']
|
||||
self.signing_secret = kwargs['signing_secret']
|
||||
self.unified_mode = kwargs['unified_mode']
|
||||
self._message_handlers = {}
|
||||
self.client = DummySlackWebClient()
|
||||
self.sent = []
|
||||
self.handle_unified_webhook = AsyncMock(return_value='ok')
|
||||
|
||||
def on_message(self, msg_type: str):
|
||||
def decorator(func):
|
||||
self._message_handlers.setdefault(msg_type, []).append(func)
|
||||
return func
|
||||
|
||||
return decorator
|
||||
|
||||
async def send_message_to_channel(self, text: str, channel_id: str):
|
||||
self.sent.append(('channel', channel_id, text))
|
||||
return {'ok': True, 'channel': channel_id, 'message': {'ts': '1.1'}}
|
||||
|
||||
async def send_message_to_one(self, text: str, user_id: str):
|
||||
self.sent.append(('person', user_id, text))
|
||||
return {'ok': True, 'channel': user_id, 'message': {'ts': '1.2'}}
|
||||
|
||||
|
||||
def manifest() -> dict:
|
||||
manifest_path = (
|
||||
pathlib.Path(__file__).parents[3]
|
||||
/ 'src'
|
||||
/ 'langbot'
|
||||
/ 'pkg'
|
||||
/ 'platform'
|
||||
/ 'adapters'
|
||||
/ 'slack'
|
||||
/ 'manifest.yaml'
|
||||
)
|
||||
return yaml.safe_load(manifest_path.read_text())
|
||||
|
||||
|
||||
def make_adapter() -> SlackAdapter:
|
||||
config = {
|
||||
'bot_token': 'xoxb-token',
|
||||
'signing_secret': 'signing-secret',
|
||||
'bot_user_id': 'B-1',
|
||||
}
|
||||
with patch('langbot.pkg.platform.adapters.slack.adapter.SlackClient', DummySlackClient):
|
||||
return SlackAdapter(config, DummyLogger())
|
||||
|
||||
|
||||
def slack_event(channel_type: str = 'im', **overrides) -> SlackEvent:
|
||||
text = overrides.get('text', 'hello')
|
||||
payload = {
|
||||
'event_id': overrides.get('event_id', 'evt-1'),
|
||||
'event': {
|
||||
'type': 'app_mention' if channel_type == 'channel' else 'message',
|
||||
'channel_type': channel_type,
|
||||
'user': overrides.get('user_id', 'U-1'),
|
||||
'channel': overrides.get('channel_id', 'C-1'),
|
||||
'ts': overrides.get('ts', '1710003600.000100'),
|
||||
'event_ts': overrides.get('ts', '1710003600.000100'),
|
||||
'blocks': [
|
||||
{
|
||||
'type': 'rich_text',
|
||||
'elements': [
|
||||
{
|
||||
'type': 'rich_text_section',
|
||||
'elements': [
|
||||
{'type': 'text', 'text': text},
|
||||
],
|
||||
}
|
||||
],
|
||||
}
|
||||
],
|
||||
},
|
||||
}
|
||||
if channel_type == 'im':
|
||||
payload['event']['blocks'] = [
|
||||
{
|
||||
'elements': [
|
||||
{
|
||||
'elements': [
|
||||
{'type': 'text', 'text': text},
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
if overrides.get('pic_url'):
|
||||
payload['event']['files'] = [{'url_private': overrides['pic_url']}]
|
||||
return SlackEvent(payload)
|
||||
|
||||
|
||||
def test_slack_supported_events_match_manifest():
|
||||
assert make_adapter().get_supported_events() == manifest()['spec']['supported_events']
|
||||
|
||||
|
||||
def test_slack_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_slack_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_slack_message_converter_maps_common_components_to_text():
|
||||
text = await SlackMessageConverter.yiri2target(
|
||||
platform_message.MessageChain(
|
||||
[
|
||||
platform_message.Source(id='msg-0', time=datetime.datetime.now()),
|
||||
platform_message.Plain(text='hi'),
|
||||
platform_message.At(target='U-2'),
|
||||
platform_message.AtAll(),
|
||||
platform_message.Image(url='https://example.test/a.png'),
|
||||
platform_message.File(name='a.txt'),
|
||||
platform_message.Quote(origin=platform_message.MessageChain([platform_message.Plain(text='quoted')])),
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
assert 'hi' in text
|
||||
assert '<@U-2>' in text
|
||||
assert '<!channel>' in text
|
||||
assert 'https://example.test/a.png' in text
|
||||
assert 'a.txt' in text
|
||||
assert 'quoted' in text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_slack_event_converter_maps_private_group_and_platform_specific():
|
||||
private_event = await SlackEventConverter().target2yiri(slack_event('im'))
|
||||
group_event = await SlackEventConverter().target2yiri(slack_event('channel'))
|
||||
platform_event = await SlackEventConverter().target2yiri(slack_event('file_share'))
|
||||
|
||||
assert isinstance(private_event, platform_events.MessageReceivedEvent)
|
||||
assert private_event.adapter_name == 'slack-eba'
|
||||
assert private_event.chat_type == platform_entities.ChatType.PRIVATE
|
||||
assert private_event.chat_id == 'U-1'
|
||||
assert str(private_event.message_chain) == 'hello'
|
||||
|
||||
assert isinstance(group_event, platform_events.MessageReceivedEvent)
|
||||
assert group_event.chat_type == platform_entities.ChatType.GROUP
|
||||
assert group_event.chat_id == 'C-1'
|
||||
assert isinstance(group_event.message_chain[1], platform_message.At)
|
||||
|
||||
assert isinstance(platform_event, platform_events.PlatformSpecificEvent)
|
||||
assert platform_event.action == 'slack.file_share'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_slack_adapter_dispatches_eba_and_legacy_and_caches_group_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.GroupMessage, legacy_listener)
|
||||
await adapter._handle_native_event(slack_event('channel'))
|
||||
|
||||
assert len(eba_calls) == 1
|
||||
assert len(legacy_calls) == 1
|
||||
received = eba_calls[0]
|
||||
assert await adapter.get_message('group', 'C-1', 'evt-1') == received
|
||||
assert (await adapter.get_group_info('C-1')).id == 'C-1'
|
||||
assert (await adapter.get_group_member_info('C-1', 'U-1')).user.id == 'U-1'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_slack_send_reply_platform_api_and_unsupported():
|
||||
adapter = make_adapter()
|
||||
source_event = await SlackEventConverter().target2yiri(slack_event('im'))
|
||||
|
||||
reply_result = await adapter.reply_message(source_event, platform_message.MessageChain([platform_message.Plain(text='reply')]))
|
||||
assert reply_result.message_id == 'evt-1'
|
||||
assert ('person', 'U-1', 'reply') in adapter.bot.sent
|
||||
|
||||
await adapter.send_message('group', 'C-1', platform_message.MessageChain([platform_message.Plain(text='hello channel')]))
|
||||
assert ('channel', 'C-1', 'hello channel') in adapter.bot.sent
|
||||
|
||||
assert await adapter.call_platform_api('get_mode', {}) == {
|
||||
'webhook': True,
|
||||
'bot_account_id': 'B-1',
|
||||
}
|
||||
assert await adapter.call_platform_api('auth_test', {}) == {'ok': True, 'user_id': 'B-1'}
|
||||
|
||||
with pytest.raises(NotSupportedError):
|
||||
await adapter.call_platform_api('missing', {})
|
||||
Reference in New Issue
Block a user