mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-06-10 15:56:03 +00:00
feat(platform): add wecom customer service eba adapter
This commit is contained in:
@@ -207,7 +207,33 @@ class WecomCSClient:
|
||||
return await self.send_text_msg(open_kfid, external_userid, msgid, content)
|
||||
if data['errcode'] != 0:
|
||||
await self.logger.error(f'发送消息失败:{data}')
|
||||
raise Exception('Failed to send message')
|
||||
raise Exception(f'Failed to send message: {data}')
|
||||
return data
|
||||
|
||||
async def send_image_msg(self, open_kfid: str, external_userid: str, msgid: str, media_id: str):
|
||||
if not await self.check_access_token():
|
||||
self.access_token = await self.get_access_token(self.secret)
|
||||
|
||||
url = f'{self.base_url}/kf/send_msg?access_token={self.access_token}'
|
||||
payload = {
|
||||
'touser': external_userid,
|
||||
'open_kfid': open_kfid,
|
||||
'msgid': msgid,
|
||||
'msgtype': 'image',
|
||||
'image': {
|
||||
'media_id': media_id,
|
||||
},
|
||||
}
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.post(url, json=payload)
|
||||
data = response.json()
|
||||
if data['errcode'] == 40014 or data['errcode'] == 42001:
|
||||
self.access_token = await self.get_access_token(self.secret)
|
||||
return await self.send_image_msg(open_kfid, external_userid, msgid, media_id)
|
||||
if data['errcode'] != 0:
|
||||
await self.logger.error(f'发送图片消息失败:{data}')
|
||||
raise Exception('Failed to send image message')
|
||||
return data
|
||||
|
||||
async def handle_callback_request(self):
|
||||
@@ -322,7 +348,7 @@ class WecomCSClient:
|
||||
if not await self.check_access_token():
|
||||
self.access_token = await self.get_access_token(self.secret)
|
||||
|
||||
url = self.base_url + '/media/upload?access_token=' + self.access_token + '&type=file'
|
||||
url = self.base_url + '/media/upload?access_token=' + self.access_token + '&type=image'
|
||||
file_bytes = None
|
||||
file_name = 'uploaded_file.txt'
|
||||
|
||||
@@ -368,7 +394,7 @@ class WecomCSClient:
|
||||
self.access_token = await self.get_access_token(self.secret)
|
||||
media_id = await self.upload_to_work(image)
|
||||
if data.get('errcode', 0) != 0:
|
||||
raise Exception('failed to upload file')
|
||||
raise Exception(f'failed to upload image: {data}')
|
||||
|
||||
media_id = data.get('media_id')
|
||||
return media_id
|
||||
|
||||
5
src/langbot/pkg/platform/adapters/wecomcs/__init__.py
Normal file
5
src/langbot/pkg/platform/adapters/wecomcs/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
"""WeCom Customer Service EBA platform adapter."""
|
||||
|
||||
from langbot.pkg.platform.adapters.wecomcs.adapter import WecomCSAdapter
|
||||
|
||||
__all__ = ['WecomCSAdapter']
|
||||
227
src/langbot/pkg/platform/adapters/wecomcs/adapter.py
Normal file
227
src/langbot/pkg/platform/adapters/wecomcs/adapter.py
Normal file
@@ -0,0 +1,227 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
import traceback
|
||||
import typing
|
||||
import uuid
|
||||
|
||||
import pydantic
|
||||
|
||||
from langbot.libs.wecom_customer_service_api.api import WecomCSClient
|
||||
from langbot.libs.wecom_customer_service_api.wecomcsevent import WecomCSEvent
|
||||
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.wecomcs.api_impl import WecomCSAPIMixin
|
||||
from langbot.pkg.platform.adapters.wecomcs.event_converter import WecomCSEventConverter
|
||||
from langbot.pkg.platform.adapters.wecomcs.message_converter import WecomCSMessageConverter
|
||||
from langbot.pkg.platform.adapters.wecomcs.platform_api import PLATFORM_API_MAP
|
||||
from langbot.pkg.platform.adapters.wecomcs.types import parse_private_chat_id
|
||||
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 WecomCSAdapter(WecomCSAPIMixin, abstract_platform_adapter.AbstractPlatformAdapter):
|
||||
bot: WecomCSClient = pydantic.Field(exclude=True)
|
||||
|
||||
message_converter: WecomCSMessageConverter = WecomCSMessageConverter()
|
||||
event_converter: WecomCSEventConverter = WecomCSEventConverter()
|
||||
|
||||
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'WeComCS missing required config fields: {missing_keys}')
|
||||
|
||||
bot = WecomCSClient(
|
||||
corpid=config['corpid'],
|
||||
secret=config['secret'],
|
||||
token=config['token'],
|
||||
EncodingAESKey=config['EncodingAESKey'],
|
||||
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}')
|
||||
|
||||
external_userid, open_kfid = parse_private_chat_id(target_id)
|
||||
content_list = await WecomCSMessageConverter.yiri2target(message, self.bot)
|
||||
raw_results = []
|
||||
for content in content_list:
|
||||
raw_results.append(await self._send_content(open_kfid, external_userid, self._make_outbound_msgid(), 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 WecomCSEventConverter.yiri2target(message_source)
|
||||
if not isinstance(wecom_event, WecomCSEvent):
|
||||
raise ValueError('WeComCS reply_message requires a WecomCSEvent source object')
|
||||
content_list = await WecomCSMessageConverter.yiri2target(message, self.bot)
|
||||
raw_results = []
|
||||
for content in content_list:
|
||||
raw_results.append(
|
||||
await self._send_content(
|
||||
wecom_event.receiver_id,
|
||||
wecom_event.user_id,
|
||||
self._make_outbound_msgid(),
|
||||
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('WeComCS 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: WecomCSEvent):
|
||||
await self._handle_native_event(event)
|
||||
|
||||
for msg_type in ('text', 'image', 'file', 'voice'):
|
||||
self.bot.on_message(msg_type)(on_message)
|
||||
|
||||
async def _handle_native_event(self, event: WecomCSEvent):
|
||||
self.bot_account_id = event.receiver_id or self.bot_account_id
|
||||
try:
|
||||
if event.message_id and str(event.message_id) in self._message_cache:
|
||||
await self.logger.debug(f'Skip duplicated WeComCS message: {event.message_id}')
|
||||
return
|
||||
|
||||
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 wecomcs 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, open_kfid: str, external_userid: str, msgid: str, content: dict):
|
||||
content_type = content.get('type')
|
||||
if content_type == 'text':
|
||||
return await self.bot.send_text_msg(open_kfid, external_userid, msgid, content.get('content', ''))
|
||||
if content_type == 'image':
|
||||
return await self.bot.send_image_msg(open_kfid, external_userid, msgid, content['media_id'])
|
||||
raise NotSupportedError(f'send_content:{content_type}')
|
||||
|
||||
@staticmethod
|
||||
def _make_outbound_msgid() -> str:
|
||||
return f'lb-{int(time.time() * 1000)}-{uuid.uuid4().hex[:8]}'
|
||||
82
src/langbot/pkg/platform/adapters/wecomcs/api_impl.py
Normal file
82
src/langbot/pkg/platform/adapters/wecomcs/api_impl.py
Normal file
@@ -0,0 +1,82 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import typing
|
||||
|
||||
from langbot.libs.wecom_customer_service_api.api import WecomCSClient
|
||||
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 WecomCSAPIMixin:
|
||||
bot: WecomCSClient
|
||||
_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_customer_info(str(user_id))
|
||||
if not info:
|
||||
raise NotSupportedError('get_user_info:not_found')
|
||||
return platform_entities.User(
|
||||
id=info.get('external_userid') or user_id,
|
||||
nickname=info.get('nickname') or str(user_id),
|
||||
avatar_url=info.get('avatar'),
|
||||
username=info.get('external_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')
|
||||
78
src/langbot/pkg/platform/adapters/wecomcs/event_converter.py
Normal file
78
src/langbot/pkg/platform/adapters/wecomcs/event_converter.py
Normal file
@@ -0,0 +1,78 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import typing
|
||||
|
||||
from langbot.libs.wecom_customer_service_api.api import WecomCSClient
|
||||
from langbot.libs.wecom_customer_service_api.wecomcsevent import WecomCSEvent
|
||||
import langbot_plugin.api.definition.abstract.platform.adapter as abstract_platform_adapter
|
||||
from langbot.pkg.platform.adapters.wecomcs.message_converter import WecomCSMessageConverter
|
||||
from langbot.pkg.platform.adapters.wecomcs.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 WecomCSEventConverter(abstract_platform_adapter.AbstractEventConverter):
|
||||
@staticmethod
|
||||
async def yiri2target(event: platform_events.Event) -> WecomCSEvent | None:
|
||||
return getattr(event, 'source_platform_object', None)
|
||||
|
||||
@staticmethod
|
||||
async def target2legacy(event: WecomCSEvent, bot: WecomCSClient | None = None) -> platform_events.FriendMessage | None:
|
||||
eba_event = await WecomCSEventConverter.target2yiri(event, bot)
|
||||
if hasattr(eba_event, 'to_legacy_event'):
|
||||
return eba_event.to_legacy_event()
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
async def target2yiri(event: WecomCSEvent, bot: WecomCSClient | None = None) -> platform_events.Event | None:
|
||||
if event.type in {'text', 'image', 'file', 'voice'}:
|
||||
return await WecomCSEventConverter.message_to_eba(event, bot)
|
||||
return WecomCSEventConverter.platform_specific(event, f'wecomcs.{event.type or "unknown"}')
|
||||
|
||||
@staticmethod
|
||||
async def message_to_eba(event: WecomCSEvent, bot: WecomCSClient | None = None) -> platform_events.MessageReceivedEvent:
|
||||
message_chain = await WecomCSMessageConverter.target2yiri(event)
|
||||
sender = await WecomCSEventConverter.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.receiver_id),
|
||||
group=None,
|
||||
timestamp=float(event.timestamp or 0),
|
||||
source_platform_object=event,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
async def user_from_event(event: WecomCSEvent, bot: WecomCSClient | None = None) -> platform_entities.User:
|
||||
nickname = str(event.user_id or '')
|
||||
avatar_url = None
|
||||
raw: dict[str, typing.Any] = {}
|
||||
if bot and event.user_id:
|
||||
try:
|
||||
raw = await bot.get_customer_info(event.user_id) or {}
|
||||
nickname = raw.get('nickname') or nickname
|
||||
avatar_url = raw.get('avatar')
|
||||
except Exception:
|
||||
raw = {}
|
||||
|
||||
return platform_entities.User(
|
||||
id=event.user_id or '',
|
||||
nickname=nickname,
|
||||
avatar_url=avatar_url,
|
||||
username=raw.get('external_userid') or None,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def platform_specific(event: WecomCSEvent, 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,
|
||||
)
|
||||
106
src/langbot/pkg/platform/adapters/wecomcs/manifest.yaml
Normal file
106
src/langbot/pkg/platform/adapters/wecomcs/manifest.yaml
Normal file
@@ -0,0 +1,106 @@
|
||||
apiVersion: v1
|
||||
kind: MessagePlatformAdapter
|
||||
|
||||
metadata:
|
||||
name: wecomcs-eba
|
||||
label:
|
||||
en_US: WeCom Customer Service (EBA)
|
||||
zh_Hans: 企业微信客服 (EBA)
|
||||
zh_Hant: 企業微信客服 (EBA)
|
||||
description:
|
||||
en_US: WeCom Customer Service adapter with Event-Based Agents support
|
||||
zh_Hans: 企业微信客服适配器(EBA 架构版本),通过统一 Webhook 接收客服会话消息
|
||||
zh_Hant: 企業微信客服適配器(EBA 架構版本),透過統一 Webhook 接收客服會話訊息
|
||||
icon: wecom.png
|
||||
|
||||
spec:
|
||||
categories:
|
||||
- china
|
||||
help_links:
|
||||
zh: https://link.langbot.app/zh/platforms/wecomcs
|
||||
en: https://link.langbot.app/en/platforms/wecomcs
|
||||
ja: https://link.langbot.app/ja/platforms/wecomcs
|
||||
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 Customer Service 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: 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 Customer Service access token is usable", zh_Hans: "检查当前企业微信客服 access token 是否可用" }
|
||||
- action: refresh_access_token
|
||||
description: { en_US: "Refresh the WeCom Customer Service access token", zh_Hans: "刷新企业微信客服 access token" }
|
||||
- action: get_customer_info
|
||||
description: { en_US: "Get WeCom Customer Service customer information by external user ID", zh_Hans: "按 external_userid 获取企业微信客服客户信息" }
|
||||
|
||||
execution:
|
||||
python:
|
||||
path: ./adapter.py
|
||||
attr: WecomCSAdapter
|
||||
@@ -0,0 +1,91 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
|
||||
from langbot.libs.wecom_customer_service_api.api import WecomCSClient
|
||||
import langbot_plugin.api.definition.abstract.platform.adapter as abstract_platform_adapter
|
||||
from langbot_plugin.api.entities.builtin.platform import message as platform_message
|
||||
from langbot_plugin.api.entities.builtin.platform.errors import NotSupportedError
|
||||
|
||||
|
||||
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 WecomCSMessageConverter(abstract_platform_adapter.AbstractMessageConverter):
|
||||
@staticmethod
|
||||
async def yiri2target(message_chain: platform_message.MessageChain, bot: WecomCSClient) -> 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.Forward):
|
||||
for node in msg.node_list:
|
||||
content_list.extend(await WecomCSMessageConverter.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 WecomCSMessageConverter.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'})
|
||||
elif isinstance(msg, (platform_message.Voice, platform_message.File, platform_message.Face)):
|
||||
raise NotSupportedError(f'wecomcs_send_component:{msg.type}')
|
||||
else:
|
||||
content_list.append({'type': 'text', 'content': str(msg)})
|
||||
|
||||
return content_list
|
||||
|
||||
@staticmethod
|
||||
async def target2yiri(event: dict) -> platform_message.MessageChain:
|
||||
message_id = event.get('msgid') or ''
|
||||
timestamp = event.get('send_time') or event.get('sendtime') or datetime.datetime.now().timestamp()
|
||||
components: list[platform_message.MessageComponent] = [
|
||||
platform_message.Source(id=message_id, time=datetime.datetime.fromtimestamp(float(timestamp))),
|
||||
]
|
||||
|
||||
msgtype = event.get('msgtype')
|
||||
if msgtype == 'text':
|
||||
components.append(platform_message.Plain(text=(event.get('text') or {}).get('content', '')))
|
||||
elif msgtype == 'image':
|
||||
components.append(platform_message.Image(base64=event.get('picurl') or ''))
|
||||
elif msgtype == 'file':
|
||||
file_data = event.get('file') or {}
|
||||
components.append(
|
||||
platform_message.File(
|
||||
id=file_data.get('media_id'),
|
||||
name=file_data.get('filename') or file_data.get('file_name') or '',
|
||||
size=file_data.get('file_size') or 0,
|
||||
)
|
||||
)
|
||||
elif msgtype == 'voice':
|
||||
voice_data = event.get('voice') or {}
|
||||
components.append(platform_message.Voice(voice_id=voice_data.get('media_id') or ''))
|
||||
else:
|
||||
components.append(platform_message.Unknown(text=f'[unsupported wecomcs msgtype: {msgtype or "unknown"}]'))
|
||||
|
||||
return platform_message.MessageChain(components)
|
||||
29
src/langbot/pkg/platform/adapters/wecomcs/platform_api.py
Normal file
29
src/langbot/pkg/platform/adapters/wecomcs/platform_api.py
Normal file
@@ -0,0 +1,29 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import typing
|
||||
|
||||
from langbot.libs.wecom_customer_service_api.api import WecomCSClient
|
||||
|
||||
|
||||
async def check_access_token(bot: WecomCSClient, params: dict) -> dict:
|
||||
return {'valid': await bot.check_access_token()}
|
||||
|
||||
|
||||
async def refresh_access_token(bot: WecomCSClient, params: dict) -> dict:
|
||||
bot.access_token = await bot.get_access_token(bot.secret)
|
||||
return {'ok': bool(bot.access_token)}
|
||||
|
||||
|
||||
async def get_customer_info(bot: WecomCSClient, params: dict) -> dict:
|
||||
user_id = params.get('external_userid') or params.get('user_id') or params.get('userid')
|
||||
if not user_id:
|
||||
raise ValueError('external_userid is required')
|
||||
info = await bot.get_customer_info(str(user_id))
|
||||
return info or {}
|
||||
|
||||
|
||||
PLATFORM_API_MAP: dict[str, typing.Callable[[WecomCSClient, dict], typing.Awaitable[dict]]] = {
|
||||
'check_access_token': check_access_token,
|
||||
'refresh_access_token': refresh_access_token,
|
||||
'get_customer_info': get_customer_info,
|
||||
}
|
||||
19
src/langbot/pkg/platform/adapters/wecomcs/types.py
Normal file
19
src/langbot/pkg/platform/adapters/wecomcs/types.py
Normal file
@@ -0,0 +1,19 @@
|
||||
from __future__ import annotations
|
||||
|
||||
ADAPTER_NAME = 'wecomcs-eba'
|
||||
|
||||
|
||||
def make_private_chat_id(user_id: str | int | None, open_kfid: str | int | None) -> str:
|
||||
"""Build the routable private chat id used by the WeCom CS EBA adapter."""
|
||||
user = str(user_id or '')
|
||||
kfid = str(open_kfid or '')
|
||||
if not user or not kfid:
|
||||
return user
|
||||
return f'{user}|{kfid}'
|
||||
|
||||
|
||||
def parse_private_chat_id(chat_id: str | int) -> tuple[str, str]:
|
||||
user_id, sep, open_kfid = str(chat_id).partition('|')
|
||||
if not user_id or not sep or not open_kfid:
|
||||
raise ValueError('WeComCS target_id must be formatted as "external_userid|open_kfid"')
|
||||
return user_id, open_kfid
|
||||
BIN
src/langbot/pkg/platform/adapters/wecomcs/wecom.png
Normal file
BIN
src/langbot/pkg/platform/adapters/wecomcs/wecom.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 257 KiB |
Reference in New Issue
Block a user