fix(onebot): report API-sent private messages
Emit message_sent.private after successful friend messages sent through OneBot actions or the WebUI debug console when QQ does not provide an inbound self echo. Keep a later QQ echo as the canonical stored event while suppressing duplicate downstream delivery across both race orders. Match echoes by conversation, sequence, message ID, and a bounded time window; leave group messages, temporary sessions, split file sends, unreliable receipts, and messages sent manually from the QQ client unchanged. Add regression coverage for action-only reporting, both echo race orders, hash collisions, cached-but-unreported events, temporary sessions, and incomplete receipts. Fixes #251
This commit is contained in:
6 files changed
+390
-38
No files matched your search
@@ -180,7 +180,7 @@ async function runConvertAndDispatch(ctx: OneBotInstanceContext, log: Logger, ev
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
}
|
||||
ctx.dispatchEvent(converted);
|
||||
ctx.dispatchEvent(converted, 'bridge');
|
||||
log.trace(() => [`recv ${event.kind} ⇒ ${String(converted.post_type ?? '?')} (${Date.now() - startedAt}ms)`]);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Bridge } from '@snowluma/core/bridge';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { WebHonorType } from '@snowluma/protocol/web/group-honor';
|
||||
import type { ApiActionContext } from './api-handler';
|
||||
import type { ApiActionContext, MessageSendResult } from './api-handler';
|
||||
import type { ConverterContext } from './event-converter';
|
||||
import type { MediaStore } from './media-store';
|
||||
import type { MessageStore } from './message-store';
|
||||
@@ -53,12 +53,18 @@ export interface OneBotInstanceContext {
|
||||
config: OneBotConfig;
|
||||
musicSignUrl?: string;
|
||||
cacheMessageMeta(messageId: number, meta: MessageMeta): void;
|
||||
dispatchEvent(event: JsonObject): void;
|
||||
dispatchEvent(event: JsonObject, source?: 'bridge' | 'send'): void;
|
||||
}
|
||||
|
||||
export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
const { bridge, messageStore, mediaStore, reactionStore } = ref;
|
||||
|
||||
const reportSelfSent = async (result: Promise<MessageSendResult>) => {
|
||||
const settled = await result;
|
||||
if (settled.echoEvent) ref.dispatchEvent(settled.echoEvent, 'send');
|
||||
return settled;
|
||||
};
|
||||
|
||||
return {
|
||||
bridge,
|
||||
|
||||
@@ -71,7 +77,10 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
),
|
||||
canSendImage: () => true,
|
||||
canSendRecord: () => true,
|
||||
sendPrivateMessage: (userId, message, autoEscape, tempGroupId) => sendPrivateMessage(ref, userId, message, autoEscape, tempGroupId),
|
||||
sendPrivateMessage: (userId, message, autoEscape, tempGroupId) =>
|
||||
tempGroupId === undefined
|
||||
? reportSelfSent(sendPrivateMessage(ref, userId, message, autoEscape))
|
||||
: sendPrivateMessage(ref, userId, message, autoEscape, tempGroupId),
|
||||
sendGroupMessage: (groupId, message, autoEscape) => sendGroupMessage(ref, groupId, message, autoEscape),
|
||||
deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta),
|
||||
getFriendList: () => getFriendList(bridge),
|
||||
|
||||
@@ -29,6 +29,11 @@ import {
|
||||
type NetworkShutdownResult,
|
||||
} from './network';
|
||||
import { ReactionStore } from './reaction-store';
|
||||
import {
|
||||
sameSelfSentMessage,
|
||||
selfSentEventKey,
|
||||
SELF_SENT_ECHO_WINDOW_MS,
|
||||
} from './self-sent-event';
|
||||
import type { ApiResponse, JsonObject, JsonValue, MessageMeta, OneBotConfig } from './types';
|
||||
|
||||
const moduleLog = createLogger('Event');
|
||||
@@ -51,6 +56,8 @@ export class OneBotInstance {
|
||||
private readonly startedAt = Date.now();
|
||||
/** Per-conversation last-reply timestamp for the `#sl` cooldown. */
|
||||
private readonly statusCommandCooldown = new Map<string, number>();
|
||||
/** Action-side events awaiting a possible canonical QQ echo. */
|
||||
private readonly pendingSelfSentEchoes = new Map<string, { event: JsonObject; expiresAt: number }>();
|
||||
private eventPipeline: EventPipelineHandle | null = null;
|
||||
private eventPipelineDrain: Promise<void> = Promise.resolve();
|
||||
private disposePromise: Promise<NetworkShutdownResult> | null = null;
|
||||
@@ -137,7 +144,7 @@ export class OneBotInstance {
|
||||
config,
|
||||
musicSignUrl: globalSettings.musicSignUrl,
|
||||
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
|
||||
dispatchEvent: (event) => this.dispatchEvent(event),
|
||||
dispatchEvent: (event, source = 'bridge') => this.dispatchEvent(event, source),
|
||||
};
|
||||
this.ctx = ctx;
|
||||
|
||||
@@ -271,17 +278,58 @@ export class OneBotInstance {
|
||||
return this.pids.size === 0;
|
||||
}
|
||||
|
||||
private dispatchEvent(event: JsonObject): void {
|
||||
this.cacheMessageEvent(event);
|
||||
this.logReceivedMessage(event);
|
||||
// Built-in `#sl`: always cache + log first (a swallowed `#sl` is still
|
||||
// observable locally); only forwarding to downstream adapters is gated.
|
||||
if (this.handleStatusCommand(event)) return;
|
||||
private dispatchEvent(event: JsonObject, source: 'bridge' | 'send' = 'bridge'): void {
|
||||
if (source === 'bridge') {
|
||||
this.cacheMessageEvent(event);
|
||||
if (this.consumePendingSelfSentEcho(event)) {
|
||||
this.log.trace(
|
||||
'duplicate self-message echo suppressed message_id=%d message_seq=%d',
|
||||
toInt(event.message_id),
|
||||
toInt(event.message_seq),
|
||||
);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
this.cacheMessageEvent(event);
|
||||
this.rememberPendingSelfSentEcho(event);
|
||||
}
|
||||
// The send path already logged the real peer and payload. Logging its
|
||||
// synthetic event here would produce a second, less accurate "received"
|
||||
// line whose private user_id points at the bot itself.
|
||||
if (source === 'bridge') this.logReceivedMessage(event);
|
||||
// Built-in `#sl` only consumes events observed from QQ. Action-originated
|
||||
// messages must not recursively trigger the command handler.
|
||||
if (source === 'bridge' && this.handleStatusCommand(event)) return;
|
||||
void this.networkManager.emitEvent(event).catch((err) => {
|
||||
this.log.warn('emitEvent failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
private rememberPendingSelfSentEcho(event: JsonObject): void {
|
||||
const key = selfSentEventKey(event);
|
||||
if (key === null) return;
|
||||
const now = Date.now();
|
||||
this.sweepPendingSelfSentEchoes(now);
|
||||
this.pendingSelfSentEchoes.set(key, { event, expiresAt: now + SELF_SENT_ECHO_WINDOW_MS });
|
||||
}
|
||||
|
||||
private consumePendingSelfSentEcho(event: JsonObject): boolean {
|
||||
const key = selfSentEventKey(event);
|
||||
if (key === null) return false;
|
||||
const now = Date.now();
|
||||
this.sweepPendingSelfSentEchoes(now);
|
||||
const pending = this.pendingSelfSentEchoes.get(key);
|
||||
if (!pending || !sameSelfSentMessage(pending.event, event)) return false;
|
||||
this.pendingSelfSentEchoes.delete(key);
|
||||
return true;
|
||||
}
|
||||
|
||||
private sweepPendingSelfSentEchoes(now: number): void {
|
||||
for (const [key, pending] of this.pendingSelfSentEchoes) {
|
||||
if (pending.expiresAt <= now) this.pendingSelfSentEchoes.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Built-in `#sl` status command. Returns `true` when the event matched AND
|
||||
* `swallow` is configured — the caller then skips `emitEvent` so downstream
|
||||
|
||||
@@ -9,6 +9,7 @@ import type { OneBotInstanceContext } from '../instance-context';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
|
||||
import { MessageElementValidationError, parseMessage } from '../message-parser';
|
||||
import type { MessageStore } from '../message-store';
|
||||
import { sameSelfSentMessage } from '../self-sent-event';
|
||||
import type { JsonArray, JsonObject, JsonValue, MessageMeta } from '../types';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
@@ -497,7 +498,9 @@ export async function setEssenceMessage(
|
||||
* copy. Centralizes the `isGroup ↔ eventName ↔ hashMessageIdInt32 event
|
||||
* constant` coupling that was hand-paired in six send/forward paths — a
|
||||
* mismatch there silently produced a wrong message_id or wrong event
|
||||
* attribution. Returns the derived message id.
|
||||
* attribution. Returns the derived message id and, for an eligible plain C2C
|
||||
* Action send, an event for the OneBot dispatch path when QQ has not already
|
||||
* supplied the canonical echo.
|
||||
*/
|
||||
async function finalizeSend(
|
||||
ref: OneBotInstanceContext,
|
||||
@@ -505,7 +508,8 @@ async function finalizeSend(
|
||||
targetId: number,
|
||||
receipt: { sequence: number; clientSequence: number; random: number; timestamp: number },
|
||||
elements: MessageElement[],
|
||||
): Promise<number> {
|
||||
reportEcho = false,
|
||||
): Promise<MessageSendResult> {
|
||||
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
|
||||
const messageId = hashMessageIdInt32(receipt.sequence, targetId, eventName);
|
||||
ref.cacheMessageMeta(messageId, {
|
||||
@@ -517,7 +521,7 @@ async function finalizeSend(
|
||||
random: receipt.random,
|
||||
timestamp: receipt.timestamp,
|
||||
});
|
||||
await cacheSelfSentMessage(ref, {
|
||||
const echoEvent = await cacheSelfSentMessage(ref, {
|
||||
isGroup,
|
||||
sessionId: targetId,
|
||||
messageId,
|
||||
@@ -525,7 +529,9 @@ async function finalizeSend(
|
||||
timestamp: receipt.timestamp,
|
||||
elements,
|
||||
});
|
||||
return messageId;
|
||||
return reportEcho && echoEvent && receipt.sequence > 0 && receipt.timestamp > 0
|
||||
? { messageId, echoEvent }
|
||||
: { messageId };
|
||||
}
|
||||
|
||||
async function cacheSelfSentMessage(
|
||||
@@ -538,16 +544,15 @@ async function cacheSelfSentMessage(
|
||||
timestamp: number;
|
||||
elements: MessageElement[];
|
||||
},
|
||||
): Promise<void> {
|
||||
): Promise<JsonObject | null> {
|
||||
const { isGroup, sessionId, messageId, sequence, timestamp, elements } = options;
|
||||
if (!Number.isInteger(messageId) || messageId === 0) return;
|
||||
if (!Number.isInteger(messageId) || messageId === 0) return null;
|
||||
|
||||
// Defensive: tests mock `ref.messageStore` as `{ findEvent: ... } as any`
|
||||
// without the full MessageStore surface. Production always has it. Bail
|
||||
// quietly when the helper isn't there — the user-visible `cacheMessageMeta`
|
||||
// already covers recall/delete; only `/get_msg` lookup degrades.
|
||||
// Defensive: tests may mock `ref.messageStore` without the full MessageStore
|
||||
// surface. Production always has it. Without storage, recall still works via
|
||||
// cacheMessageMeta, but `/get_msg` and the synthetic event are unavailable.
|
||||
const storeEvent = (ref.messageStore as { storeEvent?: typeof ref.messageStore.storeEvent }).storeEvent;
|
||||
if (typeof storeEvent !== 'function') return;
|
||||
if (typeof storeEvent !== 'function') return null;
|
||||
|
||||
try {
|
||||
// We deliberately pass no URL resolvers — for a synthetic self-sent
|
||||
@@ -595,16 +600,23 @@ async function cacheSelfSentMessage(
|
||||
event.target_id = sessionId;
|
||||
}
|
||||
|
||||
// Store directly via messageStore (bypassing dispatchEvent — we
|
||||
// don't want to broadcast this synthetic event over the WS bridge;
|
||||
// the QQ server's own echo-back is the source of truth for that).
|
||||
// QQ can win the race between the send receipt and local event
|
||||
// construction. Keep its richer canonical event and let the already-run
|
||||
// bridge dispatch remain the single downstream notification.
|
||||
const existing = ref.messageStore.findEvent(messageId);
|
||||
if (existing && sameSelfSentMessage(existing, event)) return null;
|
||||
|
||||
// Persist before dispatch so `/get_msg` is immediately consistent for a
|
||||
// client reacting to the synthetic message_sent notification.
|
||||
storeEvent.call(ref.messageStore, messageId, isGroup, sessionId, sequence, eventName, event);
|
||||
return event;
|
||||
} catch (err) {
|
||||
// Never let event-cache failures sink the send call — recall + return
|
||||
// value are what callers care about; /get_msg degrading to "not found"
|
||||
// is the worst case here and matches the previous behaviour.
|
||||
// Never turn a successful QQ send into a failed Action after the fact.
|
||||
// The warning keeps the loss observable; `/get_msg` and the optional
|
||||
// synthetic event degrade together while recall still uses cached meta.
|
||||
log.warn('[OneBot] failed to cache self-sent message %d: %s',
|
||||
messageId, err instanceof Error ? err.message : String(err));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -808,9 +820,11 @@ export async function sendPrivateMessage(
|
||||
}
|
||||
if (!lastReceipt) throw new Error('message is empty');
|
||||
|
||||
const messageId = await finalizeSend(ref, false, userId, lastReceipt, elements);
|
||||
|
||||
return { messageId };
|
||||
// Dedicated C2C file sends may split one Action into several QQ messages.
|
||||
// A single synthetic event would misrepresent that wire behaviour, so only
|
||||
// report the one-batch friend path handled by sendPrivate().
|
||||
const reportEcho = tempGroupId === undefined && allFileElements.length === 0;
|
||||
return finalizeSend(ref, false, userId, lastReceipt, elements, reportEcho);
|
||||
}
|
||||
|
||||
export async function sendGroupMessage(
|
||||
@@ -909,9 +923,7 @@ export async function sendGroupMessage(
|
||||
}
|
||||
if (!lastReceipt) throw new Error('message is empty');
|
||||
|
||||
const messageId = await finalizeSend(ref, true, groupId, lastReceipt, elements);
|
||||
|
||||
return { messageId };
|
||||
return finalizeSend(ref, true, groupId, lastReceipt, elements);
|
||||
}
|
||||
|
||||
export interface ForwardPreviewMeta {
|
||||
@@ -935,7 +947,7 @@ export async function sendGroupForwardMessage(
|
||||
const forwardId = await ref.bridge.apis.forward.upload(nodes, groupId);
|
||||
const previewElement = buildForwardPreviewElement(forwardId, nodes, true, meta);
|
||||
const receipt = await ref.bridge.apis.message.sendGroup(groupId, [previewElement]);
|
||||
const messageId = await finalizeSend(ref, true, groupId, receipt, [previewElement]);
|
||||
const { messageId } = await finalizeSend(ref, true, groupId, receipt, [previewElement]);
|
||||
|
||||
return { messageId, forwardId };
|
||||
}
|
||||
@@ -953,7 +965,7 @@ export async function sendPrivateForwardMessage(
|
||||
const forwardId = await ref.bridge.apis.forward.upload(nodes, undefined, userId);
|
||||
const previewElement = buildForwardPreviewElement(forwardId, nodes, false, meta);
|
||||
const receipt = await ref.bridge.apis.message.sendPrivate(userId, [previewElement]);
|
||||
const messageId = await finalizeSend(ref, false, userId, receipt, [previewElement]);
|
||||
const { messageId } = await finalizeSend(ref, false, userId, receipt, [previewElement]);
|
||||
|
||||
return { messageId, forwardId };
|
||||
}
|
||||
@@ -1002,10 +1014,10 @@ export async function forwardSingleMessage(
|
||||
let messageIdOut: number;
|
||||
if (target.groupId) {
|
||||
receipt = await ref.bridge.apis.message.sendGroup(target.groupId, elements);
|
||||
messageIdOut = await finalizeSend(ref, true, target.groupId, receipt, elements);
|
||||
({ messageId: messageIdOut } = await finalizeSend(ref, true, target.groupId, receipt, elements));
|
||||
} else {
|
||||
receipt = await ref.bridge.apis.message.sendPrivate(target.userId!, elements);
|
||||
messageIdOut = await finalizeSend(ref, false, target.userId!, receipt, elements);
|
||||
({ messageId: messageIdOut } = await finalizeSend(ref, false, target.userId!, receipt, elements));
|
||||
}
|
||||
|
||||
return { messageId: messageIdOut };
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { JsonObject } from './types';
|
||||
|
||||
export const SELF_SENT_ECHO_WINDOW_MS = 120_000;
|
||||
|
||||
/**
|
||||
* Match the action-side copy of a sent message with QQ's later canonical
|
||||
* echo. The message hash alone is insufficient because it is a signed 32-bit
|
||||
* value and can collide; sequence, conversation and a bounded time window are
|
||||
* part of the identity as well.
|
||||
*/
|
||||
export function sameSelfSentMessage(left: JsonObject, right: JsonObject): boolean {
|
||||
const leftKey = selfSentEventKey(left);
|
||||
const rightKey = selfSentEventKey(right);
|
||||
if (leftKey === null || leftKey !== rightKey) return false;
|
||||
|
||||
const leftTime = toInt(left.time);
|
||||
const rightTime = toInt(right.time);
|
||||
return leftTime > 0
|
||||
&& rightTime > 0
|
||||
&& Math.abs(leftTime - rightTime) * 1000 <= SELF_SENT_ECHO_WINDOW_MS;
|
||||
}
|
||||
|
||||
/** Stable identity for a self-sent event, excluding its bounded timestamp. */
|
||||
export function selfSentEventKey(event: JsonObject): string | null {
|
||||
if (event.post_type !== 'message_sent') return null;
|
||||
if (event.message_type !== 'private' && event.message_type !== 'group') return null;
|
||||
|
||||
const messageId = toInt(event.message_id);
|
||||
const sequence = toInt(event.message_seq);
|
||||
const session = event.message_type === 'group'
|
||||
? toInt(event.group_id)
|
||||
: (toInt(event.target_id) || toInt(event.user_id));
|
||||
if (messageId === 0 || sequence <= 0 || session <= 0) return null;
|
||||
return `${event.message_type}:${session}:${sequence}:${messageId}`;
|
||||
}
|
||||
|
||||
function toInt(value: unknown): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
const parsed = Number(value);
|
||||
if (Number.isFinite(parsed)) return Math.trunc(parsed);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { BridgeInterface } from '../../core/src/bridge/bridge-interface';
|
||||
import { OneBotInstance } from '../src/instance';
|
||||
import { buildApiContext, type OneBotInstanceContext } from '../src/instance-context';
|
||||
import { hashMessageIdInt32, PRIVATE_MESSAGE_EVENT } from '../src/message-id';
|
||||
import { TempSessionStore } from '../src/temp-session-store';
|
||||
import type { JsonObject, OneBotConfig } from '../src/types';
|
||||
|
||||
const SELF_ID = 10001;
|
||||
const PEER_ID = 20002;
|
||||
const RECEIPT = {
|
||||
messageId: 123456,
|
||||
sequence: 87,
|
||||
clientSequence: 9,
|
||||
random: 123456,
|
||||
timestamp: 1_700_000_000,
|
||||
};
|
||||
|
||||
function makeContext(receipt = RECEIPT): {
|
||||
ctx: OneBotInstanceContext;
|
||||
dispatchEvent: ReturnType<typeof vi.fn<(event: JsonObject) => void>>;
|
||||
events: Map<number, JsonObject>;
|
||||
} {
|
||||
const events = new Map<number, JsonObject>();
|
||||
const dispatchEvent = vi.fn<(event: JsonObject) => void>();
|
||||
const bridge = {
|
||||
identity: { nickname: 'SnowLuma' },
|
||||
apis: {
|
||||
message: {
|
||||
sendPrivate: vi.fn(async () => receipt),
|
||||
sendGroupTempMessage: vi.fn(async () => receipt),
|
||||
},
|
||||
},
|
||||
resolveUserUid: vi.fn(async () => 'u_peer'),
|
||||
} as unknown as BridgeInterface;
|
||||
|
||||
const ctx = {
|
||||
uin: String(SELF_ID),
|
||||
selfId: SELF_ID,
|
||||
bridge,
|
||||
messageStore: {
|
||||
findEvent: (messageId: number) => events.get(messageId) ?? null,
|
||||
findMeta: () => null,
|
||||
resolveReplySequence: () => null,
|
||||
storeEvent: (messageId: number, _isGroup: boolean, _sessionId: number, _sequence: number, _eventName: string, event: JsonObject) => {
|
||||
events.set(messageId, event);
|
||||
},
|
||||
},
|
||||
mediaStore: {},
|
||||
reactionStore: {},
|
||||
tempSessions: new TempSessionStore(),
|
||||
converterCtx: {},
|
||||
config: {
|
||||
networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] },
|
||||
} as OneBotConfig,
|
||||
cacheMessageMeta: vi.fn(),
|
||||
dispatchEvent,
|
||||
} as unknown as OneBotInstanceContext;
|
||||
|
||||
return { ctx, dispatchEvent, events };
|
||||
}
|
||||
|
||||
interface InstanceHarness {
|
||||
dispatch(event: JsonObject, source: 'send' | 'bridge'): void;
|
||||
emitEvent: ReturnType<typeof vi.fn<(event: JsonObject) => Promise<void>>>;
|
||||
stored: Map<number, JsonObject>;
|
||||
}
|
||||
|
||||
function makeInstanceHarness(): InstanceHarness {
|
||||
const stored = new Map<number, JsonObject>();
|
||||
const emitEvent = vi.fn(async (_event: JsonObject) => {});
|
||||
const instance = Object.create(OneBotInstance.prototype) as OneBotInstance;
|
||||
Object.assign(instance as unknown as Record<string, unknown>, {
|
||||
bridge: { identity: {} },
|
||||
ctx: {
|
||||
config: {
|
||||
statusCommand: { enabled: false, swallow: false, cooldownSeconds: 5, trigger: '#sl' },
|
||||
},
|
||||
},
|
||||
log: { success: vi.fn(), trace: vi.fn(), warn: vi.fn() },
|
||||
messageStore: {
|
||||
findEvent: (messageId: number) => stored.get(messageId) ?? null,
|
||||
storeEvent: (messageId: number, _isGroup: boolean, _sessionId: number, _sequence: number, _eventName: string, event: JsonObject) => {
|
||||
stored.set(messageId, event);
|
||||
},
|
||||
},
|
||||
networkManager: { emitEvent },
|
||||
statusCommandCooldown: new Map(),
|
||||
pendingSelfSentEchoes: new Map(),
|
||||
});
|
||||
const dispatch = (instance as unknown as {
|
||||
dispatchEvent(event: JsonObject, source: 'send' | 'bridge'): void;
|
||||
}).dispatchEvent.bind(instance);
|
||||
return { dispatch, emitEvent, stored };
|
||||
}
|
||||
|
||||
function privateSentEvent(overrides: JsonObject = {}): JsonObject {
|
||||
return {
|
||||
time: RECEIPT.timestamp,
|
||||
self_id: SELF_ID,
|
||||
post_type: 'message_sent',
|
||||
message_type: 'private',
|
||||
sub_type: 'friend',
|
||||
message_id: 987654,
|
||||
message_seq: RECEIPT.sequence,
|
||||
user_id: SELF_ID,
|
||||
target_id: PEER_ID,
|
||||
message: [{ type: 'text', data: { text: 'hello' } }],
|
||||
raw_message: 'hello',
|
||||
sender: { user_id: SELF_ID, nickname: 'SnowLuma' },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('OneBot self-sent events', () => {
|
||||
it('reports a private message sent through an action', async () => {
|
||||
const { ctx, dispatchEvent } = makeContext();
|
||||
const api = buildApiContext(ctx);
|
||||
|
||||
const result = await api.sendPrivateMessage(PEER_ID, [
|
||||
{ type: 'text', data: { text: 'hello' } },
|
||||
], false);
|
||||
|
||||
expect(result.messageId).not.toBe(0);
|
||||
expect(dispatchEvent).toHaveBeenCalledOnce();
|
||||
expect(dispatchEvent).toHaveBeenCalledWith(expect.objectContaining({
|
||||
post_type: 'message_sent',
|
||||
message_type: 'private',
|
||||
sub_type: 'friend',
|
||||
self_id: SELF_ID,
|
||||
user_id: SELF_ID,
|
||||
target_id: PEER_ID,
|
||||
message_seq: RECEIPT.sequence,
|
||||
}), 'send');
|
||||
});
|
||||
|
||||
it('does not report a later QQ echo after the action event', () => {
|
||||
const { dispatch, emitEvent, stored } = makeInstanceHarness();
|
||||
const sentEvent = privateSentEvent();
|
||||
const qqEcho: JsonObject = {
|
||||
...sentEvent,
|
||||
raw_message: 'canonical echo',
|
||||
sender: { user_id: SELF_ID, nickname: 'Server profile' },
|
||||
};
|
||||
|
||||
dispatch(sentEvent, 'send');
|
||||
dispatch(qqEcho, 'bridge');
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledOnce();
|
||||
expect(stored.get(987654)?.raw_message).toBe('canonical echo');
|
||||
});
|
||||
|
||||
it('does not dispatch an event for a receipt without a reliable sequence', async () => {
|
||||
const { ctx, dispatchEvent } = makeContext({ ...RECEIPT, sequence: 0 });
|
||||
const api = buildApiContext(ctx);
|
||||
|
||||
await api.sendPrivateMessage(PEER_ID, [
|
||||
{ type: 'text', data: { text: 'hello' } },
|
||||
], false);
|
||||
|
||||
expect(dispatchEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps an earlier QQ echo and does not report the later action event', async () => {
|
||||
const { ctx, dispatchEvent, events } = makeContext();
|
||||
const messageId = hashMessageIdInt32(RECEIPT.sequence, PEER_ID, PRIVATE_MESSAGE_EVENT);
|
||||
const qqEcho: JsonObject = {
|
||||
time: RECEIPT.timestamp,
|
||||
self_id: SELF_ID,
|
||||
post_type: 'message_sent',
|
||||
message_type: 'private',
|
||||
sub_type: 'friend',
|
||||
message_id: messageId,
|
||||
message_seq: RECEIPT.sequence,
|
||||
user_id: SELF_ID,
|
||||
target_id: PEER_ID,
|
||||
message: [{ type: 'text', data: { text: 'hello' } }],
|
||||
raw_message: 'canonical echo',
|
||||
sender: { user_id: SELF_ID, nickname: 'Server profile' },
|
||||
};
|
||||
events.set(messageId, qqEcho);
|
||||
|
||||
const api = buildApiContext(ctx);
|
||||
const result = await api.sendPrivateMessage(PEER_ID, [
|
||||
{ type: 'text', data: { text: 'hello' } },
|
||||
], false);
|
||||
|
||||
expect(result.messageId).toBe(messageId);
|
||||
expect(dispatchEvent).not.toHaveBeenCalled();
|
||||
expect(events.get(messageId)).toBe(qqEcho);
|
||||
});
|
||||
|
||||
it('does not invent a friend event for a group temporary-session send', async () => {
|
||||
const groupId = 30003;
|
||||
const { ctx, dispatchEvent } = makeContext();
|
||||
ctx.tempSessions.record(PEER_ID, groupId);
|
||||
|
||||
const api = buildApiContext(ctx);
|
||||
await api.sendPrivateMessage(PEER_ID, [
|
||||
{ type: 'text', data: { text: 'hello' } },
|
||||
], false, groupId);
|
||||
|
||||
expect(dispatchEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not suppress a bridge echo that was cached but never reported', () => {
|
||||
const { dispatch, emitEvent, stored } = makeInstanceHarness();
|
||||
const cached: JsonObject = {
|
||||
time: RECEIPT.timestamp,
|
||||
self_id: SELF_ID,
|
||||
post_type: 'message_sent',
|
||||
message_type: 'group',
|
||||
sub_type: 'normal',
|
||||
message_id: 7654321,
|
||||
message_seq: RECEIPT.sequence,
|
||||
group_id: 30003,
|
||||
user_id: SELF_ID,
|
||||
message: [],
|
||||
raw_message: '',
|
||||
sender: { user_id: SELF_ID },
|
||||
};
|
||||
stored.set(7654321, cached);
|
||||
|
||||
dispatch({ ...cached, raw_message: 'canonical echo' }, 'bridge');
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledOnce();
|
||||
expect(stored.get(7654321)?.raw_message).toBe('canonical echo');
|
||||
});
|
||||
|
||||
it('does not suppress a hash collision from another conversation', () => {
|
||||
const { dispatch, emitEvent } = makeInstanceHarness();
|
||||
const sentEvent = privateSentEvent();
|
||||
|
||||
dispatch(sentEvent, 'send');
|
||||
dispatch({ ...sentEvent, target_id: PEER_ID + 1 }, 'bridge');
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user