From 4a51e3d6861cd74061b84e57a5acf0e631f600b0 Mon Sep 17 00:00:00 2001 From: H3CoF6 <1707889225@qq.com> Date: Fri, 8 May 2026 01:56:23 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=BC=95=E5=85=A5web=E6=96=B9=E6=B3=95?= =?UTF-8?q?=EF=BC=8C=E5=AE=9E=E7=8E=B0group=20honor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/core/src/bridge/bridge-actions.ts | 118 +++++++++++++++++- packages/core/src/bridge/bridge.ts | 5 + packages/core/src/bridge/proto/oidb-action.ts | 32 ++++- packages/core/src/bridge/web/group-honor.ts | 55 ++++++++ packages/core/src/bridge/web/request-util.ts | 111 ++++++++++++++++ .../core/src/onebot/actions/group-info.ts | 29 ++++- packages/core/src/onebot/api-handler.ts | 4 + packages/core/src/onebot/instance-context.ts | 3 + 8 files changed, 349 insertions(+), 8 deletions(-) create mode 100644 packages/core/src/bridge/web/group-honor.ts create mode 100644 packages/core/src/bridge/web/request-util.ts diff --git a/packages/core/src/bridge/bridge-actions.ts b/packages/core/src/bridge/bridge-actions.ts index 153adf8f..91147557 100644 --- a/packages/core/src/bridge/bridge-actions.ts +++ b/packages/core/src/bridge/bridge-actions.ts @@ -10,6 +10,8 @@ import { buildSendElems } from './builders/element-builder'; import { parseMsgPush } from './handlers/msg-push-handler'; import type { ForwardNodePayload, MessageElement } from './events'; import { PushMsgSchema } from './proto/message'; +import { RequestUtil } from './web/request-util'; +import { getHonorListWebAPI, WebHonorType } from './web/group-honor'; import { OidbMuteMemberSchema, OidbMuteAllSchema, @@ -42,7 +44,12 @@ import { NTV2RichMediaReqSchema, NTV2RichMediaRespSchema, GroupRecallRequestSchema, - C2CRecallRequestSchema, SsoReadedReportReqSchema, + C2CRecallRequestSchema, + SsoReadedReportReqSchema, + OidbClientKeyRespSchema, + OidbClientKeyReqSchema, + OidbGetPskeyReqSchema, + OidbGetPskeyRespSchema } from './proto/oidb-action'; import { FileUploadExtSchema } from './proto/highway'; import { @@ -1289,4 +1296,113 @@ export async function markGroupMessageRead( if (!result.success) { throw new Error(result.errorMessage || 'mark group message read failed'); } +} + +export async function forceFetchClientKey(bridge: Bridge) { + const resp = await sendOidbAndDecode( + bridge, + 'OidbSvcTrpcTcp.0x102a_1', + 0x102A, + 1, + {}, + OidbClientKeyReqSchema, + OidbClientKeyRespSchema + ); + + const clientKey = resp?.clientKey || ''; + const keyIndex = String(resp?.keyIndex || '19'); // 不知道是什么 + + return { + clientKey, + keyIndex, + expireTime: String(resp?.expireTime || '1800') + }; +} + +export async function getPSkey(bridge: Bridge, domainList: string[]) { + const resp = await sendOidbAndDecode( + bridge, + 'OidbSvcTrpcTcp.0x102a_0', + 0x102A, + 0, + { domainList }, + OidbGetPskeyReqSchema, + OidbGetPskeyRespSchema + ); + + const domainPskeyMap = new Map(); + + if (resp?.pskeyItems && Array.isArray(resp.pskeyItems)) { + for (const item of resp.pskeyItems) { + if (item.domain && item.pskey) { + domainPskeyMap.set(item.domain, item.pskey); + } + } + } + + return { + domainPskeyMap, + }; +} + +export async function getCookies(bridge: Bridge, domain: string) { + const ClientKeyData = await forceFetchClientKey(bridge); + + // 构造 ptlogin2 跳转 URL + const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.qqInfo.uin + + '&clientkey=' + ClientKeyData.clientKey + + '&u1=https%3A%2F%2F' + domain + '%2F' + bridge.qqInfo.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex; + + const data = await RequestUtil.HttpsGetCookies(requestUrl); + + if (!data['p_skey'] || data['p_skey'].length === 0) { + try { + const pskeyData = await getPSkey(bridge, [domain]); + const pskey = pskeyData.domainPskeyMap.get(domain); + if (pskey) { + data['p_skey'] = pskey; + } + } catch { + return data; + } + } + + return data; +} + +export async function getGroupHonorInfo(bridge: Bridge, groupId: number, type: WebHonorType | string) { + const groupCode = groupId.toString(); + const cookieObject = await getCookies(bridge, 'qun.qq.com'); + + const honorInfo: any = { + group_id: groupId, + current_talkative: null, + talkative_list: [], + performer_list: [], + legend_list: [], + emotion_list: [], + strong_newbie_list: [], + }; + + if (type === WebHonorType.TALKATIVE || type === WebHonorType.ALL) { + const talkativeList = await getHonorListWebAPI(cookieObject, groupCode, 1); + if (talkativeList.length > 0) { + honorInfo.current_talkative = talkativeList[0]; + honorInfo.talkative_list = talkativeList; + } + } + + if (type === WebHonorType.PERFORMER || type === WebHonorType.ALL) { + honorInfo.performer_list = await getHonorListWebAPI(cookieObject, groupCode, 2); + } + + if (type === WebHonorType.LEGEND || type === WebHonorType.ALL) { + honorInfo.legend_list = await getHonorListWebAPI(cookieObject, groupCode, 3); + } + + if (type === WebHonorType.EMOTION || type === WebHonorType.ALL) { + honorInfo.emotion_list = await getHonorListWebAPI(cookieObject, groupCode, 6); + } + + return honorInfo; } \ No newline at end of file diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index bda7155d..c8973cee 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -26,6 +26,7 @@ import { fetchGroupRequests as fetchGroupRequests_, fetchDownloadRKeys as fetchDownloadRKeys_, } from './bridge-contacts'; +import { WebHonorType } from './web/group-honor'; import { muteGroupMember as muteGroupMember_, muteGroupAll as muteGroupAll_, @@ -64,6 +65,7 @@ import { markGroupMessageRead as markPrivateMsgAsRead_, setFriendRemark as setFriendRemark_, fetchGroupFileCount as fetchGroupFileCount_, + getGroupHonorInfo as getGroupHonorInfo_, } from './bridge-actions'; import type { GroupFilesResult } from './bridge-actions'; import type { MediaIndexNode } from './bridge-actions'; @@ -450,6 +452,9 @@ export class Bridge { async markGroupMsgAsRead(groupId: number, sequence: number): Promise { return markGroupMsgAsRead_(this, groupId, sequence); } async markPrivateMsgAsRead(userId: number, sequence: number): Promise { return markPrivateMsgAsRead_(this, userId, sequence); } async setFriendRemark(userId: number, remark: string): Promise { return setFriendRemark_(this, userId, remark); } + async getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise { + return getGroupHonorInfo_(this, groupId, type); + } async fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { return fetchGroupFileCount_(this, groupId); } } diff --git a/packages/core/src/bridge/proto/oidb-action.ts b/packages/core/src/bridge/proto/oidb-action.ts index 7f79d0f0..981a5627 100644 --- a/packages/core/src/bridge/proto/oidb-action.ts +++ b/packages/core/src/bridge/proto/oidb-action.ts @@ -804,4 +804,34 @@ export const C2CReadedReportItemSchema = { export const SsoReadedReportReqSchema = { groupList: { field: 1, type: 'repeated_message' as const, schema: GroupReadedReportItemSchema }, c2cList: { field: 2, type: 'repeated_message' as const, schema: C2CReadedReportItemSchema }, -} satisfies ProtoSchema; \ No newline at end of file +} satisfies ProtoSchema; + + +// --- 0x102A_1: Get Client Key --- + +export const OidbClientKeyReqSchema = { +} satisfies ProtoSchema; + +export const OidbClientKeyRespSchema = { + keyIndex: { field: 2, type: 'uint32' as const }, + clientKey: { field: 3, type: 'string' as const }, + expireTime: { field: 4, type: 'uint32' as const }, +} satisfies ProtoSchema; + + +// --- 0x102A_0: Get PSKey --- + +export const OidbGetPskeyReqSchema = { + domainList: { field: 1, type: 'repeated_string' as const }, +} satisfies ProtoSchema; + +export const OidbPskeyItemSchema = { + domain: { field: 1, type: 'string' as const }, + pskey: { field: 2, type: 'string' as const }, + expireTime: { field: 3, type: 'uint64' as const }, +} satisfies ProtoSchema; + +export const OidbGetPskeyRespSchema = { + pskeyItems: { field: 1, type: 'repeated_message' as const, schema: OidbPskeyItemSchema }, +} satisfies ProtoSchema; + diff --git a/packages/core/src/bridge/web/group-honor.ts b/packages/core/src/bridge/web/group-honor.ts new file mode 100644 index 00000000..231969d4 --- /dev/null +++ b/packages/core/src/bridge/web/group-honor.ts @@ -0,0 +1,55 @@ +import { RequestUtil } from './request-util'; + +export enum WebHonorType { + TALKATIVE = 'talkative', + PERFORMER = 'performer', + LEGEND = 'legend', + EMOTION = 'emotion', + ALL = 'all', +} + +// 将 Cookie 对象转换为字符串的工具函数 +function cookieToString(cookieObject: Record): string { + return Object.entries(cookieObject) + .map(([key, value]) => `${key}=${value}`) + .join('; '); +} + +async function fetchHonorData(cookieObject: Record, groupCode: string, type: number) { + let resJson; + try { + const res = await RequestUtil.HttpGetText( + `https://qun.qq.com/interactive/honorlist?${new URLSearchParams({ + gc: groupCode, + type: type.toString(), + }).toString()}`, + 'GET', + '', + { Cookie: cookieToString(cookieObject) } + ); + const match = /window\.__INITIAL_STATE__=(.*?);/.exec(res); + if (match?.[1]) { + resJson = JSON.parse(match[1].trim()); + } + return type === 1 ? resJson?.talkativeList : resJson?.actorList; + } catch (e) { + throw new Error(`获取群 ${groupCode} 类型 ${type} 的荣誉信息失败: ${e}`); + } +} + +export async function getHonorListWebAPI(cookieObject: Record, groupCode: string, type: number) { + try { + const data = await fetchHonorData(cookieObject, groupCode, type); + if (!data) return []; + + return data.map((item: any) => ({ + user_id: item?.uin, + nickname: item?.name, + avatar: item?.avatar, + description: item?.desc, + })); + } catch (e) { + // console.error(e); + return []; + } +} \ No newline at end of file diff --git a/packages/core/src/bridge/web/request-util.ts b/packages/core/src/bridge/web/request-util.ts new file mode 100644 index 00000000..b70a62ca --- /dev/null +++ b/packages/core/src/bridge/web/request-util.ts @@ -0,0 +1,111 @@ +import https from 'node:https'; +import http from 'node:http'; + +export class RequestUtil { + static async HttpsGetCookies(url: string): Promise<{ [key: string]: string; }> { + const client = url.startsWith('https') ? https : http; + return new Promise((resolve, reject) => { + const req = client.get(url, (res) => { + const cookies: { [key: string]: string; } = {}; + + res.on('data', () => { }); // 必须消耗流 + res.on('end', () => { + this.handleRedirect(res, url, cookies) + .then(resolve) + .catch(reject); + }); + + if (res.headers['set-cookie']) { + this.extractCookies(res.headers['set-cookie'], cookies); + } + }); + + req.on('error', (error: Error) => { + reject(error); + }); + }); + } + + private static async handleRedirect(res: http.IncomingMessage, url: string, cookies: { [key: string]: string; }): Promise<{ [key: string]: string; }> { + if (res.statusCode === 301 || res.statusCode === 302) { + if (res.headers.location) { + const redirectUrl = new URL(res.headers.location, url); + const redirectCookies = await this.HttpsGetCookies(redirectUrl.href); + return { ...cookies, ...redirectCookies }; + } + } + return cookies; + } + + private static extractCookies(setCookieHeaders: string[], cookies: { [key: string]: string; }) { + setCookieHeaders.forEach((cookie) => { + const parts = cookie.split(';')[0]?.split('='); + if (parts) { + const key = parts[0]; + const value = parts[1]; + if (key && value && key.length > 0 && value.length > 0) { + cookies[key] = value; + } + } + }); + } + + static async HttpGetJson(url: string, method: string = 'GET', data?: any, headers: { + [key: string]: string; + } = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5): Promise { + const option = new URL(url); + const protocol = url.startsWith('https://') ? https : http; + const options = { + hostname: option.hostname, + port: option.port, + path: option.pathname + option.search, + method, + headers, + }; + + return new Promise((resolve, reject) => { + const req = protocol.request(options, (res: http.IncomingMessage) => { + if ((res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307 || res.statusCode === 308) && res.headers.location) { + if (maxRedirects <= 0) { + reject(new Error('Too many redirects')); + return; + } + const redirectUrl = new URL(res.headers.location, url).href; + this.HttpGetJson(redirectUrl, method, data, headers, isJsonRet, isArgJson, maxRedirects - 1) + .then(resolve) + .catch(reject); + return; + } + + let responseBody = ''; + res.on('data', (chunk: string | Buffer) => { responseBody += chunk.toString(); }); + + res.on('end', () => { + try { + if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) { + if (isJsonRet) { + resolve(JSON.parse(responseBody) as T); + } else { + resolve(responseBody as T); + } + } else { + reject(new Error(`Unexpected status code: ${res.statusCode}`)); + } + } catch (parseError: any) { + reject(new Error(parseError.message)); + } + }); + }); + + req.on('error', (error: Error) => reject(error)); + if (method === 'POST' || method === 'PUT' || method === 'PATCH') { + req.write(isArgJson ? JSON.stringify(data) : data); + } + req.end(); + }); + } + + static async HttpGetText(url: string, method: string = 'GET', data?: any, headers: { [key: string]: string; } = {}) { + return this.HttpGetJson(url, method, data, headers, false, false); + } +} \ No newline at end of file diff --git a/packages/core/src/onebot/actions/group-info.ts b/packages/core/src/onebot/actions/group-info.ts index 3f5efd9e..bbe79a03 100644 --- a/packages/core/src/onebot/actions/group-info.ts +++ b/packages/core/src/onebot/actions/group-info.ts @@ -1,6 +1,7 @@ import type { ApiHandler, ApiActionContext } from '../api-handler'; -import { asNumber, asBoolean } from '../api-handler'; +import { asNumber, asBoolean, asString } from '../api-handler'; import { RETCODE, failedResponse, okResponse } from '../types'; +import { WebHonorType } from '@/bridge/web/group-honor'; export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('get_group_list', async (params) => { @@ -54,11 +55,27 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('get_group_honor_info', async (params) => { const groupId = asNumber(params.group_id); - if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - return okResponse({ - group_id: groupId, current_talkative: null, talkative_list: [], - performer_list: [], legend_list: [], strong_newbie_list: [], emotion_list: [], - }); + const typeStr = asString(params.type) || 'all'; + + if (!groupId) { + return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); + } + + if (!ctx.getGroupHonorInfo) { + return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + } + + const typeValues = Object.values(WebHonorType) as string[]; + if (!typeValues.includes(typeStr)) { + return failedResponse(RETCODE.BAD_REQUEST, `invalid type, must be one of ${typeValues.join(', ')}`); + } + + try { + const honorInfo = await ctx.getGroupHonorInfo(groupId, typeStr as WebHonorType); + return okResponse(honorInfo); + } catch (e) { + return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`); + } }); h.registerAction('get_group_system_msg', async () => { diff --git a/packages/core/src/onebot/api-handler.ts b/packages/core/src/onebot/api-handler.ts index 0266d6e3..fe9cdea4 100644 --- a/packages/core/src/onebot/api-handler.ts +++ b/packages/core/src/onebot/api-handler.ts @@ -10,6 +10,8 @@ import { register as registerGroupFile } from './actions/group-file'; import { register as registerRequest } from './actions/request'; import { register as registerExtended } from './actions/extended'; +import { WebHonorType } from '@/bridge/web/group-honor'; + export interface MessageSendResult { messageId: number; meta?: MessageMeta; @@ -80,6 +82,8 @@ export interface ApiActionContext { setMsgEmojiLike?: (messageId: number, emojiId: string, set: boolean) => Promise; markGroupMsgAsRead?: (groupId: number, sequence: number) => Promise; markPrivateMsgAsRead?: (userId: number, sequence: number) => Promise; + // Web + getGroupHonorInfo?: (groupId: number, type: WebHonorType | string) => Promise; } type ActionHandler = (params: JsonObject) => Promise; diff --git a/packages/core/src/onebot/instance-context.ts b/packages/core/src/onebot/instance-context.ts index 00320639..baf6d2bd 100644 --- a/packages/core/src/onebot/instance-context.ts +++ b/packages/core/src/onebot/instance-context.ts @@ -8,6 +8,7 @@ import { parseMessage } from './message-parser'; import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id'; import type { JsonObject, JsonValue, MessageMeta } from './types'; import { createLogger } from '../utils/logger'; +import {WebHonorType} from "@/bridge/web/group-honor"; const log = createLogger('OneBot'); @@ -121,6 +122,8 @@ export function buildApiContext(ref: InstanceRef): ApiActionContext { }, markGroupMsgAsRead: (groupId: number, sequence: number) => bridge.markGroupMsgAsRead(groupId, sequence), markPrivateMsgAsRead: (userId: number, sequence: number) => bridge.markPrivateMsgAsRead(userId, sequence), + // web + getGroupHonorInfo: (groupId: number, type: WebHonorType | string)=> bridge.getGroupHonorInfo(groupId, type) }; }