diff --git a/packages/core/src/bridge/apis/web.ts b/packages/core/src/bridge/apis/web.ts index 38ee1db4..c6f28126 100644 --- a/packages/core/src/bridge/apis/web.ts +++ b/packages/core/src/bridge/apis/web.ts @@ -6,10 +6,15 @@ import { getHonorListWebAPI, WebHonorType, type WebHonorItem } from '@snowluma/p import { getDaySignedListWebAPI, type SignedListMember } from '@snowluma/protocol/web/group-signin'; import { deleteGroupNotice as deleteGroupNoticeHttp, + GROUP_NOTICE_TYPE_NEW_MEMBERS, + GROUP_NOTICE_TYPE_NORMAL, getGroupNoticeWebAPI, setGroupNoticeWebAPI, uploadGroupNoticeImage, type SetNoticeRetSuccess, + type WebApiGroupNoticeCollection, + type WebApiGroupNoticeFeed, + type WebApiGroupNoticeRet, } from '@snowluma/protocol/web/group-notice'; import { RequestUtil } from '@snowluma/protocol/web/request-util'; import type { Bridge } from '../bridge'; @@ -42,6 +47,113 @@ export interface WebNoticeInfo { }; settings: import('@snowluma/common/json').JsonValue; 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(); + 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) ─────────────── @@ -243,12 +355,7 @@ export class WebApi { async sendNotice( groupId: number, content: string, - options?: { - image?: string; // local path, http URL, or undefined (text-only) - pinned?: number; - type?: number; - confirm_required?: number; - }, + options?: SendNoticeOptions, ): Promise { const bridge = asBridge(this.ctx); const groupCode = groupId.toString(); @@ -266,29 +373,30 @@ export class WebApi { const imageBuffer = Buffer.from(loaded.bytes); const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer); - if (picInfo) { - picId = picInfo.id; - imgWidth = picInfo.width; - imgHeight = picInfo.height; - } + picId = picInfo.id; + imgWidth = picInfo.width; + imgHeight = picInfo.height; } const ret = await setGroupNoticeWebAPI( cookieObject, groupCode, content, - options?.pinned ?? 0, - options?.type ?? 1, - 1, - 1, - options?.confirm_required ?? 1, - picId, - imgWidth, - imgHeight, + { + pinned: options?.pinned, + type: options?.type, + sendToNewMembers: options?.sendToNewMembers, + isShowEditCard: options?.isShowEditCard, + tipWindowType: options?.tipWindowType, + confirmRequired: options?.confirmRequired, + picId, + imgWidth, + imgHeight, + }, ); - if (!ret || ret.ec !== 0) { - throw new Error(`设置群公告失败: ${ret?.em || '未知错误(Cookie过期或权限不足)'}`); + if (ret.ec !== 0) { + throw new Error(`设置群公告失败: ec=${ret.ec ?? 'missing'}, em=${ret.em ?? 'missing'}`); } return ret; @@ -300,39 +408,7 @@ export class WebApi { const cookieObject = await getCookies(bridge, 'qun.qq.com'); const ret = await getGroupNoticeWebAPI(cookieObject, groupCode); - if (!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; + return mapGroupNoticeResponse(ret); } async deleteNotice(groupId: number, fid: string): Promise { diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index e5a0efb2..9b00eb1e 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -424,20 +424,33 @@ export const actions = [ // 群公告 groupAction({ name: '_send_group_notice', - summary: '发送群公告', + summary: '发送群公告(支持置顶、弹窗、新成员、群昵称引导与确认)', params: { - content: f.string({ allowEmpty: false }), - image: f.string().default('').role('image'), - pinned: f.raw(), - type: f.raw(), - confirm_required: f.raw(), + content: f.string({ allowEmpty: false }).describe('公告正文'), + image: f.string().default('').role('image').describe('可选公告图片(本地路径、URL 或 base64)'), + pinned: f.int({ min: 0, max: 1 }).default(0).describe('是否置顶:1=置顶,0=不置顶'), + type: f.int().optional().describe('发布类型:1=普通公告,20=新成员公告;建议使用 send_to_new_members'), + 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) => { const options = { image: p.image || undefined, - pinned: p.pinned !== undefined ? Number(p.pinned) : 0, - type: p.type !== undefined ? Number(p.type) : 1, - confirm_required: p.confirm_required !== undefined ? Number(p.confirm_required) : 1, + pinned: p.pinned, + type: p.type, + 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); @@ -448,6 +461,7 @@ export const actions = [ groupAction({ name: '_get_group_notice', summary: '获取群公告', + returns: '普通公告与新成员公告的合并数组;send_to_new_members 标识后者', readOnly: true, run: async (p, ctx) => { const notices = await ctx.bridge.apis.web.getNotice(p.group_id); diff --git a/packages/protocol/src/web/group-notice.ts b/packages/protocol/src/web/group-notice.ts index 00c41760..f566edb0 100644 --- a/packages/protocol/src/web/group-notice.ts +++ b/packages/protocol/src/web/group-notice.ts @@ -13,28 +13,65 @@ export interface SetNoticeRetSuccess { export interface UploadImageRetSuccess { ec?: number; + em?: string; id?: string; [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 { fid: string; u: number; pubt: number; + type?: number | string; + pinned?: number | string; msg: { text: string; - pics?: Array<{ id: string; w: number; h: number }>; + pics?: Array<{ id: string; w: number | string; h: number | string }>; }; settings: JsonValue; read_num: number; - [key: string]: JsonValue; + [key: string]: JsonValue | undefined; } +export type WebApiGroupNoticeCollection = WebApiGroupNoticeFeed[] | Record; + export interface WebApiGroupNoticeRet { ec: number; em?: string; - feeds?: Record; - [key: string]: JsonValue | Record | undefined; + feeds?: WebApiGroupNoticeCollection; + /** Announcements shown to members when they newly join the group. */ + inst?: WebApiGroupNoticeCollection; + [key: string]: JsonValue | WebApiGroupNoticeCollection | undefined; } export function calculateBkn(key: string): string { @@ -46,6 +83,100 @@ export function calculateBkn(key: string): string { 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 */ @@ -53,70 +184,64 @@ export async function setGroupNoticeWebAPI( cookieObject: Record, groupCode: string, content: string, - pinned: number = 0, - type: number = 1, - isShowEditCard: number = 1, - tipWindowType: number = 1, - confirmRequired: number = 1, - picId: string = '', - imgWidth: number = 540, - imgHeight: number = 300 -): Promise { - try { - // 分别获取 skey 和 p_skey - const skey = cookieObject['skey'] || ''; - const pskey = cookieObject['p_skey'] || skey; + options: SetGroupNoticeOptions = {}, +): Promise { + const resolved = resolveGroupNoticeOptions(options); - const bodyBkn = calculateBkn(skey); - const urlBkn = calculateBkn(pskey); - // - // console.log(skey) - // console.log(pskey) - // - // console.log(urlBkn); - // console.log(bodyBkn) + // QQ validates these independently: the body token comes from skey while + // the URL token comes from p_skey (falling back to skey when absent). + const skey = cookieObject['skey'] || ''; + const pskey = cookieObject['p_skey'] || skey; + const bodyBkn = calculateBkn(skey); + const urlBkn = calculateBkn(pskey); - const settings = JSON.stringify({ - is_show_edit_card: isShowEditCard, - tip_window_type: tipWindowType, - confirm_required: confirmRequired, - }); + const settings = JSON.stringify({ + is_show_edit_card: resolved.isShowEditCard, + tip_window_type: resolved.tipWindowType, + confirm_required: resolved.confirmRequired, + }); - const bodyParams: Record = { - qid: groupCode, - bkn: bodyBkn, - text: content, - pinned: pinned.toString(), - type: type.toString(), - settings, - }; + const bodyParams: Record = { + qid: groupCode, + bkn: bodyBkn, + text: content, + pinned: resolved.pinned.toString(), + type: resolved.type.toString(), + settings, + }; - if (picId !== '') { - bodyParams.pic = picId; - bodyParams.imgWidth = imgWidth.toString(); - bodyParams.imgHeight = imgHeight.toString(); - } - - // 注意这里:URL 必须使用 skey 算出来的 bkn - const url = `https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=${urlBkn}`; - const body = new URLSearchParams(bodyParams).toString(); - - const ret = await RequestUtil.HttpGetJson( - url, - 'POST', - body, - { - Cookie: cookieToString(cookieObject), - 'Content-Type': 'application/x-www-form-urlencoded' - }, - true, - false - ); - return ret; - } catch (e) { - log.warn('group-notice add failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e)); - return undefined; + if (resolved.picId !== '') { + bodyParams.pic = resolved.picId; + bodyParams.imgWidth = resolved.imgWidth.toString(); + bodyParams.imgHeight = resolved.imgHeight.toString(); } + + const endpoint = resolved.sendToNewMembers ? 'add_qun_instruction' : 'add_qun_notice'; + const url = `https://web.qun.qq.com/cgi-bin/announce/${endpoint}?bkn=${urlBkn}`; + const body = new URLSearchParams(bodyParams).toString(); + + 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( + url, + 'POST', + body, + { + Cookie: cookieToString(cookieObject), + 'Content-Type': 'application/x-www-form-urlencoded', + }, + true, + false, + ); } /** @@ -127,44 +252,37 @@ export async function getGroupNoticeWebAPI( groupCode: string, start: number = -1, // -1 表示第一页 count: number = 20 // 抓包中是 10,你可以根据需要调整 -): Promise { - try { - const skey = cookieObject['skey'] || ''; - const pskey = cookieObject['p_skey'] || skey; +): Promise { + const skey = cookieObject['skey'] || ''; + const pskey = cookieObject['p_skey'] || skey; - const bodyBkn = calculateBkn(skey); // URL 使用 skey 算出的 bkn - const urlBkn = calculateBkn(pskey); // Body 使用 p_skey 算出的 bkn + const bodyBkn = calculateBkn(skey); + const urlBkn = calculateBkn(pskey); - const bodyParams = new URLSearchParams({ - qid: groupCode, - bkn: bodyBkn, // Body 中传入 p_skey 计算结果 - ft: '23', - s: start.toString(), // 分页游标 - n: count.toString(), // 获取数量 - i: '1', - ni: '1' - }).toString(); + const bodyParams = new URLSearchParams({ + qid: groupCode, + bkn: bodyBkn, + ft: '23', + s: start.toString(), + n: count.toString(), + i: '1', + ni: '1', + }).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( - url, - 'POST', - bodyParams, - { - Cookie: cookieToString(cookieObject), - 'Content-Type': 'application/x-www-form-urlencoded', - 'Referer': 'https://web.qun.qq.com/mannounce/index.html?_wv=1031&_bid=148' - }, - true, - 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; - } + return RequestUtil.HttpGetJson( + url, + 'POST', + bodyParams, + { + Cookie: cookieToString(cookieObject), + 'Content-Type': 'application/x-www-form-urlencoded', + 'Referer': 'https://web.qun.qq.com/mannounce/index.html?_wv=1031&_bid=148', + }, + true, + false, + ); } /** * 上传群公告图片 Web API @@ -172,63 +290,52 @@ export async function getGroupNoticeWebAPI( export async function uploadGroupNoticeImage( cookieObject: Record, imageBuffer: Buffer -): Promise<{ id: string; width: number; height: number } | undefined> { - try { - const bkn = calculateBkn(cookieObject['skey']); - const boundary = `-----------------------------${Date.now()}`; +): Promise<{ id: string; width: number; height: number }> { + const bkn = calculateBkn(cookieObject['skey'] || ''); + const boundary = `-----------------------------${Date.now()}`; - const parts: Buffer[] = []; - parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="bkn"\r\n\r\n${bkn}\r\n`)); - parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="source"\r\n\r\ntroopNotice\r\n`)); - parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="m"\r\n\r\n0\r\n`)); - parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="pic_up"; filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`)); - parts.push(imageBuffer); - parts.push(Buffer.from(`\r\n--${boundary}--\r\n`)); + const parts: Buffer[] = []; + parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="bkn"\r\n\r\n${bkn}\r\n`)); + parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="source"\r\n\r\ntroopNotice\r\n`)); + parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="m"\r\n\r\n0\r\n`)); + parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="pic_up"; filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`)); + parts.push(imageBuffer); + parts.push(Buffer.from(`\r\n--${boundary}--\r\n`)); - const body = Buffer.concat(parts); + const body = Buffer.concat(parts); - const options = { - hostname: 'web.qun.qq.com', - path: '/cgi-bin/announce/upload_img', - method: 'POST', - headers: { - 'Content-Type': `multipart/form-data; boundary=${boundary}`, - 'Content-Length': body.length, - 'Cookie': cookieToString(cookieObject), - }, - }; + const options = { + hostname: 'web.qun.qq.com', + path: '/cgi-bin/announce/upload_img', + method: 'POST', + headers: { + 'Content-Type': `multipart/form-data; boundary=${boundary}`, + 'Content-Length': body.length, + 'Cookie': cookieToString(cookieObject), + }, + }; - return new Promise((resolve) => { - const req = https.request(options, (res) => { - let data = ''; - res.on('data', (chunk) => { data += chunk; }); - res.on('end', () => { - try { - const result = JSON.parse(data) as UploadImageRetSuccess; - if (result.ec === 0 && result.id) { - const unescapedIdStr = result.id.replace(/"/g, '"'); + return new Promise((resolve, reject) => { + const req = https.request(options, (res) => { + let data = ''; + res.on('data', (chunk) => { data += chunk; }); + res.on('end', () => { + if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) { + reject(new Error(`group notice image upload returned HTTP ${res.statusCode ?? 'unknown'}`)); + return; + } - const idObj = JSON.parse(unescapedIdStr); - resolve({ id: idObj.id, width: parseInt(idObj.w), height: parseInt(idObj.h) }); - } else { - resolve(undefined); - } - } catch { - resolve(undefined); - } - }); + try { + resolve(parseGroupNoticeImageUploadResponse(data)); + } catch (error) { + reject(error instanceof Error ? error : new Error(String(error))); + } }); - req.on('error', (err) => { - log.warn('uploadGroupNoticeImage transport error: %s', err.message); - resolve(undefined); - }); - req.write(body); - req.end(); }); - } catch (e) { - log.warn('uploadGroupNoticeImage failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e)); - return undefined; - } + req.on('error', (error) => reject(new Error(`group notice image upload transport error: ${error.message}`, { cause: error }))); + req.write(body); + req.end(); + }); } /**