fix:Fix the issue where quoting a message in replies was ineffective

Previous behavior:
Replies visually displayed a quote block, but the quoted content was blank or invalid, and clicking to jump to the original message also failed.

Fixed behavior:
The quote now correctly references the original message, displaying its actual content and enabling a functional jump to the quoted message.
This commit is contained in:
venti1112 committed 2026-05-06 15:53:11 +08:00
1 parent 4a92292e49
commit de7533ca81
8 files changed
+407 -27

No files matched your search

+2 -9
View File
@@ -475,17 +475,10 @@ function elementsToText(elements: MessageElement[]): string {
function printEvent(event: QQEventVariant): void {
switch (event.kind) {
case 'group_message': {
const c = elementsToText(event.elements);
const s = event.senderCard || event.senderNick || String(event.senderUin);
eventLog.success('群 %d | %s(%d): %s', event.groupId, s, event.senderUin, c);
break;
}
case 'group_message':
case 'friend_message':
eventLog.info('私聊 %s(%d): %s', event.senderNick || String(event.senderUin), event.senderUin, elementsToText(event.elements));
break;
case 'temp_message':
eventLog.info('临时 %d(群%d): %s', event.senderUin, event.groupId, elementsToText(event.elements));
// Message logging is handled by OneBot layer with message ID
break;
case 'group_recall':
eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin);
@@ -54,11 +54,21 @@ function makeMentionElem(element: MessageElement): ProtoElem {
}
function makeReplyElem(element: MessageElement): ProtoElem {
return {
srcMsg: {
origSeqs: [element.replySeq! & 0xFFFFFFFF],
} as any,
const seq = element.replySeq! & 0xFFFFFFFF;
const srcMsg: any = {
origSeqs: [seq],
};
// Add additional fields if available for better reply display
if (element.replySenderUin) {
srcMsg.senderUin = BigInt(element.replySenderUin);
}
if (element.replyTime) {
srcMsg.time = element.replyTime;
}
return { srcMsg };
}
function makeJsonElem(element: MessageElement): ProtoElem {
+4
View File
@@ -13,6 +13,10 @@ export interface MessageElement {
fileName?: string;
fileSize?: number;
replySeq?: number;
replyMessageId?: number; // For reply: original message ID (for logging)
replySenderUin?: number; // For reply: original sender's UIN
replyTime?: number; // For reply: original message timestamp
replyRandom?: number; // For reply: original message random/msgId
url?: string;
subType?: number;
duration?: number;
+100 -5
View File
@@ -1,5 +1,5 @@
import type { Bridge } from '../bridge/bridge';
import type { ForwardNodePayload } from '../bridge/events';
import type { ForwardNodePayload, MessageElement } from '../bridge/events';
import type { QQInfo } from '../bridge/qq-info';
import type { ApiActionContext, MessageSendResult } from './api-handler';
import { elementsToOneBotSegments } from './event-converter';
@@ -7,6 +7,9 @@ import { MessageStore } from './message-store';
import { parseMessage } from './message-parser';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
import type { JsonObject, JsonValue, MessageMeta } from './types';
import { createLogger } from '../utils/logger';
const log = createLogger('OneBot');
export interface InstanceRef {
uin: string;
@@ -412,6 +415,68 @@ async function handleSetEssence(bridge: Bridge, messageStore: MessageStore, mess
await bridge.setGroupEssence(meta.targetId, meta.sequence, meta.random, enable);
}
// --- Send message logging ---
function logSentMessage(isGroup: boolean, targetId: number, elements: MessageElement[]): void {
const type = isGroup ? '群聊' : '私聊';
const parts: string[] = [];
// Check for reply element
const replyElem = elements.find(e => e.type === 'reply');
if (replyElem && replyElem.replyMessageId) {
parts.push(`[回复:${replyElem.replyMessageId}]`);
}
// Build message content preview
for (const elem of elements) {
if (elem.type === 'reply') continue; // Already handled
switch (elem.type) {
case 'text':
if (elem.text) {
const preview = elem.text.length > 50 ? elem.text.substring(0, 50) + '...' : elem.text;
parts.push(preview);
}
break;
case 'image':
parts.push('[图片]');
break;
case 'face':
parts.push('[表情]');
break;
case 'at':
if (elem.text) parts.push(elem.text.trim());
break;
case 'record':
parts.push('[语音]');
break;
case 'video':
parts.push('[视频]');
break;
case 'json':
parts.push('[JSON消息]');
break;
case 'xml':
parts.push('[XML消息]');
break;
case 'markdown':
parts.push('[Markdown]');
break;
case 'forward':
parts.push('[转发消息]');
break;
case 'poke':
parts.push('[戳一戳]');
break;
default:
break;
}
}
const content = parts.join(' ').trim() || '[空消息]';
log.info(`${type} ${targetId} | 发送:${content}`);
}
// --- Send message ---
async function handleSendPrivate(
@@ -421,8 +486,20 @@ async function handleSendPrivate(
autoEscape: boolean,
): Promise<MessageSendResult> {
const elements = await parseMessage(message, autoEscape, {
resolveReplySequence: (replyMessageId) =>
ref.messageStore.resolveReplySequence(false, userId, replyMessageId),
resolveReplySequence: (replyMessageId) => {
return ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
},
resolveReplyMeta: (replyMessageId) => {
const meta = ref.messageStore.findMeta(replyMessageId);
if (meta) {
return {
senderUin: meta.targetId, // For received messages, targetId is the sender
time: meta.timestamp,
random: meta.random,
};
}
return null;
},
musicSignUrl: ref.musicSignUrl,
});
if (elements.length === 0) throw new Error('message is empty');
@@ -430,6 +507,9 @@ async function handleSendPrivate(
const receipt = await ref.bridge.sendPrivateMessage(userId, elements);
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
// Log sent message
logSentMessage(false, userId, elements);
// Cache the sent message meta
ref.cacheMessageMeta(messageId, {
isGroup: false,
@@ -451,8 +531,20 @@ async function handleSendGroup(
autoEscape: boolean,
): Promise<MessageSendResult> {
const elements = await parseMessage(message, autoEscape, {
resolveReplySequence: (replyMessageId) =>
ref.messageStore.resolveReplySequence(true, groupId, replyMessageId),
resolveReplySequence: (replyMessageId) => {
return ref.messageStore.resolveReplySequence(true, groupId, replyMessageId);
},
resolveReplyMeta: (replyMessageId) => {
const event = ref.messageStore.findEvent(replyMessageId);
if (event) {
return {
senderUin: typeof event.user_id === 'number' ? event.user_id : parseInt(String(event.user_id || '0'), 10),
time: typeof event.time === 'number' ? event.time : parseInt(String(event.time || '0'), 10),
random: 0, // Group messages might not have random field in event
};
}
return null;
},
musicSignUrl: ref.musicSignUrl,
});
if (elements.length === 0) throw new Error('message is empty');
@@ -460,6 +552,9 @@ async function handleSendGroup(
const receipt = await ref.bridge.sendGroupMessage(groupId, elements);
const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT);
// Log sent message
logSentMessage(true, groupId, elements);
// Cache the sent message meta
ref.cacheMessageMeta(messageId, {
isGroup: true,
+55
View File
@@ -12,6 +12,9 @@ import type { JsonObject, MessageMeta, OneBotConfig } from './types';
import { HttpTransport } from './http-transport';
import { HttpPostTransport } from './http-post-transport';
import { WsTransport } from './ws-transport';
import { createLogger } from '../utils/logger';
const log = createLogger('Event');
export class OneBotInstance {
readonly uin: string;
@@ -153,10 +156,62 @@ export class OneBotInstance {
private dispatchEvent(event: JsonObject): void {
this.cacheMessageEvent(event);
this.logReceivedMessage(event);
this.wsTransport.publishEvent(event);
this.httpPostTransport.publishEvent(event);
}
private logReceivedMessage(event: JsonObject): void {
if (event.post_type !== 'message') return;
const messageId = toInt(event.message_id);
const isGroup = event.message_type === 'group';
// Build message preview
const parts: string[] = [];
const message = event.message;
if (Array.isArray(message)) {
for (const seg of message) {
if (seg.type === 'text' && seg.data?.text) {
const text = String(seg.data.text);
const preview = text.length > 50 ? text.substring(0, 50) + '...' : text;
parts.push(preview);
} else if (seg.type === 'image') {
parts.push('[图片]');
} else if (seg.type === 'face') {
parts.push('[表情]');
} else if (seg.type === 'at') {
parts.push(`@${seg.data?.qq || ''}`);
} else if (seg.type === 'reply') {
parts.push(`[回复:${seg.data?.id || ''}]`);
} else if (seg.type === 'record') {
parts.push('[语音]');
} else if (seg.type === 'video') {
parts.push('[视频]');
} else {
parts.push(`[${seg.type}]`);
}
}
}
const content = parts.join(' ').trim() || '[空消息]';
const idStr = `ID:${messageId}`;
if (isGroup) {
const groupId = toInt(event.group_id);
const userId = toInt(event.user_id);
const sender = event.sender as any;
const nickname = sender?.card || sender?.nickname || String(userId);
log.success(`群 ${groupId} | ${nickname}(${userId}): ${idStr} ${content}`);
} else {
const userId = toInt(event.user_id);
const sender = event.sender as any;
const nickname = sender?.nickname || String(userId);
log.success(`私聊 ${nickname}(${userId}): ${idStr} ${content}`);
}
}
private cacheMessageEvent(event: JsonObject): void {
if (event.post_type !== 'message') return;
+18 -1
View File
@@ -7,6 +7,7 @@ import type { JsonValue, JsonObject } from './types';
export interface ParseMessageOptions {
resolveReplySequence?: (replyMessageId: number) => number | null;
resolveReplyMeta?: (replyMessageId: number) => { senderUin: number; time: number; random: number } | null;
musicSignUrl?: string;
}
@@ -102,7 +103,23 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
if (options?.resolveReplySequence) {
const resolved = options.resolveReplySequence(id);
if (typeof resolved === 'number' && resolved > 0) {
return { type: 'reply', replySeq: resolved };
const element: MessageElement = {
type: 'reply',
replySeq: resolved,
replyMessageId: id // Keep the original messageId for logging
};
// Try to get additional meta info for better reply display
if (options?.resolveReplyMeta) {
const meta = options.resolveReplyMeta(id);
if (meta) {
element.replySenderUin = meta.senderUin;
element.replyTime = meta.time;
element.replyRandom = meta.random;
}
}
return element;
}
}
+24 -8
View File
@@ -120,15 +120,31 @@ export class MessageStore {
}
resolveReplySequence(isGroup: boolean, sessionId: number, messageId: number): number | null {
if (!Number.isInteger(sessionId) || sessionId <= 0 || !isValidMessageId(messageId)) return null;
const row = this.db.prepare(
`SELECT sequence
FROM messages
WHERE is_group = ? AND session_id = ? AND message_hash = ?
LIMIT 1`
).get(isGroup ? 1 : 0, sessionId, messageId) as { sequence: number } | undefined;
if (!Number.isInteger(sessionId) || sessionId <= 0 || !isValidMessageId(messageId)) {
return null;
}
if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) return null;
// For private messages, we cannot rely on session_id matching because:
// - When receiving: session_id is the sender's UIN
// - When sending reply: sessionId parameter is the recipient's UIN (who we're sending to)
// So for private messages, we only match by message_hash and is_group flag.
const row = isGroup
? this.db.prepare(
`SELECT sequence
FROM messages
WHERE is_group = 1 AND session_id = ? AND message_hash = ?
LIMIT 1`
).get(sessionId, messageId) as { sequence: number } | undefined
: this.db.prepare(
`SELECT sequence
FROM messages
WHERE is_group = 0 AND message_hash = ?
LIMIT 1`
).get(messageId) as { sequence: number } | undefined;
if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) {
return null;
}
return row.sequence;
}
+190
View File
@@ -0,0 +1,190 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { MessageStore } from '../src/onebot/message-store';
import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../src/onebot/message-id';
import fs from 'fs';
import path from 'path';
describe('MessageStore', () => {
const testDbPath = path.join('data', 'test', 'messages-test.db');
let store: MessageStore;
beforeEach(() => {
// Clean up any existing test database
try {
fs.unlinkSync(testDbPath);
} catch {
// Ignore if file doesn't exist
}
store = new MessageStore(testDbPath);
});
afterEach(() => {
store.close();
// Clean up test database
try {
fs.unlinkSync(testDbPath);
} catch {
// Ignore cleanup errors
}
});
describe('resolveReplySequence', () => {
it('resolves group message reply sequence', () => {
const groupId = 123456;
const sequence = 100;
const messageId = hashMessageIdInt32(sequence, groupId, GROUP_MESSAGE_EVENT);
// Store a group message
store.storeMeta(messageId, {
isGroup: true,
targetId: groupId,
sequence,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
timestamp: Date.now(),
});
// Resolve the reply sequence
const resolved = store.resolveReplySequence(true, groupId, messageId);
expect(resolved).toBe(sequence);
});
it('resolves private message reply sequence without session_id matching', () => {
// Simulate receiving a private message from user 111111
const senderUin = 111111;
const sequence = 200;
const messageId = hashMessageIdInt32(sequence, senderUin, PRIVATE_MESSAGE_EVENT);
// Store the received message (session_id is sender's UIN)
store.storeMeta(messageId, {
isGroup: false,
targetId: senderUin,
sequence,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
timestamp: Date.now(),
});
// When replying to this message, we send to the sender (who becomes the recipient)
// The key fix: resolveReplySequence should work even when sessionId doesn't match
const resolved = store.resolveReplySequence(false, senderUin, messageId);
expect(resolved).toBe(sequence);
// More importantly: it should also work when we pass a different sessionId
// (which was the bug - we were passing recipient UIN instead of sender UIN)
const differentUin = 999999;
const resolvedWithDifferentSession = store.resolveReplySequence(false, differentUin, messageId);
expect(resolvedWithDifferentSession).toBe(sequence);
});
it('returns null for non-existent message', () => {
const resolved = store.resolveReplySequence(true, 123456, 999999);
expect(resolved).toBeNull();
});
it('returns null for invalid messageId', () => {
const resolved = store.resolveReplySequence(true, 123456, 0);
expect(resolved).toBeNull();
});
it('returns null for invalid sessionId', () => {
const messageId = hashMessageIdInt32(100, 123456, GROUP_MESSAGE_EVENT);
const resolved = store.resolveReplySequence(true, 0, messageId);
expect(resolved).toBeNull();
});
it('distinguishes between group and private messages', () => {
const sessionId = 123456;
const sequence = 300;
// Store a group message
const groupMessageId = hashMessageIdInt32(sequence, sessionId, GROUP_MESSAGE_EVENT);
store.storeMeta(groupMessageId, {
isGroup: true,
targetId: sessionId,
sequence,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
timestamp: Date.now(),
});
// Store a private message with same sequence but different hash
const privateMessageId = hashMessageIdInt32(sequence, sessionId, PRIVATE_MESSAGE_EVENT);
store.storeMeta(privateMessageId, {
isGroup: false,
targetId: sessionId,
sequence,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
timestamp: Date.now(),
});
// Should resolve correctly based on isGroup flag
const groupResolved = store.resolveReplySequence(true, sessionId, groupMessageId);
expect(groupResolved).toBe(sequence);
const privateResolved = store.resolveReplySequence(false, sessionId, privateMessageId);
expect(privateResolved).toBe(sequence);
// Should not cross-resolve
const wrongGroupResolve = store.resolveReplySequence(true, sessionId, privateMessageId);
expect(wrongGroupResolve).toBeNull();
const wrongPrivateResolve = store.resolveReplySequence(false, sessionId, groupMessageId);
expect(wrongPrivateResolve).toBeNull();
});
});
describe('storeEvent and findEvent', () => {
it('stores and retrieves event data', () => {
const messageId = 12345;
const event = {
post_type: 'message',
message_type: 'group',
message_id: messageId,
group_id: 123456,
message: 'test message',
time: Date.now(),
};
store.storeEvent(messageId, true, 123456, 100, GROUP_MESSAGE_EVENT, event);
const retrieved = store.findEvent(messageId);
expect(retrieved).toEqual(event);
});
it('returns null for non-existent event', () => {
const retrieved = store.findEvent(999999);
expect(retrieved).toBeNull();
});
});
describe('storeMeta and findMeta', () => {
it('stores and retrieves message meta', () => {
const messageId = 54321;
const meta = {
isGroup: true,
targetId: 123456,
sequence: 100,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: 1,
random: 12345,
timestamp: Date.now(),
};
store.storeMeta(messageId, meta);
const retrieved = store.findMeta(messageId);
expect(retrieved).toEqual(meta);
});
it('returns null for non-existent meta', () => {
const retrieved = store.findMeta(999999);
expect(retrieved).toBeNull();
});
});
});