feat(onebot): expose public contact profiles

Refs #615
This commit is contained in:
DrSmoothl committed 2026-11-02 08:06:27 +08:00
1 parent 2b63f375fc
commit 45c3a6841a
34 files changed
+2427 -211

No files matched your search

+51
View File
@@ -0,0 +1,51 @@
# Contact profiles
`get_friend_list` and `get_friends_with_category` preserve their existing result
shapes and add optional public profile fields to each friend. By default they
only read the paginated roster: they do not issue a profile request for every
friend. Both accept `with_profile: true` to explicitly query additional details.
Large lists may require a longer client timeout.
Explicit enrichment uses a five-minute cache belonging to the current account,
deduplicates simultaneous queries and limits aggregate profile concurrency to
four. Values already supplied by the roster take precedence, including empty
strings, zero and false. An enrichment failure fails the action after draining
the current batch; it is logged, is not cached and is not automatically retried.
A later call may retry it. The ordinary flat list retains its existing logged
fallback to cached friends when the roster cannot be refreshed.
Friend rows contain `user_id`, `nickname`, `remark`, and `category_id` when
available. Public fields also appear in `get_stranger_info` when QQ supplies them:
| Fields | Meaning |
| --- | --- |
| `long_nick`, `sex`, `age`, `level` | Signature, gender, age and QQ level |
| `birthday_year`, `birthday_month`, `birthday_day` | Birthday; a hidden year is omitted |
| `phone_num`, `email` | Contact details made available by the profile |
| `country`, `province`, `city`, `college` | Location and school |
| `is_qq_vip`, `is_vip`, `is_years_vip`, `vip_level` | Ordinary membership, super membership (existing meaning of `is_vip`), annual membership and level |
| `privilege_icons` | `jump_url` if supplied, plus `open` and `closed` icon lists |
Each privilege entry may contain `type`, `level`, `flag`, `is_big`, `jump_url`,
`icon_url` and `deluxe_icon_url`. The two icon URLs can coexist. Flags retain
their server values; they are not guessed to mean annual or premium membership.
Local downloaded icon paths are not part of the response.
Missing data is omitted rather than replaced with false, zero or an empty list.
An explicitly returned empty icon-list body produces `open: [], closed: []`;
unavailable icon data omits `privilege_icons`. Existing required stranger fields
and aliases retain their earlier defaults. Malformed optional birthdays are
logged without recording their values; malformed text or privilege payloads
fail decoding.
SDK calls keep the existing options argument:
```ts
const friends = await client.getFriendList({ withProfile: true, timeoutMs: 120_000 });
const categories = await client.call('get_friends_with_category', { with_profile: true });
```
The exported `FriendInfo`, `StrangerInfo`, `PublicProfileFields` and
`ProfilePrivilege` types describe these fields. Returned availability depends
on QQ and the account's access; requesting enrichment does not guarantee every
field is present.
@@ -0,0 +1,54 @@
const privilegeSchema = {
type: 'object',
properties: {
type: { type: 'integer', description: '业务类型' },
level: { type: 'integer', description: '业务等级' },
flag: { type: 'integer', description: '服务端业务标志' },
is_big: { type: 'integer', description: '服务端大图标标志' },
jump_url: { type: 'string', description: '业务跳转地址' },
icon_url: { type: 'string', description: '普通图标地址' },
deluxe_icon_url: { type: 'string', description: '高级图标地址,可与普通图标同时存在' },
},
};
export const publicProfileProperties = {
long_nick: { type: 'string', description: '个性签名' },
sex: { type: 'string', enum: ['male', 'female', 'unknown'], description: '性别' },
age: { type: 'integer', description: '年龄' },
level: { type: 'integer', description: 'QQ 等级' },
birthday_year: { type: 'integer', description: '生日年份,未公开时省略' },
birthday_month: { type: 'integer', description: '生日月份(1-12)' },
birthday_day: { type: 'integer', description: '生日日期(1-31)' },
phone_num: { type: 'string', description: '资料卡公开的电话号码' },
email: { type: 'string', description: '资料卡公开的邮箱' },
country: { type: 'string', description: '国家' },
province: { type: 'string', description: '省份' },
city: { type: 'string', description: '城市' },
college: { type: 'string', description: '学校' },
is_qq_vip: { type: 'boolean', description: '普通会员状态' },
is_vip: { type: 'boolean', description: '超级会员状态,兼容已有接口' },
is_years_vip: { type: 'boolean', description: '年费会员状态' },
vip_level: { type: 'integer', description: '会员等级' },
privilege_icons: {
type: 'object',
description: '业务图标;未返回该资料时省略整个字段,空列表表示没有该类图标',
properties: {
jump_url: { type: 'string', description: '业务列表跳转地址' },
open: { type: 'array', description: '已开通业务', items: privilegeSchema },
closed: { type: 'array', description: '未开通业务', items: privilegeSchema },
},
required: ['open', 'closed'],
},
};
export const friendResultSchema = {
type: 'object',
properties: {
user_id: { type: 'integer', description: '好友 QQ 号' },
nickname: { type: 'string', description: '好友昵称' },
remark: { type: 'string', description: '好友备注' },
category_id: { type: 'integer', description: '好友分组编号,有来源时返回' },
...publicProfileProperties,
},
required: ['user_id', 'nickname', 'remark'],
};
+18 -18
View File
@@ -21,6 +21,8 @@ import {
} from '../types';
import { defineAction, groupAction, groupUserAction, f, type Field } from '../action-kit';
import { groupInfoReturnsSchema } from './group-info';
import { friendResultSchema } from './contact-profile-schema';
import { formatFriend } from '../modules/contact-profile';
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
import {
messageIdSchema,
@@ -2647,7 +2649,8 @@ export const actions = [
],
summary: '获取分组好友列表',
readOnly: true,
returns: '好友分组数组;每组包含 categoryId、categoryName、categoryMbCount 和 buddyList。',
returns:
'好友分组数组;buddyList 与 get_friend_list 使用相同资料字段。默认只使用列表回包,with_profile=true 主动补查,失败会报错;未返回的资料省略。',
returnsSchema: {
type: 'array',
description: '带分组的好友列表',
@@ -2660,33 +2663,30 @@ export const actions = [
buddyList: {
type: 'array',
description: '该分组内的好友',
items: {
type: 'object',
properties: {
user_id: { type: 'integer', description: 'QQ 号' },
nickname: { type: 'string', description: '昵称' },
remark: { type: 'string', description: '好友备注' },
},
required: ['user_id', 'nickname', 'remark'],
},
items: friendResultSchema,
},
},
required: ['categoryId', 'categoryName', 'categoryMbCount', 'buddyList'],
},
},
params: {},
run: async (_p, ctx) => {
const categories = await ctx.bridge.apis.contacts.fetchFriendCategories();
params: {
with_profile: f
.bool()
.default(false)
.describe('主动补查好友公开资料,按账号缓存五分钟;大列表可能耗时较长'),
},
run: async (p, ctx) => {
const categories = await ctx.bridge.apis.contacts.fetchFriendCategories({
withProfile: p.with_profile,
});
return okResponse(
categories.map((category) => ({
categoryId: category.categoryId,
categoryName: category.categoryName,
categoryMbCount: category.memberCount,
buddyList: category.friends.map((friend) => ({
user_id: friend.uin,
nickname: friend.nickname,
remark: friend.remark,
})),
buddyList: category.friends.map((friend) =>
formatFriend(friend, category.categoryId),
),
})),
);
},
+18 -14
View File
@@ -1,5 +1,6 @@
import { defineAction, f } from '../action-kit';
import { okResponse } from '../types';
import { failedResponse, okResponse, RETCODE } from '../types';
import { friendResultSchema, publicProfileProperties } from './contact-profile-schema';
export const actions = [
defineAction({
@@ -12,23 +13,25 @@ export const actions = [
],
summary: '获取好友列表',
readOnly: true,
returns: '好友列表数组,每项含 QQ 号、昵称与备注。',
returns:
'好友列表,包含账号、昵称、备注及回包已有的公开资料;with_profile=true 时主动补查,失败会报错。未返回的资料省略,零、空字符串和 false 保留。',
returnsSchema: {
type: 'array',
items: {
type: 'object',
properties: {
user_id: { type: 'integer', description: '好友 QQ 号' },
nickname: { type: 'string', description: '好友昵称' },
remark: { type: 'string', description: '好友备注' },
},
required: ['user_id', 'nickname', 'remark'],
},
items: friendResultSchema,
},
params: {},
run: async (_p, ctx) => {
params: {
with_profile: f
.bool()
.default(false)
.describe('主动补查好友公开资料,按账号缓存五分钟;大列表可能耗时较长'),
},
run: async (p, ctx) => {
if (ctx.getFriendList) {
return okResponse(await ctx.getFriendList());
return okResponse(await ctx.getFriendList(p.with_profile));
}
if (p.with_profile) {
return failedResponse(RETCODE.ACTION_FAILED, 'friend profile provider unavailable');
}
return okResponse([]);
@@ -53,6 +56,7 @@ export const actions = [
returnsSchema: {
type: 'object',
properties: {
...publicProfileProperties,
user_id: { type: 'integer', description: 'QQ 号' },
uid: { type: 'string', description: '账号唯一标识(仅查到资料时返回)' },
qid: { type: 'string', description: '自定义账号标识(仅查到资料时返回)' },
+1 -1
View File
@@ -76,7 +76,7 @@ export interface ApiActionContext {
deleteMessage: (messageId: number, meta: MessageMeta) => Promise<void>;
canSendImage: () => boolean;
canSendRecord: () => boolean;
getFriendList: () => Promise<JsonObject[]>;
getFriendList: (withProfile?: boolean) => Promise<JsonObject[]>;
getGroupList: (noCache?: boolean) => Promise<JsonObject[]>;
getGroupInfo: (groupId: number, noCache?: boolean) => Promise<JsonObject | null>;
getGroupMemberList: (groupId: number, noCache?: boolean) => Promise<JsonObject[]>;
+1 -1
View File
@@ -100,7 +100,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
sendGroupMessage: (groupId, message, autoEscape) =>
sendGroupMessage(ref, groupId, message, autoEscape),
deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta),
getFriendList: () => getFriendList(bridge),
getFriendList: (withProfile) => getFriendList(bridge, withProfile),
getGroupList: (noCache) => getGroupList(bridge, noCache),
getGroupInfo: (groupId, noCache) => getGroupInfo(bridge, groupId, noCache),
getGroupMemberList: (groupId, noCache) => getGroupMemberList(bridge, groupId, noCache),
+28 -13
View File
@@ -15,6 +15,7 @@ import {
import type { QidianCorpInfo } from '@snowluma/protocol/services/qidian/fetch-corp-info';
import type { OneBotInstanceContext } from '../instance-context';
import type { JsonObject } from '../types';
import { formatFriend, formatPublicProfile } from './contact-profile';
const REQUESTER_PROFILE_CONCURRENCY = 4;
const log = createLogger('OneBot.Contacts');
@@ -50,21 +51,28 @@ async function fetchSingleGroupMembers(
}
}
function toFriendRow(friend: { uin: number; nickname: string; remark: string }): JsonObject {
return {
user_id: friend.uin,
nickname: friend.nickname,
remark: friend.remark,
};
}
export async function getFriendList(bridge: BridgeInterface): Promise<JsonObject[]> {
export async function getFriendList(
bridge: BridgeInterface,
withProfile = false,
): Promise<JsonObject[]> {
let rows: JsonObject[];
try {
rows = (await bridge.apis.contacts.fetchFriendList()).map(toFriendRow);
} catch {
rows = bridge.identity.friends.map(toFriendRow);
rows = (await bridge.apis.contacts.fetchFriendList({ withProfile })).map((friend) =>
formatFriend(friend),
);
} catch (error) {
log.warn(
'friend list refresh failed: withProfile=%s error=%s',
withProfile,
error instanceof Error ? error.message : String(error),
);
if (withProfile) {
throw error;
}
rows = bridge.identity.friends.map((friend) => formatFriend(friend));
}
const occupied = new Set(rows.map((row) => Number(row.user_id)));
@@ -394,6 +402,8 @@ function formatStrangerInfo(p: UserProfileInfo, corp?: QidianCorpInfo | null): J
...(p.svipFlag !== undefined ? { is_vip: p.svipFlag } : {}),
...(p.yearVipFlag !== undefined ? { is_years_vip: p.yearVipFlag } : {}),
...(p.vipLevel !== undefined ? { vip_level: p.vipLevel } : {}),
...(p.vipFlag !== undefined ? { is_qq_vip: p.vipFlag } : {}),
...formatPublicProfile(p.profile),
status: p.status ?? 0,
extStatus: p.extStatus ?? 0,
ext_status: p.extStatus ?? 0,
@@ -446,7 +456,12 @@ export async function getStrangerInfo(
const p = await bridge.apis.contacts.fetchUserProfile(userId);
const corp = await strangerCorpInfo(bridge, p);
return formatStrangerInfo(p, corp);
} catch {
} catch (error) {
log.warn(
'user profile refresh failed, checking cached profile: user=%d error=%s',
userId,
error instanceof Error ? error.message : String(error),
);
const p = bridge.identity.findUserProfile(userId);
if (p) {
@@ -0,0 +1,64 @@
import type { FriendInfo, ProfilePrivilege, PublicProfileFields } from '@snowluma/protocol/qq-info';
import type { JsonObject } from '../types';
function formatPrivilege(value: ProfilePrivilege): JsonObject {
return {
...(value.type !== undefined ? { type: value.type } : {}),
...(value.level !== undefined ? { level: value.level } : {}),
...(value.flag !== undefined ? { flag: value.flag } : {}),
...(value.isBig !== undefined ? { is_big: value.isBig } : {}),
...(value.jumpUrl !== undefined ? { jump_url: value.jumpUrl } : {}),
...(value.iconUrl !== undefined ? { icon_url: value.iconUrl } : {}),
...(value.deluxeIconUrl !== undefined ? { deluxe_icon_url: value.deluxeIconUrl } : {}),
};
}
export function formatPublicProfile(profile: PublicProfileFields = {}): JsonObject {
const result: JsonObject = {};
for (const [source, target] of [
['sign', 'long_nick'],
['sex', 'sex'],
['age', 'age'],
['level', 'level'],
['birthdayYear', 'birthday_year'],
['birthdayMonth', 'birthday_month'],
['birthdayDay', 'birthday_day'],
['phoneNum', 'phone_num'],
['email', 'email'],
['country', 'country'],
['province', 'province'],
['city', 'city'],
['college', 'college'],
['vipFlag', 'is_qq_vip'],
['svipFlag', 'is_vip'],
['yearVipFlag', 'is_years_vip'],
['vipLevel', 'vip_level'],
] as const) {
if (profile[source] !== undefined) {
result[target] = profile[source];
}
}
if (profile.privilegeIcons !== undefined) {
result.privilege_icons = {
...(profile.privilegeIcons.jumpUrl !== undefined
? { jump_url: profile.privilegeIcons.jumpUrl }
: {}),
open: profile.privilegeIcons.open.map(formatPrivilege),
closed: profile.privilegeIcons.closed.map(formatPrivilege),
};
}
return result;
}
export function formatFriend(friend: FriendInfo, categoryId = friend.categoryId): JsonObject {
return {
user_id: friend.uin,
nickname: friend.nickname,
remark: friend.remark,
...(categoryId !== undefined ? { category_id: categoryId } : {}),
...formatPublicProfile(friend.profile),
};
}
@@ -180,6 +180,69 @@ function makeGroupRequest(overrides: Partial<GroupRequestInfo> = {}): GroupReque
};
}
describe('public contact profile output', () => {
const profile = {
sign: '',
age: 0,
level: 0,
sex: 'unknown' as const,
vipFlag: false,
svipFlag: false,
country: 'CN',
city: 'City',
email: '',
birthdayMonth: 2,
birthdayDay: 29,
privilegeIcons: {
open: [{ type: 1, iconUrl: 'normal', deluxeIconUrl: 'deluxe' }],
closed: [],
},
};
const expected = {
long_nick: '',
age: 0,
level: 0,
sex: 'unknown',
is_qq_vip: false,
is_vip: false,
country: 'CN',
city: 'City',
email: '',
birthday_month: 2,
birthday_day: 29,
privilege_icons: {
open: [{ type: 1, icon_url: 'normal', deluxe_icon_url: 'deluxe' }],
closed: [],
},
};
it('returns the same public fields for friends and stranger profiles without invented values', async () => {
const fetchFriendList = vi.fn(async () => [
{ ...makeFriend(123, 'Name'), categoryId: 0, profile },
]);
const bridge = fakeBridge({
fetchFriendList,
fetchUserProfile: vi.fn(async () => ({ ...makeProfile(123, 'Name'), profile })),
});
const friends = await getFriendList(bridge, true);
expect(friends[0]).toMatchObject({ user_id: 123, category_id: 0, ...expected });
expect(friends[0]).not.toHaveProperty('phone_num');
expect(friends[0]).not.toHaveProperty('birthday_year');
expect(fetchFriendList).toHaveBeenCalledWith({ withProfile: true });
expect(await getStrangerInfo(bridge, 123)).toMatchObject(expected);
});
it('does not mask explicit enrichment failures with cached friends', async () => {
const bridge = fakeBridge({
fetchFriendList: vi.fn().mockRejectedValue(new Error('profile failed')),
identity: fakeIdentity({ friends: [makeFriend(123, 'Cached')] }),
});
await expect(getFriendList(bridge, true)).rejects.toThrow('profile failed');
// The legacy ordinary-list cache behavior remains available.
expect((await getFriendList(bridge))[0]?.nickname).toBe('Cached');
});
});
// ─── Tests ───
describe('onebot/contact-actions / getLoginInfo', () => {
+51 -1
View File
@@ -828,6 +828,56 @@ describe('extended-actions / get_essence_msg_list', () => {
});
describe('extended-actions / get_friends_with_category', () => {
it('forwards explicit enrichment and uses the same public field names', async () => {
const fetchFriendCategories = vi.fn(async () => [
{
categoryId: 0,
categoryName: 'Friends',
memberCount: 1,
sortId: 0,
friends: [
{
uin: 10001,
uid: 'u1',
nickname: 'Name',
remark: '',
profile: {
sign: '',
age: 0,
vipFlag: false,
privilegeIcons: { open: [], closed: [] },
},
},
],
},
]);
const handler = makeHandler(fakeCtx(fakeBridge({ fetchFriendCategories })));
expect(
await handler.handle('get_friends_with_category', { with_profile: true }),
).toMatchObject({
status: 'ok',
data: [
{
buddyList: [
{
user_id: 10001,
category_id: 0,
long_nick: '',
age: 0,
is_qq_vip: false,
privilege_icons: { open: [], closed: [] },
},
],
},
],
});
expect(fetchFriendCategories).toHaveBeenCalledWith({ withProfile: true });
expect(
await handler.handle('get_friends_with_category', { with_profile: 'invalid' }),
).toMatchObject({ status: 'failed' });
expect(fetchFriendCategories).toHaveBeenCalledOnce();
});
it('returns the exact categorized friend contract', async () => {
const fetchFriendCategories = vi.fn(async () => [
{
@@ -848,7 +898,7 @@ describe('extended-actions / get_friends_with_category', () => {
categoryId: 7,
categoryName: 'Work',
categoryMbCount: 1,
buddyList: [{ user_id: 10001, nickname: 'Alice', remark: 'A' }],
buddyList: [{ user_id: 10001, nickname: 'Alice', remark: 'A', category_id: 7 }],
},
]);
});
+18 -1
View File
@@ -1,9 +1,26 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
import type { ApiActionContext } from '../src/api-handler';
import { actions } from '../src/actions/friend';
const getStrangerInfo = actions.find((action) => action.names[0] === 'get_stranger_info');
describe('get_friend_list profile option', () => {
it('defaults off, validates the option and forwards explicit enrichment', async () => {
const action = actions.find((entry) => entry.names[0] === 'get_friend_list')!;
const getFriendList = vi.fn(async () => []);
const handler = action.toHandler({ getFriendList } as unknown as ApiActionContext);
await handler({});
expect(getFriendList).toHaveBeenLastCalledWith(false);
await handler({ with_profile: true });
expect(getFriendList).toHaveBeenLastCalledWith(true);
expect(await handler({ with_profile: 'invalid' })).toMatchObject({ status: 'failed' });
expect(getFriendList).toHaveBeenCalledTimes(2);
expect(
await action.toHandler({} as ApiActionContext)({ with_profile: true }),
).toMatchObject({ status: 'failed', wording: 'friend profile provider unavailable' });
});
});
if (!getStrangerInfo) {
throw new Error('get_stranger_info action missing');
}
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import { actionParams } from '../../sdk/tests/fixtures/action-contracts';
import { actions as extended } from '../src/actions/extended';
import { actions as friend } from '../src/actions/friend';
import { actions as albums } from '../src/actions/group-album';
import { actions as groupAdmin } from '../src/actions/group-admin';
import { actions as qzone } from '../src/actions/qzone';
@@ -9,6 +10,7 @@ import { actions as streamDownload } from '../src/actions/stream-download';
import { actions as streamFile } from '../src/actions/stream-file';
const actions = [
...friend,
...extended,
...albums,
...groupAdmin,