import type { EndpointProfileConfiguration } from 'zhin.js/adapter'; /** QQ Official Bot protocol helpers. Canonicalization is owned by Core. */ import { EndpointDeliveryError, type ConversationKind, type ConversationRef } from '@zhin.js/im-contract'; import { formatCompact, getLogger } from '@zhin.js/logger'; import { resolveQqIntents } from './qq-intents.js'; import { resolveAdapterNotifyTarget, type AdapterNotifyTarget, type ResolvedAdapterNotifyTarget } from 'zhin.js/adapter'; const logger = getLogger('qq'); /** One endpoint config after AdapterIndex expands `plugins..endpoints`. */ export interface QqEndpointConfig extends EndpointProfileConfiguration { readonly id: string; readonly appid: string; readonly secret: string; /** Default `websocket`. `webhook` / `middleware` use httpHostToken POST. */ readonly mode?: 'websocket' | 'webhook' | 'middleware'; readonly sandbox?: boolean; /** Publish supported C2C replies while generated; false keeps complete delivery. */ readonly streaming?: boolean; readonly streamingIntervalMs?: number; /** Explicit intents; when omitted, derived from `botKind` (default public). */ readonly intents?: readonly string[]; /** public | private — drives default intents when `intents` omitted. */ readonly botKind?: string; readonly accessTokenUrl?: string; readonly gatewayUrl?: string; readonly streamProxy?: import('./stream-proxy.js').QqStreamProxy; readonly webhookPath?: string; /** Optional out-of-band outage notification target (usually an ICQQ instance). */ readonly notify?: AdapterNotifyTarget; } export interface ResolvedQqWebsocketConfig { readonly context: 'qq'; readonly mode: 'websocket'; readonly id: string; readonly appid: string; readonly secret: string; readonly sandbox: boolean; readonly streaming?: boolean; readonly streamingIntervalMs?: number; readonly intents?: readonly string[]; readonly accessTokenUrl?: string; readonly gatewayUrl?: string; readonly streamProxy?: import('./stream-proxy.js').QqStreamProxy; readonly notify?: ResolvedAdapterNotifyTarget; } export interface ResolvedQqHttpConfig { readonly context: 'qq'; readonly mode: 'webhook' | 'middleware'; readonly id: string; readonly appid: string; readonly secret: string; readonly webhookPath: string; readonly sandbox: boolean; readonly streaming?: boolean; readonly streamingIntervalMs?: number; readonly notify?: ResolvedAdapterNotifyTarget; } export type ResolvedQqConfig = ResolvedQqWebsocketConfig | ResolvedQqHttpConfig; export type QqChannelKind = 'private' | 'group' | 'channel' | 'direct'; export interface QqInboundMessage { readonly event?: unknown; readonly platformSentAt?: number; readonly id: string; readonly content: string; readonly channelKind: QqChannelKind; readonly channelId: string; readonly authorId: string; readonly authorName: string; readonly authorRoles?: string[]; readonly timestamp: number; readonly guildId?: string; readonly rawMessage?: string; /** canonical 入站段(text/mention/face/image/audio/video/file/reply),与 content 同源 */ readonly segments?: readonly import('@zhin.js/core').Segment[]; /** * 入站是否 @ 当前机器人:统一按 mentions 判定。群场景只认 is_you(@ 另一个 * 机器人时 bot:true 但无 is_you,不误判);bot 回退仅限频道 AT 事件。 * 群 GROUP_MESSAGE_CREATE 的非 @ 消息不置位。新 Runtime 纯文本 content 需经 * metadata 传递。 */ readonly mentioned?: boolean; } export interface QqWireSegment { readonly type: string; readonly data?: Record; } export function resolveQqConfig(config: QqEndpointConfig): ResolvedQqConfig { const id = requiredEndpointField(config.id, 'id'); const appid = requiredEndpointField(config.appid, 'appid'); const secret = requiredEndpointField(config.secret, 'secret'); const mode = config.mode ?? 'websocket'; const streamingIntervalMs = config.streamingIntervalMs ?? 500; if (!Number.isFinite(streamingIntervalMs) || streamingIntervalMs < 0) throw new TypeError('streamingIntervalMs must be a non-negative finite number'); const notify = resolveAdapterNotifyTarget(config.notify); if (mode === 'webhook' || mode === 'middleware') { const webhookPathRaw = config.webhookPath ?? '/qq/webhook'; const webhookPath = webhookPathRaw.startsWith('/') ? webhookPathRaw : `/${webhookPathRaw}`; return { context: 'qq', mode, id, appid, secret, webhookPath, sandbox: config.sandbox === true, streaming: config.streaming !== false, streamingIntervalMs, ...(notify ? { notify } : {}), }; } if (config.streamProxy && (!Number.isInteger(config.streamProxy.port) || config.streamProxy.port < 1 || config.streamProxy.port > 65535 || typeof config.streamProxy.serverName !== 'string' || !config.streamProxy.serverName || /[\s/:@?#]/.test(config.streamProxy.serverName))) throw new TypeError('Invalid QQ streamProxy port/serverName'); return { context: 'qq', mode: 'websocket', id, appid, secret, sandbox: config.sandbox === true, streaming: config.streaming !== false, streamingIntervalMs, intents: resolveQqIntents({ intents: config.intents, botKind: config.botKind, }), accessTokenUrl: config.accessTokenUrl, gatewayUrl: config.gatewayUrl, ...(config.streamProxy ? { streamProxy: config.streamProxy } : {}), ...(notify ? { notify } : {}), }; } function requiredEndpointField(value: unknown, field: 'id' | 'appid' | 'secret'): string { if (typeof value !== 'string' || !value.trim()) { throw new TypeError(`QQ endpoint requires a non-empty ${field}`); } return value.trim(); } /** * 入站归一化 → ConversationRef:`direct`(频道私信)映射为 guild 容器内的 * private 会话;频道消息的所属 guild 进 `parent`。 */ export function qqInboundConversation(endpointKey: string, msg: QqInboundMessage): ConversationRef { const kind: ConversationKind = msg.channelKind === 'direct' ? 'private' : msg.channelKind; return { endpoint: { id: endpointKey, adapter: endpointKey.split('\0')[0] ?? endpointKey }, kind, id: msg.channelId, ...(msg.guildId && (msg.channelKind === 'channel' || msg.channelKind === 'direct') ? { parent: { kind: 'channel' as const, id: msg.guildId } } : {}), }; } /** 出站:guild 容器内的 private 会话即 QQ `direct`(频道私信)。 */ export function qqOutboundKind(conversation: ConversationRef): QqChannelKind { if (conversation.kind === 'private' && conversation.parent?.kind === 'channel') return 'direct'; return conversation.kind; } export function senderDisplayName(msg: QqInboundMessage): string { return msg.authorName || msg.authorId; } export function formatInboundContent(msg: QqInboundMessage): string { const text = (msg.content || msg.rawMessage || '').trim(); return text || '(Empty message)'; } /** * Wire-encode an already-rendered outbound payload into a plain text / QQ Sendable string. * Segment canonicalization is intentionally not done here. */ export function formatOutboundText(payload: unknown): string { if (typeof payload === 'string') return payload; const segments: Array = Array.isArray(payload) ? payload as Array : payload && typeof payload === 'object' && 'type' in (payload as object) ? [payload as QqWireSegment] : []; if (segments.length === 0) { return payload == null ? '' : typeof payload === 'object' ? JSON.stringify(payload) : String(payload); } return segments .map((item) => { if (typeof item === 'string') return item; const data = item.data ?? {}; switch (item.type) { case 'text': return String(data.text ?? data.content ?? ''); case 'at': { const id = String(data.user_id ?? data.qq ?? data.id ?? ''); return id ? `<@!${id}>` : ''; } case 'image': { const src = String(data.url || data.file || ''); // base64/本地路径由 formatOutbound 走媒体上传,文本视图静默省略; // 仅当彻底缺少来源时留痕,避免出站静默降级排障无头绪。 if (!src) { logger.warn(formatCompact({ op: 'qq_outbound_image_dropped', reason: 'missing_source', })); return ''; } return /^https?:\/\//.test(src) ? src : ''; } case 'reply': return ''; default: return data.text != null ? String(data.text) : ''; } }) .filter(Boolean) .join(''); } /** * Parse a compound messageId produced by `send()`: `kind-channelId:qqMsgId`. */ export function parseCompoundMessageId(messageId: string): { kind: QqChannelKind; channelId: string; qqMsgId: string; } { const hyphen = messageId.indexOf('-'); if (hyphen <= 0) throw new Error(`invalid QQ messageId format: ${messageId}`); const kind = messageId.slice(0, hyphen); if (kind !== 'private' && kind !== 'group' && kind !== 'channel' && kind !== 'direct') { throw new Error(`invalid QQ messageId kind: ${kind}`); } const rest = messageId.slice(hyphen + 1); const colon = rest.indexOf(':'); if (colon <= 0) throw new Error(`invalid QQ messageId format: ${messageId}`); return { kind, channelId: rest.slice(0, colon), qqMsgId: rest.slice(colon + 1) }; } /** 从 QQ API SendResult / 审核回包中解析出站消息 ID */ export function resolveOutboundMessageId(result: unknown): string { if (!result || typeof result !== 'object') { throw new EndpointDeliveryError('delivery_unconfirmed', 'QQ 发送消息失败:响应为空', 'unknown'); } const row = result as Record; if (typeof row.code === 'number' && Number.isFinite(row.code) && row.code !== 0) { throw new EndpointDeliveryError('platform_rejected', `QQ platform rejected the outbound request (${row.code})`, 'rejected'); } const nested = row.data && typeof row.data === 'object' ? row.data as Record : undefined; const id = row.id ?? row.message_id ?? nested?.id ?? nested?.message_id; if ((typeof id !== 'string' && typeof id !== 'number') || String(id).trim() === '' || (typeof id === 'number' && !Number.isFinite(id))) { const code = row.code; const rejected = typeof code === 'number' && Number.isFinite(code) && code !== 0; throw new EndpointDeliveryError( rejected ? 'platform_rejected' : 'delivery_unconfirmed', code != null ? 'QQ outbound response is unconfirmed' : 'QQ 发送消息失败:响应缺少消息 ID', rejected ? 'rejected' : 'unknown', ); } return String(id); }