feat(platform): add qqofficial eba adapter

This commit is contained in:
WangCham
2026-06-02 16:51:45 +08:00
parent 8a42fd8b21
commit 7e5d74a1ad
15 changed files with 1469 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
"""QQ Official API EBA platform adapter."""
from langbot.pkg.platform.adapters.qqofficial.adapter import QQOfficialAdapter
__all__ = ['QQOfficialAdapter']

View File

@@ -0,0 +1,400 @@
from __future__ import annotations
import asyncio
import time
import traceback
import typing
import pydantic
from langbot.libs.qq_official_api.api import QQOfficialClient
from langbot.libs.qq_official_api.qqofficialevent import QQOfficialEvent
from langbot.pkg.platform.adapters.qqofficial.api_impl import QQOfficialAPIMixin
from langbot.pkg.platform.adapters.qqofficial.errors import NotSupportedError
from langbot.pkg.platform.adapters.qqofficial.event_converter import QQOfficialEventConverter
from langbot.pkg.platform.adapters.qqofficial.message_converter import QQOfficialMessageConverter
from langbot.pkg.platform.adapters.qqofficial.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 QQOfficialAdapter(QQOfficialAPIMixin, abstract_platform_adapter.AbstractPlatformAdapter):
bot: typing.Any = pydantic.Field(exclude=True)
message_converter: QQOfficialMessageConverter = QQOfficialMessageConverter()
event_converter: QQOfficialEventConverter = QQOfficialEventConverter()
config: dict
bot_uuid: str | None = None
enable_webhook: bool = False
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] = {}
_stream_ctx: dict[str, dict] = {}
_stream_ctx_ts: dict[str, float] = {}
_fallback_text: dict[str, str] = {}
_fallback_text_ts: dict[str, float] = {}
_ws_task: asyncio.Task | None = None
_STREAM_CTX_TTL = 300
class Config:
arbitrary_types_allowed = True
def __init__(self, config: dict, logger: abstract_platform_logger.AbstractEventLogger):
required_keys = ['appid', 'secret', 'token']
missing_keys = [key for key in required_keys if not config.get(key)]
if missing_keys:
raise Exception(f'QQOfficial EBA adapter missing config: {missing_keys}')
enable_webhook = config.get('enable-webhook', config.get('enable_webhook', False))
bot = QQOfficialClient(
app_id=config['appid'],
secret=config['secret'],
token=config['token'],
logger=logger,
unified_mode=enable_webhook,
)
super().__init__(
config=config,
logger=logger,
bot=bot,
bot_account_id=config['appid'],
bot_uuid=None,
enable_webhook=enable_webhook,
listeners={},
_message_cache={},
_user_cache={},
_group_cache={},
_member_cache={},
_stream_ctx={},
_stream_ctx_ts={},
_fallback_text={},
_fallback_text_ts={},
_ws_task=None,
)
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_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:
raw = await self._send_content_list(str(target_type), str(target_id), await QQOfficialMessageConverter.yiri2target(message))
return platform_events.MessageResult(raw={'results': raw})
async def reply_message(
self,
message_source: platform_events.MessageEvent,
message: platform_message.MessageChain,
quote_origin: bool = False,
) -> platform_events.MessageResult:
source = await QQOfficialEventConverter.yiri2target(message_source)
if not isinstance(source, QQOfficialEvent):
raise ValueError('QQOfficial reply_message requires a QQOfficialEvent source object')
target_type, target_id = self._reply_target(source)
raw = await self._send_content_list(
target_type,
target_id,
await QQOfficialMessageConverter.yiri2target(message),
msg_id=source.d_id,
)
return platform_events.MessageResult(message_id=source.d_id or source.id, raw={'results': 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):
if self.enable_webhook:
await self.logger.info('QQ Official EBA adapter running in unified webhook mode')
while True:
await asyncio.sleep(1)
else:
await self._run_websocket()
async def kill(self) -> bool:
if self._ws_task:
self._ws_task.cancel()
try:
await self._ws_task
except asyncio.CancelledError:
pass
self._ws_task = None
return True
async def is_muted(self, group_id: int | None = None) -> bool:
return False
async def is_stream_output_supported(self) -> bool:
return bool(self.config.get('enable-stream-reply') or self.config.get('enable_stream_reply'))
async def create_message_card(self, message_id: str, event: platform_events.MessageEvent) -> bool:
source = event.source_platform_object
if not isinstance(source, QQOfficialEvent) or source.t != 'C2C_MESSAGE_CREATE':
return False
self._stream_ctx[message_id] = {
'user_openid': source.user_openid,
'msg_id': source.d_id,
'stream_msg_id': None,
'msg_seq': 1,
'index': 0,
'last_update_ts': 0,
'accumulated_text': '',
'sent_length': 0,
'session_started': False,
}
self._stream_ctx_ts[message_id] = time.time()
return True
async def reply_message_chunk(
self,
message_source: platform_events.MessageEvent,
bot_message: dict,
message: platform_message.MessageChain,
quote_origin: bool = False,
is_final: bool = False,
):
await self._cleanup_stale_streams()
chunk_text = '\n\n'.join(component.text for component in message if isinstance(component, platform_message.Plain))
message_id = bot_message.get('resp_message_id') if isinstance(bot_message, dict) else getattr(bot_message, 'resp_message_id', None)
if not message_id or message_id not in self._stream_ctx:
if chunk_text:
self._fallback_text[message_id] = self._fallback_text.get(message_id, '') + chunk_text
self._fallback_text_ts[message_id] = time.time()
if is_final:
full_text = self._fallback_text.pop(message_id, '')
if full_text:
await self.reply_message(message_source, platform_message.MessageChain([platform_message.Plain(text=full_text)]), quote_origin)
return
ctx = self._stream_ctx[message_id]
if chunk_text:
ctx['accumulated_text'] += chunk_text
if not ctx['session_started']:
if not ctx['accumulated_text']:
return
ctx['session_started'] = True
content_to_send = ctx['accumulated_text'][ctx['sent_length'] :]
if not content_to_send and not is_final:
return
now = time.time()
if not is_final and (now - ctx['last_update_ts']) < 0.5:
return
ctx['last_update_ts'] = now
resp = await self.bot.send_stream_msg(
user_openid=ctx['user_openid'],
content=content_to_send,
event_id=ctx['msg_id'],
msg_id=ctx['msg_id'],
msg_seq=ctx['msg_seq'],
index=ctx['index'],
stream_msg_id=ctx['stream_msg_id'],
input_state=10 if is_final else 1,
)
if isinstance(resp, dict) and resp.get('id'):
ctx['stream_msg_id'] = resp['id']
ctx['sent_length'] = len(ctx['accumulated_text'])
ctx['index'] += 1
if is_final:
self._stream_ctx.pop(message_id, None)
self._stream_ctx_ts.pop(message_id, None)
def _register_native_handlers(self):
for event_type in ('C2C_MESSAGE_CREATE', 'DIRECT_MESSAGE_CREATE', 'GROUP_AT_MESSAGE_CREATE', 'AT_MESSAGE_CREATE'):
self.bot.on_message(event_type)(self._handle_native_event)
async def _handle_native_event(self, event: QQOfficialEvent):
self.bot_account_id = self.config.get('appid', self.bot_account_id)
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 qqofficial 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 _run_websocket(self):
await self.logger.info('QQ Official EBA adapter starting in WebSocket mode')
async def on_ready():
await self.logger.info('QQ Official WebSocket connected and ready')
async def on_event(event_type: str, event_data: dict):
if event_type not in {'C2C_MESSAGE_CREATE', 'DIRECT_MESSAGE_CREATE', 'GROUP_AT_MESSAGE_CREATE', 'AT_MESSAGE_CREATE'}:
await self._dispatch_eba_event(QQOfficialEventConverter.platform_specific(QQOfficialEvent({'t': event_type, **(event_data or {})}), f'qqofficial.{event_type}'))
return
if not isinstance(event_data, dict):
await self.logger.warning(f'Event data is not dict, skipping: {event_type} -> {type(event_data)}')
return
payload = {'t': event_type, 'd': event_data}
message_data = await self.bot.get_message(payload)
if message_data:
await self.bot._handle_message(QQOfficialEvent.from_payload(message_data))
async def on_error(error: Exception):
await self.logger.error(f'QQ Official WebSocket error: {error}')
self._ws_task = asyncio.create_task(self.bot.connect_gateway_loop(on_event, on_ready, on_error))
try:
await self._ws_task
except asyncio.CancelledError:
pass
@staticmethod
def _reply_target(event: QQOfficialEvent) -> tuple[str, str]:
if event.t == 'C2C_MESSAGE_CREATE':
return 'person', event.user_openid
if event.t == 'GROUP_AT_MESSAGE_CREATE':
return 'group', event.group_openid
if event.t == 'AT_MESSAGE_CREATE':
return 'channel', event.channel_id
if event.t == 'DIRECT_MESSAGE_CREATE':
return 'channel_private', event.guild_id
raise NotSupportedError(f'reply_message:{event.t or "unknown_event"}')
async def _send_content_list(self, target_type: str, target_id: str, content_list: list[dict], msg_id: str | None = None) -> list[dict]:
target_type = self._normalize_target_type(target_type)
results: list[dict] = []
for content in content_list:
content_type = content.get('type', 'text')
if target_type == 'channel':
if content_type == 'text':
raw = await self.bot.send_channle_group_text_msg(target_id, content.get('content', ''), msg_id)
results.append({'type': content_type, 'raw': raw})
continue
if target_type == 'channel_private':
if content_type == 'text':
raw = await self.bot.send_channle_private_text_msg(target_id, content.get('content', ''), msg_id)
results.append({'type': content_type, 'raw': raw})
continue
if content_type == 'text':
if target_type == 'c2c':
raw = await self.bot.send_private_text_msg(target_id, content.get('content', ''), msg_id)
elif target_type == 'group':
raw = await self.bot.send_group_text_msg(target_id, content.get('content', ''), msg_id)
else:
raise NotSupportedError(f'send_message:{target_type}')
results.append({'type': content_type, 'raw': raw})
elif content_type == 'image':
raw = await self.bot.send_image_msg(target_type, target_id, file_url=content.get('url'), file_data=content.get('base64'), msg_id=msg_id)
results.append({'type': content_type, 'raw': raw})
elif content_type == 'voice':
raw = await self.bot.send_voice_msg(target_type, target_id, file_url=content.get('url'), file_data=content.get('base64'), msg_id=msg_id)
results.append({'type': content_type, 'raw': raw})
elif content_type == 'file':
raw = await self.bot.send_file_msg(
target_type,
target_id,
file_url=content.get('url'),
file_data=content.get('base64'),
file_name=content.get('name', 'file'),
msg_id=msg_id,
)
results.append({'type': content_type, 'raw': raw})
return results
@staticmethod
def _normalize_target_type(target_type: str) -> str:
if target_type in {'person', 'private', 'friend', 'c2c'}:
return 'c2c'
if target_type in {'group', 'group_openid'}:
return 'group'
if target_type in {'channel', 'guild'}:
return 'channel'
if target_type in {'channel_private', 'direct', 'dm'}:
return 'channel_private'
return target_type
async def _cleanup_stale_streams(self):
now = time.time()
for message_id in [key for key, ts in self._stream_ctx_ts.items() if now - ts > self._STREAM_CTX_TTL]:
self._stream_ctx.pop(message_id, None)
self._stream_ctx_ts.pop(message_id, None)
for message_id in [key for key, ts in self._fallback_text_ts.items() if now - ts > self._STREAM_CTX_TTL]:
self._fallback_text.pop(message_id, None)
self._fallback_text_ts.pop(message_id, None)

View File

@@ -0,0 +1,103 @@
from __future__ import annotations
import typing
from langbot.pkg.platform.adapters.qqofficial.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 QQOfficialAPIMixin:
_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_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 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 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')
async def mute_member(self, group_id: typing.Union[int, str], user_id: typing.Union[int, str], duration: int = 0):
raise NotSupportedError('mute_member')
async def unmute_member(self, group_id: typing.Union[int, str], user_id: typing.Union[int, str]):
raise NotSupportedError('unmute_member')
async def kick_member(self, group_id: typing.Union[int, str], user_id: typing.Union[int, str]):
raise NotSupportedError('kick_member')
async def leave_group(self, group_id: typing.Union[int, str]):
raise NotSupportedError('leave_group')

View File

@@ -0,0 +1,11 @@
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

View File

@@ -0,0 +1,116 @@
from __future__ import annotations
import datetime
import time
import typing
from langbot.libs.qq_official_api.qqofficialevent import QQOfficialEvent
from langbot.pkg.platform.adapters.qqofficial.message_converter import QQOfficialMessageConverter
from langbot.pkg.platform.adapters.qqofficial.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 QQOfficialEventConverter(abstract_platform_adapter.AbstractEventConverter):
@staticmethod
async def yiri2target(event: platform_events.Event) -> typing.Any:
return getattr(event, 'source_platform_object', None)
async def target2legacy(self, event: QQOfficialEvent) -> 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: QQOfficialEvent) -> platform_events.Event:
if event.t in {'C2C_MESSAGE_CREATE', 'DIRECT_MESSAGE_CREATE', 'GROUP_AT_MESSAGE_CREATE', 'AT_MESSAGE_CREATE'}:
return await self.message_to_eba(event)
return self.platform_specific(event, f'qqofficial.{event.t or "unknown"}')
async def message_to_eba(self, event: QQOfficialEvent) -> platform_events.MessageReceivedEvent:
timestamp = _timestamp_value(event.timestamp)
sender = platform_entities.User(
id=self._sender_id(event),
nickname=event.username or self._sender_id(event),
)
chat_type = platform_entities.ChatType.PRIVATE
chat_id = self._private_chat_id(event)
group = None
if event.t in {'GROUP_AT_MESSAGE_CREATE', 'AT_MESSAGE_CREATE'}:
chat_type = platform_entities.ChatType.GROUP
chat_id = event.channel_id if event.t == 'AT_MESSAGE_CREATE' else event.group_openid
chat_id = chat_id or event.group_openid or 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.d_id or event.id or '',
message_chain=await QQOfficialMessageConverter.target2yiri(event),
sender=sender,
chat_type=chat_type,
chat_id=chat_id or '',
group=group,
timestamp=timestamp,
source_platform_object=event,
)
@staticmethod
def _sender_id(event: QQOfficialEvent) -> str:
member_openid = event.member_openid or event.get('member_openid', '')
if event.t in {'GROUP_AT_MESSAGE_CREATE', 'AT_MESSAGE_CREATE'}:
return member_openid or event.user_openid or event.d_author_id or ''
return event.user_openid or member_openid or event.d_author_id or event.guild_id or event.group_openid or ''
@staticmethod
def _private_chat_id(event: QQOfficialEvent) -> str:
if event.t == 'DIRECT_MESSAGE_CREATE':
return event.guild_id or event.user_openid or ''
return event.user_openid or event.guild_id or ''
@staticmethod
def platform_specific(event: QQOfficialEvent, 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.timestamp),
source_platform_object=event,
)
def _timestamp_value(value: str) -> float:
if not value:
return time.time()
try:
return float(datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S%z').timestamp())
except (TypeError, ValueError):
return time.time()

View File

@@ -0,0 +1,120 @@
apiVersion: v1
kind: MessagePlatformAdapter
metadata:
name: qqofficial-eba
label:
en_US: QQ Official API (EBA)
zh_Hans: QQ 官方 API (EBA)
zh_Hant: QQ 官方 API (EBA)
description:
en_US: QQ Official API adapter with Event-Based Agents support, using Webhook or WebSocket mode.
zh_Hans: QQ 官方 API 适配器EBA 架构版本),支持 Webhook 和 WebSocket 两种连接模式。
zh_Hant: QQ 官方 API 適配器EBA 架構版本),支援 Webhook 和 WebSocket 兩種連線模式。
icon: qqofficial.svg
spec:
categories:
- china
help_links:
zh: https://link.langbot.app/zh/platforms/qqofficial
en: https://link.langbot.app/en/platforms/qqofficial
ja: https://link.langbot.app/ja/platforms/qqofficial
config:
- name: appid
label:
en_US: App ID
zh_Hans: 应用 ID
zh_Hant: 應用 ID
type: string
required: true
default: ""
- name: secret
label:
en_US: Secret
zh_Hans: 密钥
zh_Hant: 密鑰
type: string
required: true
default: ""
- name: token
label:
en_US: Token
zh_Hans: 令牌
zh_Hant: 令牌
type: string
required: true
default: ""
- name: enable-webhook
label:
en_US: Enable Webhook Mode
zh_Hans: 启用 Webhook 模式
zh_Hant: 啟用 Webhook 模式
description:
en_US: If enabled, the bot receives messages through LangBot's unified webhook endpoint. Otherwise it uses the QQ WebSocket gateway.
zh_Hans: 启用后,机器人通过 LangBot 统一 Webhook 接收消息;否则使用 QQ WebSocket 网关。
zh_Hant: 啟用後,機器人透過 LangBot 統一 Webhook 接收訊息;否則使用 QQ WebSocket 閘道。
type: boolean
required: true
default: false
- name: enable-stream-reply
label:
en_US: Enable Stream Reply Mode
zh_Hans: 启用流式回复模式
zh_Hant: 啟用串流回覆模式
description:
en_US: If enabled, the adapter uses QQ Official streaming replies for C2C private messages.
zh_Hans: 启用后,适配器会对 C2C 私聊使用 QQ 官方流式回复。
zh_Hant: 啟用後,適配器會對 C2C 私聊使用 QQ 官方串流回覆。
type: boolean
required: true
default: false
- 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 QQ Official API webhook configuration.
zh_Hans: 复制此地址并粘贴到 QQ 官方 API 的 Webhook 配置中。
zh_Hant: 複製此地址並貼到 QQ 官方 API 的 Webhook 設定中。
type: webhook-url
required: false
default: ""
show_if:
field: enable-webhook
operator: eq
value: true
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_member_list
- get_group_member_info
- call_platform_api
platform_specific_apis:
- action: check_access_token
description: { en_US: "Check whether the cached QQ Official access token is usable", zh_Hans: "检查当前缓存的 QQ 官方 access token 是否可用" }
- action: refresh_access_token
description: { en_US: "Force refresh the QQ Official access token", zh_Hans: "强制刷新 QQ 官方 access token" }
- action: get_gateway_url
description: { en_US: "Return the QQ Official WebSocket gateway URL", zh_Hans: "获取 QQ 官方 WebSocket 网关地址" }
- action: get_mode
description: { en_US: "Return adapter receive and stream-reply mode", zh_Hans: "返回适配器接收模式和流式回复模式" }
execution:
python:
path: ./adapter.py
attr: QQOfficialAdapter

View File

@@ -0,0 +1,104 @@
from __future__ import annotations
import datetime
import re
from langbot.libs.qq_official_api.qqofficialevent import QQOfficialEvent
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 _is_base64_data(value: str) -> bool:
if not value:
return False
if value.startswith('data:'):
return True
if value.startswith(('http://', 'https://', '/', './', '../')):
return False
return bool(re.fullmatch(r'[A-Za-z0-9+/=\s]{20,}', value))
class QQOfficialMessageConverter(abstract_platform_adapter.AbstractMessageConverter):
@staticmethod
async def yiri2target(message_chain: platform_message.MessageChain) -> list[dict]:
content_list: list[dict] = []
for component in message_chain:
if isinstance(component, platform_message.Source):
continue
if isinstance(component, platform_message.Plain):
content_list.append({'type': 'text', 'content': component.text})
elif isinstance(component, platform_message.At):
content_list.append({'type': 'text', 'content': f'@{component.display or component.target}'})
elif isinstance(component, platform_message.AtAll):
content_list.append({'type': 'text', 'content': '@all'})
elif isinstance(component, platform_message.Image):
content_list.append(QQOfficialMessageConverter._media_payload(component, 'image'))
elif isinstance(component, platform_message.Voice):
content_list.append(QQOfficialMessageConverter._media_payload(component, 'voice'))
elif isinstance(component, platform_message.File):
payload = QQOfficialMessageConverter._media_payload(component, 'file')
payload['name'] = component.name or component.id or 'file'
content_list.append(payload)
elif isinstance(component, platform_message.Quote):
if component.id is not None:
content_list.append({'type': 'text', 'content': f'[Quote {component.id}]'})
if component.origin:
content_list.extend(await QQOfficialMessageConverter.yiri2target(component.origin))
elif isinstance(component, platform_message.Forward):
for node in component.node_list:
if node.message_chain:
content_list.extend(await QQOfficialMessageConverter.yiri2target(node.message_chain))
else:
text = str(component)
if text:
content_list.append({'type': 'text', 'content': text})
return content_list
@staticmethod
def _media_payload(component, content_type: str) -> dict:
url = getattr(component, 'url', '') or getattr(component, 'path', '') or None
b64 = getattr(component, 'base64', '') or None
if url and not b64 and _is_base64_data(url):
b64 = url
url = None
return {'type': content_type, 'url': url, 'base64': b64}
@staticmethod
async def target2yiri(event: QQOfficialEvent) -> platform_message.MessageChain:
components: list[platform_message.MessageComponent] = [
platform_message.Source(id=event.d_id or event.id or '', time=_parse_timestamp(event.timestamp)),
]
if event.t in {'GROUP_AT_MESSAGE_CREATE', 'AT_MESSAGE_CREATE'}:
components.append(platform_message.At(target='justbot'))
if event.attachments:
try:
base64_url = await image.get_qq_official_image_base64(
pic_url=event.attachments,
content_type=event.content_type,
)
components.append(platform_message.Image(base64=base64_url))
except Exception:
components.append(platform_message.Image(url=event.attachments))
if event.content:
components.append(platform_message.Plain(text=event.content))
if len(components) == 1 or (
len(components) == 2 and isinstance(components[1], platform_message.At)
):
components.append(platform_message.Unknown(text=f'[unsupported qqofficial event: {event.t or "unknown"}]'))
return platform_message.MessageChain(components)
def _parse_timestamp(value: str) -> datetime.datetime:
if not value:
return datetime.datetime.now()
try:
return datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S%z')
except (TypeError, ValueError):
return datetime.datetime.now()

View File

@@ -0,0 +1,37 @@
from __future__ import annotations
import typing
async def check_access_token(adapter, params: dict) -> dict:
ok = await adapter.bot.check_access_token()
return {'ok': bool(ok), 'expires_at': getattr(adapter.bot, 'access_token_expiry_time', None)}
async def refresh_access_token(adapter, params: dict) -> dict:
adapter.bot.access_token = ''
adapter.bot.access_token_expiry_time = None
await adapter.bot.get_access_token()
return {'ok': bool(adapter.bot.access_token), 'expires_at': adapter.bot.access_token_expiry_time}
async def get_gateway_url(adapter, params: dict) -> dict:
url = await adapter.bot.get_gateway_url()
return {'url': url}
async def get_mode(adapter, params: dict) -> dict:
return {
'webhook': bool(adapter.enable_webhook),
'stream_reply': bool(adapter.config.get('enable-stream-reply') or adapter.config.get('enable_stream_reply')),
'bot_account_id': adapter.bot_account_id,
}
PLATFORM_API_MAP: dict[str, typing.Callable[[typing.Any, dict], typing.Awaitable[dict]]] = {
'check_access_token': check_access_token,
'refresh_access_token': refresh_access_token,
'get_gateway_url': get_gateway_url,
'get_mode': get_mode,
}

View File

@@ -0,0 +1,2 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="96px" height="96px"><path fill="#FFC107" d="M17.5,44c-3.6,0-6.5-1.6-6.5-3.5s2.9-3.5,6.5-3.5s6.5,1.6,6.5,3.5S21.1,44,17.5,44z M37,40.5c0-1.9-2.9-3.5-6.5-3.5S24,38.6,24,40.5s2.9,3.5,6.5,3.5S37,42.4,37,40.5z"/><path fill="#37474F" d="M37.2,22.2c-0.1-0.3-0.2-0.6-0.3-1c0.1-0.5,0.1-1,0.1-1.5c0-1.4-0.1-2.6-0.1-3.6C36.9,9.4,31.1,4,24,4S11,9.4,11,16.1c0,0.9,0,2.2,0,3.6c0,0.5,0,1,0.1,1.5c-0.1,0.3-0.2,0.6-0.3,1c-1.9,2.7-3.8,6-3.8,8.5C7,35.5,8.4,35,8.4,35c0.6,0,1.6-1,2.5-2.1C13,38.8,18,43,24,43s11-4.2,13.1-10.1C38,34,39,35,39.6,35c0,0,1.4,0.5,1.4-4.3C41,28.2,39.1,24.8,37.2,22.2z"/><path fill="#ECEFF1" d="M14.7,23c-0.5,1.5-0.7,3.1-0.7,4.8C14,35.1,18.5,41,24,41s10-5.9,10-13.2c0-1.7-0.3-3.3-0.7-4.8H14.7z"/><path fill="#FFF" d="M23,13.5c0,1.9-1.1,3.5-2.5,3.5S18,15.4,18,13.5s1.1-3.5,2.5-3.5S23,11.6,23,13.5z M27.5,10c-1.4,0-2.5,1.6-2.5,3.5s1.1,3.5,2.5,3.5s2.5-1.6,2.5-3.5S28.9,10,27.5,10z"/><path fill="#37474F" d="M22,13.5c0,0.8-0.4,1.5-1,1.5s-1-0.7-1-1.5s0.4-1.5,1-1.5S22,12.7,22,13.5z M27,12c-0.6,0-1,0.7-1,1.5s0.4-0.5,1-0.5s1,1.3,1,0.5S27.6,12,27,12z"/><path fill="#FFC107" d="M32,19.5c0,0.8-3.6,2.5-8,2.5s-8-1.7-8-2.5s3.6-1.5,8-1.5S32,18.7,32,19.5z"/><path fill="#FF3D00" d="M38.7,21.2c-0.4-1.5-1-2.2-2.1-1.3c0,0-5.9,3.1-12.5,3.1v0.1l0-0.1c-6.6,0-12.5-3.1-12.5-3.1c-1.1-0.8-1.7-0.2-2.1,1.3c-0.4,1.5-0.7,2,0.7,2.8c0.1,0.1,1.4,0.8,3.4,1.7c-0.6,3.5-0.5,6.8-0.5,7c0.1,1.5,1.3,1.3,2.9,1.3c1.6-0.1,2.9,0,2.9-1.6c0-0.9,0-2.9,0.3-5c1.6,0.3,3.2,0.6,5,0.6l0,0v0c7.3,0,13.7-3.9,13.9-4C39.3,23.3,39,22.8,38.7,21.2z"/><path fill="#DD2C00" d="M13.2,27.7c1.6,0.6,3.5,1.3,5.6,1.7c0-0.6,0.1-1.3,0.2-2c-2.1-0.5-4-1.1-5.5-1.7C13.4,26.4,13.3,27.1,13.2,27.7z"/></svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

@@ -0,0 +1,14 @@
from __future__ import annotations
import pydantic
ADAPTER_NAME = 'qqofficial-eba'
class QQOfficialAdapterConfig(pydantic.BaseModel):
appid: str
secret: str
token: str
enable_webhook: bool = False
enable_stream_reply: bool = False