feat(group-notice): support advanced announcement controls
Route regular and new-member announcements through their correct web endpoints. Validate option conflicts, preserve existing defaults, merge returned notice collections, and surface transport and upload failures.
This commit is contained in:
3 files changed
+335
-138
No files matched your search
@@ -6,10 +6,15 @@ import { getHonorListWebAPI, WebHonorType, type WebHonorItem } from '@snowluma/p
|
|||||||
import { getDaySignedListWebAPI, type SignedListMember } from '@snowluma/protocol/web/group-signin';
|
import { getDaySignedListWebAPI, type SignedListMember } from '@snowluma/protocol/web/group-signin';
|
||||||
import {
|
import {
|
||||||
deleteGroupNotice as deleteGroupNoticeHttp,
|
deleteGroupNotice as deleteGroupNoticeHttp,
|
||||||
|
GROUP_NOTICE_TYPE_NEW_MEMBERS,
|
||||||
|
GROUP_NOTICE_TYPE_NORMAL,
|
||||||
getGroupNoticeWebAPI,
|
getGroupNoticeWebAPI,
|
||||||
setGroupNoticeWebAPI,
|
setGroupNoticeWebAPI,
|
||||||
uploadGroupNoticeImage,
|
uploadGroupNoticeImage,
|
||||||
type SetNoticeRetSuccess,
|
type SetNoticeRetSuccess,
|
||||||
|
type WebApiGroupNoticeCollection,
|
||||||
|
type WebApiGroupNoticeFeed,
|
||||||
|
type WebApiGroupNoticeRet,
|
||||||
} from '@snowluma/protocol/web/group-notice';
|
} from '@snowluma/protocol/web/group-notice';
|
||||||
import { RequestUtil } from '@snowluma/protocol/web/request-util';
|
import { RequestUtil } from '@snowluma/protocol/web/request-util';
|
||||||
import type { Bridge } from '../bridge';
|
import type { Bridge } from '../bridge';
|
||||||
@@ -42,6 +47,113 @@ export interface WebNoticeInfo {
|
|||||||
};
|
};
|
||||||
settings: import('@snowluma/common/json').JsonValue;
|
settings: import('@snowluma/common/json').JsonValue;
|
||||||
read_num: number;
|
read_num: number;
|
||||||
|
/** Server response type. Regular notices are commonly returned as 6. */
|
||||||
|
type: number;
|
||||||
|
pinned: number;
|
||||||
|
send_to_new_members: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SendNoticeOptions {
|
||||||
|
image?: string;
|
||||||
|
pinned?: number;
|
||||||
|
type?: number;
|
||||||
|
sendToNewMembers?: boolean;
|
||||||
|
isShowEditCard?: number;
|
||||||
|
tipWindowType?: number;
|
||||||
|
confirmRequired?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function finiteNumber(value: unknown, field: string): number {
|
||||||
|
const parsed = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : Number.NaN;
|
||||||
|
if (!Number.isFinite(parsed)) {
|
||||||
|
throw new Error(`invalid group notice response: ${field} must be a finite number`);
|
||||||
|
}
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
function collectionValues(
|
||||||
|
collection: WebApiGroupNoticeCollection | undefined,
|
||||||
|
field: 'feeds' | 'inst',
|
||||||
|
): WebApiGroupNoticeFeed[] {
|
||||||
|
if (collection === undefined) return [];
|
||||||
|
if (Array.isArray(collection)) return collection;
|
||||||
|
if (collection === null || typeof collection !== 'object') {
|
||||||
|
throw new Error(`invalid group notice response: ${field} must be an array or object`);
|
||||||
|
}
|
||||||
|
return Object.values(collection);
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapGroupNoticeFeed(feed: WebApiGroupNoticeFeed, sendToNewMembers: boolean): WebNoticeInfo {
|
||||||
|
if (!feed || typeof feed !== 'object') {
|
||||||
|
throw new Error('invalid group notice response: feed must be an object');
|
||||||
|
}
|
||||||
|
if (typeof feed.fid !== 'string' || feed.fid.length === 0) {
|
||||||
|
throw new Error('invalid group notice response: feed.fid must be a non-empty string');
|
||||||
|
}
|
||||||
|
if (!feed.msg || typeof feed.msg !== 'object' || typeof feed.msg.text !== 'string') {
|
||||||
|
throw new Error(`invalid group notice response: feed ${feed.fid} has no message text`);
|
||||||
|
}
|
||||||
|
if (feed.settings === undefined) {
|
||||||
|
throw new Error(`invalid group notice response: feed ${feed.fid} has no settings`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const image = (feed.msg.pics ?? []).map((pic, index) => {
|
||||||
|
if (!pic || typeof pic !== 'object' || typeof pic.id !== 'string') {
|
||||||
|
throw new Error(`invalid group notice response: feed ${feed.fid} image ${index} is malformed`);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
id: pic.id,
|
||||||
|
height: finiteNumber(pic.h, `feed ${feed.fid} image ${index}.h`),
|
||||||
|
width: finiteNumber(pic.w, `feed ${feed.fid} image ${index}.w`),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const responseType = feed.type === undefined
|
||||||
|
? sendToNewMembers ? GROUP_NOTICE_TYPE_NEW_MEMBERS : GROUP_NOTICE_TYPE_NORMAL
|
||||||
|
: finiteNumber(feed.type, `feed ${feed.fid}.type`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
notice_id: feed.fid,
|
||||||
|
sender_id: finiteNumber(feed.u, `feed ${feed.fid}.u`),
|
||||||
|
publish_time: finiteNumber(feed.pubt, `feed ${feed.fid}.pubt`),
|
||||||
|
message: {
|
||||||
|
text: feed.msg.text,
|
||||||
|
image,
|
||||||
|
images: image,
|
||||||
|
},
|
||||||
|
settings: feed.settings,
|
||||||
|
read_num: finiteNumber(feed.read_num, `feed ${feed.fid}.read_num`),
|
||||||
|
type: responseType,
|
||||||
|
pinned: feed.pinned === undefined ? 0 : finiteNumber(feed.pinned, `feed ${feed.fid}.pinned`),
|
||||||
|
send_to_new_members: sendToNewMembers || responseType === GROUP_NOTICE_TYPE_NEW_MEMBERS,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Merge QQ's regular (`feeds`) and new-member (`inst`) announcement lists. */
|
||||||
|
export function mapGroupNoticeResponse(ret: WebApiGroupNoticeRet): WebNoticeInfo[] {
|
||||||
|
if (ret.ec !== 0) {
|
||||||
|
throw new Error(`获取公告失败: ec=${ret.ec}, em=${ret.em ?? 'missing'}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const notices: WebNoticeInfo[] = [];
|
||||||
|
const indexByNoticeId = new Map<string, number>();
|
||||||
|
const append = (collection: WebApiGroupNoticeCollection | undefined, sendToNewMembers: boolean, field: 'feeds' | 'inst') => {
|
||||||
|
for (const feed of collectionValues(collection, field)) {
|
||||||
|
const mapped = mapGroupNoticeFeed(feed, sendToNewMembers);
|
||||||
|
const existingIndex = indexByNoticeId.get(mapped.notice_id);
|
||||||
|
if (existingIndex === undefined) {
|
||||||
|
indexByNoticeId.set(mapped.notice_id, notices.length);
|
||||||
|
notices.push(mapped);
|
||||||
|
} else if (sendToNewMembers) {
|
||||||
|
// If QQ returns the same item in both collections, `inst` is the
|
||||||
|
// authoritative signal that it targets new members.
|
||||||
|
notices[existingIndex] = mapped;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
append(ret.feeds, false, 'feeds');
|
||||||
|
append(ret.inst, true, 'inst');
|
||||||
|
return notices;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─────────────── private helpers (cookie acquisition) ───────────────
|
// ─────────────── private helpers (cookie acquisition) ───────────────
|
||||||
@@ -243,12 +355,7 @@ export class WebApi {
|
|||||||
async sendNotice(
|
async sendNotice(
|
||||||
groupId: number,
|
groupId: number,
|
||||||
content: string,
|
content: string,
|
||||||
options?: {
|
options?: SendNoticeOptions,
|
||||||
image?: string; // local path, http URL, or undefined (text-only)
|
|
||||||
pinned?: number;
|
|
||||||
type?: number;
|
|
||||||
confirm_required?: number;
|
|
||||||
},
|
|
||||||
): Promise<SetNoticeRetSuccess> {
|
): Promise<SetNoticeRetSuccess> {
|
||||||
const bridge = asBridge(this.ctx);
|
const bridge = asBridge(this.ctx);
|
||||||
const groupCode = groupId.toString();
|
const groupCode = groupId.toString();
|
||||||
@@ -266,29 +373,30 @@ export class WebApi {
|
|||||||
const imageBuffer = Buffer.from(loaded.bytes);
|
const imageBuffer = Buffer.from(loaded.bytes);
|
||||||
|
|
||||||
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
|
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
|
||||||
if (picInfo) {
|
|
||||||
picId = picInfo.id;
|
picId = picInfo.id;
|
||||||
imgWidth = picInfo.width;
|
imgWidth = picInfo.width;
|
||||||
imgHeight = picInfo.height;
|
imgHeight = picInfo.height;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
const ret = await setGroupNoticeWebAPI(
|
const ret = await setGroupNoticeWebAPI(
|
||||||
cookieObject,
|
cookieObject,
|
||||||
groupCode,
|
groupCode,
|
||||||
content,
|
content,
|
||||||
options?.pinned ?? 0,
|
{
|
||||||
options?.type ?? 1,
|
pinned: options?.pinned,
|
||||||
1,
|
type: options?.type,
|
||||||
1,
|
sendToNewMembers: options?.sendToNewMembers,
|
||||||
options?.confirm_required ?? 1,
|
isShowEditCard: options?.isShowEditCard,
|
||||||
|
tipWindowType: options?.tipWindowType,
|
||||||
|
confirmRequired: options?.confirmRequired,
|
||||||
picId,
|
picId,
|
||||||
imgWidth,
|
imgWidth,
|
||||||
imgHeight,
|
imgHeight,
|
||||||
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!ret || ret.ec !== 0) {
|
if (ret.ec !== 0) {
|
||||||
throw new Error(`设置群公告失败: ${ret?.em || '未知错误(Cookie过期或权限不足)'}`);
|
throw new Error(`设置群公告失败: ec=${ret.ec ?? 'missing'}, em=${ret.em ?? 'missing'}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return ret;
|
return ret;
|
||||||
@@ -300,39 +408,7 @@ export class WebApi {
|
|||||||
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
const cookieObject = await getCookies(bridge, 'qun.qq.com');
|
||||||
|
|
||||||
const ret = await getGroupNoticeWebAPI(cookieObject, groupCode);
|
const ret = await getGroupNoticeWebAPI(cookieObject, groupCode);
|
||||||
if (!ret) {
|
return mapGroupNoticeResponse(ret);
|
||||||
throw new Error('获取公告失败');
|
|
||||||
}
|
|
||||||
|
|
||||||
const retNotices: WebNoticeInfo[] = [];
|
|
||||||
|
|
||||||
if (ret.feeds) {
|
|
||||||
for (const key in ret.feeds) {
|
|
||||||
const feed = ret.feeds[key];
|
|
||||||
if (!feed) continue;
|
|
||||||
|
|
||||||
const image = feed.msg?.pics?.map((pic) => ({
|
|
||||||
id: pic.id,
|
|
||||||
height: pic.h,
|
|
||||||
width: pic.w,
|
|
||||||
})) || [];
|
|
||||||
|
|
||||||
retNotices.push({
|
|
||||||
notice_id: feed.fid,
|
|
||||||
sender_id: feed.u,
|
|
||||||
publish_time: feed.pubt,
|
|
||||||
message: {
|
|
||||||
text: feed.msg?.text || '',
|
|
||||||
image,
|
|
||||||
images: image,
|
|
||||||
},
|
|
||||||
settings: feed.settings,
|
|
||||||
read_num: feed.read_num,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return retNotices;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteNotice(groupId: number, fid: string): Promise<boolean> {
|
async deleteNotice(groupId: number, fid: string): Promise<boolean> {
|
||||||
|
|||||||
@@ -424,20 +424,33 @@ export const actions = [
|
|||||||
// 群公告
|
// 群公告
|
||||||
groupAction({
|
groupAction({
|
||||||
name: '_send_group_notice',
|
name: '_send_group_notice',
|
||||||
summary: '发送群公告',
|
summary: '发送群公告(支持置顶、弹窗、新成员、群昵称引导与确认)',
|
||||||
params: {
|
params: {
|
||||||
content: f.string({ allowEmpty: false }),
|
content: f.string({ allowEmpty: false }).describe('公告正文'),
|
||||||
image: f.string().default('').role('image'),
|
image: f.string().default('').role('image').describe('可选公告图片(本地路径、URL 或 base64)'),
|
||||||
pinned: f.raw(),
|
pinned: f.int({ min: 0, max: 1 }).default(0).describe('是否置顶:1=置顶,0=不置顶'),
|
||||||
type: f.raw(),
|
type: f.int().optional().describe('发布类型:1=普通公告,20=新成员公告;建议使用 send_to_new_members'),
|
||||||
confirm_required: f.raw(),
|
send_to_new_members: f.bool().optional().describe('是否在成员新加入群时发送(与 type=20 等价)'),
|
||||||
|
is_show_edit_card: f.int({ min: 0, max: 1 }).default(1).describe('是否引导群成员修改群昵称:1=是,0=否'),
|
||||||
|
tip_window_type: f.int({ min: 0, max: 1 }).default(1).describe('弹窗展示:0=开启弹窗,1=关闭弹窗(QQ 原始字段为反向语义)'),
|
||||||
|
confirm_required: f.int({ min: 0, max: 1 }).default(1).describe('是否需要群成员确认收到:1=是,0=否'),
|
||||||
},
|
},
|
||||||
|
rules: (r) => [
|
||||||
|
r.rule('type must be 1 (regular) or 20 (new members)', (p) => p.type === undefined || p.type === 1 || p.type === 20),
|
||||||
|
r.rule(
|
||||||
|
'send_to_new_members conflicts with type',
|
||||||
|
(p) => p.send_to_new_members === undefined || p.type === undefined || p.type === (p.send_to_new_members ? 20 : 1),
|
||||||
|
),
|
||||||
|
],
|
||||||
run: async (p, ctx) => {
|
run: async (p, ctx) => {
|
||||||
const options = {
|
const options = {
|
||||||
image: p.image || undefined,
|
image: p.image || undefined,
|
||||||
pinned: p.pinned !== undefined ? Number(p.pinned) : 0,
|
pinned: p.pinned,
|
||||||
type: p.type !== undefined ? Number(p.type) : 1,
|
type: p.type,
|
||||||
confirm_required: p.confirm_required !== undefined ? Number(p.confirm_required) : 1,
|
sendToNewMembers: p.send_to_new_members,
|
||||||
|
isShowEditCard: p.is_show_edit_card,
|
||||||
|
tipWindowType: p.tip_window_type,
|
||||||
|
confirmRequired: p.confirm_required,
|
||||||
};
|
};
|
||||||
|
|
||||||
await ctx.bridge.apis.web.sendNotice(p.group_id, p.content, options);
|
await ctx.bridge.apis.web.sendNotice(p.group_id, p.content, options);
|
||||||
@@ -448,6 +461,7 @@ export const actions = [
|
|||||||
groupAction({
|
groupAction({
|
||||||
name: '_get_group_notice',
|
name: '_get_group_notice',
|
||||||
summary: '获取群公告',
|
summary: '获取群公告',
|
||||||
|
returns: '普通公告与新成员公告的合并数组;send_to_new_members 标识后者',
|
||||||
readOnly: true,
|
readOnly: true,
|
||||||
run: async (p, ctx) => {
|
run: async (p, ctx) => {
|
||||||
const notices = await ctx.bridge.apis.web.getNotice(p.group_id);
|
const notices = await ctx.bridge.apis.web.getNotice(p.group_id);
|
||||||
|
|||||||
@@ -13,28 +13,65 @@ export interface SetNoticeRetSuccess {
|
|||||||
|
|
||||||
export interface UploadImageRetSuccess {
|
export interface UploadImageRetSuccess {
|
||||||
ec?: number;
|
ec?: number;
|
||||||
|
em?: string;
|
||||||
id?: string;
|
id?: string;
|
||||||
[key: string]: JsonValue | undefined;
|
[key: string]: JsonValue | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const GROUP_NOTICE_TYPE_NORMAL = 1;
|
||||||
|
export const GROUP_NOTICE_TYPE_NEW_MEMBERS = 20;
|
||||||
|
|
||||||
|
export interface SetGroupNoticeOptions {
|
||||||
|
pinned?: number;
|
||||||
|
/** Raw publish type kept for OneBot compatibility: 1=regular, 20=new members. */
|
||||||
|
type?: number;
|
||||||
|
/** Semantic alias for selecting the new-member announcement endpoint. */
|
||||||
|
sendToNewMembers?: boolean;
|
||||||
|
isShowEditCard?: number;
|
||||||
|
/** QQ uses inverted semantics here: 0=show popup, 1=do not show popup. */
|
||||||
|
tipWindowType?: number;
|
||||||
|
confirmRequired?: number;
|
||||||
|
picId?: string;
|
||||||
|
imgWidth?: number;
|
||||||
|
imgHeight?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ResolvedGroupNoticeOptions {
|
||||||
|
pinned: 0 | 1;
|
||||||
|
type: typeof GROUP_NOTICE_TYPE_NORMAL | typeof GROUP_NOTICE_TYPE_NEW_MEMBERS;
|
||||||
|
sendToNewMembers: boolean;
|
||||||
|
isShowEditCard: 0 | 1;
|
||||||
|
tipWindowType: 0 | 1;
|
||||||
|
confirmRequired: 0 | 1;
|
||||||
|
picId: string;
|
||||||
|
imgWidth: number;
|
||||||
|
imgHeight: number;
|
||||||
|
}
|
||||||
|
|
||||||
export interface WebApiGroupNoticeFeed {
|
export interface WebApiGroupNoticeFeed {
|
||||||
fid: string;
|
fid: string;
|
||||||
u: number;
|
u: number;
|
||||||
pubt: number;
|
pubt: number;
|
||||||
|
type?: number | string;
|
||||||
|
pinned?: number | string;
|
||||||
msg: {
|
msg: {
|
||||||
text: string;
|
text: string;
|
||||||
pics?: Array<{ id: string; w: number; h: number }>;
|
pics?: Array<{ id: string; w: number | string; h: number | string }>;
|
||||||
};
|
};
|
||||||
settings: JsonValue;
|
settings: JsonValue;
|
||||||
read_num: number;
|
read_num: number;
|
||||||
[key: string]: JsonValue;
|
[key: string]: JsonValue | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type WebApiGroupNoticeCollection = WebApiGroupNoticeFeed[] | Record<string, WebApiGroupNoticeFeed>;
|
||||||
|
|
||||||
export interface WebApiGroupNoticeRet {
|
export interface WebApiGroupNoticeRet {
|
||||||
ec: number;
|
ec: number;
|
||||||
em?: string;
|
em?: string;
|
||||||
feeds?: Record<string, WebApiGroupNoticeFeed>;
|
feeds?: WebApiGroupNoticeCollection;
|
||||||
[key: string]: JsonValue | Record<string, WebApiGroupNoticeFeed> | undefined;
|
/** Announcements shown to members when they newly join the group. */
|
||||||
|
inst?: WebApiGroupNoticeCollection;
|
||||||
|
[key: string]: JsonValue | WebApiGroupNoticeCollection | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function calculateBkn(key: string): string {
|
export function calculateBkn(key: string): string {
|
||||||
@@ -46,6 +83,100 @@ export function calculateBkn(key: string): string {
|
|||||||
return (hash & 0x7FFFFFFF).toString();
|
return (hash & 0x7FFFFFFF).toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function binaryOption(name: string, value: number | undefined, fallback: 0 | 1): 0 | 1 {
|
||||||
|
const resolved = value ?? fallback;
|
||||||
|
if (resolved !== 0 && resolved !== 1) {
|
||||||
|
throw new RangeError(`${name} must be 0 or 1, received ${resolved}`);
|
||||||
|
}
|
||||||
|
return resolved;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the public compatibility fields into the exact QQ request mode.
|
||||||
|
* Kept pure so both runtime callers and tests share one conflict check.
|
||||||
|
*/
|
||||||
|
export function resolveGroupNoticeOptions(options: SetGroupNoticeOptions = {}): ResolvedGroupNoticeOptions {
|
||||||
|
if (options.sendToNewMembers !== undefined && typeof options.sendToNewMembers !== 'boolean') {
|
||||||
|
throw new TypeError(`sendToNewMembers must be a boolean, received ${typeof options.sendToNewMembers}`);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
options.type !== undefined &&
|
||||||
|
options.type !== GROUP_NOTICE_TYPE_NORMAL &&
|
||||||
|
options.type !== GROUP_NOTICE_TYPE_NEW_MEMBERS
|
||||||
|
) {
|
||||||
|
throw new RangeError(
|
||||||
|
`type must be ${GROUP_NOTICE_TYPE_NORMAL} (regular) or ${GROUP_NOTICE_TYPE_NEW_MEMBERS} (new members), received ${options.type}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const semanticType = options.sendToNewMembers === undefined
|
||||||
|
? undefined
|
||||||
|
: options.sendToNewMembers
|
||||||
|
? GROUP_NOTICE_TYPE_NEW_MEMBERS
|
||||||
|
: GROUP_NOTICE_TYPE_NORMAL;
|
||||||
|
|
||||||
|
if (options.type !== undefined && semanticType !== undefined && options.type !== semanticType) {
|
||||||
|
throw new Error(
|
||||||
|
`sendToNewMembers=${options.sendToNewMembers} conflicts with type=${options.type}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const type = options.type ?? semanticType ?? GROUP_NOTICE_TYPE_NORMAL;
|
||||||
|
const imgWidth = options.imgWidth ?? 540;
|
||||||
|
const imgHeight = options.imgHeight ?? 300;
|
||||||
|
if (!Number.isFinite(imgWidth) || imgWidth <= 0 || !Number.isFinite(imgHeight) || imgHeight <= 0) {
|
||||||
|
throw new RangeError(`group notice image dimensions must be positive finite numbers, received ${imgWidth}x${imgHeight}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
pinned: binaryOption('pinned', options.pinned, 0),
|
||||||
|
type,
|
||||||
|
sendToNewMembers: type === GROUP_NOTICE_TYPE_NEW_MEMBERS,
|
||||||
|
// Preserve SnowLuma's established defaults for existing callers.
|
||||||
|
isShowEditCard: binaryOption('isShowEditCard', options.isShowEditCard, 1),
|
||||||
|
tipWindowType: binaryOption('tipWindowType', options.tipWindowType, 1),
|
||||||
|
confirmRequired: binaryOption('confirmRequired', options.confirmRequired, 1),
|
||||||
|
picId: options.picId ?? '',
|
||||||
|
imgWidth,
|
||||||
|
imgHeight,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parse QQ's HTML-escaped JSON metadata returned by the image upload CGI. */
|
||||||
|
export function parseGroupNoticeImageUploadResponse(data: string): { id: string; width: number; height: number } {
|
||||||
|
let result: UploadImageRetSuccess;
|
||||||
|
try {
|
||||||
|
result = JSON.parse(data) as UploadImageRetSuccess;
|
||||||
|
} catch (cause) {
|
||||||
|
throw new Error('group notice image upload returned invalid JSON', { cause });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.ec !== 0 || !result.id) {
|
||||||
|
throw new Error(`group notice image upload failed: ec=${result.ec ?? 'missing'} em=${result.em ?? 'missing'}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
let idObj: { id?: unknown; w?: unknown; h?: unknown };
|
||||||
|
try {
|
||||||
|
idObj = JSON.parse(result.id.replace(/"/g, '"')) as { id?: unknown; w?: unknown; h?: unknown };
|
||||||
|
} catch (cause) {
|
||||||
|
throw new Error('group notice image upload returned invalid image metadata JSON', { cause });
|
||||||
|
}
|
||||||
|
|
||||||
|
const width = Number(idObj.w);
|
||||||
|
const height = Number(idObj.h);
|
||||||
|
if (
|
||||||
|
typeof idObj.id !== 'string' ||
|
||||||
|
idObj.id.length === 0 ||
|
||||||
|
!Number.isFinite(width) ||
|
||||||
|
width <= 0 ||
|
||||||
|
!Number.isFinite(height) ||
|
||||||
|
height <= 0
|
||||||
|
) {
|
||||||
|
throw new Error('group notice image upload returned malformed image metadata');
|
||||||
|
}
|
||||||
|
return { id: idObj.id, width, height };
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 发送群公告 Web API
|
* 发送群公告 Web API
|
||||||
*/
|
*/
|
||||||
@@ -53,70 +184,64 @@ export async function setGroupNoticeWebAPI(
|
|||||||
cookieObject: Record<string, string>,
|
cookieObject: Record<string, string>,
|
||||||
groupCode: string,
|
groupCode: string,
|
||||||
content: string,
|
content: string,
|
||||||
pinned: number = 0,
|
options: SetGroupNoticeOptions = {},
|
||||||
type: number = 1,
|
): Promise<SetNoticeRetSuccess> {
|
||||||
isShowEditCard: number = 1,
|
const resolved = resolveGroupNoticeOptions(options);
|
||||||
tipWindowType: number = 1,
|
|
||||||
confirmRequired: number = 1,
|
// QQ validates these independently: the body token comes from skey while
|
||||||
picId: string = '',
|
// the URL token comes from p_skey (falling back to skey when absent).
|
||||||
imgWidth: number = 540,
|
|
||||||
imgHeight: number = 300
|
|
||||||
): Promise<SetNoticeRetSuccess | undefined> {
|
|
||||||
try {
|
|
||||||
// 分别获取 skey 和 p_skey
|
|
||||||
const skey = cookieObject['skey'] || '';
|
const skey = cookieObject['skey'] || '';
|
||||||
const pskey = cookieObject['p_skey'] || skey;
|
const pskey = cookieObject['p_skey'] || skey;
|
||||||
|
|
||||||
const bodyBkn = calculateBkn(skey);
|
const bodyBkn = calculateBkn(skey);
|
||||||
const urlBkn = calculateBkn(pskey);
|
const urlBkn = calculateBkn(pskey);
|
||||||
//
|
|
||||||
// console.log(skey)
|
|
||||||
// console.log(pskey)
|
|
||||||
//
|
|
||||||
// console.log(urlBkn);
|
|
||||||
// console.log(bodyBkn)
|
|
||||||
|
|
||||||
const settings = JSON.stringify({
|
const settings = JSON.stringify({
|
||||||
is_show_edit_card: isShowEditCard,
|
is_show_edit_card: resolved.isShowEditCard,
|
||||||
tip_window_type: tipWindowType,
|
tip_window_type: resolved.tipWindowType,
|
||||||
confirm_required: confirmRequired,
|
confirm_required: resolved.confirmRequired,
|
||||||
});
|
});
|
||||||
|
|
||||||
const bodyParams: Record<string, string> = {
|
const bodyParams: Record<string, string> = {
|
||||||
qid: groupCode,
|
qid: groupCode,
|
||||||
bkn: bodyBkn,
|
bkn: bodyBkn,
|
||||||
text: content,
|
text: content,
|
||||||
pinned: pinned.toString(),
|
pinned: resolved.pinned.toString(),
|
||||||
type: type.toString(),
|
type: resolved.type.toString(),
|
||||||
settings,
|
settings,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (picId !== '') {
|
if (resolved.picId !== '') {
|
||||||
bodyParams.pic = picId;
|
bodyParams.pic = resolved.picId;
|
||||||
bodyParams.imgWidth = imgWidth.toString();
|
bodyParams.imgWidth = resolved.imgWidth.toString();
|
||||||
bodyParams.imgHeight = imgHeight.toString();
|
bodyParams.imgHeight = resolved.imgHeight.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 注意这里:URL 必须使用 skey 算出来的 bkn
|
const endpoint = resolved.sendToNewMembers ? 'add_qun_instruction' : 'add_qun_notice';
|
||||||
const url = `https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=${urlBkn}`;
|
const url = `https://web.qun.qq.com/cgi-bin/announce/${endpoint}?bkn=${urlBkn}`;
|
||||||
const body = new URLSearchParams(bodyParams).toString();
|
const body = new URLSearchParams(bodyParams).toString();
|
||||||
|
|
||||||
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
|
log.debug(
|
||||||
|
'group-notice publish: group=%s target=%s pinned=%d edit-card=%d popup=%s confirm=%d image=%s',
|
||||||
|
groupCode,
|
||||||
|
resolved.sendToNewMembers ? 'new-members' : 'regular',
|
||||||
|
resolved.pinned,
|
||||||
|
resolved.isShowEditCard,
|
||||||
|
resolved.tipWindowType === 0 ? 'on' : 'off',
|
||||||
|
resolved.confirmRequired,
|
||||||
|
resolved.picId ? 'yes' : 'no',
|
||||||
|
);
|
||||||
|
|
||||||
|
return RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
|
||||||
url,
|
url,
|
||||||
'POST',
|
'POST',
|
||||||
body,
|
body,
|
||||||
{
|
{
|
||||||
Cookie: cookieToString(cookieObject),
|
Cookie: cookieToString(cookieObject),
|
||||||
'Content-Type': 'application/x-www-form-urlencoded'
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||||||
},
|
},
|
||||||
true,
|
true,
|
||||||
false
|
false,
|
||||||
);
|
);
|
||||||
return ret;
|
|
||||||
} catch (e) {
|
|
||||||
log.warn('group-notice add failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -127,44 +252,37 @@ export async function getGroupNoticeWebAPI(
|
|||||||
groupCode: string,
|
groupCode: string,
|
||||||
start: number = -1, // -1 表示第一页
|
start: number = -1, // -1 表示第一页
|
||||||
count: number = 20 // 抓包中是 10,你可以根据需要调整
|
count: number = 20 // 抓包中是 10,你可以根据需要调整
|
||||||
): Promise<WebApiGroupNoticeRet | undefined> {
|
): Promise<WebApiGroupNoticeRet> {
|
||||||
try {
|
|
||||||
const skey = cookieObject['skey'] || '';
|
const skey = cookieObject['skey'] || '';
|
||||||
const pskey = cookieObject['p_skey'] || skey;
|
const pskey = cookieObject['p_skey'] || skey;
|
||||||
|
|
||||||
const bodyBkn = calculateBkn(skey); // URL 使用 skey 算出的 bkn
|
const bodyBkn = calculateBkn(skey);
|
||||||
const urlBkn = calculateBkn(pskey); // Body 使用 p_skey 算出的 bkn
|
const urlBkn = calculateBkn(pskey);
|
||||||
|
|
||||||
const bodyParams = new URLSearchParams({
|
const bodyParams = new URLSearchParams({
|
||||||
qid: groupCode,
|
qid: groupCode,
|
||||||
bkn: bodyBkn, // Body 中传入 p_skey 计算结果
|
bkn: bodyBkn,
|
||||||
ft: '23',
|
ft: '23',
|
||||||
s: start.toString(), // 分页游标
|
s: start.toString(),
|
||||||
n: count.toString(), // 获取数量
|
n: count.toString(),
|
||||||
i: '1',
|
i: '1',
|
||||||
ni: '1'
|
ni: '1',
|
||||||
}).toString();
|
}).toString();
|
||||||
|
|
||||||
const url = `https://web.qun.qq.com/cgi-bin/announce/list_announce?bkn=${urlBkn}`;
|
const url = `https://web.qun.qq.com/cgi-bin/announce/list_announce?bkn=${urlBkn}`;
|
||||||
|
|
||||||
const ret = await RequestUtil.HttpGetJson<WebApiGroupNoticeRet>(
|
return RequestUtil.HttpGetJson<WebApiGroupNoticeRet>(
|
||||||
url,
|
url,
|
||||||
'POST',
|
'POST',
|
||||||
bodyParams,
|
bodyParams,
|
||||||
{
|
{
|
||||||
Cookie: cookieToString(cookieObject),
|
Cookie: cookieToString(cookieObject),
|
||||||
'Content-Type': 'application/x-www-form-urlencoded',
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||||||
'Referer': 'https://web.qun.qq.com/mannounce/index.html?_wv=1031&_bid=148'
|
'Referer': 'https://web.qun.qq.com/mannounce/index.html?_wv=1031&_bid=148',
|
||||||
},
|
},
|
||||||
true,
|
true,
|
||||||
false
|
false,
|
||||||
);
|
);
|
||||||
// console.log(JSON.stringify(ret, null, 2));
|
|
||||||
return ret?.ec === 0 ? ret : undefined;
|
|
||||||
} catch (e) {
|
|
||||||
log.warn('getGroupNoticeList failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* 上传群公告图片 Web API
|
* 上传群公告图片 Web API
|
||||||
@@ -172,9 +290,8 @@ export async function getGroupNoticeWebAPI(
|
|||||||
export async function uploadGroupNoticeImage(
|
export async function uploadGroupNoticeImage(
|
||||||
cookieObject: Record<string, string>,
|
cookieObject: Record<string, string>,
|
||||||
imageBuffer: Buffer
|
imageBuffer: Buffer
|
||||||
): Promise<{ id: string; width: number; height: number } | undefined> {
|
): Promise<{ id: string; width: number; height: number }> {
|
||||||
try {
|
const bkn = calculateBkn(cookieObject['skey'] || '');
|
||||||
const bkn = calculateBkn(cookieObject['skey']);
|
|
||||||
const boundary = `-----------------------------${Date.now()}`;
|
const boundary = `-----------------------------${Date.now()}`;
|
||||||
|
|
||||||
const parts: Buffer[] = [];
|
const parts: Buffer[] = [];
|
||||||
@@ -198,37 +315,27 @@ export async function uploadGroupNoticeImage(
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve, reject) => {
|
||||||
const req = https.request(options, (res) => {
|
const req = https.request(options, (res) => {
|
||||||
let data = '';
|
let data = '';
|
||||||
res.on('data', (chunk) => { data += chunk; });
|
res.on('data', (chunk) => { data += chunk; });
|
||||||
res.on('end', () => {
|
res.on('end', () => {
|
||||||
try {
|
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
|
||||||
const result = JSON.parse(data) as UploadImageRetSuccess;
|
reject(new Error(`group notice image upload returned HTTP ${res.statusCode ?? 'unknown'}`));
|
||||||
if (result.ec === 0 && result.id) {
|
return;
|
||||||
const unescapedIdStr = result.id.replace(/"/g, '"');
|
}
|
||||||
|
|
||||||
const idObj = JSON.parse(unescapedIdStr);
|
try {
|
||||||
resolve({ id: idObj.id, width: parseInt(idObj.w), height: parseInt(idObj.h) });
|
resolve(parseGroupNoticeImageUploadResponse(data));
|
||||||
} else {
|
} catch (error) {
|
||||||
resolve(undefined);
|
reject(error instanceof Error ? error : new Error(String(error)));
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
resolve(undefined);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
req.on('error', (err) => {
|
req.on('error', (error) => reject(new Error(`group notice image upload transport error: ${error.message}`, { cause: error })));
|
||||||
log.warn('uploadGroupNoticeImage transport error: %s', err.message);
|
|
||||||
resolve(undefined);
|
|
||||||
});
|
|
||||||
req.write(body);
|
req.write(body);
|
||||||
req.end();
|
req.end();
|
||||||
});
|
});
|
||||||
} catch (e) {
|
|
||||||
log.warn('uploadGroupNoticeImage failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
Reference in new issue
Block a user