mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-06-04 21:06:03 +00:00
feat(platform): add slack eba adapter
This commit is contained in:
5
src/langbot/pkg/platform/adapters/slack/__init__.py
Normal file
5
src/langbot/pkg/platform/adapters/slack/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from langbot.pkg.platform.adapters.slack.adapter import SlackAdapter
|
||||
|
||||
__all__ = ['SlackAdapter']
|
||||
212
src/langbot/pkg/platform/adapters/slack/adapter.py
Normal file
212
src/langbot/pkg/platform/adapters/slack/adapter.py
Normal file
@@ -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
|
||||
93
src/langbot/pkg/platform/adapters/slack/api_impl.py
Normal file
93
src/langbot/pkg/platform/adapters/slack/api_impl.py
Normal file
@@ -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')
|
||||
10
src/langbot/pkg/platform/adapters/slack/errors.py
Normal file
10
src/langbot/pkg/platform/adapters/slack/errors.py
Normal 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
|
||||
103
src/langbot/pkg/platform/adapters/slack/event_converter.py
Normal file
103
src/langbot/pkg/platform/adapters/slack/event_converter.py
Normal file
@@ -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()
|
||||
81
src/langbot/pkg/platform/adapters/slack/manifest.yaml
Normal file
81
src/langbot/pkg/platform/adapters/slack/manifest.yaml
Normal file
@@ -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
|
||||
80
src/langbot/pkg/platform/adapters/slack/message_converter.py
Normal file
80
src/langbot/pkg/platform/adapters/slack/message_converter.py
Normal file
@@ -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()
|
||||
23
src/langbot/pkg/platform/adapters/slack/platform_api.py
Normal file
23
src/langbot/pkg/platform/adapters/slack/platform_api.py
Normal file
@@ -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,
|
||||
}
|
||||
BIN
src/langbot/pkg/platform/adapters/slack/slack.png
Normal file
BIN
src/langbot/pkg/platform/adapters/slack/slack.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 5.7 KiB |
3
src/langbot/pkg/platform/adapters/slack/types.py
Normal file
3
src/langbot/pkg/platform/adapters/slack/types.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from __future__ import annotations
|
||||
|
||||
ADAPTER_NAME = 'slack-eba'
|
||||
Reference in New Issue
Block a user