feat: 引入web方法,实现group honor
This commit is contained in:
1 parent
99c74b4a66
commit
4a51e3d686
8 files changed
+349
-8
No files matched your search
@@ -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<any>(
|
||||
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<any>(
|
||||
bridge,
|
||||
'OidbSvcTrpcTcp.0x102a_0',
|
||||
0x102A,
|
||||
0,
|
||||
{ domainList },
|
||||
OidbGetPskeyReqSchema,
|
||||
OidbGetPskeyRespSchema
|
||||
);
|
||||
|
||||
const domainPskeyMap = new Map<string, string>();
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -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<void> { return markGroupMsgAsRead_(this, groupId, sequence); }
|
||||
async markPrivateMsgAsRead(userId: number, sequence: number): Promise<void> { return markPrivateMsgAsRead_(this, userId, sequence); }
|
||||
async setFriendRemark(userId: number, remark: string): Promise<void> { return setFriendRemark_(this, userId, remark); }
|
||||
async getGroupHonorInfo(groupId: number, type: WebHonorType | string): Promise<any> {
|
||||
return getGroupHonorInfo_(this, groupId, type);
|
||||
}
|
||||
async fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { return fetchGroupFileCount_(this, groupId); }
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
} 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;
|
||||
|
||||
@@ -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, string>): string {
|
||||
return Object.entries(cookieObject)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
async function fetchHonorData(cookieObject: Record<string, string>, 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<string, string>, 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 [];
|
||||
}
|
||||
}
|
||||
@@ -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<T>(url: string, method: string = 'GET', data?: any, headers: {
|
||||
[key: string]: string;
|
||||
} = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5): Promise<T> {
|
||||
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<T>(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<string>(url, method, data, headers, false, false);
|
||||
}
|
||||
}
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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<void>;
|
||||
markGroupMsgAsRead?: (groupId: number, sequence: number) => Promise<void>;
|
||||
markPrivateMsgAsRead?: (userId: number, sequence: number) => Promise<void>;
|
||||
// Web
|
||||
getGroupHonorInfo?: (groupId: number, type: WebHonorType | string) => Promise<any>;
|
||||
}
|
||||
|
||||
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
|
||||
|
||||
@@ -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)
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user