feat(onebot): reply into group temp sessions (临时会话) (#212)
send_private_msg / send_msg can now reply to a group temp-session message by passing the source group_id. Inbound temp messages surface their source group on sender.group_id; a reply is only made into a temp session the bot has an inbound record of. Group temp replies route through RoutingHead.grpTmp (field 3).
This commit is contained in:
19 files changed
+311
-15
No files matched your search
@@ -52,13 +52,17 @@ export const actions = [
|
||||
auto_escape: f.bool().default(false),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
if (p.message_type === 'group' || p.group_id !== undefined) {
|
||||
// Group temp-session reply: message_type=private with BOTH a user_id and
|
||||
// a group_id (the source group). Detect it first so a group_id here
|
||||
// doesn't get misrouted to a group message.
|
||||
const isTempReply = p.message_type === 'private' && p.user_id !== undefined && p.group_id !== undefined;
|
||||
if (!isTempReply && (p.message_type === 'group' || p.group_id !== undefined)) {
|
||||
if (p.group_id === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
const result = await ctx.sendGroupMessage(p.group_id, p.message, p.auto_escape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
}
|
||||
if (p.user_id === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape);
|
||||
const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape, isTempReply ? p.group_id : undefined);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
},
|
||||
}),
|
||||
@@ -67,9 +71,19 @@ export const actions = [
|
||||
name: 'send_private_msg',
|
||||
summary: '发送私聊消息',
|
||||
returns: '{ message_id: number }',
|
||||
params: { user_id: f.userId(), message: f.message(), auto_escape: f.bool().default(false) },
|
||||
params: {
|
||||
user_id: f.userId(),
|
||||
message: f.message(),
|
||||
// Optional source group: reply into that group's temp session (临时会话)
|
||||
// instead of a friend chat. int({min:0}) rather than groupId (which
|
||||
// rejects 0): a client that fills every field with group_id:0 must keep
|
||||
// working as a plain private send, so 0/absent means "no temp session".
|
||||
group_id: f.int({ min: 0 }).optional(),
|
||||
auto_escape: f.bool().default(false),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape);
|
||||
const tempGroupId = p.group_id && p.group_id > 0 ? p.group_id : undefined;
|
||||
const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape, tempGroupId);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -32,7 +32,7 @@ export interface ApiActionContext {
|
||||
isOnline: () => boolean;
|
||||
getMessage: (messageId: number) => JsonObject | null;
|
||||
getMessageMeta: (messageId: number) => MessageMeta | null;
|
||||
sendPrivateMessage: (userId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
|
||||
sendPrivateMessage: (userId: number, message: JsonValue, autoEscape: boolean, tempGroupId?: number) => Promise<MessageSendResult>;
|
||||
sendGroupMessage: (groupId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
|
||||
deleteMessage: (messageId: number, meta: MessageMeta) => Promise<void>;
|
||||
canSendImage: () => boolean;
|
||||
|
||||
@@ -34,6 +34,18 @@ async function convertPrivateMessage(
|
||||
ctx.messageIdResolver, false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT,
|
||||
);
|
||||
const segments = await toSegments(ctx, event.elements, false, event.senderUin);
|
||||
const sender: JsonObject = {
|
||||
user_id: event.senderUin,
|
||||
nickname: event.senderNick,
|
||||
sex: 'unknown',
|
||||
age: 0,
|
||||
};
|
||||
// A temp (group-originated) message carries its source group so a client can
|
||||
// reply via send_private_msg(user_id, group_id=sender.group_id). Mirrors
|
||||
// go-cqhttp / NapCat, which expose it on sender.group_id.
|
||||
if (subType === 'group' && 'groupId' in event && event.groupId > 0) {
|
||||
sender.group_id = event.groupId;
|
||||
}
|
||||
return message(ctx, event, postType, {
|
||||
message_type: 'private',
|
||||
sub_type: subType,
|
||||
@@ -43,12 +55,7 @@ async function convertPrivateMessage(
|
||||
message: segments,
|
||||
raw_message: segmentsToRawMessage(segments),
|
||||
font: 0,
|
||||
sender: {
|
||||
user_id: event.senderUin,
|
||||
nickname: event.senderNick,
|
||||
sex: 'unknown',
|
||||
age: 0,
|
||||
},
|
||||
sender,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,9 @@ export function registerEventPipeline(ctx: OneBotInstanceContext): () => void {
|
||||
disposers.push(
|
||||
ctx.bridge.events.on('temp_message', async (event) => {
|
||||
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, 0);
|
||||
// Record this group temp session so a later reply is limited to sessions
|
||||
// the peer opened.
|
||||
ctx.tempSessions.record(event.senderUin, event.groupId);
|
||||
await convertAndDispatch(ctx, log, event);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { ApiActionContext } from './api-handler';
|
||||
import type { ConverterContext } from './event-converter';
|
||||
import type { MediaStore } from './media-store';
|
||||
import type { MessageStore } from './message-store';
|
||||
import type { TempSessionStore } from './temp-session-store';
|
||||
import {
|
||||
getDownloadRKeys,
|
||||
getFriendList,
|
||||
@@ -46,6 +47,8 @@ export interface OneBotInstanceContext {
|
||||
messageStore: MessageStore;
|
||||
mediaStore: MediaStore;
|
||||
reactionStore: ReactionStore;
|
||||
/** Group temp-session records — see {@link TempSessionStore}. */
|
||||
tempSessions: TempSessionStore;
|
||||
converterCtx: ConverterContext;
|
||||
config: OneBotConfig;
|
||||
musicSignUrl?: string;
|
||||
@@ -65,7 +68,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
getMessageMeta: (messageId) => messageStore.findMeta(messageId),
|
||||
canSendImage: () => true,
|
||||
canSendRecord: () => true,
|
||||
sendPrivateMessage: (userId, message, autoEscape) => sendPrivateMessage(ref, userId, message, autoEscape),
|
||||
sendPrivateMessage: (userId, message, autoEscape, tempGroupId) => sendPrivateMessage(ref, userId, message, autoEscape, tempGroupId),
|
||||
sendGroupMessage: (groupId, message, autoEscape) => sendGroupMessage(ref, groupId, message, autoEscape),
|
||||
deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta),
|
||||
getFriendList: () => getFriendList(bridge),
|
||||
|
||||
@@ -6,6 +6,7 @@ import { ApiHandler, type ActionObserver } from './api-handler';
|
||||
import type { ConverterContext } from './event-converter';
|
||||
import { registerEventPipeline } from './event-pipeline';
|
||||
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
|
||||
import { TempSessionStore } from './temp-session-store';
|
||||
import { RKeyCache } from './instance-rkey';
|
||||
import type { GlobalSettings } from './global-config';
|
||||
import { MediaIndexer } from './media-indexer';
|
||||
@@ -116,6 +117,7 @@ export class OneBotInstance {
|
||||
messageStore: this.messageStore,
|
||||
mediaStore: this.mediaStore,
|
||||
reactionStore: this.reactionStore,
|
||||
tempSessions: new TempSessionStore(),
|
||||
converterCtx: this.converterCtx,
|
||||
config,
|
||||
musicSignUrl: globalSettings.musicSignUrl,
|
||||
|
||||
@@ -546,7 +546,14 @@ export async function sendPrivateMessage(
|
||||
userId: number,
|
||||
message: JsonValue,
|
||||
autoEscape: boolean,
|
||||
/** When set, reply into this group's temp session instead of friend c2c. */
|
||||
tempGroupId?: number,
|
||||
): Promise<MessageSendResult> {
|
||||
// A temp-session reply is only allowed into a session the peer opened.
|
||||
const isTempReply = tempGroupId !== undefined && ref.tempSessions.has(userId, tempGroupId);
|
||||
if (tempGroupId !== undefined && !isTempReply) {
|
||||
throw new Error(`cannot send to user ${userId} in group ${tempGroupId}: no such temp session`);
|
||||
}
|
||||
const elements = await parseMessage(message, autoEscape, {
|
||||
resolveReplySequence: (replyMessageId) => {
|
||||
return ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
|
||||
@@ -639,12 +646,22 @@ export async function sendPrivateMessage(
|
||||
}
|
||||
}
|
||||
|
||||
// Route text/media batches through the temp-session primitive when replying
|
||||
// passively, else the normal friend c2c path.
|
||||
const sendText = (elems: MessageElement[]) =>
|
||||
isTempReply && tempGroupId !== undefined
|
||||
? ref.bridge.apis.message.sendGroupTempMessage(userId, tempGroupId, elems)
|
||||
: ref.bridge.apis.message.sendPrivate(userId, elems);
|
||||
|
||||
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendPrivate>> | undefined;
|
||||
if (nonFileElements.length > 0) {
|
||||
try {
|
||||
lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements);
|
||||
lastReceipt = await sendText(nonFileElements);
|
||||
logSentMessage(false, userId, nonFileElements);
|
||||
} catch (err) {
|
||||
// A temp-session reply can't fall back to the c2c file path (friend-only)
|
||||
// — surface the original error rather than mis-routing.
|
||||
if (tempGroupId !== undefined) throw err;
|
||||
// Highway upload failed — if a large video triggered it, fall back to
|
||||
// file upload for that element (private messages cannot carry file
|
||||
// elements through the element pipeline).
|
||||
@@ -661,6 +678,9 @@ export async function sendPrivateMessage(
|
||||
}
|
||||
}
|
||||
if (allFileElements.length > 0) {
|
||||
if (tempGroupId !== undefined) {
|
||||
throw new Error('temp-session reply does not support file or oversized-video segments');
|
||||
}
|
||||
const userUid = await ref.bridge.resolveUserUid(userId);
|
||||
if (!userUid) throw new Error(`c2c file send: could not resolve uid for user ${userId}`);
|
||||
for (const fileEl of allFileElements) {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Records the group temp sessions the bot has received a message from, so a
|
||||
* reply can be limited to sessions the peer opened. Written only on the receive
|
||||
* path, read only on the send path. Keyed by `${userUin}:${groupUin}` — a user
|
||||
* may hold sessions from several groups. Entries expire after
|
||||
* {@link TEMP_SESSION_TTL_MS}.
|
||||
*/
|
||||
|
||||
/** Reply window: 7 days after the last inbound temp message. */
|
||||
export const TEMP_SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export class TempSessionStore {
|
||||
/** key → expiry epoch ms. */
|
||||
private readonly sessions = new Map<string, number>();
|
||||
|
||||
private static key(userUin: number, groupUin: number): string {
|
||||
return `${userUin}:${groupUin}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Record (or refresh) an inbound temp session. Called from the receive path.
|
||||
* No-op without a source group (groupUin<=0) — the session stays receive-only.
|
||||
*/
|
||||
record(userUin: number, groupUin: number, now: number = Date.now()): void {
|
||||
if (userUin <= 0 || groupUin <= 0) return;
|
||||
// Opportunistically prune expired entries here — `has` only removes keys it
|
||||
// reads, so a stream of never-replied sessions would otherwise grow the map
|
||||
// unbounded.
|
||||
this.sweep(now);
|
||||
this.sessions.set(TempSessionStore.key(userUin, groupUin), now + TEMP_SESSION_TTL_MS);
|
||||
}
|
||||
|
||||
/** True iff a reply is allowed for this exact (user, group). Prunes on read. */
|
||||
has(userUin: number, groupUin: number, now: number = Date.now()): boolean {
|
||||
const key = TempSessionStore.key(userUin, groupUin);
|
||||
const expiresAt = this.sessions.get(key);
|
||||
if (expiresAt === undefined) return false;
|
||||
if (expiresAt <= now) {
|
||||
this.sessions.delete(key);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Drop all expired entries. `has` also prunes lazily. */
|
||||
sweep(now: number = Date.now()): void {
|
||||
for (const [key, expiresAt] of this.sessions) {
|
||||
if (expiresAt <= now) this.sessions.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user