feat(onebot): add Qzone profile read and update actions (#586)

Add actions to read a space name and description and update the current account profile. Preserve omitted fields and support explicit empty values, with matching SDK types, MCP discovery, documentation, and tests.
This commit is contained in:
Qiao authored and GitHub committed 2026-10-25 19:48:46 +08:00
1 parent 5c9328206f
commit 4d55608b56
16 files changed
+862 -3

No files matched your search

+14
View File
@@ -4,16 +4,20 @@ import {
getQzoneFeeds,
getQzoneMsgDetail,
getQzoneMsgList,
getQzoneProfile,
publishQzoneMsg,
replyQzoneComment,
setQzoneBlack,
setQzoneLike,
setQzoneProfile,
updateQzoneMsgRight,
uploadQzoneImageFromSource,
type QzoneCommentResult,
type QzoneFeedsPage,
type QzoneMsgDetailResult,
type QzoneMsgListResult,
type QzoneProfile,
type QzoneProfileUpdate,
type QzonePublishResult,
type QzoneReplyTarget,
type QzoneUpdateRightResult,
@@ -30,6 +34,16 @@ import type { BridgeContext } from '../bridge-context';
export class QzoneApi {
constructor(private readonly ctx: BridgeContext) {}
async getProfile(targetUin?: number): Promise<QzoneProfile> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzoneProfile(cookieObject, this.ctx.identity.uin, targetUin?.toString());
}
async setProfile(profile: QzoneProfileUpdate): Promise<void> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
await setQzoneProfile(cookieObject, this.ctx.identity.uin, profile);
}
/**
* 获取说说列表。`targetUin` 省略时取机器人自己的空间。
* `pos` 为起始偏移,`num` 为本页数量(服务端上限约 20/页)。
+55
View File
@@ -20,6 +20,61 @@ describe('apis/qzone', () => {
return { bridge, getCookies, fetchSpy };
}
it.each([undefined, 20002])(
'getProfile reads owner %s with the current account credentials',
async (targetUin) => {
const { bridge, getCookies } = bridgeWithWeb();
const profile = { name: 'My space', description: 'Notes' };
const getProfile = vi.spyOn(qzoneWeb, 'getQzoneProfile').mockResolvedValue(profile);
expect(await new QzoneApi(bridge as never).getProfile(targetUin)).toEqual(profile);
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(getProfile).toHaveBeenCalledWith(
{ p_skey: 'PSK' },
'10001',
targetUin?.toString(),
);
},
);
it('getProfile propagates cookie and protocol failures', async () => {
const { bridge, getCookies } = bridgeWithWeb();
const api = new QzoneApi(bridge as never);
const getProfile = vi
.spyOn(qzoneWeb, 'getQzoneProfile')
.mockRejectedValue(new Error('denied'));
await expect(api.getProfile(20002)).rejects.toThrow('denied');
getCookies.mockRejectedValueOnce(new Error('cookie failure'));
await expect(api.getProfile()).rejects.toThrow('cookie failure');
expect(getProfile).toHaveBeenCalledTimes(1);
});
it.each([{ name: 'New name' }, { description: '' }, { name: '', description: 'New notes' }])(
'setProfile writes only the supplied fields to the current account (%j)',
async (profile) => {
const { bridge, getCookies } = bridgeWithWeb();
const setProfile = vi.spyOn(qzoneWeb, 'setQzoneProfile').mockResolvedValue();
await new QzoneApi(bridge as never).setProfile(profile);
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(setProfile).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', profile);
},
);
it('setProfile propagates cookie and protocol failures', async () => {
const { bridge, getCookies } = bridgeWithWeb();
const api = new QzoneApi(bridge as never);
const setProfile = vi
.spyOn(qzoneWeb, 'setQzoneProfile')
.mockRejectedValue(new Error('captcha required'));
await expect(api.setProfile({ name: 'New name' })).rejects.toThrow('captcha required');
getCookies.mockRejectedValueOnce(new Error('cookie failure'));
await expect(api.setProfile({ description: 'Notes' })).rejects.toThrow('cookie failure');
expect(setProfile).toHaveBeenCalledTimes(1);
});
it.each([undefined, 20002])(
'getMsgDetail uses current-account credentials for owner %s',
async (targetUin) => {
+129 -1
View File
@@ -11257,6 +11257,70 @@
},
"category": "空间"
},
{
"name": "get_qzone_profile",
"aliases": [],
"summary": "获取 QQ 空间名称和说明(默认当前账号)",
"returns": "空间名称和说明。",
"returnsSchema": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "空间名称"
},
"description": {
"type": "string",
"description": "空间说明"
}
},
"required": [
"name",
"description"
]
},
"examples": [
{
"summary": "获取当前账号的空间名称和说明",
"params": {}
},
{
"summary": "获取指定账号的空间名称和说明",
"params": {
"target_uin": 10001
},
"notes": "需要有该空间的访问权限。"
}
],
"readOnly": true,
"params": [
{
"name": "target_uin",
"type": "uint",
"required": false,
"role": "user_id",
"schema": {
"type": "integer",
"minimum": 1
},
"desc": "目标 QQ 号,省略则取机器人自己"
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"target_uin": {
"type": "integer",
"minimum": 1,
"description": "目标 QQ 号,省略则取机器人自己",
"x-role": "user_id"
}
},
"additionalProperties": true
},
"category": "空间"
},
{
"name": "get_recent_contact",
"aliases": [],
@@ -17420,6 +17484,70 @@
},
"category": "空间"
},
{
"name": "set_qzone_profile",
"aliases": [],
"summary": "修改当前账号的 QQ 空间名称或说明",
"returnsSchema": {
"type": "null",
"description": "成功时 data 为 null;失败另见响应的 status、retcode 和 wording"
},
"examples": [
{
"summary": "修改当前账号的空间名称和说明",
"params": {
"name": "我的空间",
"description": "记录日常"
},
"notes": "仅修改提供的字段;空字符串表示清空对应字段。"
},
{
"summary": "清空当前账号的空间说明",
"params": {
"description": ""
}
}
],
"readOnly": false,
"params": [
{
"name": "name",
"type": "string",
"required": false,
"schema": {
"type": "string"
},
"desc": "新的空间名称,空字符串表示清空,省略则保留"
},
{
"name": "description",
"type": "string",
"required": false,
"schema": {
"type": "string"
},
"desc": "新的空间说明,空字符串表示清空,省略则保留"
}
],
"invariants": [
"at least one of: name, description"
],
"inputSchema": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "新的空间名称,空字符串表示清空,省略则保留"
},
"description": {
"type": "string",
"description": "新的空间说明,空字符串表示清空,省略则保留"
}
},
"additionalProperties": true
},
"category": "空间"
},
{
"name": "set_restart",
"aliases": [],
@@ -18882,7 +19010,7 @@
},
{
"category": "空间",
"count": 10
"count": 12
},
{
"category": "系统表情",
+129 -1
View File
@@ -11260,6 +11260,70 @@ export const ACTIONS: CatalogAction[] = [
},
"category": "空间"
},
{
"name": "get_qzone_profile",
"aliases": [],
"summary": "获取 QQ 空间名称和说明(默认当前账号)",
"returns": "空间名称和说明。",
"returnsSchema": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "空间名称"
},
"description": {
"type": "string",
"description": "空间说明"
}
},
"required": [
"name",
"description"
]
},
"examples": [
{
"summary": "获取当前账号的空间名称和说明",
"params": {}
},
{
"summary": "获取指定账号的空间名称和说明",
"params": {
"target_uin": 10001
},
"notes": "需要有该空间的访问权限。"
}
],
"readOnly": true,
"params": [
{
"name": "target_uin",
"type": "uint",
"required": false,
"role": "user_id",
"schema": {
"type": "integer",
"minimum": 1
},
"desc": "目标 QQ 号,省略则取机器人自己"
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"target_uin": {
"type": "integer",
"minimum": 1,
"description": "目标 QQ 号,省略则取机器人自己",
"x-role": "user_id"
}
},
"additionalProperties": true
},
"category": "空间"
},
{
"name": "get_recent_contact",
"aliases": [],
@@ -17423,6 +17487,70 @@ export const ACTIONS: CatalogAction[] = [
},
"category": "空间"
},
{
"name": "set_qzone_profile",
"aliases": [],
"summary": "修改当前账号的 QQ 空间名称或说明",
"returnsSchema": {
"type": "null",
"description": "成功时 data 为 null;失败另见响应的 status、retcode 和 wording"
},
"examples": [
{
"summary": "修改当前账号的空间名称和说明",
"params": {
"name": "我的空间",
"description": "记录日常"
},
"notes": "仅修改提供的字段;空字符串表示清空对应字段。"
},
{
"summary": "清空当前账号的空间说明",
"params": {
"description": ""
}
}
],
"readOnly": false,
"params": [
{
"name": "name",
"type": "string",
"required": false,
"schema": {
"type": "string"
},
"desc": "新的空间名称,空字符串表示清空,省略则保留"
},
{
"name": "description",
"type": "string",
"required": false,
"schema": {
"type": "string"
},
"desc": "新的空间说明,空字符串表示清空,省略则保留"
}
],
"invariants": [
"at least one of: name, description"
],
"inputSchema": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "新的空间名称,空字符串表示清空,省略则保留"
},
"description": {
"type": "string",
"description": "新的空间说明,空字符串表示清空,省略则保留"
}
},
"additionalProperties": true
},
"category": "空间"
},
{
"name": "set_restart",
"aliases": [],
@@ -18886,7 +19014,7 @@ export const CATEGORIES: CatalogCategory[] = [
},
{
"category": "空间",
"count": 10
"count": 12
},
{
"category": "系统表情",
+63
View File
@@ -36,6 +36,69 @@ const qzoneCommentProperties = {
const qzoneCommentRequired = ['uin', 'name', 'time', 'content', 'comment_id'];
export const actions = [
defineAction({
name: 'get_qzone_profile',
examples: [
{
summary: '获取当前账号的空间名称和说明',
params: {},
},
{
summary: '获取指定账号的空间名称和说明',
params: { target_uin: 10001 },
notes: '需要有该空间的访问权限。',
},
],
readOnly: true,
summary: '获取 QQ 空间名称和说明(默认当前账号)',
returns: '空间名称和说明。',
returnsSchema: {
type: 'object',
properties: {
name: { type: 'string', description: '空间名称' },
description: { type: 'string', description: '空间说明' },
},
required: ['name', 'description'],
},
params: {
target_uin: f.userId().describe('目标 QQ 号,省略则取机器人自己').optional(),
},
run: async (p, ctx) => okResponse(await ctx.bridge.apis.qzone.getProfile(p.target_uin)),
}),
defineAction({
name: 'set_qzone_profile',
examples: [
{
summary: '修改当前账号的空间名称和说明',
params: { name: '我的空间', description: '记录日常' },
notes: '仅修改提供的字段;空字符串表示清空对应字段。',
},
{
summary: '清空当前账号的空间说明',
params: { description: '' },
},
],
readOnly: false,
summary: '修改当前账号的 QQ 空间名称或说明',
returnsSchema: {
type: 'null',
description: '成功时 data 为 null;失败另见响应的 status、retcode 和 wording',
},
params: {
name: f.string().describe('新的空间名称,空字符串表示清空,省略则保留').optional(),
description: f
.string()
.describe('新的空间说明,空字符串表示清空,省略则保留')
.optional(),
},
rules: (r) => [r.atLeastOneOf('name', 'description')],
run: async (p, ctx) => {
await ctx.bridge.apis.qzone.setProfile(p);
return okResponse(null);
},
}),
// get_qzone_msg_list — 获取 QQ 空间说说列表。无 go-cqhttp 标准,自定义命名。
// 默认取机器人自己的空间;传 target_uin 可查看指定账号(需有权限)。
// 复用 qzone.qq.com 的 cookie/g_tk 基建(与群相册同源),纯 web,无 trpc。
+104
View File
@@ -10,6 +10,110 @@ function makeHandler(qzone: Record<string, unknown>): ApiHandler {
}
describe('qzone actions', () => {
it.each([undefined, '20002'])(
'get_qzone_profile returns the requested profile and normalizes owner %s',
async (targetUin) => {
const profile = { name: 'My space', description: 'Notes' };
const getProfile = vi.fn().mockResolvedValue(profile);
const params = targetUin === undefined ? {} : { target_uin: targetUin };
expect(
await makeHandler({ getProfile }).handle('get_qzone_profile', params),
).toMatchObject({
status: 'ok',
retcode: 0,
data: profile,
});
expect(getProfile).toHaveBeenCalledWith(targetUin === undefined ? undefined : 20002);
},
);
it.each([0, 'bad'])(
'get_qzone_profile rejects invalid owners before fetching (%s)',
async (targetUin) => {
const getProfile = vi.fn();
expect(
await makeHandler({ getProfile }).handle('get_qzone_profile', {
target_uin: targetUin,
}),
).toMatchObject({
status: 'failed',
retcode: 1400,
});
expect(getProfile).not.toHaveBeenCalled();
},
);
it.each(['get_qzone_profile', 'set_qzone_profile'])(
'%s exposes upstream errors',
async (action) => {
const failure = new Error('qzone profile failed: code=-3000 need login');
const method = vi.fn().mockRejectedValue(failure);
const handler = makeHandler({ getProfile: method, setProfile: method });
const params = action === 'set_qzone_profile' ? { name: 'New name' } : {};
const response = await handler.handle(action, params);
expect(response).toMatchObject({ status: 'failed', retcode: 100 });
expect(response.wording).toContain('code=-3000 need login');
},
);
it.each([{ name: 'New name' }, { description: '' }, { name: '', description: 'New notes' }])(
'set_qzone_profile forwards supplied fields and preserves explicit empty values (%j)',
async (params) => {
const setProfile = vi.fn().mockResolvedValue(undefined);
expect(
await makeHandler({ setProfile }).handle('set_qzone_profile', params),
).toMatchObject({
status: 'ok',
retcode: 0,
data: null,
});
expect(setProfile).toHaveBeenCalledWith({
name: params.name,
description: params.description,
});
},
);
it.each([{}, { target_uin: 20002 }, { name: {} }, { description: [] }])(
'set_qzone_profile rejects missing or invalid updates before writing (%j)',
async (params) => {
const setProfile = vi.fn();
expect(
await makeHandler({ setProfile }).handle('set_qzone_profile', params),
).toMatchObject({
status: 'failed',
retcode: 1400,
});
expect(setProfile).not.toHaveBeenCalled();
},
);
it('set_qzone_profile cannot select a different account', async () => {
const setProfile = vi.fn().mockResolvedValue(undefined);
await makeHandler({ setProfile }).handle('set_qzone_profile', {
name: 'New name',
target_uin: 20002,
});
expect(setProfile).toHaveBeenCalledWith({ name: 'New name', description: undefined });
});
it('classifies profile reads and writes separately', () => {
expect(
actions.find((action) => action.names.includes('get_qzone_profile'))?.describe()
.readOnly,
).toBe(true);
expect(
actions.find((action) => action.names.includes('set_qzone_profile'))?.describe()
.readOnly,
).toBe(false);
});
it('get_qzone_feeds retains defaults and forwards optional continuation without stripping result fields', async () => {
const result = { feeds: [], has_more: true, next_cursor: 'next' };
const getFeeds = vi.fn().mockResolvedValue(result);
+87
View File
@@ -70,6 +70,17 @@ export interface QzoneMsgListResult {
msglist: QzoneEmotion[];
}
export interface QzoneProfile {
[key: string]: JsonValue;
name: string;
description: string;
}
export interface QzoneProfileUpdate {
name?: string;
description?: string;
}
export interface QzoneCommentReply {
[key: string]: JsonValue;
uin: number;
@@ -2228,3 +2239,79 @@ export async function updateQzoneMsgRight(
return { ugc_right: Number(data.ugc_right ?? right) };
}
interface RawQzoneProfileResponse {
code?: number;
subcode?: number;
message?: string;
data?: {
spacename?: string;
desc?: string;
};
}
export async function getQzoneProfile(
cookieObject: Record<string, string>,
selfUin: string,
targetUin = selfUin,
): Promise<QzoneProfile> {
const params = new URLSearchParams({
uin: targetUin,
vuin: selfUin,
fupdate: '1',
rd: String(Math.random()),
g_tk: getBknFromCookie(cookieObject),
});
const url = `https://h5.qzone.qq.com/proxy/domain/base.qzone.qq.com/cgi-bin/user/cgi_userinfo_get_all?${params}`;
const text = await RequestUtil.HttpGetText(url, 'GET', '', {
Cookie: cookieToString(cookieObject),
});
const response = parseQzoneJson<RawQzoneProfileResponse>(text);
if (response.code !== 0 || (response.subcode !== undefined && response.subcode !== 0)) {
throw new Error(
`qzone profile failed: code=${response.code} subcode=${response.subcode ?? 0} ${response.message ?? ''}`.trim(),
);
}
if (typeof response.data?.spacename !== 'string' || typeof response.data.desc !== 'string') {
throw new Error('invalid qzone profile response');
}
return { name: response.data.spacename, description: response.data.desc };
}
export async function setQzoneProfile(
cookieObject: Record<string, string>,
selfUin: string,
profile: QzoneProfileUpdate,
): Promise<void> {
const params = new URLSearchParams({ uin: selfUin, pageindex: '3', fupdate: '1' });
let bitmap = 0;
// The space settings form uses a field bitmap; omit the separate rich-text signature.
// https://qzonestyle.gtimg.cn/qzone/v6/setting/profile/scripts/profile.js
if (profile.name !== undefined) {
params.set('spacename', profile.name.replaceAll('\r', ''));
bitmap |= 2048;
}
if (profile.description !== undefined) {
params.set('desc', profile.description.replaceAll('\r', ''));
bitmap |= 4096;
}
params.set('mb', String(bitmap));
const url = `https://h5.qzone.qq.com/proxy/domain/w.qzone.qq.com/cgi-bin/user/cgi_apply_updateuserinfo_new?g_tk=${getBknFromCookie(cookieObject)}`;
const text = await RequestUtil.HttpGetText(url, 'POST', params.toString(), {
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded',
});
const response = parseQzoneJson<RawQzoneProfileResponse>(text);
if (response.code !== 0 || (response.subcode !== undefined && response.subcode !== 0)) {
throw new Error(
`qzone profile update failed: code=${response.code} subcode=${response.subcode ?? 0} ${response.message ?? ''}`.trim(),
);
}
}
@@ -0,0 +1,148 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { getQzoneProfile, setQzoneProfile } from '@snowluma/protocol/web/qzone';
import { RequestUtil, getBknFromCookie } from '@snowluma/protocol/web/request-util';
const cookies = { p_skey: 'PSK', skey: 'SK', uin: 'o10000' };
describe('qzone / getQzoneProfile', () => {
afterEach(() => vi.restoreAllMocks());
it('reads the selected space with the current account credentials and returns only its name and description', async () => {
const request = vi
.spyOn(RequestUtil, 'HttpGetText')
.mockResolvedValue(
'_Callback({"code":0,"data":{"spacename":"我的空间","desc":"生活 & 照片","nickname":"QQ昵称","signature":"private"}});',
);
await expect(getQzoneProfile(cookies, '10000', '20002')).resolves.toEqual({
name: '我的空间',
description: '生活 & 照片',
});
const [url, method, body, headers] = request.mock.calls[0]!;
const parsed = new URL(url);
expect(parsed.origin + parsed.pathname).toBe(
'https://h5.qzone.qq.com/proxy/domain/base.qzone.qq.com/cgi-bin/user/cgi_userinfo_get_all',
);
expect(Object.fromEntries(parsed.searchParams)).toMatchObject({
uin: '20002',
vuin: '10000',
fupdate: '1',
g_tk: getBknFromCookie(cookies),
});
expect(method).toBe('GET');
expect(body).toBe('');
expect(headers).toMatchObject({ Cookie: expect.stringContaining('p_skey=PSK') });
});
it('defaults to the current space and preserves empty fields', async () => {
const request = vi
.spyOn(RequestUtil, 'HttpGetText')
.mockResolvedValue('{"code":0,"data":{"spacename":"","desc":""}}');
await expect(getQzoneProfile(cookies, '10000')).resolves.toEqual({
name: '',
description: '',
});
expect(new URL(request.mock.calls[0]![0]).searchParams.get('uin')).toBe('10000');
});
it.each([
{},
{ code: 0 },
{ code: 0, data: { spacename: 'Name' } },
{ code: 0, data: { spacename: 42, desc: '' } },
])('rejects an incomplete profile instead of substituting empty values (%j)', async (data) => {
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue(JSON.stringify(data));
await expect(getQzoneProfile(cookies, '10000')).rejects.toThrow(/qzone profile/);
});
it('propagates login, access and transport failures', async () => {
vi.spyOn(RequestUtil, 'HttpGetText')
.mockResolvedValueOnce('{"code":-3000,"message":"need login"}')
.mockResolvedValueOnce('{"code":0,"subcode":-4001,"message":"denied"}')
.mockRejectedValueOnce(new Error('network down'));
await expect(getQzoneProfile(cookies, '10000')).rejects.toThrow('code=-3000');
await expect(getQzoneProfile(cookies, '10000')).rejects.toThrow('subcode=-4001');
await expect(getQzoneProfile(cookies, '10000')).rejects.toThrow('network down');
});
});
describe('qzone / setQzoneProfile', () => {
afterEach(() => vi.restoreAllMocks());
it.each([
{ profile: { name: '新名称' }, fields: { spacename: '新名称' }, bitmap: '2048' },
{ profile: { description: '' }, fields: { desc: '' }, bitmap: '4096' },
{
profile: { name: '名称 & +', description: '第一行\r\n第二行' },
fields: { spacename: '名称 & +', desc: '第一行\n第二行' },
bitmap: '6144',
},
])(
'updates only the supplied fields with bitmap $bitmap',
async ({ profile, fields, bitmap }) => {
const request = vi
.spyOn(RequestUtil, 'HttpGetText')
.mockResolvedValue('frameElement.callback({"code":0});');
await expect(setQzoneProfile(cookies, '10000', profile)).resolves.toBeUndefined();
expect(request).toHaveBeenCalledTimes(1);
const [url, method, body, headers] = request.mock.calls[0]!;
const parsed = new URL(url);
expect(parsed.origin + parsed.pathname).toBe(
'https://h5.qzone.qq.com/proxy/domain/w.qzone.qq.com/cgi-bin/user/cgi_apply_updateuserinfo_new',
);
expect(parsed.searchParams.get('g_tk')).toBe(getBknFromCookie(cookies));
expect(method).toBe('POST');
expect(Object.fromEntries(new URLSearchParams(body))).toEqual({
uin: '10000',
pageindex: '3',
fupdate: '1',
mb: bitmap,
...fields,
});
expect(headers).toMatchObject({
Cookie: expect.stringContaining('p_skey=PSK'),
'Content-Type': 'application/x-www-form-urlencoded',
});
},
);
it.each([-3001, -3002, -3000])(
'reports upstream rejection %s without retrying',
async (code) => {
const request = vi
.spyOn(RequestUtil, 'HttpGetText')
.mockResolvedValue(JSON.stringify({ code, message: 'verification required' }));
await expect(setQzoneProfile(cookies, '10000', { name: 'Name' })).rejects.toThrow(
`code=${code}`,
);
expect(request).toHaveBeenCalledTimes(1);
},
);
it('rejects a missing success code, non-zero subcode, HTML and network failures', async () => {
vi.spyOn(RequestUtil, 'HttpGetText')
.mockResolvedValueOnce('{}')
.mockResolvedValueOnce('{"code":0,"subcode":-1,"message":"denied"}')
.mockResolvedValueOnce('<html>login</html>')
.mockRejectedValueOnce(new Error('network down'));
await expect(setQzoneProfile(cookies, '10000', { name: 'Name' })).rejects.toThrow(
/qzone profile update/,
);
await expect(setQzoneProfile(cookies, '10000', { name: 'Name' })).rejects.toThrow(
'subcode=-1',
);
await expect(setQzoneProfile(cookies, '10000', { name: 'Name' })).rejects.toThrow(
'invalid response from qzone api',
);
await expect(setQzoneProfile(cookies, '10000', { name: 'Name' })).rejects.toThrow(
'network down',
);
});
});
+15
View File
@@ -144,6 +144,21 @@ const response = await bot.rawResponse('get_status');
`raw` 会在 SnowLuma 返回 `status: "failed"` 或非零 `retcode` 时抛出 `SnowLumaApiError`;`rawResponse` 会保留完整响应。
### 读取与修改空间资料
`get_qzone_profile` 返回 QQ 空间的名称和说明;这两个字段独立于 QQ 昵称和个性签名。
```ts
const profile = await bot.raw('get_qzone_profile', {}); // 当前账号
console.log(profile.name, profile.description);
await bot.raw('get_qzone_profile', { target_uin: '10002' });
await bot.raw('set_qzone_profile', { name: '我的空间' });
await bot.raw('set_qzone_profile', { description: '' }); // 清空说明
```
`set_qzone_profile` 只修改当前账号,至少提供 `name`、`description` 中的一项;省略字段保持原值,空字符串表示清空。成功返回 `null`,登录失效、访问受限或上游要求验证时会抛出 `SnowLumaApiError`。修改后可再次读取资料确认结果。
### 读取空间说说评论
`get_qzone_msg_detail` 是只读扩展动作,`raw` 提供参数和结果类型:
+2
View File
@@ -179,6 +179,7 @@ export const SNOWLUMA_ACTIONS = [
'get_qzone_feeds',
'get_qzone_msg_detail',
'get_qzone_msg_list',
'get_qzone_profile',
'get_rkey_server',
'get_share_link',
'like_qzone',
@@ -203,6 +204,7 @@ export const SNOWLUMA_ACTIONS = [
'set_group_robot_add_option',
'set_qzone_ban',
'set_qzone_msg_right',
'set_qzone_profile',
'share_group_ex',
'share_peer',
'test_download_stream',
+5
View File
@@ -97,6 +97,7 @@ import type {
GetQunAlbumListParams,
GetQzoneFeedsParams,
GetQzoneMsgListParams,
GetQzoneProfileParams,
GroupAlbumCommentParams,
GroupAlbumMediaLikeParams,
GroupAlbumMediaParams,
@@ -115,6 +116,7 @@ import type {
SetGroupRobotAddOptionParams,
SetQzoneBanParams,
SetQzoneMsgRightParams,
SetQzoneProfileParams,
SharePeerParams,
TestDownloadStreamParams,
UploadFileStreamParams,
@@ -184,6 +186,7 @@ import type {
QzoneFeedsResult,
QzoneMsgListResult,
QzonePublishResult,
QzoneProfileResult,
QzoneUpdateRightResult,
RkeyServerResult,
SendFlashMsgResult,
@@ -396,6 +399,7 @@ export interface SnowLumaActionMap {
get_qun_album_list: { params: GetQunAlbumListParams; data: QunAlbumListResult };
get_qzone_feeds: { params: GetQzoneFeedsParams; data: QzoneFeedsResult };
get_qzone_msg_list: { params: GetQzoneMsgListParams; data: QzoneMsgListResult };
get_qzone_profile: { params: GetQzoneProfileParams; data: QzoneProfileResult };
get_rkey_server: { params: JsonObject; data: RkeyServerResult };
get_share_link: { params: FilesetIdParams; data: string };
like_qzone: { params: LikeQzoneParams; data: EmptyData };
@@ -423,6 +427,7 @@ export interface SnowLumaActionMap {
set_group_robot_add_option: { params: SetGroupRobotAddOptionParams; data: EmptyData };
set_qzone_ban: { params: SetQzoneBanParams; data: EmptyData };
set_qzone_msg_right: { params: SetQzoneMsgRightParams; data: QzoneUpdateRightResult };
set_qzone_profile: { params: SetQzoneProfileParams; data: EmptyData };
share_group_ex: { params: ActionGroupIdParams; data: string };
share_peer: { params: SharePeerParams; data: ArkShareResult };
test_download_stream: { params: TestDownloadStreamParams; data: TestDownloadStreamResult };
+12
View File
@@ -577,6 +577,18 @@ export interface GetQzoneFeedsParams extends JsonObject {
cursor?: string;
}
export interface GetQzoneProfileParams extends JsonObject {
/** Defaults to the current account's space. */
target_uin?: ActionNumberInput;
}
/** Updates the current account's space; omitted fields are preserved. */
export type SetQzoneProfileParams = JsonObject &
(
| { name: ActionStringInput; description?: ActionStringInput }
| { name?: ActionStringInput; description: ActionStringInput }
);
export interface QzoneMsgIdParams extends JsonObject {
tid: ActionStringInput;
}
+5
View File
@@ -396,6 +396,11 @@ export interface QzoneMsgListResult extends JsonObject {
msglist: QzoneEmotion[];
}
export interface QzoneProfileResult extends JsonObject {
name: string;
description: string;
}
export interface QzoneFeed extends JsonObject {
uin: number;
nickname: string;
+6
View File
@@ -56,6 +56,7 @@ export const actionParams = {
get_qun_album_list: { group_id: '10001', attach_info: '' },
get_qzone_feeds: { page_num: '1', count: '10', cursor: 'cursor-from-previous-response' },
get_qzone_msg_list: { target_uin: '10002', pos: '0', num: '20' },
get_qzone_profile: { target_uin: '10002' },
get_rkey_server: {},
get_share_link: fileset,
like_qzone: qzoneLike,
@@ -99,6 +100,7 @@ export const actionParams = {
},
set_qzone_ban: { user_id: '10002', enable: false },
set_qzone_msg_right: { tid: 'post', ugc_right: '128', target_uins: ['10002'] },
set_qzone_profile: { name: 'Space', description: '' },
share_group_ex: { group_id: '10001' },
share_peer: peer,
test_download_stream: { error: false },
@@ -155,6 +157,7 @@ export type CoveredAction =
| 'get_qun_album_list'
| 'get_qzone_feeds'
| 'get_qzone_msg_list'
| 'get_qzone_profile'
| 'get_rkey_server'
| 'get_share_link'
| 'like_qzone'
@@ -176,6 +179,7 @@ export type CoveredAction =
| 'set_group_robot_add_option'
| 'set_qzone_ban'
| 'set_qzone_msg_right'
| 'set_qzone_profile'
| 'share_group_ex'
| 'share_peer'
| 'test_download_stream'
@@ -364,6 +368,7 @@ export const actionResults = {
},
],
},
get_qzone_profile: { name: 'Space', description: 'Description' },
get_rkey_server: { expired_time: 1, name: 'SnowLuma', private_rkey: 'fixture' },
get_share_link: 'https://example.com/share',
like_qzone: null,
@@ -385,6 +390,7 @@ export const actionResults = {
set_group_robot_add_option: null,
set_qzone_ban: null,
set_qzone_msg_right: { ugc_right: 128 },
set_qzone_profile: null,
share_group_ex: '{}',
share_peer: { arkMsg: '{}' },
test_download_stream: {
+22
View File
@@ -74,9 +74,11 @@ export const feedContent: string | null | undefined = feeds.feeds[0].content;
export const feedPhotos: string[] | null | undefined = feeds.feeds[0].images;
export const feedLikeCount: number | null | undefined = feeds.feeds[0].like_count;
export const feedCursor: string | null | undefined = feeds.next_cursor;
if (feedCursor) {
await http.raw('get_qzone_feeds', { cursor: feedCursor, count: 10 });
}
export const legacyFeedsResult: ActionResult<'get_qzone_feeds'> = {
feeds: [{ uin: 10002, nickname: 'User', time: 1, appid: 311, key: 'post', html: '' }],
has_more: false,
@@ -93,6 +95,26 @@ export const legacyQzoneComment: ActionParams<'comment_qzone'> = {
images: ['https://example.com/image.png'],
};
export const legacyQzoneResult: ActionResult<'comment_qzone'> = { comment_id: '' };
const qzoneProfile = await http.raw('get_qzone_profile', actionParams.get_qzone_profile);
export const qzoneName: string = qzoneProfile.name;
export const qzoneDescription: string = qzoneProfile.description;
export const ownQzoneProfile = http.raw('get_qzone_profile', {});
export const qzoneProfileUpdate: Promise<null> = ws.raw('set_qzone_profile', {
name: 'Space',
description: '',
});
export const qzoneNameOnly: ActionParams<'set_qzone_profile'> = { name: 'Space' };
export const qzoneDescriptionOnly: ActionParams<'set_qzone_profile'> = { description: '' };
export const qzoneScalarFields: ActionParams<'set_qzone_profile'> = {
name: 123,
description: false,
};
// @ts-expect-error a space profile patch requires at least one field
export const emptyQzoneProfilePatch: ActionParams<'set_qzone_profile'> = {};
export const invalidQzoneProfilePatch: ActionParams<'set_qzone_profile'> = {
// @ts-expect-error profile fields accept string, number or boolean primitives
description: [],
};
const speech = await ws.raw('get_record_text', { message_id: -42 });
const transcription: string = speech.text;
const flash = await http.raw('get_fileset_info', { fileset_id: 'files' });
+66 -1
View File
@@ -1,13 +1,78 @@
import { describe, expect, expectTypeOf, it, vi } from 'vitest';
import type { QzoneMsgDetailResult } from '../src';
import type { QzoneMsgDetailResult, QzoneProfileResult } from '../src';
import {
SnowLumaAbortError,
SnowLumaApiError,
SnowLumaAuthError,
SnowLumaHttpClient,
SnowLumaParseError,
} from '../src';
describe('SnowLumaHttpClient', () => {
it('reads typed space profiles for the current and an explicit account', async () => {
const data: QzoneProfileResult = { name: 'Space', description: 'Description' };
const fetchImpl = vi
.fn()
.mockImplementation(
async () => new Response(JSON.stringify({ status: 'ok', retcode: 0, data })),
);
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
const own = await client.raw('get_qzone_profile', {});
const other = await client.raw('get_qzone_profile', { target_uin: '10002' });
expectTypeOf(own).toEqualTypeOf<QzoneProfileResult>();
expect(other).toEqual(data);
expect(
fetchImpl.mock.calls.map((call) => JSON.parse((call[1] as RequestInit).body as string)),
).toEqual([
{ action: 'get_qzone_profile', params: {} },
{ action: 'get_qzone_profile', params: { target_uin: '10002' } },
]);
});
it('preserves omitted and empty space profile fields and returns null', async () => {
const fetchImpl = vi
.fn()
.mockImplementation(
async () => new Response(JSON.stringify({ status: 'ok', retcode: 0, data: null })),
);
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
const result = await client.raw('set_qzone_profile', { name: 'Space' });
expectTypeOf(result).toEqualTypeOf<null>();
expect(result).toBeNull();
await expect(client.raw('set_qzone_profile', { description: '' })).resolves.toBeNull();
expect(
fetchImpl.mock.calls.map((call) => JSON.parse((call[1] as RequestInit).body as string)),
).toEqual([
{ action: 'set_qzone_profile', params: { name: 'Space' } },
{ action: 'set_qzone_profile', params: { description: '' } },
]);
});
it('propagates space profile update failures', async () => {
const fetchImpl = vi.fn(
async () =>
new Response(
JSON.stringify({
status: 'failed',
retcode: 1200,
data: null,
wording: 'Qzone requires verification',
}),
),
);
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
const request = client.raw('set_qzone_profile', { name: 'Space' });
await expect(request).rejects.toMatchObject({
name: 'SnowLumaApiError',
retcode: 1200,
wording: 'Qzone requires verification',
});
await expect(request).rejects.toBeInstanceOf(SnowLumaApiError);
});
it('reads a typed Qzone comment page through raw', async () => {
const data: QzoneMsgDetailResult = {
tid: 'T1',