mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-06-27 16:04:21 +00:00
feat(platform): add slack eba adapter
This commit is contained in:
@@ -24,6 +24,7 @@ Current acceptance report: [EBA Adapter Acceptance Report](./acceptance-report.m
|
|||||||
| WeComBot | Migrated; private text and outbound/API plugin E2E verified, feedback/group gaps remain | [WeComBot](./wecombot.md) |
|
| WeComBot | Migrated; private text and outbound/API plugin E2E verified, feedback/group gaps remain | [WeComBot](./wecombot.md) |
|
||||||
| Official Account | Migrated; private text plugin E2E verified, proactive outbound not supported | [Official Account](./officialaccount.md) |
|
| Official Account | Migrated; private text plugin E2E verified, proactive outbound not supported | [Official Account](./officialaccount.md) |
|
||||||
| QQ Official API | Migrated; WebSocket inbound reached LangBot, model config blocked reply | [QQ Official API](./qqofficial.md) |
|
| QQ Official API | Migrated; WebSocket inbound reached LangBot, model config blocked reply | [QQ Official API](./qqofficial.md) |
|
||||||
|
| Slack | Migrated; private text and outbound/API plugin E2E verified | [Slack](./slack.md) |
|
||||||
|
|
||||||
## Documentation Checklist
|
## Documentation Checklist
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ Scope:
|
|||||||
- `wecomcs-eba`
|
- `wecomcs-eba`
|
||||||
- `officialaccount-eba`
|
- `officialaccount-eba`
|
||||||
- `qqofficial-eba`
|
- `qqofficial-eba`
|
||||||
|
- `slack-eba`
|
||||||
|
|
||||||
This report follows `acceptance-checklist.md`. Evidence levels are intentionally strict:
|
This report follows `acceptance-checklist.md`. Evidence levels are intentionally strict:
|
||||||
|
|
||||||
@@ -38,6 +39,7 @@ This report follows `acceptance-checklist.md`. Evidence levels are intentionally
|
|||||||
| WeCom Customer Service | Partial EBA acceptance | WeCom Customer Service is split into the EBA directory with manifest, converters, API mixin, platform API map, unit tests, docs, and a direct live probe scaffold. Real WeChat customer-side UI text reached `EBAEventProbe`; plugin outbound text/image and safe cache-backed common APIs passed. Inbound media and platform-specific API live coverage remain pending; later fallback text sends were blocked by WeCom `95001 send msg count limit`. |
|
| WeCom Customer Service | Partial EBA acceptance | WeCom Customer Service is split into the EBA directory with manifest, converters, API mixin, platform API map, unit tests, docs, and a direct live probe scaffold. Real WeChat customer-side UI text reached `EBAEventProbe`; plugin outbound text/image and safe cache-backed common APIs passed. Inbound media and platform-specific API live coverage remain pending; later fallback text sends were blocked by WeCom `95001 send msg count limit`. |
|
||||||
| Official Account | Partial EBA acceptance | WeChat Official Account is split into the EBA directory with manifest, converters, cache-backed safe APIs, platform API map, unit tests, and a direct live probe scaffold. Real WeChat Official Account UI private text reached `EBAEventProbe`; safe cache-backed common APIs and declared platform APIs passed. Proactive outbound `send_message` is not supported because replies must be tied to inbound webhook windows; inbound image/voice live UI evidence remains pending. |
|
| Official Account | Partial EBA acceptance | WeChat Official Account is split into the EBA directory with manifest, converters, cache-backed safe APIs, platform API map, unit tests, and a direct live probe scaffold. Real WeChat Official Account UI private text reached `EBAEventProbe`; safe cache-backed common APIs and declared platform APIs passed. Proactive outbound `send_message` is not supported because replies must be tied to inbound webhook windows; inbound image/voice live UI evidence remains pending. |
|
||||||
| QQ Official API | Partial EBA acceptance | QQ Official API is split into the EBA directory with manifest, converters, cache-backed safe APIs, platform API map, unit tests, docs, and a direct live probe scaffold. A real WebSocket-mode QQ Official bot reached the LangBot pipeline on `dev.rockchin.top`; reply/outbound evidence is blocked by the test model provider returning `model_not_found` for `deepseek-v3`. |
|
| QQ Official API | Partial EBA acceptance | QQ Official API is split into the EBA directory with manifest, converters, cache-backed safe APIs, platform API map, unit tests, docs, and a direct live probe scaffold. A real WebSocket-mode QQ Official bot reached the LangBot pipeline on `dev.rockchin.top`; reply/outbound evidence is blocked by the test model provider returning `model_not_found` for `deepseek-v3`. |
|
||||||
|
| Slack | Partial EBA acceptance | Slack is split into the EBA directory with manifest, converters, cache-backed safe APIs, platform API map, unit tests, docs, and a direct live probe scaffold. Real Slack private text reached `EBAEventProbe`; safe common APIs, outbound component fallback sweep, and declared Slack platform APIs passed. Channel mention and real inbound media evidence remain pending. |
|
||||||
|
|
||||||
Telegram and DingTalk now have real user-side UI image/file upload evidence in plugin JSONL. Discord and aiocqhttp do not yet have real UI inbound image/file evidence.
|
Telegram and DingTalk now have real user-side UI image/file upload evidence in plugin JSONL. Discord and aiocqhttp do not yet have real UI inbound image/file evidence.
|
||||||
|
|
||||||
@@ -58,6 +60,8 @@ Telegram and DingTalk now have real user-side UI image/file upload evidence in p
|
|||||||
| WeCom Customer Service | WeChat customer-side UI, `客服消息 -> 浪波智能客服` on `dev.rockchin.top` | `/home/wgc/LangBotxg/LangBotEbaTest/data/temp/wecomcs_eba_plugin_probe.jsonl` |
|
| WeCom Customer Service | WeChat customer-side UI, `客服消息 -> 浪波智能客服` on `dev.rockchin.top` | `/home/wgc/LangBotxg/LangBotEbaTest/data/temp/wecomcs_eba_plugin_probe.jsonl` |
|
||||||
| Official Account | WeChat desktop client, subscribed Official Account on `dev.rockchin.top` | `/home/wgc/LangBotxg/LangBotEbaTest/data/temp/officialaccount_eba_plugin_probe.jsonl` |
|
| Official Account | WeChat desktop client, subscribed Official Account on `dev.rockchin.top` | `/home/wgc/LangBotxg/LangBotEbaTest/data/temp/officialaccount_eba_plugin_probe.jsonl` |
|
||||||
| QQ Official API unit | local mocked QQ Official client paths | `tests/unit_tests/platform/test_qqofficial_eba_adapter.py` |
|
| QQ Official API unit | local mocked QQ Official client paths | `tests/unit_tests/platform/test_qqofficial_eba_adapter.py` |
|
||||||
|
| Slack unit | local mocked Slack client paths | `tests/unit_tests/platform/test_slack_eba_adapter.py` |
|
||||||
|
| Slack private | Slack workspace private DM on `dev.rockchin.top` | `/home/wgc/LangBotxg/LangBotEbaTest/data/temp/slack_eba_plugin_probe.jsonl` |
|
||||||
|
|
||||||
All plugin runs used SDK standalone runtime ports `5400/5401`, LangBot `--standalone-runtime`, and the real plugin at `langbot-plugin-demo/EBAEventProbe`.
|
All plugin runs used SDK standalone runtime ports `5400/5401`, LangBot `--standalone-runtime`, and the real plugin at `langbot-plugin-demo/EBAEventProbe`.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
# Slack EBA Adapter
|
||||||
|
|
||||||
|
## Structure
|
||||||
|
|
||||||
|
Slack is migrated into `src/langbot/pkg/platform/adapters/slack/` with the standard EBA adapter layout:
|
||||||
|
|
||||||
|
- `adapter.py` owns lifecycle, listener dispatch, unified webhook handling, outbound send/reply, and event caches.
|
||||||
|
- `event_converter.py` maps Slack `im` and `app_mention` channel events to `message.received`.
|
||||||
|
- `message_converter.py` maps common `MessageChain` components to Slack text fallback and maps inbound Slack text/image payloads back to EBA components.
|
||||||
|
- `api_impl.py` provides cache-backed common read APIs.
|
||||||
|
- `platform_api.py` declares safe Slack-specific API actions.
|
||||||
|
- `manifest.yaml` declares `slack-eba`.
|
||||||
|
|
||||||
|
The legacy `src/langbot/pkg/platform/sources/slack.py` adapter is kept unchanged.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
| Field | Required | Notes |
|
||||||
|
|-------|----------|-------|
|
||||||
|
| `webhook_url` | No | Generated by LangBot. Paste it into Slack Event Subscriptions. |
|
||||||
|
| `bot_token` | Yes | Slack bot token, usually `xoxb-...`. |
|
||||||
|
| `signing_secret` | Yes | Slack app signing secret. |
|
||||||
|
|
||||||
|
## Events
|
||||||
|
|
||||||
|
| Event | Notes |
|
||||||
|
|-------|-------|
|
||||||
|
| `message.received` | Emitted for private `im` messages and channel `app_mention` events. Channel messages are mapped to group chats. |
|
||||||
|
| `platform.specific` | Reserved for Slack event types that are not converted into common message events. |
|
||||||
|
|
||||||
|
## Common APIs
|
||||||
|
|
||||||
|
Required:
|
||||||
|
|
||||||
|
- `send_message`
|
||||||
|
- `reply_message`
|
||||||
|
|
||||||
|
Optional:
|
||||||
|
|
||||||
|
- `get_message`
|
||||||
|
- `get_user_info`
|
||||||
|
- `get_friend_list`
|
||||||
|
- `get_group_info`
|
||||||
|
- `get_group_list`
|
||||||
|
- `get_group_member_list`
|
||||||
|
- `get_group_member_info`
|
||||||
|
- `call_platform_api`
|
||||||
|
|
||||||
|
Cache-backed APIs are only available after the relevant inbound event has been observed.
|
||||||
|
|
||||||
|
## Platform APIs
|
||||||
|
|
||||||
|
| Action | Notes |
|
||||||
|
|--------|-------|
|
||||||
|
| `get_mode` | Returns webhook mode and configured bot account id. |
|
||||||
|
| `auth_test` | Calls Slack `auth.test` with the configured bot token. |
|
||||||
|
|
||||||
|
## Known Limits
|
||||||
|
|
||||||
|
- Slack file/image outbound is currently represented as text fallback because the existing Slack SDK wrapper only exposes `chat_postMessage`.
|
||||||
|
- Inbound channel coverage follows the legacy adapter behavior: only `app_mention` events are treated as group messages.
|
||||||
|
- Real live testing requires a public callback URL configured in Slack Event Subscriptions.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
Local mocked unit coverage validates manifest parity, event conversion, legacy listener compatibility, cache-backed APIs, send/reply routing, and declared platform APIs.
|
||||||
|
|
||||||
|
Plugin E2E evidence was captured on June 2, 2026 against `dev.rockchin.top` with Slack private DM input and `EBAEventProbe` through the standalone runtime.
|
||||||
|
|
||||||
|
Evidence file: `/home/wgc/LangBotxg/LangBotEbaTest/data/temp/slack_eba_plugin_probe.jsonl`.
|
||||||
|
|
||||||
|
Observed:
|
||||||
|
|
||||||
|
- Real Slack private text produced `MessageReceived` with `adapter_name=slack-eba`, `Source + Plain`, private chat type, and filled `bot_uuid`.
|
||||||
|
- Safe common APIs passed: `get_message`, `get_user_info`, `get_friend_list`.
|
||||||
|
- Outbound component fallback sweep passed through `send_message`: plain/at/face, image, quote, file, and forward.
|
||||||
|
- Declared Slack platform APIs passed: `get_mode`, `auth_test`.
|
||||||
|
|
||||||
|
Still pending:
|
||||||
|
|
||||||
|
- Channel `app_mention` plugin E2E.
|
||||||
|
- Real inbound Slack file/image UI evidence.
|
||||||
|
|
||||||
|
Live probe scaffold: `tests/e2e/live_slack_eba_probe.py`.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from langbot.pkg.platform.adapters.slack.adapter import SlackAdapter
|
||||||
|
|
||||||
|
__all__ = ['SlackAdapter']
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import traceback
|
||||||
|
import typing
|
||||||
|
|
||||||
|
import pydantic
|
||||||
|
|
||||||
|
from langbot.libs.slack_api.api import SlackClient
|
||||||
|
from langbot.libs.slack_api.slackevent import SlackEvent
|
||||||
|
from langbot.pkg.platform.adapters.slack.api_impl import SlackAPIMixin
|
||||||
|
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
|
||||||
|
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 SlackAdapter(SlackAPIMixin, abstract_platform_adapter.AbstractPlatformAdapter):
|
||||||
|
bot: typing.Any = pydantic.Field(exclude=True)
|
||||||
|
|
||||||
|
message_converter: SlackMessageConverter = SlackMessageConverter()
|
||||||
|
event_converter: SlackEventConverter = SlackEventConverter()
|
||||||
|
|
||||||
|
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] = {}
|
||||||
|
_group_cache: dict[str, platform_entities.UserGroup] = {}
|
||||||
|
_member_cache: dict[tuple[str, str], platform_entities.UserGroupMember] = {}
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
arbitrary_types_allowed = True
|
||||||
|
|
||||||
|
def __init__(self, config: dict, logger: abstract_platform_logger.AbstractEventLogger):
|
||||||
|
required_keys = ['bot_token', 'signing_secret']
|
||||||
|
missing_keys = [key for key in required_keys if not config.get(key)]
|
||||||
|
if missing_keys:
|
||||||
|
raise Exception(f'Slack EBA adapter missing config: {missing_keys}')
|
||||||
|
|
||||||
|
bot = SlackClient(
|
||||||
|
bot_token=config['bot_token'],
|
||||||
|
signing_secret=config['signing_secret'],
|
||||||
|
logger=logger,
|
||||||
|
unified_mode=True,
|
||||||
|
)
|
||||||
|
super().__init__(
|
||||||
|
config=config,
|
||||||
|
logger=logger,
|
||||||
|
bot=bot,
|
||||||
|
bot_account_id=config.get('bot_user_id', ''),
|
||||||
|
bot_uuid=None,
|
||||||
|
listeners={},
|
||||||
|
_message_cache={},
|
||||||
|
_user_cache={},
|
||||||
|
_group_cache={},
|
||||||
|
_member_cache={},
|
||||||
|
)
|
||||||
|
self.event_converter = SlackEventConverter(config['bot_token'])
|
||||||
|
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 [
|
||||||
|
'send_message',
|
||||||
|
'reply_message',
|
||||||
|
'get_message',
|
||||||
|
'get_user_info',
|
||||||
|
'get_friend_list',
|
||||||
|
'get_group_info',
|
||||||
|
'get_group_list',
|
||||||
|
'get_group_member_list',
|
||||||
|
'get_group_member_info',
|
||||||
|
'call_platform_api',
|
||||||
|
]
|
||||||
|
|
||||||
|
async def send_message(
|
||||||
|
self,
|
||||||
|
target_type: str,
|
||||||
|
target_id: str,
|
||||||
|
message: platform_message.MessageChain,
|
||||||
|
) -> platform_events.MessageResult:
|
||||||
|
content = await SlackMessageConverter.yiri2target(message)
|
||||||
|
raw = await self._send_text(str(target_type), str(target_id), content)
|
||||||
|
return platform_events.MessageResult(raw=raw)
|
||||||
|
|
||||||
|
async def reply_message(
|
||||||
|
self,
|
||||||
|
message_source: platform_events.MessageEvent,
|
||||||
|
message: platform_message.MessageChain,
|
||||||
|
quote_origin: bool = False,
|
||||||
|
) -> platform_events.MessageResult:
|
||||||
|
source = await SlackEventConverter.yiri2target(message_source)
|
||||||
|
if not isinstance(source, SlackEvent):
|
||||||
|
raise ValueError('Slack reply_message requires a SlackEvent source object')
|
||||||
|
target_type = 'channel' if source.type == 'channel' else 'person'
|
||||||
|
target_id = source.channel_id if source.type == 'channel' else source.user_id
|
||||||
|
raw = await self._send_text(target_type, target_id, await SlackMessageConverter.yiri2target(message))
|
||||||
|
return platform_events.MessageResult(message_id=source.message_id, raw=raw)
|
||||||
|
|
||||||
|
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}')
|
||||||
|
return await handler(self, dict(params or {}))
|
||||||
|
|
||||||
|
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):
|
||||||
|
await self.logger.info('Slack EBA adapter running in unified webhook mode')
|
||||||
|
while True:
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
|
||||||
|
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 ('im', 'channel'):
|
||||||
|
self.bot.on_message(msg_type)(self._handle_native_event)
|
||||||
|
|
||||||
|
async def _handle_native_event(self, event: SlackEvent):
|
||||||
|
try:
|
||||||
|
if platform_events.FriendMessage in self.listeners or platform_events.GroupMessage in self.listeners:
|
||||||
|
legacy_event = await self.event_converter.target2legacy(event)
|
||||||
|
if legacy_event and type(legacy_event) in self.listeners:
|
||||||
|
await self.listeners[type(legacy_event)](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 slack 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 not isinstance(event, platform_events.MessageReceivedEvent):
|
||||||
|
return
|
||||||
|
self._message_cache[str(event.message_id)] = event
|
||||||
|
self._user_cache[str(event.sender.id)] = event.sender
|
||||||
|
if event.group:
|
||||||
|
self._group_cache[str(event.group.id)] = event.group
|
||||||
|
self._member_cache[(str(event.group.id), str(event.sender.id))] = platform_entities.UserGroupMember(
|
||||||
|
user=event.sender,
|
||||||
|
group_id=event.group.id,
|
||||||
|
role=platform_entities.MemberRole.MEMBER,
|
||||||
|
display_name=event.sender.nickname,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def _send_text(self, target_type: str, target_id: str, content: str) -> dict:
|
||||||
|
target_type = self._normalize_target_type(target_type)
|
||||||
|
if target_type == 'person':
|
||||||
|
raw = await self.bot.send_message_to_one(content, target_id)
|
||||||
|
elif target_type == 'channel':
|
||||||
|
raw = await self.bot.send_message_to_channel(content, target_id)
|
||||||
|
else:
|
||||||
|
raise NotSupportedError(f'send_message:{target_type}')
|
||||||
|
return {'target_type': target_type, 'target_id': target_id, 'raw': raw}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _normalize_target_type(target_type: str) -> str:
|
||||||
|
if target_type in {'person', 'private', 'friend', 'im', 'dm'}:
|
||||||
|
return 'person'
|
||||||
|
if target_type in {'group', 'channel'}:
|
||||||
|
return 'channel'
|
||||||
|
return target_type
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import typing
|
||||||
|
|
||||||
|
from langbot.pkg.platform.adapters.slack.errors import NotSupportedError
|
||||||
|
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 SlackAPIMixin:
|
||||||
|
_message_cache: dict[str, platform_events.MessageReceivedEvent]
|
||||||
|
_user_cache: dict[str, platform_entities.User]
|
||||||
|
_group_cache: dict[str, platform_entities.UserGroup]
|
||||||
|
_member_cache: dict[tuple[str, str], platform_entities.UserGroupMember]
|
||||||
|
|
||||||
|
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 get_group_info(self, group_id: typing.Union[int, str]) -> platform_entities.UserGroup:
|
||||||
|
group = self._group_cache.get(str(group_id))
|
||||||
|
if group is None:
|
||||||
|
raise NotSupportedError('get_group_info:not_cached')
|
||||||
|
return group
|
||||||
|
|
||||||
|
async def get_group_list(self) -> list[platform_entities.UserGroup]:
|
||||||
|
return list(self._group_cache.values())
|
||||||
|
|
||||||
|
async def get_group_member_list(
|
||||||
|
self,
|
||||||
|
group_id: typing.Union[int, str],
|
||||||
|
) -> list[platform_entities.UserGroupMember]:
|
||||||
|
return [member for (cached_group_id, _), member in self._member_cache.items() if cached_group_id == str(group_id)]
|
||||||
|
|
||||||
|
async def get_group_member_info(
|
||||||
|
self,
|
||||||
|
group_id: typing.Union[int, str],
|
||||||
|
user_id: typing.Union[int, str],
|
||||||
|
) -> platform_entities.UserGroupMember:
|
||||||
|
member = self._member_cache.get((str(group_id), str(user_id)))
|
||||||
|
if member is None:
|
||||||
|
raise NotSupportedError('get_group_member_info:not_cached')
|
||||||
|
return member
|
||||||
|
|
||||||
|
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')
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
import typing
|
||||||
|
|
||||||
|
from langbot.libs.slack_api.slackevent import SlackEvent
|
||||||
|
from langbot.pkg.platform.adapters.slack.message_converter import SlackMessageConverter
|
||||||
|
from langbot.pkg.platform.adapters.slack.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 SlackEventConverter(abstract_platform_adapter.AbstractEventConverter):
|
||||||
|
def __init__(self, bot_token: str = ''):
|
||||||
|
self.bot_token = bot_token
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
async def yiri2target(event: platform_events.Event) -> typing.Any:
|
||||||
|
return getattr(event, 'source_platform_object', None)
|
||||||
|
|
||||||
|
async def target2legacy(self, event: SlackEvent) -> platform_events.FriendMessage | platform_events.GroupMessage | None:
|
||||||
|
eba_event = await self.target2yiri(event)
|
||||||
|
if not isinstance(eba_event, platform_events.MessageReceivedEvent):
|
||||||
|
return None
|
||||||
|
if eba_event.chat_type == platform_entities.ChatType.PRIVATE:
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
return platform_events.GroupMessage(
|
||||||
|
sender=platform_entities.GroupMember(
|
||||||
|
id=eba_event.sender.id,
|
||||||
|
member_name=eba_event.sender.nickname,
|
||||||
|
permission='MEMBER',
|
||||||
|
group=platform_entities.Group(
|
||||||
|
id=eba_event.group.id if eba_event.group else eba_event.chat_id,
|
||||||
|
name=eba_event.group.name if eba_event.group else '',
|
||||||
|
permission=platform_entities.Permission.Member,
|
||||||
|
),
|
||||||
|
special_title='',
|
||||||
|
),
|
||||||
|
message_chain=eba_event.message_chain,
|
||||||
|
time=eba_event.timestamp,
|
||||||
|
source_platform_object=event,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def target2yiri(self, event: SlackEvent) -> platform_events.Event:
|
||||||
|
if event.type in {'im', 'channel'}:
|
||||||
|
return await self.message_to_eba(event)
|
||||||
|
return self.platform_specific(event, f'slack.{event.type or "unknown"}')
|
||||||
|
|
||||||
|
async def message_to_eba(self, event: SlackEvent) -> platform_events.MessageReceivedEvent:
|
||||||
|
sender_id = event.user_id or ''
|
||||||
|
sender = platform_entities.User(
|
||||||
|
id=sender_id,
|
||||||
|
nickname=event.sender_name or sender_id,
|
||||||
|
)
|
||||||
|
chat_type = platform_entities.ChatType.PRIVATE
|
||||||
|
chat_id = sender_id
|
||||||
|
group = None
|
||||||
|
if event.type == 'channel':
|
||||||
|
chat_type = platform_entities.ChatType.GROUP
|
||||||
|
chat_id = event.channel_id or ''
|
||||||
|
group = platform_entities.UserGroup(id=str(chat_id), name=str(chat_id))
|
||||||
|
|
||||||
|
return platform_events.MessageReceivedEvent(
|
||||||
|
type='message.received',
|
||||||
|
adapter_name=ADAPTER_NAME,
|
||||||
|
message_id=event.message_id or event.get('event', {}).get('event_ts') or '',
|
||||||
|
message_chain=await SlackMessageConverter.target2yiri(event, self.bot_token),
|
||||||
|
sender=sender,
|
||||||
|
chat_type=chat_type,
|
||||||
|
chat_id=chat_id or '',
|
||||||
|
group=group,
|
||||||
|
timestamp=_timestamp_value(event),
|
||||||
|
source_platform_object=event,
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def platform_specific(event: SlackEvent, action: str) -> platform_events.PlatformSpecificEvent:
|
||||||
|
return platform_events.PlatformSpecificEvent(
|
||||||
|
type='platform.specific',
|
||||||
|
adapter_name=ADAPTER_NAME,
|
||||||
|
action=action,
|
||||||
|
data=dict(event),
|
||||||
|
timestamp=_timestamp_value(event),
|
||||||
|
source_platform_object=event,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _timestamp_value(event: SlackEvent) -> float:
|
||||||
|
raw_ts = event.get('event', {}).get('ts') or event.get('event', {}).get('event_ts')
|
||||||
|
try:
|
||||||
|
return float(raw_ts)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return time.time()
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
apiVersion: v1
|
||||||
|
kind: MessagePlatformAdapter
|
||||||
|
|
||||||
|
metadata:
|
||||||
|
name: slack-eba
|
||||||
|
label:
|
||||||
|
en_US: Slack (EBA)
|
||||||
|
zh_Hans: Slack (EBA)
|
||||||
|
zh_Hant: Slack (EBA)
|
||||||
|
description:
|
||||||
|
en_US: Slack adapter with Event-Based Agents support, using LangBot's unified webhook endpoint.
|
||||||
|
zh_Hans: Slack 适配器(EBA 架构版本),通过 LangBot 统一 Webhook 接收 Slack 事件订阅消息。
|
||||||
|
zh_Hant: Slack 適配器(EBA 架構版本),透過 LangBot 統一 Webhook 接收 Slack 事件訂閱訊息。
|
||||||
|
icon: slack.png
|
||||||
|
|
||||||
|
spec:
|
||||||
|
categories:
|
||||||
|
- popular
|
||||||
|
- global
|
||||||
|
help_links:
|
||||||
|
zh: https://link.langbot.app/zh/platforms/slack
|
||||||
|
en: https://link.langbot.app/en/platforms/slack
|
||||||
|
ja: https://link.langbot.app/ja/platforms/slack
|
||||||
|
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 Slack app's event subscription configuration.
|
||||||
|
zh_Hans: 复制此地址并粘贴到 Slack 应用的事件订阅配置中。
|
||||||
|
zh_Hant: 複製此地址並貼到 Slack 應用的事件訂閱設定中。
|
||||||
|
type: webhook-url
|
||||||
|
required: false
|
||||||
|
default: ""
|
||||||
|
- name: bot_token
|
||||||
|
label:
|
||||||
|
en_US: Bot Token
|
||||||
|
zh_Hans: 机器人令牌
|
||||||
|
zh_Hant: 機器人令牌
|
||||||
|
type: string
|
||||||
|
required: true
|
||||||
|
default: ""
|
||||||
|
- name: signing_secret
|
||||||
|
label:
|
||||||
|
en_US: Signing Secret
|
||||||
|
zh_Hans: 签名密钥
|
||||||
|
zh_Hant: 簽名密鑰
|
||||||
|
type: string
|
||||||
|
required: true
|
||||||
|
default: ""
|
||||||
|
|
||||||
|
supported_events:
|
||||||
|
- message.received
|
||||||
|
- platform.specific
|
||||||
|
|
||||||
|
supported_apis:
|
||||||
|
required:
|
||||||
|
- send_message
|
||||||
|
- reply_message
|
||||||
|
optional:
|
||||||
|
- get_message
|
||||||
|
- get_user_info
|
||||||
|
- get_friend_list
|
||||||
|
- get_group_info
|
||||||
|
- get_group_list
|
||||||
|
- get_group_member_list
|
||||||
|
- get_group_member_info
|
||||||
|
- call_platform_api
|
||||||
|
|
||||||
|
platform_specific_apis:
|
||||||
|
- action: get_mode
|
||||||
|
description: { en_US: "Return adapter webhook mode", zh_Hans: "返回适配器 Webhook 模式" }
|
||||||
|
- action: auth_test
|
||||||
|
description: { en_US: "Call Slack auth.test with the configured bot token", zh_Hans: "使用配置的机器人令牌调用 Slack auth.test" }
|
||||||
|
|
||||||
|
execution:
|
||||||
|
python:
|
||||||
|
path: ./adapter.py
|
||||||
|
attr: SlackAdapter
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
|
||||||
|
from langbot.libs.slack_api.slackevent import SlackEvent
|
||||||
|
from langbot.pkg.utils import image
|
||||||
|
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 SlackMessageConverter(abstract_platform_adapter.AbstractMessageConverter):
|
||||||
|
@staticmethod
|
||||||
|
async def yiri2target(message_chain: platform_message.MessageChain) -> str:
|
||||||
|
parts: list[str] = []
|
||||||
|
for component in message_chain:
|
||||||
|
if isinstance(component, platform_message.Source):
|
||||||
|
continue
|
||||||
|
if isinstance(component, platform_message.Plain):
|
||||||
|
parts.append(component.text)
|
||||||
|
elif isinstance(component, platform_message.At):
|
||||||
|
parts.append(f'<@{component.target}>')
|
||||||
|
elif isinstance(component, platform_message.AtAll):
|
||||||
|
parts.append('<!channel>')
|
||||||
|
elif isinstance(component, platform_message.Image):
|
||||||
|
parts.append(component.url or '[Image]')
|
||||||
|
elif isinstance(component, platform_message.Voice):
|
||||||
|
parts.append(component.url or '[Voice]')
|
||||||
|
elif isinstance(component, platform_message.File):
|
||||||
|
parts.append(component.url or component.name or component.id or '[File]')
|
||||||
|
elif isinstance(component, platform_message.Quote):
|
||||||
|
if component.id is not None:
|
||||||
|
parts.append(f'[Quote {component.id}]')
|
||||||
|
if component.origin:
|
||||||
|
parts.append(await SlackMessageConverter.yiri2target(component.origin))
|
||||||
|
elif isinstance(component, platform_message.Forward):
|
||||||
|
for node in component.node_list:
|
||||||
|
if node.message_chain:
|
||||||
|
parts.append(await SlackMessageConverter.yiri2target(node.message_chain))
|
||||||
|
else:
|
||||||
|
text = str(component)
|
||||||
|
if text:
|
||||||
|
parts.append(text)
|
||||||
|
return '\n'.join(part for part in parts if part)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
async def target2yiri(event: SlackEvent, bot_token: str = '') -> platform_message.MessageChain:
|
||||||
|
message_id = event.message_id or event.get('event', {}).get('event_ts') or ''
|
||||||
|
components: list[platform_message.MessageComponent] = [
|
||||||
|
platform_message.Source(
|
||||||
|
id=message_id,
|
||||||
|
time=_event_datetime(event),
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
|
if event.type == 'channel':
|
||||||
|
components.append(platform_message.At(target='SlackBot'))
|
||||||
|
|
||||||
|
if event.pic_url:
|
||||||
|
try:
|
||||||
|
components.append(platform_message.Image(base64=await image.get_slack_image_to_base64(event.pic_url, bot_token)))
|
||||||
|
except Exception:
|
||||||
|
components.append(platform_message.Image(url=event.pic_url))
|
||||||
|
|
||||||
|
if event.text:
|
||||||
|
components.append(platform_message.Plain(text=event.text))
|
||||||
|
|
||||||
|
if len(components) == 1 or (
|
||||||
|
len(components) == 2 and isinstance(components[1], platform_message.At)
|
||||||
|
):
|
||||||
|
components.append(platform_message.Unknown(text=f'[unsupported slack event: {event.type or "unknown"}]'))
|
||||||
|
|
||||||
|
return platform_message.MessageChain(components)
|
||||||
|
|
||||||
|
|
||||||
|
def _event_datetime(event: SlackEvent) -> datetime.datetime:
|
||||||
|
raw_ts = event.get('event', {}).get('ts') or event.get('event', {}).get('event_ts')
|
||||||
|
try:
|
||||||
|
return datetime.datetime.fromtimestamp(float(raw_ts))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return datetime.datetime.now()
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import typing
|
||||||
|
|
||||||
|
|
||||||
|
async def get_mode(adapter, params: dict) -> dict:
|
||||||
|
return {
|
||||||
|
'webhook': True,
|
||||||
|
'bot_account_id': adapter.bot_account_id,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def auth_test(adapter, params: dict) -> dict:
|
||||||
|
response = await adapter.bot.client.auth_test()
|
||||||
|
if hasattr(response, 'data'):
|
||||||
|
return dict(response.data)
|
||||||
|
return dict(response)
|
||||||
|
|
||||||
|
|
||||||
|
PLATFORM_API_MAP: dict[str, typing.Callable[[typing.Any, dict], typing.Awaitable[dict]]] = {
|
||||||
|
'get_mode': get_mode,
|
||||||
|
'auth_test': auth_test,
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 5.7 KiB |
@@ -0,0 +1,3 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
ADAPTER_NAME = 'slack-eba'
|
||||||
@@ -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()
|
||||||
@@ -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