mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-07-17 01:46:07 +00:00
feat(platform): add wecom eba adapters
This commit is contained in:
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import traceback
|
||||
import typing
|
||||
|
||||
import pydantic
|
||||
|
||||
from langbot.libs.wecom_api.api import WecomClient
|
||||
from langbot.libs.wecom_api.wecomevent import WecomEvent
|
||||
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.pkg.platform.adapters.wecom.api_impl import WecomAPIMixin
|
||||
from langbot.pkg.platform.adapters.wecom.event_converter import WecomEventConverter
|
||||
from langbot.pkg.platform.adapters.wecom.message_converter import WecomMessageConverter
|
||||
from langbot.pkg.platform.adapters.wecom.platform_api import PLATFORM_API_MAP
|
||||
from langbot_plugin.api.entities.builtin.platform import events as platform_events
|
||||
from langbot_plugin.api.entities.builtin.platform import message as platform_message
|
||||
from langbot_plugin.api.entities.builtin.platform.errors import NotSupportedError
|
||||
|
||||
|
||||
class WecomAdapter(WecomAPIMixin, abstract_platform_adapter.AbstractPlatformAdapter):
|
||||
bot: WecomClient = pydantic.Field(exclude=True)
|
||||
|
||||
message_converter: WecomMessageConverter = WecomMessageConverter()
|
||||
event_converter: WecomEventConverter = WecomEventConverter()
|
||||
|
||||
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, typing.Any] = {}
|
||||
|
||||
class Config:
|
||||
arbitrary_types_allowed = True
|
||||
|
||||
def __init__(self, config: dict, logger: abstract_platform_logger.AbstractEventLogger):
|
||||
required_keys = [
|
||||
'corpid',
|
||||
'secret',
|
||||
'token',
|
||||
'EncodingAESKey',
|
||||
]
|
||||
missing_keys = [key for key in required_keys if key not in config]
|
||||
if missing_keys:
|
||||
raise Exception(f'WeCom missing required config fields: {missing_keys}')
|
||||
|
||||
bot = WecomClient(
|
||||
corpid=config['corpid'],
|
||||
secret=config['secret'],
|
||||
token=config['token'],
|
||||
EncodingAESKey=config['EncodingAESKey'],
|
||||
contacts_secret=config.get('contacts_secret', ''),
|
||||
logger=logger,
|
||||
unified_mode=True,
|
||||
api_base_url=config.get('api_base_url', 'https://qyapi.weixin.qq.com/cgi-bin'),
|
||||
)
|
||||
|
||||
super().__init__(
|
||||
config=config,
|
||||
logger=logger,
|
||||
bot=bot,
|
||||
bot_account_id='',
|
||||
bot_uuid=None,
|
||||
listeners={},
|
||||
_message_cache={},
|
||||
_user_cache={},
|
||||
)
|
||||
self._register_native_handlers()
|
||||
|
||||
def set_bot_uuid(self, bot_uuid: str):
|
||||
self.bot_uuid = bot_uuid
|
||||
|
||||
def get_supported_events(self) -> list[str]:
|
||||
return [
|
||||
'message.received',
|
||||
'platform.specific',
|
||||
]
|
||||
|
||||
def get_supported_apis(self) -> list[str]:
|
||||
return [
|
||||
'send_message',
|
||||
'reply_message',
|
||||
'get_message',
|
||||
'get_user_info',
|
||||
'get_friend_list',
|
||||
'call_platform_api',
|
||||
]
|
||||
|
||||
async def send_message(
|
||||
self,
|
||||
target_type: str,
|
||||
target_id: str,
|
||||
message: platform_message.MessageChain,
|
||||
) -> platform_events.MessageResult:
|
||||
if target_type not in ('person', 'private'):
|
||||
raise NotSupportedError(f'send_message:{target_type}')
|
||||
|
||||
user_id, agent_id = self._parse_target_id(target_id)
|
||||
content_list = await WecomMessageConverter.yiri2target(message, self.bot)
|
||||
raw_results = []
|
||||
for content in content_list:
|
||||
raw_results.append(await self._send_content(user_id, agent_id, content))
|
||||
return platform_events.MessageResult(raw={'results': raw_results})
|
||||
|
||||
async def reply_message(
|
||||
self,
|
||||
message_source: platform_events.MessageEvent,
|
||||
message: platform_message.MessageChain,
|
||||
quote_origin: bool = False,
|
||||
) -> platform_events.MessageResult:
|
||||
wecom_event = await WecomEventConverter.yiri2target(message_source)
|
||||
if not isinstance(wecom_event, WecomEvent):
|
||||
raise ValueError('WeCom reply_message requires a WecomEvent source object')
|
||||
content_list = await WecomMessageConverter.yiri2target(message, self.bot)
|
||||
raw_results = []
|
||||
for content in content_list:
|
||||
raw_results.append(await self._send_content(wecom_event.user_id, int(wecom_event.agent_id), content))
|
||||
return platform_events.MessageResult(message_id=wecom_event.message_id, raw={'results': raw_results})
|
||||
|
||||
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.bot, params)
|
||||
|
||||
def register_listener(
|
||||
self,
|
||||
event_type: typing.Type[platform_events.Event],
|
||||
callback: typing.Callable[
|
||||
[platform_events.Event, abstract_platform_adapter.AbstractMessagePlatformAdapter], None
|
||||
],
|
||||
):
|
||||
self.listeners[event_type] = callback
|
||||
|
||||
def unregister_listener(
|
||||
self,
|
||||
event_type: typing.Type[platform_events.Event],
|
||||
callback: typing.Callable[
|
||||
[platform_events.Event, abstract_platform_adapter.AbstractMessagePlatformAdapter], None
|
||||
],
|
||||
):
|
||||
registered = self.listeners.get(event_type)
|
||||
if registered is callback:
|
||||
self.listeners.pop(event_type, None)
|
||||
|
||||
async def handle_unified_webhook(self, bot_uuid: str, path: str, request):
|
||||
return await self.bot.handle_unified_webhook(request)
|
||||
|
||||
async def run_async(self):
|
||||
async def keep_alive():
|
||||
while True:
|
||||
await asyncio.sleep(1)
|
||||
|
||||
await self.logger.info('WeCom EBA adapter running in unified webhook mode')
|
||||
await keep_alive()
|
||||
|
||||
async def kill(self) -> bool:
|
||||
return True
|
||||
|
||||
async def is_muted(self, group_id: int | None = None) -> bool:
|
||||
return False
|
||||
|
||||
def _register_native_handlers(self):
|
||||
async def on_message(event: WecomEvent):
|
||||
await self._handle_native_event(event)
|
||||
|
||||
self.bot.on_message('text')(on_message)
|
||||
self.bot.on_message('image')(on_message)
|
||||
|
||||
async def _handle_native_event(self, event: WecomEvent):
|
||||
self.bot_account_id = event.receiver_id or self.bot_account_id
|
||||
try:
|
||||
if platform_events.FriendMessage in self.listeners:
|
||||
legacy_event = await self.event_converter.target2legacy(event, self.bot)
|
||||
if legacy_event:
|
||||
callback = self.listeners.get(type(legacy_event))
|
||||
if callback:
|
||||
await callback(legacy_event, self)
|
||||
|
||||
eba_event = await self.event_converter.target2yiri(event, self.bot)
|
||||
if eba_event:
|
||||
self._cache_event(eba_event)
|
||||
await self._dispatch_eba_event(eba_event)
|
||||
except Exception:
|
||||
await self.logger.error(f'Error in wecom 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
|
||||
|
||||
async def _send_content(self, user_id: str, agent_id: int, content: dict):
|
||||
content_type = content.get('type')
|
||||
if content_type == 'text':
|
||||
return await self.bot.send_private_msg(user_id, agent_id, content.get('content', ''))
|
||||
if content_type == 'image':
|
||||
return await self.bot.send_image(user_id, agent_id, content['media_id'])
|
||||
if content_type == 'voice':
|
||||
return await self.bot.send_voice(user_id, agent_id, content['media_id'])
|
||||
if content_type == 'file':
|
||||
return await self.bot.send_file(user_id, agent_id, content['media_id'])
|
||||
raise NotSupportedError(f'send_content:{content_type}')
|
||||
|
||||
@staticmethod
|
||||
def _parse_target_id(target_id: str) -> tuple[str, int]:
|
||||
user_id, sep, agent_id = str(target_id).partition('|')
|
||||
if not user_id or not sep or not agent_id:
|
||||
raise ValueError('WeCom target_id must be formatted as "user_id|agent_id"')
|
||||
return user_id, int(agent_id)
|
||||
@@ -0,0 +1,79 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import typing
|
||||
|
||||
from langbot.libs.wecom_api.api import WecomClient
|
||||
from langbot_plugin.api.entities.builtin.platform import entities as platform_entities
|
||||
from langbot_plugin.api.entities.builtin.platform import events as platform_events
|
||||
from langbot_plugin.api.entities.builtin.platform import message as platform_message
|
||||
from langbot_plugin.api.entities.builtin.platform.errors import NotSupportedError
|
||||
|
||||
|
||||
class WecomAPIMixin:
|
||||
bot: WecomClient
|
||||
_message_cache: dict[str, platform_events.MessageReceivedEvent]
|
||||
_user_cache: dict[str, platform_entities.User]
|
||||
|
||||
async def get_message(
|
||||
self,
|
||||
chat_type: str,
|
||||
chat_id: typing.Union[int, str],
|
||||
message_id: typing.Union[int, str],
|
||||
) -> platform_events.MessageReceivedEvent:
|
||||
event = self._message_cache.get(str(message_id))
|
||||
if event is None:
|
||||
raise NotSupportedError('get_message:message_not_cached')
|
||||
return event
|
||||
|
||||
async def get_user_info(self, user_id: typing.Union[int, str]) -> platform_entities.User:
|
||||
cached = self._user_cache.get(str(user_id))
|
||||
if cached is not None:
|
||||
return cached
|
||||
info = await self.bot.get_user_info(str(user_id))
|
||||
return platform_entities.User(
|
||||
id=info.get('userid') or user_id,
|
||||
nickname=info.get('name') or str(user_id),
|
||||
username=info.get('alias') or info.get('userid') or None,
|
||||
)
|
||||
|
||||
async def get_friend_list(self) -> list[platform_entities.User]:
|
||||
return list(self._user_cache.values())
|
||||
|
||||
async def upload_file(self, file_data: bytes, filename: str) -> str:
|
||||
raise NotSupportedError('upload_file')
|
||||
|
||||
async def get_file_url(self, file_id: str) -> str:
|
||||
raise NotSupportedError('get_file_url')
|
||||
|
||||
async def get_group_info(self, group_id: typing.Union[int, str]) -> platform_entities.UserGroup:
|
||||
raise NotSupportedError('get_group_info')
|
||||
|
||||
async def get_group_member_list(
|
||||
self,
|
||||
group_id: typing.Union[int, str],
|
||||
) -> list[platform_entities.UserGroupMember]:
|
||||
raise NotSupportedError('get_group_member_list')
|
||||
|
||||
async def get_group_member_info(
|
||||
self,
|
||||
group_id: typing.Union[int, str],
|
||||
user_id: typing.Union[int, str],
|
||||
) -> platform_entities.UserGroupMember:
|
||||
raise NotSupportedError('get_group_member_info')
|
||||
|
||||
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')
|
||||
@@ -0,0 +1,91 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import typing
|
||||
|
||||
from langbot.libs.wecom_api.api import WecomClient
|
||||
from langbot.libs.wecom_api.wecomevent import WecomEvent
|
||||
import langbot_plugin.api.definition.abstract.platform.adapter as abstract_platform_adapter
|
||||
from langbot.pkg.platform.adapters.wecom.message_converter import WecomMessageConverter
|
||||
from langbot.pkg.platform.adapters.wecom.types import ADAPTER_NAME, make_private_chat_id
|
||||
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 WecomEventConverter(abstract_platform_adapter.AbstractEventConverter):
|
||||
@staticmethod
|
||||
async def yiri2target(event: platform_events.Event) -> WecomEvent | None:
|
||||
return getattr(event, 'source_platform_object', None)
|
||||
|
||||
@staticmethod
|
||||
async def target2legacy(event: WecomEvent, bot: WecomClient | None = None) -> platform_events.FriendMessage | None:
|
||||
eba_event = await WecomEventConverter.target2yiri(event, bot)
|
||||
if hasattr(eba_event, 'to_legacy_event'):
|
||||
return eba_event.to_legacy_event()
|
||||
if event.type in {'text', 'image'} and eba_event is not None:
|
||||
friend = platform_entities.Friend(
|
||||
id=f'u{event.user_id}',
|
||||
nickname=getattr(getattr(eba_event, 'sender', None), 'nickname', str(event.user_id or '')),
|
||||
remark='',
|
||||
)
|
||||
return platform_events.FriendMessage(
|
||||
sender=friend,
|
||||
message_chain=eba_event.message_chain,
|
||||
time=getattr(eba_event, 'timestamp', None),
|
||||
source_platform_object=event,
|
||||
)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
async def target2yiri(event: WecomEvent, bot: WecomClient | None = None) -> platform_events.Event | None:
|
||||
if event.type in {'text', 'image'}:
|
||||
return await WecomEventConverter.message_to_eba(event, bot)
|
||||
return WecomEventConverter.platform_specific(event, f'message.{event.detail_type or event.type or "unknown"}')
|
||||
|
||||
@staticmethod
|
||||
async def message_to_eba(event: WecomEvent, bot: WecomClient | None = None) -> platform_events.MessageReceivedEvent:
|
||||
if event.type == 'image':
|
||||
message_chain = await WecomMessageConverter.target2yiri_image(event.picurl, event.message_id)
|
||||
else:
|
||||
message_chain = await WecomMessageConverter.target2yiri_text(event.message, event.message_id)
|
||||
|
||||
sender = await WecomEventConverter.user_from_event(event, bot)
|
||||
return platform_events.MessageReceivedEvent(
|
||||
type='message.received',
|
||||
adapter_name=ADAPTER_NAME,
|
||||
message_id=event.message_id or '',
|
||||
message_chain=message_chain,
|
||||
sender=sender,
|
||||
chat_type=platform_entities.ChatType.PRIVATE,
|
||||
chat_id=make_private_chat_id(event.user_id, event.agent_id),
|
||||
group=None,
|
||||
timestamp=float(event.timestamp or 0),
|
||||
source_platform_object=event,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
async def user_from_event(event: WecomEvent, bot: WecomClient | None = None) -> platform_entities.User:
|
||||
nickname = str(event.user_id or '')
|
||||
raw: dict[str, typing.Any] = {}
|
||||
if bot and event.user_id:
|
||||
try:
|
||||
raw = await bot.get_user_info(event.user_id)
|
||||
nickname = raw.get('name') or nickname
|
||||
except Exception:
|
||||
raw = {}
|
||||
|
||||
return platform_entities.User(
|
||||
id=event.user_id or '',
|
||||
nickname=nickname,
|
||||
username=raw.get('alias') or raw.get('userid') or None,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def platform_specific(event: WecomEvent, action: str) -> platform_events.PlatformSpecificEvent:
|
||||
return platform_events.PlatformSpecificEvent(
|
||||
type='platform.specific',
|
||||
adapter_name=ADAPTER_NAME,
|
||||
action=action,
|
||||
data=dict(event),
|
||||
timestamp=float(event.timestamp or 0),
|
||||
source_platform_object=event,
|
||||
)
|
||||
@@ -0,0 +1,117 @@
|
||||
apiVersion: v1
|
||||
kind: MessagePlatformAdapter
|
||||
|
||||
metadata:
|
||||
name: wecom-eba
|
||||
label:
|
||||
en_US: WeCom (EBA)
|
||||
zh_Hans: 企业微信 (EBA)
|
||||
zh_Hant: 企業微信 (EBA)
|
||||
description:
|
||||
en_US: WeCom application message adapter (EBA architecture)
|
||||
zh_Hans: 企业微信内部应用消息适配器(EBA 架构版本)
|
||||
zh_Hant: 企業微信內部應用訊息適配器(EBA 架構版本)
|
||||
icon: wecom.png
|
||||
|
||||
spec:
|
||||
categories:
|
||||
- popular
|
||||
- china
|
||||
help_links:
|
||||
zh: https://link.langbot.app/zh/platforms/wecom
|
||||
en: https://link.langbot.app/en/platforms/wecom
|
||||
ja: https://link.langbot.app/ja/platforms/wecom
|
||||
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 WeCom app's webhook configuration
|
||||
zh_Hans: 复制此地址并粘贴到企业微信应用的 Webhook 配置中
|
||||
zh_Hant: 複製此地址並貼到企業微信應用的 Webhook 設定中
|
||||
type: webhook-url
|
||||
required: false
|
||||
default: ""
|
||||
- name: corpid
|
||||
label:
|
||||
en_US: Corpid
|
||||
zh_Hans: 企业ID
|
||||
zh_Hant: 企業ID
|
||||
type: string
|
||||
required: true
|
||||
default: ""
|
||||
- name: secret
|
||||
label:
|
||||
en_US: Secret
|
||||
zh_Hans: 密钥 (Secret)
|
||||
zh_Hant: 密鑰 (Secret)
|
||||
type: string
|
||||
required: true
|
||||
default: ""
|
||||
- name: token
|
||||
label:
|
||||
en_US: Token
|
||||
zh_Hans: 令牌 (Token)
|
||||
zh_Hant: 令牌 (Token)
|
||||
type: string
|
||||
required: true
|
||||
default: ""
|
||||
- name: EncodingAESKey
|
||||
label:
|
||||
en_US: EncodingAESKey
|
||||
zh_Hans: 消息加解密密钥 (EncodingAESKey)
|
||||
zh_Hant: 訊息加解密密鑰 (EncodingAESKey)
|
||||
type: string
|
||||
required: true
|
||||
default: ""
|
||||
- name: contacts_secret
|
||||
label:
|
||||
en_US: Contacts Secret
|
||||
zh_Hans: 通讯录密钥
|
||||
zh_Hant: 通訊錄密鑰
|
||||
type: string
|
||||
required: false
|
||||
default: ""
|
||||
- name: api_base_url
|
||||
label:
|
||||
en_US: API Base URL
|
||||
zh_Hans: API 基础 URL
|
||||
zh_Hant: API 基礎 URL
|
||||
description:
|
||||
en_US: Optional WeCom API base URL for private network or reverse proxy deployments.
|
||||
zh_Hans: 可选,若部署在内网环境并通过反向代理访问企业微信 API,可根据文档填写此项
|
||||
zh_Hant: 可選,若部署在內網環境並透過反向代理存取企業微信 API,可根據文件填寫此項
|
||||
type: string
|
||||
required: false
|
||||
default: "https://qyapi.weixin.qq.com/cgi-bin"
|
||||
|
||||
supported_events:
|
||||
- message.received
|
||||
- platform.specific
|
||||
|
||||
supported_apis:
|
||||
required:
|
||||
- send_message
|
||||
- reply_message
|
||||
optional:
|
||||
- get_message
|
||||
- get_user_info
|
||||
- get_friend_list
|
||||
- call_platform_api
|
||||
|
||||
platform_specific_apis:
|
||||
- action: check_access_token
|
||||
description: { en_US: "Check whether the current WeCom access token is usable", zh_Hans: "检查当前企业微信 access token 是否可用" }
|
||||
- action: refresh_access_token
|
||||
description: { en_US: "Refresh the WeCom access token", zh_Hans: "刷新企业微信 access token" }
|
||||
- action: get_user_info
|
||||
description: { en_US: "Get WeCom user information by user ID", zh_Hans: "按用户 ID 获取企业微信用户信息" }
|
||||
- action: send_to_all
|
||||
description: { en_US: "Send an application text message to all contacts available to the configured contacts secret", zh_Hans: "使用配置的通讯录密钥向可见成员群发应用文本消息" }
|
||||
|
||||
execution:
|
||||
python:
|
||||
path: ./adapter.py
|
||||
attr: WecomAdapter
|
||||
@@ -0,0 +1,82 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
|
||||
from langbot.libs.wecom_api.api import WecomClient
|
||||
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
|
||||
|
||||
|
||||
def split_string_by_bytes(text: str, limit: int = 2048, encoding: str = 'utf-8') -> list[str]:
|
||||
"""Split text without cutting a multi-byte character in half."""
|
||||
bytes_data = text.encode(encoding)
|
||||
total_len = len(bytes_data)
|
||||
parts: list[str] = []
|
||||
start = 0
|
||||
|
||||
while start < total_len:
|
||||
end = min(start + limit, total_len)
|
||||
chunk = bytes_data[start:end]
|
||||
part = chunk.decode(encoding, errors='ignore')
|
||||
part_len = len(part.encode(encoding))
|
||||
if part_len == 0 and end < total_len:
|
||||
start += 1
|
||||
continue
|
||||
parts.append(part)
|
||||
start += part_len
|
||||
|
||||
return parts
|
||||
|
||||
|
||||
class WecomMessageConverter(abstract_platform_adapter.AbstractMessageConverter):
|
||||
@staticmethod
|
||||
async def yiri2target(message_chain: platform_message.MessageChain, bot: WecomClient) -> list[dict]:
|
||||
content_list: list[dict] = []
|
||||
|
||||
for msg in message_chain:
|
||||
if isinstance(msg, platform_message.Source):
|
||||
continue
|
||||
if isinstance(msg, platform_message.Plain):
|
||||
content_list.extend({'type': 'text', 'content': chunk} for chunk in split_string_by_bytes(msg.text))
|
||||
elif isinstance(msg, platform_message.Image):
|
||||
content_list.append({'type': 'image', 'media_id': await bot.get_media_id(msg)})
|
||||
elif isinstance(msg, platform_message.Voice):
|
||||
content_list.append({'type': 'voice', 'media_id': await bot.get_media_id(msg)})
|
||||
elif isinstance(msg, platform_message.File):
|
||||
content_list.append({'type': 'file', 'media_id': await bot.get_media_id(msg)})
|
||||
elif isinstance(msg, platform_message.Forward):
|
||||
for node in msg.node_list:
|
||||
content_list.extend(await WecomMessageConverter.yiri2target(node.message_chain, bot))
|
||||
elif isinstance(msg, platform_message.Quote):
|
||||
if msg.id is not None:
|
||||
content_list.append({'type': 'text', 'content': f'[Quote {msg.id}] '})
|
||||
if msg.origin:
|
||||
content_list.extend(await WecomMessageConverter.yiri2target(msg.origin, bot))
|
||||
elif isinstance(msg, platform_message.At):
|
||||
content_list.append({'type': 'text', 'content': f'@{msg.display or msg.target}'})
|
||||
elif isinstance(msg, platform_message.AtAll):
|
||||
content_list.append({'type': 'text', 'content': '@all'})
|
||||
else:
|
||||
content_list.append({'type': 'text', 'content': str(msg)})
|
||||
|
||||
return content_list
|
||||
|
||||
@staticmethod
|
||||
async def target2yiri_text(message: str | None, message_id: int | str | None = -1) -> platform_message.MessageChain:
|
||||
return platform_message.MessageChain(
|
||||
[
|
||||
platform_message.Source(id=message_id, time=datetime.datetime.now()),
|
||||
platform_message.Plain(text=message or ''),
|
||||
]
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
async def target2yiri_image(picurl: str, message_id: int | str | None = -1) -> platform_message.MessageChain:
|
||||
image_base64, image_format = await image.get_wecom_image_base64(pic_url=picurl)
|
||||
return platform_message.MessageChain(
|
||||
[
|
||||
platform_message.Source(id=message_id, time=datetime.datetime.now()),
|
||||
platform_message.Image(base64=f'data:image/{image_format};base64,{image_base64}'),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,40 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import typing
|
||||
|
||||
from langbot.libs.wecom_api.api import WecomClient
|
||||
|
||||
|
||||
async def check_access_token(bot: WecomClient, params: dict) -> dict:
|
||||
return {'valid': await bot.check_access_token()}
|
||||
|
||||
|
||||
async def refresh_access_token(bot: WecomClient, params: dict) -> dict:
|
||||
bot.access_token = await bot.get_access_token(bot.secret)
|
||||
return {'ok': bool(bot.access_token)}
|
||||
|
||||
|
||||
async def get_user_info(bot: WecomClient, params: dict) -> dict:
|
||||
user_id = params.get('user_id') or params.get('userid')
|
||||
if not user_id:
|
||||
raise ValueError('user_id is required')
|
||||
return await bot.get_user_info(str(user_id))
|
||||
|
||||
|
||||
async def send_to_all(bot: WecomClient, params: dict) -> dict:
|
||||
content = params.get('content')
|
||||
agent_id = params.get('agent_id') or params.get('agentid')
|
||||
if not content:
|
||||
raise ValueError('content is required')
|
||||
if agent_id is None:
|
||||
raise ValueError('agent_id is required')
|
||||
await bot.send_to_all(str(content), int(agent_id))
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
PLATFORM_API_MAP: dict[str, typing.Callable[[WecomClient, dict], typing.Awaitable[dict]]] = {
|
||||
'check_access_token': check_access_token,
|
||||
'refresh_access_token': refresh_access_token,
|
||||
'get_user_info': get_user_info,
|
||||
'send_to_all': send_to_all,
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
ADAPTER_NAME = 'wecom-eba'
|
||||
|
||||
|
||||
def make_private_chat_id(user_id: str | int | None, agent_id: str | int | None) -> str:
|
||||
"""Build the routable private chat id used by the WeCom EBA adapter."""
|
||||
user = str(user_id or '')
|
||||
agent = str(agent_id or '')
|
||||
if not user or not agent:
|
||||
return user
|
||||
return f'{user}|{agent}'
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 257 KiB |
Reference in New Issue
Block a user