fix(onebot): expose robot status for group members

Fetch QQ's versioned robot UIN ranges, classify and persist member status, and surface is_robot from both group member actions.

Preserve unknown legacy cache entries and fail visibly when classification is unavailable.

Closes #265
This commit is contained in:
DrSmoothl committed 2026-07-21 23:27:01 +08:00
1 parent ff60221330
commit eed2e692b1
16 files changed
+596 -36

No files matched your search

+25 -7
View File
@@ -76,6 +76,7 @@ interface MemberInput {
joinTime?: number;
lastSentTime?: number;
shutUpTime?: number;
isRobot?: boolean;
active?: boolean;
}
@@ -102,6 +103,7 @@ interface MemberRow {
join_time: number;
last_sent_time: number;
shut_up_time: number;
is_robot: number | null;
active: number;
}
@@ -179,6 +181,7 @@ export class IdentityService {
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('PRAGMA synchronous = NORMAL');
this.initSchema();
this.migrateSchema();
this.loadSnapshot();
}
@@ -711,6 +714,7 @@ export class IdentityService {
join_time INTEGER NOT NULL DEFAULT 0,
last_sent_time INTEGER NOT NULL DEFAULT 0,
shut_up_time INTEGER NOT NULL DEFAULT 0,
is_robot INTEGER,
active INTEGER NOT NULL DEFAULT 1,
updated_at INTEGER NOT NULL,
UNIQUE(group_id, uid),
@@ -725,6 +729,14 @@ export class IdentityService {
`);
}
private migrateSchema(): void {
const columns = this.db!.prepare('PRAGMA table_info(group_members)').all() as Array<{ name: string }>;
if (columns.some((column) => column.name === 'is_robot')) return;
this.db!.exec('ALTER TABLE group_members ADD COLUMN is_robot INTEGER');
this.log.info('identity schema migrated: added group_members.is_robot');
}
private loadSnapshot(): void {
const friendRows = this.pstmt(
`SELECT uid, uin, nickname, remark
@@ -766,7 +778,7 @@ export class IdentityService {
const select = this.pstmt(
`SELECT group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time
join_time, last_sent_time, shut_up_time, is_robot
FROM group_members
WHERE group_id = ? AND active = 1`,
);
@@ -783,6 +795,7 @@ export class IdentityService {
join_time: number;
last_sent_time: number;
shut_up_time: number;
is_robot: number | null;
}>;
const members = rows.map(rowToMemberInfo);
this.setGroupMembersInMemory(groupId, members);
@@ -904,6 +917,7 @@ export class IdentityService {
joinTime: normalizeNonNegative(input.joinTime, primary?.join_time ?? 0),
lastSentTime: normalizeNonNegative(input.lastSentTime, primary?.last_sent_time ?? 0),
shutUpTime: normalizeNonNegative(input.shutUpTime, primary?.shut_up_time ?? 0),
isRobot: input.isRobot === undefined ? (primary?.is_robot ?? null) : input.isRobot ? 1 : 0,
active: input.active === false ? 0 : input.active === true ? 1 : (primary?.active ?? 1),
updatedAt: nowSeconds(),
};
@@ -915,7 +929,7 @@ export class IdentityService {
this.pstmt(
`UPDATE group_members
SET uid = ?, uin = ?, nickname = ?, card = ?, role = ?, level = ?, title = ?,
join_time = ?, last_sent_time = ?, shut_up_time = ?, active = ?, updated_at = ?
join_time = ?, last_sent_time = ?, shut_up_time = ?, is_robot = ?, active = ?, updated_at = ?
WHERE id = ?`,
).run(
merged.uid,
@@ -928,6 +942,7 @@ export class IdentityService {
merged.joinTime,
merged.lastSentTime,
merged.shutUpTime,
merged.isRobot,
merged.active,
merged.updatedAt,
primary.id,
@@ -938,8 +953,8 @@ export class IdentityService {
this.pstmt(
`INSERT INTO group_members
(group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time, active, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
join_time, last_sent_time, shut_up_time, is_robot, active, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
).run(
input.groupId,
merged.uid,
@@ -952,6 +967,7 @@ export class IdentityService {
merged.joinTime,
merged.lastSentTime,
merged.shutUpTime,
merged.isRobot,
merged.active,
merged.updatedAt,
);
@@ -982,7 +998,7 @@ export class IdentityService {
if (uid && uin !== null) {
return this.pstmt(
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time, active
join_time, last_sent_time, shut_up_time, is_robot, active
FROM group_members
WHERE group_id = ? AND (uid = ? OR uin = ?)
ORDER BY id`,
@@ -991,7 +1007,7 @@ export class IdentityService {
if (uid) {
return this.pstmt(
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time, active
join_time, last_sent_time, shut_up_time, is_robot, active
FROM group_members
WHERE group_id = ? AND uid = ?
ORDER BY id`,
@@ -1000,7 +1016,7 @@ export class IdentityService {
if (uin !== null) {
return this.pstmt(
`SELECT id, group_id, uid, uin, nickname, card, role, level, title,
join_time, last_sent_time, shut_up_time, active
join_time, last_sent_time, shut_up_time, is_robot, active
FROM group_members
WHERE group_id = ? AND uin = ?
ORDER BY id`,
@@ -1187,6 +1203,7 @@ function rowToMemberInfo(row: {
join_time: number;
last_sent_time: number;
shut_up_time: number;
is_robot: number | null;
}): GroupMemberInfo {
return {
uid: row.uid ?? '',
@@ -1199,6 +1216,7 @@ function rowToMemberInfo(row: {
joinTime: row.join_time,
lastSentTime: row.last_sent_time,
shutUpTime: row.shut_up_time,
isRobot: row.is_robot === null ? undefined : row.is_robot !== 0,
};
}
@@ -0,0 +1,86 @@
// 0x496_0 — fetch QQ's server-versioned robot UIN ranges.
//
// The 0xFE7_3 group-member response has no robot flag. QQ's own renderer
// initializes its robot service with this read-only request and classifies
// non-buddy UINs against the returned inclusive ranges. Keeping the config
// dynamic avoids baking Tencent's current allocation into SnowLuma.
import type { OidbBase, OidbRobotUinRangeResponse } from '@snowluma/proto-defs/oidb';
import type { OidbRobotUinRangeRequest } from '@snowluma/proto-defs/oidb-actions/base';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface RobotUinRange {
minUin: number;
maxUin: number;
}
export interface RobotUinRangeSnapshot {
version: number;
ranges: RobotUinRange[];
}
function decodeUin(value: bigint | number | undefined, label: string): number {
const decoded = Number(value ?? 0);
if (!Number.isSafeInteger(decoded) || decoded <= 0 || decoded > 0xFFFF_FFFF) {
throw new Error(`0x496_0 response has invalid ${label}: ${String(value)}`);
}
return decoded;
}
export namespace FetchRobotUinRanges {
export const command = 0x496;
export const subCommand = 0;
export type Deps = OidbSender;
export const serialize = (): OidbRobotUinRangeRequest => ({
justFetchMsgConfig: 1,
type: 1,
version: 0,
aioKeywordVersion: 0,
});
export const deserialize = (
_ctx: Deps,
body: OidbRobotUinRangeResponse,
): RobotUinRangeSnapshot => {
const config = body.robotConfig;
if (!config) {
throw new Error('0x496_0 response missing robot range config');
}
if (config.version === undefined) {
throw new Error('0x496_0 response missing robot range config version');
}
const version = Number(config.version);
if (!Number.isSafeInteger(version) || version < 0) {
throw new Error(`0x496_0 response has invalid config version: ${String(config.version)}`);
}
if (!config.ranges || config.ranges.length === 0) {
throw new Error('0x496_0 response has no robot UIN ranges');
}
const ranges = config.ranges.map((range, index) => {
const minUin = decodeUin(range.minUin, `range[${index}].minUin`);
const maxUin = decodeUin(range.maxUin, `range[${index}].maxUin`);
if (minUin > maxUin) {
throw new Error(
`0x496_0 response has inverted range[${index}]: ${minUin}-${maxUin}`,
);
}
return { minUin, maxUin };
});
return { version, ranges };
};
export const encode = (env: OidbBase<OidbRobotUinRangeRequest>): Uint8Array =>
protobuf_encode<OidbBase<OidbRobotUinRangeRequest>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbRobotUinRangeResponse> =>
protobuf_decode<OidbBase<OidbRobotUinRangeResponse>>(bytes);
export const invoke = (deps: Deps): Promise<RobotUinRangeSnapshot> =>
invokeOidb(deps, FetchRobotUinRanges, undefined);
}
+2
View File
@@ -34,6 +34,8 @@ export interface GroupMemberInfo {
uid: string;
nickname: string;
card: string;
/** Undefined until QQ's server-provided robot ranges classify this member. */
isRobot?: boolean;
role: string; // 'owner' | 'admin' | 'member'
level: number;
title: string;
@@ -0,0 +1,83 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbRobotUinRangeRequest } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { FetchRobotUinRanges } from '../../../src/oidb-services/contacts/fetch-robot-uin-ranges';
// Captured from QQ's 0x496_0 response and reduced to the versioned range
// config. Keeping this as wire bytes makes the test independent of the
// encoder used by the implementation.
const RESPONSE_FIXTURE = Buffer.from(
'0896091000180022492a4708ce01120c08fee8fdb20c10fee8fdb20c'
+ '120c08cda8fed00a10cfc5ffd00a120a08c0f8e01f10c0f8e01f12'
+ '0c08c0dcb5be0e10ffe0f2be0e120c0880fd8ef80e10ffa9f1fc0e',
'hex',
);
function makeSender(responseData = RESPONSE_FIXTURE) {
const result: SendPacketResult = {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData,
};
return { sendRawPacket: vi.fn(async () => result) };
}
describe('FetchRobotUinRanges namespace', () => {
it('routes the read-only request to 0x496_0 with QQ-compatible fields', async () => {
const sender = makeSender();
await FetchRobotUinRanges.invoke(sender);
expect(sender.sendRawPacket).toHaveBeenCalledOnce();
const [wireName, bytes] = sender.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0x496_0');
const request = protobuf_decode<OidbBase<OidbRobotUinRangeRequest>>(bytes);
expect(request.body).toEqual({
justFetchMsgConfig: 1,
type: 1,
version: 0,
aioKeywordVersion: 0,
});
});
it('decodes the server version and every inclusive UIN range', async () => {
const sender = makeSender();
await expect(FetchRobotUinRanges.invoke(sender)).resolves.toEqual({
version: 206,
ranges: [
{ minUin: 3328144510, maxUin: 3328144510 },
{ minUin: 2854196301, maxUin: 2854216399 },
{ minUin: 66600000, maxUin: 66600000 },
{ minUin: 3889000000, maxUin: 3889999999 },
{ minUin: 4010000000, maxUin: 4019999999 },
],
});
});
it('rejects a successful envelope that omits the robot range config', async () => {
const sender = makeSender(Buffer.from('089609100018002200', 'hex'));
await expect(FetchRobotUinRanges.invoke(sender))
.rejects.toThrow('0x496_0 response missing robot range config');
});
it('rejects a robot config without its version', () => {
expect(() => FetchRobotUinRanges.deserialize(makeSender(), {
robotConfig: {
ranges: [{ minUin: 3_889_000_000n, maxUin: 3_889_999_999n }],
},
})).toThrow('0x496_0 response missing robot range config version');
});
it('rejects an empty range set instead of classifying everyone as human', () => {
expect(() => FetchRobotUinRanges.deserialize(makeSender(), {
robotConfig: { version: 206, ranges: [] },
})).toThrow('0x496_0 response has no robot UIN ranges');
});
});