feat(qzone): send_qzone_msg — publish a text 说说 via web API

First Qzone WRITE path. publishQzoneMsg POSTs a form-urlencoded body to
taotao.qzone.qq.com's emotion_cgi_publish_v6 (proxied through h5.qzone),
g_tk in the query, on the bot's own space. Returns the server-assigned
tid (the handle for later delete/comment/like) + post time.

- Throws on transport failure, non-zero Qzone code (content rejected /
  rate-limited), or a success body with no tid — never reports a publish
  as succeeded without the feed id. Rejects empty content pre-flight.
- 带图 (image) publishing is a later slice (needs the upload CGI first).
- Action carries a风控/限流 caveat: publishing is an active action and
  high frequency is rate-limited by Qzone, same as sending messages.

- core: QzoneApi.publish; onebot: send_qzone_msg action; regen catalog.
- tests: form-body/url/headers lock, empty-content preflight, non-zero
  code throw, missing-tid throw, and bridge self-space threading.
This commit is contained in:
DrSmoothl committed 2026-06-20 01:40:06 +08:00
1 parent b00f5ab759
commit 9f2eb37232
6 files changed
+204 -2

No files matched your search

+8
View File
@@ -1,8 +1,10 @@
import {
getQzoneFeeds,
getQzoneMsgList,
publishQzoneMsg,
type QzoneFeedsResult,
type QzoneMsgListResult,
type QzonePublishResult,
} from '@snowluma/protocol/web/qzone';
import type { BridgeContext } from '../bridge-context';
@@ -33,4 +35,10 @@ export class QzoneApi {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return getQzoneFeeds(cookieObject, this.ctx.identity.uin, pageNum, count);
}
/** 发表一条纯文字说说,返回新说说的 tid。始终发到机器人自己的空间。 */
async publish(content: string): Promise<QzonePublishResult> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content);
}
}
+10
View File
@@ -48,4 +48,14 @@ describe('apis/qzone', () => {
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(feedsSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 3, 20);
});
it('publish posts to the bot\'s own space with the given content', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T', time: 1 });
const out = await new QzoneApi(bridge as never).publish('hello');
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello');
expect(out).toEqual({ tid: 'T', time: 1 });
});
});
+35 -1
View File
@@ -4573,6 +4573,40 @@ export const ACTIONS: CatalogAction[] = [
},
"category": "消息"
},
{
"name": "send_qzone_msg",
"aliases": [],
"summary": "发表一条纯文字说说(QQ 空间)",
"readOnly": false,
"params": [
{
"name": "content",
"type": "string",
"required": true,
"schema": {
"type": "string",
"minLength": 1
},
"desc": "说说正文"
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"content": {
"type": "string",
"minLength": 1,
"description": "说说正文"
}
},
"required": [
"content"
],
"additionalProperties": true
},
"category": "空间"
},
{
"name": "set_diy_online_status",
"aliases": [],
@@ -6693,6 +6727,6 @@ export const CATEGORIES: CatalogCategory[] = [
},
{
"category": "空间",
"count": 2
"count": 3
}
];
+20
View File
@@ -47,6 +47,26 @@ export const actions = [
}
},
}),
// send_qzone_msg — 发表一条纯文字说说。写操作,发到机器人自己的空间。
// 返回新说说的 tid(供后续 delete/comment/like 使用)。
// 注意:发说说为主动行为,高频会被 Qzone 风控,调用方需自行限流。
defineAction({
name: 'send_qzone_msg',
summary: '发表一条纯文字说说(QQ 空间)',
params: {
content: f.string({ allowEmpty: false }).describe('说说正文'),
},
run: async (p, ctx) => {
try {
const res = await ctx.bridge.apis.qzone.publish(p.content);
return okResponse(res as unknown as JsonValue);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to publish qzone msg';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
},
}),
];
export function register(h: ApiHandler, ctx: ApiActionContext): void {
+87
View File
@@ -299,3 +299,90 @@ export async function getQzoneFeeds(
return mapFeeds(data);
}
// ─────────────── 发说说 (publish emotion) — emotion_cgi_publish_v6 ───────────────
// First write path. Text-only here; 带图 (image) publishing layers an
// upload step on top in a later slice. Same cookie/g_tk plumbing + proxy
// gateway + tolerant parse as the read paths. WRITE OP — callers should
// rate-limit (publishing is an active action and Qzone风控s high frequency,
// same as sending messages).
interface RawPublishResponse {
code?: number;
subcode?: number;
message?: string;
/** Published feed id on success. */
tid?: string;
/** Post timestamp (unix seconds) on success. */
now?: number;
}
/** Result of publishing a 说说. */
export interface QzonePublishResult {
[key: string]: JsonValue;
/** The new feed's id — the handle for a later delete/comment/like. */
tid: string;
/** Unix seconds the 说说 was published. */
time: number;
}
/**
* Publish a text-only 说说 via taotao.qzone.qq.com's emotion_cgi_publish_v6
* CGI (proxied through h5.qzone.qq.com). POSTs a form-urlencoded body with
* `g_tk` in the query, on the bot's own space (`hostUin`).
*
* Errors PROPAGATE: a transport failure, a non-zero Qzone `code` (its error
* envelope, e.g. content rejected / rate-limited), or a success body that
* carries no `tid` all throw — we never report a publish as succeeded
* without the server-assigned feed id.
*/
export async function publishQzoneMsg(
cookieObject: Record<string, string>,
hostUin: string,
content: string,
): Promise<QzonePublishResult> {
if (!cookieObject || typeof cookieObject !== 'object') {
throw new Error('cookieObject is required');
}
if (!content) {
throw new Error('content is required');
}
const bkn = getBknFromCookie(cookieObject);
const url = `https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_publish_v6?g_tk=${bkn}`;
const body = new URLSearchParams({
syn_tweet_verson: '1',
paramstr: '1',
pic_template: '',
richtype: '',
richval: '',
special_url: '',
subrichtype: '',
con: content,
feedversion: '1',
ver: '1',
ugc_right: '1',
to_sign: '0',
hostuin: hostUin,
code_version: '1',
format: 'json',
qzreferrer: `https://user.qzone.qq.com/${hostUin}`,
}).toString();
const text = await RequestUtil.HttpGetText(url, 'POST', body, {
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded',
});
const data = parseQzoneJson<RawPublishResponse>(text);
if (typeof data.code === 'number' && data.code !== 0) {
log.warn('publishQzoneMsg: non-zero code (uin=%s) code=%d msg=%s', hostUin, data.code, data.message);
throw new Error(`qzone publish failed: code=${data.code} ${data.message ?? ''}`.trim());
}
if (!data.tid) {
log.warn('publishQzoneMsg: no tid in response (uin=%s) — publish likely rejected', hostUin);
throw new Error('发表说说失败:响应缺少 tid');
}
return { tid: String(data.tid), time: Number(data.now ?? 0) };
}
+44 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
import { getQzoneFeeds, getQzoneMsgList, mapFeeds, mapMsgList, parseQzoneJson } from '@snowluma/protocol/web/qzone';
import { getQzoneFeeds, getQzoneMsgList, mapFeeds, mapMsgList, parseQzoneJson, publishQzoneMsg } from '@snowluma/protocol/web/qzone';
import { RequestUtil } from '@snowluma/protocol/web/request-util';
// The 说说 list comes from taotao.qzone.qq.com's emotion_cgi_msglist_v6 CGI,
@@ -189,3 +189,46 @@ describe('qzone / getQzoneFeeds (HTTP layer)', () => {
await expect(getQzoneFeeds(cookies, '10000')).rejects.toThrow('无法获取空间好友动态');
});
});
describe('qzone / publishQzoneMsg (HTTP layer)', () => {
afterEach(() => vi.restoreAllMocks());
it('POSTs a form-urlencoded body to the proxied publish CGI and returns tid/time', async () => {
const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0,"tid":"NEWTID","now":1700000000}');
const out = await publishQzoneMsg(cookies, '10000', 'hello 世界');
expect(out).toEqual({ tid: 'NEWTID', time: 1700000000 });
const [url, method, body, headers] = spy.mock.calls[0]!;
expect(method).toBe('POST');
expect(url).toBe(
`https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_publish_v6?g_tk=${expectedGtk}`,
);
const h = headers as Record<string, string>;
expect(h['Content-Type']).toBe('application/x-www-form-urlencoded');
expect(h.Cookie).toContain('p_skey=PSK');
// form body carries the content (urlencoded) and the host uin
const form = new URLSearchParams(body as string);
expect(form.get('con')).toBe('hello 世界');
expect(form.get('hostuin')).toBe('10000');
expect(form.get('format')).toBe('json');
expect(form.get('qzreferrer')).toBe('https://user.qzone.qq.com/10000');
});
it('rejects empty content before any request', async () => {
const spy = vi.spyOn(RequestUtil, 'HttpGetText');
await expect(publishQzoneMsg(cookies, '10000', '')).rejects.toThrow('content is required');
expect(spy).not.toHaveBeenCalled();
});
it('throws on a non-zero qzone code (rejected/rate-limited)', async () => {
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":-10000,"message":"too frequent"}');
await expect(publishQzoneMsg(cookies, '10000', 'hi')).rejects.toThrow('code=-10000');
});
it('throws when the success body carries no tid', async () => {
vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0,"now":1700000000}');
await expect(publishQzoneMsg(cookies, '10000', 'hi')).rejects.toThrow('缺少 tid');
});
});