Compare commits

..

33 Commits

Author SHA1 Message Date
idranme
8b89fd7a0b Merge pull request #479 from LLOneBot/dev
release: 4.0.12
2024-10-18 21:16:46 +08:00
idranme
8239e9a243 Merge pull request #477 from LLOneBot/dev
release: 4.0.11
2024-10-16 11:44:43 +08:00
idranme
951afea794 Merge pull request #475 from LLOneBot/dev
release: 4.0.10
2024-10-15 21:09:42 +08:00
idranme
a4beeba528 Merge pull request #474 from LLOneBot/dev
release: 4.0.9
2024-10-13 23:51:30 +08:00
idranme
9b32140f87 Merge pull request #470 from LLOneBot/dev
release: 4.0.8
2024-10-13 16:36:12 +08:00
idranme
e10a67ce05 Merge pull request #468 from LLOneBot/dev
release: 4.0.7
2024-10-13 01:30:01 +08:00
idranme
e07c06f3e9 Merge pull request #467 from LLOneBot/dev
...
2024-10-13 01:17:06 +08:00
idranme
0d8d3ac24f Merge pull request #466 from LLOneBot/dev
release: 4.0.6
2024-10-13 00:48:36 +08:00
idranme
9d0f9e7096 Merge pull request #465 from LLOneBot/dev
release: 4.0.5
2024-10-12 23:58:07 +08:00
idranme
e988908784 Merge pull request #463 from LLOneBot/dev
release: 4.0.4
2024-10-11 18:22:37 +08:00
idranme
b40c81c5cb Merge pull request #462 from LLOneBot/dev
release: 4.0.3
2024-10-11 00:52:33 +08:00
idranme
457ffc0922 Merge pull request #461 from LLOneBot/dev
release: 4.0.2
2024-10-08 21:26:39 +08:00
idranme
41822eb052 Merge pull request #460 from LLOneBot/dev
release: 4.0.1
2024-10-08 20:46:09 +08:00
idranme
0bc6e23343 Merge pull request #459 from LLOneBot/dev
release: 4.0.0
2024-10-07 20:26:59 +08:00
idranme
9ec09c6eee Merge pull request #457 from LLOneBot/dev
release: 3.34.1
2024-10-03 15:18:47 +08:00
idranme
0876e4645f Merge pull request #456 from LLOneBot/dev
release: 3.34.0
2024-10-01 21:32:24 +08:00
idranme
36d990e328 Merge pull request #452 from LLOneBot/dev
release: 3.33.10
2024-09-28 14:40:11 +08:00
idranme
d5875c9e5b Merge pull request #451 from LLOneBot/dev
release: 3.33.9
2024-09-27 16:53:44 +08:00
idranme
a58fb31f8e Merge pull request #448 from LLOneBot/dev
release: 3.33.8
2024-09-26 12:57:16 +08:00
idranme
f9270c38cf Merge pull request #444 from LLOneBot/dev
release: 3.33.7
2024-09-25 14:59:34 +08:00
idranme
e5ab6134cd Merge pull request #441 from LLOneBot/dev
release: 3.33.6
2024-09-23 23:43:50 +08:00
idranme
24f09d485e Merge pull request #438 from LLOneBot/dev
release: 3.33.5
2024-09-22 21:31:55 +08:00
idranme
f400d43b8a Merge pull request #436 from LLOneBot/dev
release: 3.33.4
2024-09-21 23:29:47 +08:00
idranme
1c6364d98f Merge pull request #435 from LLOneBot/dev
release: 3.33.3
2024-09-21 21:52:54 +08:00
idranme
ac07c98ae1 Merge pull request #434 from LLOneBot/dev
release: 3.33.2
2024-09-20 23:00:09 +08:00
idranme
6c66dab3dc Merge pull request #433 from LLOneBot/dev
release: 3.33.1
2024-09-19 18:31:01 +08:00
idranme
936b1d911c Merge pull request #428 from LLOneBot/dev
release: 3.33.0
2024-09-18 20:59:57 +08:00
idranme
1876dd29ac Merge pull request #423 from LLOneBot/dev
release: 3.32.8
2024-09-17 11:59:57 +08:00
idranme
64c5eb6c04 Merge pull request #422 from LLOneBot/dev
release: 3.32.7
2024-09-16 20:48:15 +08:00
idranme
476d498e44 Merge pull request #417 from LLOneBot/dev
release: 3.32.6
2024-09-15 17:48:35 +08:00
idranme
b03bcf9a7c Merge pull request #415 from LLOneBot/dev
release: 3.32.5
2024-09-13 18:59:37 +08:00
idranme
9284fc7e8a Merge pull request #413 from LLOneBot/dev
3.32.4
2024-09-12 18:14:23 +08:00
idranme
1d63473a04 Merge pull request #411 from LLOneBot/dev
3.32.3
2024-09-11 20:52:52 +08:00
49 changed files with 1287 additions and 7919 deletions

View File

@@ -4,16 +4,12 @@
"name": "LLOneBot", "name": "LLOneBot",
"slug": "LLOneBot", "slug": "LLOneBot",
"description": "实现 OneBot 11 和 Satori 协议,用于 QQ 机器人开发", "description": "实现 OneBot 11 和 Satori 协议,用于 QQ 机器人开发",
"version": "4.1.3", "version": "4.0.12",
"icon": "./icon.webp", "icon": "./icon.webp",
"authors": [ "authors": [
{ {
"name": "linyuchen", "name": "linyuchen",
"link": "https://github.com/linyuchen" "link": "https://github.com/linyuchen"
},
{
"name": "idranme",
"link": "https://github.com/idranme"
} }
], ],
"repository": { "repository": {

View File

@@ -12,7 +12,7 @@
"deploy-win": "cmd /c \"xcopy /C /S /Y dist\\* %LITELOADERQQNT_PROFILE%\\plugins\\LLOneBot\\\"", "deploy-win": "cmd /c \"xcopy /C /S /Y dist\\* %LITELOADERQQNT_PROFILE%\\plugins\\LLOneBot\\\"",
"format": "prettier -cw .", "format": "prettier -cw .",
"check": "tsc", "check": "tsc",
"compile:proto": "pbjs --no-create --no-convert --no-delimited --no-verify -t static-module -w es6 -p src/ntqqapi/proto -o src/ntqqapi/proto/compiled.js profileLikeTip.proto groupNotify.proto message.proto richMedia.proto && pbts -o src/ntqqapi/proto/compiled.d.ts src/ntqqapi/proto/compiled.js" "compile:proto": "pbjs --no-create --no-convert --no-encode --no-verify -t static-module -w es6 -p src/ntqqapi/proto -o src/ntqqapi/proto/compiled.js systemMessage.proto profileLikeTip.proto groupMemberIncrease.proto && pbts -o src/ntqqapi/proto/compiled.d.ts src/ntqqapi/proto/compiled.js"
}, },
"author": "", "author": "",
"license": "MIT", "license": "MIT",
@@ -25,10 +25,11 @@
"cors": "^2.8.5", "cors": "^2.8.5",
"cosmokit": "^1.6.3", "cosmokit": "^1.6.3",
"express": "^5.0.1", "express": "^5.0.1",
"fast-xml-parser": "^4.5.0",
"fluent-ffmpeg": "^2.1.3", "fluent-ffmpeg": "^2.1.3",
"minato": "^3.6.0", "minato": "^3.6.0",
"protobufjs": "^7.4.0", "protobufjs": "^7.4.0",
"silk-wasm": "^3.6.3", "silk-wasm": "^3.6.1",
"ts-case-convert": "^2.1.0", "ts-case-convert": "^2.1.0",
"ws": "^8.18.0" "ws": "^8.18.0"
}, },
@@ -42,8 +43,8 @@
"electron-vite": "^2.3.0", "electron-vite": "^2.3.0",
"protobufjs-cli": "^1.1.3", "protobufjs-cli": "^1.1.3",
"typescript": "^5.6.3", "typescript": "^5.6.3",
"vite": "^5.4.10 ", "vite": "^5.4.9",
"vite-plugin-cp": "^4.0.8" "vite-plugin-cp": "^4.0.8"
}, },
"packageManager": "yarn@4.5.1" "packageManager": "yarn@4.5.0"
} }

View File

@@ -44,7 +44,6 @@ export class ConfigUtil {
token: '' token: ''
} }
const defaultConfig: Config = { const defaultConfig: Config = {
enableLLOB: true,
satori: satoriDefault, satori: satoriDefault,
ob11: ob11Default, ob11: ob11Default,
heartInterval: 60000, heartInterval: 60000,

View File

@@ -28,7 +28,6 @@ export interface SatoriConfig {
} }
export interface Config { export interface Config {
enableLLOB: boolean
satori: SatoriConfig satori: SatoriConfig
ob11: OB11Config ob11: OB11Config
token?: string token?: string
@@ -50,6 +49,8 @@ export interface Config {
/** @deprecated */ /** @deprecated */
wsPort?: string wsPort?: string
/** @deprecated */ /** @deprecated */
enableLLOB?: boolean
/** @deprecated */
reportSelfMessage?: boolean reportSelfMessage?: boolean
} }

View File

@@ -122,11 +122,8 @@ export async function uri2local(ctx: Context, uri: string, needExt?: boolean): P
const { type } = checkUriType(uri) const { type } = checkUriType(uri)
if (type === FileUriType.FileURL) { if (type === FileUriType.FileURL) {
const fileUri = uri.replace('%', '%25').replace('#', '%23') const filePath = fileURLToPath(uri)
const filePath = fileURLToPath(fileUri)
const fileName = path.basename(filePath) const fileName = path.basename(filePath)
// console.log('fileURLToPath', filePath)
// console.log('fileName', fileName)
return { success: true, errMsg: '', fileName, path: filePath, isLocal: true } return { success: true, errMsg: '', fileName, path: filePath, isLocal: true }
} }

View File

@@ -171,7 +171,7 @@ function onLoad() {
log(arg) log(arg)
}) })
const intervalId = setInterval(async () => { const intervalId = setInterval(() => {
const self = Object.assign(selfInfo, { const self = Object.assign(selfInfo, {
uin: globalThis.authData?.uin, uin: globalThis.authData?.uin,
uid: globalThis.authData?.uid, uid: globalThis.authData?.uid,
@@ -182,16 +182,6 @@ function onLoad() {
log('process pid', process.pid) log('process pid', process.pid)
const config = getConfigUtil().getConfig() const config = getConfigUtil().getConfig()
if (config.enableLLOB && (config.satori.enable || config.ob11.enable)) {
startHook()
await ctx.sleep(600)
} else {
llonebotError.otherError = 'LLOneBot 未启动'
log('LLOneBot 开关设置为关闭,不启动 LLOneBot')
return
}
ctx.plugin(Log, { ctx.plugin(Log, {
enable: config.log!, enable: config.log!,
filename: logFileName filename: logFileName
@@ -225,7 +215,7 @@ function onLoad() {
started = true started = true
llonebotError.otherError = '' llonebotError.otherError = ''
} }
}, 500) }, 600)
} }
// 创建窗口时触发 // 创建窗口时触发
@@ -234,6 +224,7 @@ function onBrowserWindowCreated(window: BrowserWindow) {
try { try {
onLoad() onLoad()
startHook()
} catch (e) { } catch (e) {
console.log(e) console.log(e)
} }

View File

@@ -16,7 +16,7 @@ import path from 'node:path'
import { existsSync } from 'node:fs' import { existsSync } from 'node:fs'
import { ReceiveCmdS } from '../hook' import { ReceiveCmdS } from '../hook'
import { RkeyManager } from '@/ntqqapi/helper/rkey' import { RkeyManager } from '@/ntqqapi/helper/rkey'
import { RichMediaDownloadCompleteNotify, RichMediaUploadCompleteNotify, RMBizType, Peer } from '@/ntqqapi/types/msg' import { RichMediaDownloadCompleteNotify, Peer } from '@/ntqqapi/types/msg'
import { calculateFileMD5 } from '@/common/utils/file' import { calculateFileMD5 } from '@/common/utils/file'
import { copyFile, stat, unlink } from 'node:fs/promises' import { copyFile, stat, unlink } from 'node:fs/promises'
import { Time } from 'cosmokit' import { Time } from 'cosmokit'
@@ -43,7 +43,7 @@ export class NTQQFileApi extends Service {
msgId, msgId,
elemId: elementId, elemId: elementId,
videoCodecFormat: 0, videoCodecFormat: 0,
exParams: { params: {
downSourceType: 1, downSourceType: 1,
triggerType: 1 triggerType: 1
} }
@@ -211,28 +211,6 @@ export class NTQQFileApi extends Service {
] ]
) )
} }
async uploadRMFileWithoutMsg(filePath: string, bizType: RMBizType, peerUid: string) {
const data = await invoke<{
notifyInfo: RichMediaUploadCompleteNotify
}>(
'nodeIKernelRichMediaService/uploadRMFileWithoutMsg',
[{
params: {
filePath,
bizType,
peerUid,
useNTV2: true
}
}],
{
cbCmd: ReceiveCmdS.MEDIA_UPLOAD_COMPLETE,
cmdCB: payload => payload.notifyInfo.filePath === filePath,
timeout: 10 * Time.second,
}
)
return data.notifyInfo
}
} }
export class NTQQFileCacheApi extends Service { export class NTQQFileCacheApi extends Service {

View File

@@ -83,7 +83,7 @@ export class NTQQGroupApi extends Service {
} }
async getGroupIgnoreNotifies() { async getGroupIgnoreNotifies() {
await this.getSingleScreenNotifies(false, 14) await this.getSingleScreenNotifies(14)
return await this.ctx.ntWindowApi.openWindow<GeneralCallResult & GroupNotifies>( return await this.ctx.ntWindowApi.openWindow<GeneralCallResult & GroupNotifies>(
NTQQWindows.GroupNotifyFilterWindow, NTQQWindows.GroupNotifyFilterWindow,
[], [],
@@ -91,18 +91,17 @@ export class NTQQGroupApi extends Service {
) )
} }
async getSingleScreenNotifies(doubt: boolean, number: number, startSeq = '') { async getSingleScreenNotifies(number: number, startSeq = '') {
await invoke(ReceiveCmdS.GROUP_NOTIFY, [], { registerEvent: true }) invoke(ReceiveCmdS.GROUP_NOTIFY, [], { registerEvent: true })
const data = await invoke<GroupNotifies>( return (await invoke<GroupNotifies>(
'nodeIKernelGroupService/getSingleScreenNotifies', 'nodeIKernelGroupService/getSingleScreenNotifies',
[{ doubt, startSeq, number }], [{ doubt: false, startSeq, number }],
{ {
cbCmd: ReceiveCmdS.GROUP_NOTIFY, cbCmd: ReceiveCmdS.GROUP_NOTIFY,
afterFirstCmd: false, afterFirstCmd: false,
} }
) )).notifies
return data.notifies
} }
async handleGroupRequest(flag: string, operateType: GroupRequestOperateTypes, reason?: string) { async handleGroupRequest(flag: string, operateType: GroupRequestOperateTypes, reason?: string) {
@@ -110,9 +109,8 @@ export class NTQQGroupApi extends Service {
const groupCode = flagitem[0] const groupCode = flagitem[0]
const seq = flagitem[1] const seq = flagitem[1]
const type = parseInt(flagitem[2]) const type = parseInt(flagitem[2])
const doubt = flagitem[3] === '1'
return await invoke(NTMethod.HANDLE_GROUP_REQUEST, [{ return await invoke(NTMethod.HANDLE_GROUP_REQUEST, [{
doubt, doubt: false,
operateMsg: { operateMsg: {
operateType, operateType,
targetMsg: { targetMsg: {
@@ -327,18 +325,4 @@ export class NTQQGroupApi extends Service {
) )
return data.infos return data.infos
} }
async getGroupFileCount(groupId: string) {
return await invoke(
'nodeIKernelRichMediaService/batchGetGroupFileCount',
[{ groupIds: [groupId] }]
)
}
async getGroupFileSpace(groupId: string) {
return await invoke(
'nodeIKernelRichMediaService/getGroupSpace',
[{ groupId }]
)
}
} }

View File

@@ -153,17 +153,7 @@ export class NTQQMsgApi extends Service {
afterFirstCmd: false, afterFirstCmd: false,
cmdCB: payload => { cmdCB: payload => {
for (const msgRecord of payload.msgList) { for (const msgRecord of payload.msgList) {
if ( if (msgRecord.peerUid === destPeer.peerUid && msgRecord.senderUid === selfUid) {
msgRecord.msgType === 11 &&
msgRecord.subMsgType === 7 &&
msgRecord.peerUid === destPeer.peerUid &&
msgRecord.senderUid === selfUid
) {
const element = msgRecord.elements[0]
const data = JSON.parse(element.arkElement!.bytesData)
if (data.app !== 'com.tencent.multimsg' || !data.meta.detail.resid) {
continue
}
return true return true
} }
} }
@@ -171,12 +161,20 @@ export class NTQQMsgApi extends Service {
} }
} }
) )
return data.msgList.find(msgRecord => { for (const msg of data.msgList) {
const { arkElement } = msgRecord.elements[0] const arkElement = msg.elements.find(ele => ele.arkElement)
if (arkElement?.bytesData.includes('com.tencent.multimsg')) { if (!arkElement) {
return true continue
} }
})! const forwardData = JSON.parse(arkElement.arkElement!.bytesData)
if (forwardData.app !== 'com.tencent.multimsg') {
continue
}
if (msg.peerUid === destPeer.peerUid && msg.senderUid === selfUid) {
return msg
}
}
throw new Error('转发消息超时')
} }
async getSingleMsg(peer: Peer, msgSeq: string) { async getSingleMsg(peer: Peer, msgSeq: string) {

View File

@@ -1,5 +1,5 @@
import { User, UserDetailInfoByUin, UserDetailInfoByUinV2, UserDetailInfo, UserDetailSource, ProfileBizType, SimpleInfo } from '../types' import { User, UserDetailInfoByUin, UserDetailInfoByUinV2, UserDetailInfo, UserDetailSource, ProfileBizType, SimpleInfo } from '../types'
import { invoke, NTClass } from '../ntcall' import { invoke } from '../ntcall'
import { getBuildVersion } from '@/common/utils' import { getBuildVersion } from '@/common/utils'
import { RequestUtil } from '@/common/utils/request' import { RequestUtil } from '@/common/utils/request'
import { isNullable, pick, Time } from 'cosmokit' import { isNullable, pick, Time } from 'cosmokit'
@@ -173,7 +173,7 @@ export class NTQQUserApi extends Service {
async getUinByUidV2(uid: string) { async getUinByUidV2(uid: string) {
let uin = (await invoke('nodeIKernelGroupService/getUinByUids', [{ uidList: [uid] }])).uins.get(uid) let uin = (await invoke('nodeIKernelGroupService/getUinByUids', [{ uidList: [uid] }])).uins.get(uid)
if (uin && uin !== '0') return uin if (uin) return uin
uin = (await invoke('nodeIKernelProfileService/getUinByUid', [{ callFrom: 'FriendsServiceImpl', uid: [uid] }])).get(uid) uin = (await invoke('nodeIKernelProfileService/getUinByUid', [{ callFrom: 'FriendsServiceImpl', uid: [uid] }])).get(uid)
if (uin) return uin if (uin) return uin
uin = (await invoke('nodeIKernelUixConvertService/getUin', [{ uids: [uid] }])).uinInfo.get(uid) uin = (await invoke('nodeIKernelUixConvertService/getUin', [{ uids: [uid] }])).uinInfo.get(uid)
@@ -288,14 +288,4 @@ export class NTQQUserApi extends Service {
) )
return data.response.robotUinRanges return data.response.robotUinRanges
} }
async quitAccount() {
return await invoke(
'quitAccount',
[],
{
className: NTClass.BUSINESS_API,
}
)
}
} }

View File

@@ -16,7 +16,7 @@ import {
BuddyReqType, BuddyReqType,
GrayTipElementSubType GrayTipElementSubType
} from './types' } from './types'
import { selfInfo } from '../common/globalVars' import { selfInfo, llonebotError } from '../common/globalVars'
import { version } from '../version' import { version } from '../version'
import { invoke } from './ntcall' import { invoke } from './ntcall'
import { Native } from './native/index' import { Native } from './native/index'
@@ -29,7 +29,7 @@ declare module 'cordis' {
'nt/message-created': (input: RawMessage) => void 'nt/message-created': (input: RawMessage) => void
'nt/message-deleted': (input: RawMessage) => void 'nt/message-deleted': (input: RawMessage) => void
'nt/message-sent': (input: RawMessage) => void 'nt/message-sent': (input: RawMessage) => void
'nt/group-notify': (input: { notify: GroupNotify, doubt: boolean }) => void 'nt/group-notify': (input: GroupNotify) => void
'nt/friend-request': (input: FriendRequest) => void 'nt/friend-request': (input: FriendRequest) => void
'nt/group-member-info-updated': (input: { groupCode: string, members: GroupMember[] }) => void 'nt/group-member-info-updated': (input: { groupCode: string, members: GroupMember[] }) => void
'nt/system-message-created': (input: Uint8Array) => void 'nt/system-message-created': (input: Uint8Array) => void
@@ -47,6 +47,11 @@ class Core extends Service {
} }
public start() { public start() {
if (!this.config.ob11.enable && !this.config.satori.enable) {
llonebotError.otherError = 'LLOneBot 未启动'
this.ctx.logger.info('LLOneBot 开关设置为关闭,不启动 LLOneBot')
return
}
this.startTime = Date.now() this.startTime = Date.now()
this.registerListener() this.registerListener()
this.ctx.logger.info(`LLOneBot/${version}`) this.ctx.logger.info(`LLOneBot/${version}`)
@@ -197,8 +202,8 @@ class Core extends Service {
recallMsgIds.push(msg.msgId) recallMsgIds.push(msg.msgId)
this.ctx.parallel('nt/message-deleted', msg) this.ctx.parallel('nt/message-deleted', msg)
} else if (sentMsgIds.get(msg.msgId)) { } else if (sentMsgIds.get(msg.msgId)) {
if (msg.sendStatus === 2) {
sentMsgIds.delete(msg.msgId) sentMsgIds.delete(msg.msgId)
if (msg.sendStatus === 2) {
this.ctx.parallel('nt/message-sent', msg) this.ctx.parallel('nt/message-sent', msg)
} }
} }
@@ -218,7 +223,7 @@ class Core extends Service {
if (payload.unreadCount) { if (payload.unreadCount) {
let notifies: GroupNotify[] let notifies: GroupNotify[]
try { try {
notifies = await this.ctx.ntGroupApi.getSingleScreenNotifies(payload.doubt, payload.unreadCount) notifies = await this.ctx.ntGroupApi.getSingleScreenNotifies(payload.unreadCount)
} catch (e) { } catch (e) {
return return
} }
@@ -228,7 +233,7 @@ class Core extends Service {
continue continue
} }
groupNotifyIgnore.push(notify.seq) groupNotifyIgnore.push(notify.seq)
this.ctx.parallel('nt/group-notify', { notify, doubt: payload.doubt }) this.ctx.parallel('nt/group-notify', notify)
} }
} }
}) })

View File

@@ -70,7 +70,6 @@ export function startHook() {
delete hookApiCallbacks[callbackId] delete hookApiCallbacks[callbackId]
} }
} else if (args[2]) { } else if (args[2]) {
if (['IPC_DOWN_2', 'IPC_DOWN_3'].includes(args[0])) {
for (const receiveData of args[2]) { for (const receiveData of args[2]) {
for (const hook of receiveHooks.values()) { for (const hook of receiveHooks.values()) {
if (hook.method.includes(receiveData.cmdName)) { if (hook.method.includes(receiveData.cmdName)) {
@@ -79,7 +78,6 @@ export function startHook() {
} }
} }
} }
}
return target.apply(thisArg, args) return target.apply(thisArg, args)
} }
}) })

View File

@@ -3,15 +3,11 @@ import { Dict } from 'cosmokit'
import { getBuildVersion } from '@/common/utils/misc' import { getBuildVersion } from '@/common/utils/misc'
import { TEMP_DIR } from '@/common/globalVars' import { TEMP_DIR } from '@/common/globalVars'
import { copyFile } from 'fs/promises' import { copyFile } from 'fs/promises'
import { ChatType, Peer } from '../types'
import path from 'node:path' import path from 'node:path'
import addon from './external/crychic-win32-x64.node?asset' import addon from './external/crychic-win32-x64.node?asset'
export class Native { export class Native {
public activated = false
private crychic?: Dict private crychic?: Dict
private seq = 0
private cb: Map<number, Function> = new Map()
constructor(private ctx: Context) { constructor(private ctx: Context) {
ctx.on('ready', () => { ctx.on('ready', () => {
@@ -39,24 +35,12 @@ export class Native {
if (!this.checkVersion()) { if (!this.checkVersion()) {
return return
} }
const handler = async (name: string, ...e: unknown[]) => {
if (name === 'cb') {
this.cb.get(e[0] as number)?.(e[1])
}
}
try { try {
const fileName = path.basename(addon) const fileName = path.basename(addon)
const dest = path.join(TEMP_DIR, fileName) const dest = path.join(TEMP_DIR, fileName)
try {
await copyFile(addon, dest) await copyFile(addon, dest)
} catch (e) {
// resource busy or locked?
this.ctx.logger.warn(e)
}
this.crychic = require(dest) this.crychic = require(dest)
this.crychic!.setCryHandler(handler)
this.crychic!.init() this.crychic!.init()
this.activated = true
} catch (e) { } catch (e) {
this.ctx.logger.warn('crychic 加载失败', e) this.ctx.logger.warn('crychic 加载失败', e)
} }
@@ -73,27 +57,4 @@ export class Native {
this.crychic.sendGroupPoke(memberUin, groupCode) this.crychic.sendGroupPoke(memberUin, groupCode)
await this.ctx.ntMsgApi.fetchUnitedCommendConfig(['100243']) await this.ctx.ntMsgApi.fetchUnitedCommendConfig(['100243'])
} }
uploadForward(peer: Peer, transmit: Uint8Array) {
return new Promise<string>(async (resolve, reject) => {
if (!this.crychic) return
let groupCode = 0
const uid = peer.peerUid
const isGroup = peer.chatType === ChatType.Group
if (isGroup) {
groupCode = +uid
}
const seq = ++this.seq
this.cb.set(seq, (resid: string) => {
this.cb.delete(seq)
resolve(resid)
})
setTimeout(() => {
this.cb.delete(seq)
reject(new Error('fake forward timeout'))
}, 5000)
this.crychic.uploadForward(seq, isGroup, uid, groupCode, transmit)
await this.ctx.ntMsgApi.fetchUnitedCommendConfig(['100243'])
})
}
} }

View File

@@ -1,6 +1,6 @@
import { ipcMain } from 'electron' import { ipcMain } from 'electron'
import { hookApiCallbacks, registerReceiveHook, removeReceiveHook } from './hook' import { hookApiCallbacks, registerReceiveHook, removeReceiveHook } from './hook'
import { getBuildVersion, log } from '../common/utils' import { log } from '../common/utils/legacyLog'
import { randomUUID } from 'node:crypto' import { randomUUID } from 'node:crypto'
import { import {
GeneralCallResult, GeneralCallResult,
@@ -114,7 +114,7 @@ export function invoke<
M extends keyof NTService[S] & string = any M extends keyof NTService[S] & string = any
>(method: Extract<unknown, `${S}/${M}`> | string, args: unknown[], options: InvokeOptions<R> = {}) { >(method: Extract<unknown, `${S}/${M}`> | string, args: unknown[], options: InvokeOptions<R> = {}) {
const className = options.className ?? NTClass.NT_API const className = options.className ?? NTClass.NT_API
const channel = options.channel ?? getBuildVersion() >= 28788 ? NTChannel.IPC_UP_3 : NTChannel.IPC_UP_2 const channel = options.channel ?? NTChannel.IPC_UP_2
const timeout = options.timeout ?? 5000 const timeout = options.timeout ?? 5000
const afterFirstCmd = options.afterFirstCmd ?? true const afterFirstCmd = options.afterFirstCmd ?? true
let eventName = className + '-' + channel[channel.length - 1] let eventName = className + '-' + channel[channel.length - 1]

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,10 @@
syntax = "proto3";
package SysMsg;
// GroupChange?
message GroupMemberIncrease {
uint32 groupCode = 1;
string memberUid = 3;
uint32 type = 4; // 130:主动 131:被邀请
string adminUid = 5;
}

View File

@@ -1,14 +0,0 @@
syntax = "proto3";
package SysMsg;
message GroupMemberChange {
uint32 groupCode = 1;
string memberUid = 3;
uint32 type = 4; // 130:主动 131:被动
string adminUid = 5;
}
message GroupInvite {
uint32 groupCode = 1;
string operatorUid = 5;
}

View File

@@ -1,134 +0,0 @@
syntax = "proto3";
package Msg;
message RoutingHead {
optional uint64 fromUin = 1;
optional string fromUid = 2;
optional uint32 fromAppid = 3;
optional uint32 fromInstid = 4;
optional uint64 toUin = 5;
optional string toUid = 6;
optional C2c c2c = 7;
optional Group group = 8;
}
message C2c {
optional string friendName = 6;
}
message Group {
optional uint64 groupCode = 1;
optional uint32 groupType = 2;
optional uint64 groupInfoSeq = 3;
optional string groupCard = 4;
optional uint32 groupCardType = 5;
optional uint32 groupLevel = 6;
optional string groupName = 7;
optional string extGroupKeyInfo = 8;
optional uint32 msgFlag = 9;
}
message ContentHead {
optional uint64 msgType = 1;
optional uint64 subType = 2;
optional uint32 c2cCmd = 3;
optional uint64 random = 4;
optional uint64 msgSeq = 5;
optional uint64 msgTime = 6;
optional uint32 pkgNum = 7;
optional uint32 pkgIndex = 8;
optional uint32 divSeq = 9;
optional uint32 autoReply = 10;
optional uint64 ntMsgSeq = 11;
optional uint64 msgUid = 12;
optional ContentHeadField15 field15 = 15;
}
message ContentHeadField15 {
optional uint32 field1 = 1;
optional uint32 field2 = 2;
optional uint32 field3 = 3;
optional string field4 = 4;
optional string field5 = 5;
}
message Message {
optional RoutingHead routingHead = 1;
optional ContentHead contentHead = 2;
optional MessageBody body = 3;
}
message MessageBody {
optional RichText richText = 1;
optional bytes msgContent = 2;
optional bytes msgEncryptContent = 3;
}
message RichText {
optional Attr attr = 1;
repeated Elem elems = 2;
}
message Elem {
optional Text text = 1;
optional Face face = 2;
optional LightAppElem lightApp = 51;
optional CommonElem commonElem = 53;
}
message Text {
optional string str = 1;
optional string link = 2;
optional bytes attr6Buf = 3;
optional bytes attr7Buf = 4;
optional bytes buf = 11;
optional bytes pbReserve = 12;
}
message Face {
optional uint32 index = 1;
optional bytes old = 2;
optional bytes buf = 11;
}
message LightAppElem {
optional bytes data = 1;
optional bytes msgResid = 2;
}
message CommonElem {
required uint32 serviceType = 1;
optional bytes pbElem = 2;
optional uint32 businessType = 3;
}
message Attr {
optional int32 codePage = 1;
optional int32 time = 2;
optional int32 random = 3;
optional int32 color = 4;
optional int32 size = 5;
optional int32 effect = 6;
optional int32 charSet = 7;
optional int32 pitchAndFamily = 8;
optional string fontName = 9;
optional bytes reserveData = 10;
}
message MarkdownElem {
string content = 1;
}
message PbMultiMsgItem {
string fileName = 1;
PbMultiMsgNew buffer = 2;
}
message PbMultiMsgNew {
repeated Message msg = 1;
}
message PbMultiMsgTransmit {
repeated Message msg = 1;
repeated PbMultiMsgItem pbItemList = 2;
}

View File

@@ -1,76 +0,0 @@
syntax = "proto3";
package RichMedia;
message MsgInfo {
repeated MsgInfoBody msgInfoBody = 1;
ExtBizInfo extBizInfo = 2;
}
message MsgInfoBody {
IndexNode index = 1;
PicInfo pic = 2;
bool fileExist = 5;
}
message IndexNode {
FileInfo info = 1;
string fileUuid = 2;
uint32 storeID = 3;
uint32 uploadTime = 4;
uint32 expire = 5;
uint32 type = 6; //0
}
message FileInfo {
uint32 fileSize = 1;
string md5HexStr = 2;
string sha1HexStr = 3;
string fileName = 4;
FileType fileType = 5;
uint32 width = 6;
uint32 height = 7;
uint32 time = 8;
uint32 original = 9;
}
message FileType {
uint32 type = 1;
uint32 picFormat = 2;
uint32 videoFormat = 3;
uint32 pttFormat = 4;
}
message PicInfo {
string urlPath = 1;
PicUrlExtParams ext = 2;
string domain = 3;
}
message PicUrlExtParams {
string originalParam = 1;
string bigParam = 2;
string thumbParam = 3;
}
message ExtBizInfo {
PicExtBizInfo pic = 1;
VideoExtBizInfo video = 2;
uint32 busiType = 10;
}
message PicExtBizInfo {
uint32 bizType = 1;
string summary = 2;
}
message VideoExtBizInfo {
bytes pbReserve = 3;
}
message PicFileIdInfo {
bytes sha1 = 2;
uint32 size = 3;
uint32 appid = 4;
uint32 time = 5;
uint32 expire = 10;
}

View File

@@ -0,0 +1,29 @@
syntax = "proto3";
package SysMsg;
message SystemMessage {
repeated SystemMessageHeader header = 1;
repeated SystemMessageMsgSpec msgSpec = 2;
SystemMessageBodyWrapper bodyWrapper = 3;
}
message SystemMessageHeader {
uint32 peerUin = 1;
//string peerUid = 2;
uint32 uin = 5;
optional string uid = 6;
}
message SystemMessageMsgSpec {
uint32 msgType = 1;
optional uint32 subType = 2;
optional uint32 subSubType = 3;
uint32 msgSeq = 5;
uint32 time = 6;
//uint64 msgId = 12;
optional uint32 other = 13;
}
message SystemMessageBodyWrapper {
bytes body = 2;
}

View File

@@ -13,7 +13,7 @@ export interface NodeIKernelBuddyService {
}[] }[]
}> }>
setBuddyRemark(arg: unknown): void setBuddyRemark(uid: number, remark: string): void
isBuddy(uid: string): boolean isBuddy(uid: string): boolean

View File

@@ -39,21 +39,5 @@ export interface NodeIKernelRichMediaService {
failFileIdList: Array<unknown> failFileIdList: Array<unknown>
} }
}> }>
batchGetGroupFileCount(groupIds: string[]): Promise<GeneralCallResult & {
groupCodes: string[]
groupFileCounts: number[]
}>
getGroupSpace(groupId: string): Promise<GeneralCallResult & {
groupSpaceResult: {
retCode: number
retMsg: string
clientWording: string
totalSpace: string
usedSpace: string
allUpload: boolean
}
}>
} }

View File

@@ -80,7 +80,7 @@ export interface SendVideoElement {
export interface SendArkElement { export interface SendArkElement {
elementType: ElementType.Ark elementType: ElementType.Ark
elementId: '' elementId: ''
arkElement: Partial<ArkElement> arkElement: ArkElement
} }
export type SendMessageElement = export type SendMessageElement =
@@ -587,31 +587,3 @@ export interface GetFileListParam {
showOnlinedocFolder: number showOnlinedocFolder: number
folderId?: string folderId?: string
} }
export interface RichMediaUploadCompleteNotify {
fileId: string
fileDownType: number
filePath: string
totalSize: string
trasferStatus: number
commonFileInfo: {
uuid: string
fileName: string
fileSize: string
md5: string
sha: string
}
}
export enum RMBizType {
Unknown,
C2CFile,
GroupFile,
C2CPic,
GroupPic,
DiscPic,
C2CVideo,
GroupVideo,
C2CPtt,
GroupPtt,
}

View File

@@ -1,8 +1,7 @@
export enum Sex { export enum Sex {
Unknown = 0, male = 0,
Male = 1, female = 2,
Female = 2, unknown = 255,
Hidden = 255
} }
export interface QQLevel { export interface QQLevel {
@@ -102,7 +101,7 @@ export interface BaseInfo {
birthday_month: number birthday_month: number
birthday_day: number birthday_day: number
age: number age: number
sex: Sex sex: number
eMail: string eMail: string
phoneNum: string phoneNum: string
categoryId: number categoryId: number

View File

@@ -23,8 +23,8 @@ interface FileResponse {
export class DownloadFile extends BaseAction<Payload, FileResponse> { export class DownloadFile extends BaseAction<Payload, FileResponse> {
actionName = ActionName.GoCQHTTP_DownloadFile actionName = ActionName.GoCQHTTP_DownloadFile
payloadSchema = Schema.object({ payloadSchema = Schema.object({
url: Schema.string(), url: String,
base64: Schema.string(), base64: String,
headers: Schema.union([String, Schema.array(String)]) headers: Schema.union([String, Schema.array(String)])
}) })

View File

@@ -1,32 +0,0 @@
import { BaseAction, Schema } from '../BaseAction'
import { ActionName } from '../types'
interface Payload {
group_id: number | string
}
interface Response {
file_count: number
limit_count: number
used_space: number
total_space: number
}
export class GetGroupFileSystemInfo extends BaseAction<Payload, Response> {
actionName = ActionName.GoCQHTTP_GetGroupFileSystemInfo
payloadSchema = Schema.object({
group_id: Schema.union([Number, String]).required()
})
async _handle(payload: Payload) {
const groupId = payload.group_id.toString()
const { groupFileCounts } = await this.ctx.ntGroupApi.getGroupFileCount(groupId)
const { groupSpaceResult } = await this.ctx.ntGroupApi.getGroupFileSpace(groupId)
return {
file_count: groupFileCounts[0],
limit_count: 10000,
used_space: +groupSpaceResult.usedSpace,
total_space: +groupSpaceResult.totalSpace,
}
}
}

View File

@@ -28,7 +28,7 @@ export class GetGroupSystemMsg extends BaseAction<void, Response> {
actionName = ActionName.GoCQHTTP_GetGroupSystemMsg actionName = ActionName.GoCQHTTP_GetGroupSystemMsg
async _handle() { async _handle() {
const singleScreenNotifies = await this.ctx.ntGroupApi.getSingleScreenNotifies(false, 10) const singleScreenNotifies = await this.ctx.ntGroupApi.getSingleScreenNotifies(10)
const data: Response = { invited_requests: [], join_requests: [] } const data: Response = { invited_requests: [], join_requests: [] }
for (const notify of singleScreenNotifies) { for (const notify of singleScreenNotifies) {
if (notify.type == 1) { if (notify.type == 1) {

View File

@@ -1,13 +1,11 @@
import { unlink } from 'node:fs/promises' import { unlink } from 'node:fs/promises'
import { OB11MessageData, OB11MessageNode } from '../../types' import { OB11MessageNode } from '../../types'
import { ActionName } from '../types' import { ActionName } from '../types'
import { BaseAction, Schema } from '../BaseAction' import { BaseAction, Schema } from '../BaseAction'
import { Peer } from '@/ntqqapi/types/msg' import { Peer } from '@/ntqqapi/types/msg'
import { ChatType, ElementType, RawMessage, SendMessageElement } from '@/ntqqapi/types' import { ChatType, ElementType, RawMessage, SendMessageElement } from '@/ntqqapi/types'
import { selfInfo } from '@/common/globalVars' import { selfInfo } from '@/common/globalVars'
import { message2List, createSendElements, sendMsg, createPeer, CreatePeerMode } from '../../helper/createMessage' import { convertMessage2List, createSendElements, sendMsg, createPeer, CreatePeerMode } from '../../helper/createMessage'
import { MessageEncoder } from '@/onebot11/helper/createMultiMessage'
import { Msg } from '@/ntqqapi/proto/compiled'
interface Payload { interface Payload {
user_id?: string | number user_id?: string | number
@@ -19,7 +17,7 @@ interface Payload {
interface Response { interface Response {
message_id: number message_id: number
forward_id: string forward_id?: string
} }
export class SendForwardMsg extends BaseAction<Payload, Response> { export class SendForwardMsg extends BaseAction<Payload, Response> {
@@ -44,90 +42,9 @@ export class SendForwardMsg extends BaseAction<Payload, Response> {
contextMode = CreatePeerMode.Private contextMode = CreatePeerMode.Private
} }
const peer = await createPeer(this.ctx, payload, contextMode) const peer = await createPeer(this.ctx, payload, contextMode)
const msg = await this.handleForwardNode(peer, messages)
const nodes = this.parseNodeContent(messages) const msgShortId = this.ctx.store.createMsgShortId({ chatType: msg.chatType, peerUid: msg.peerUid }, msg.msgId)
let fake = true return { message_id: msgShortId }
for (const node of nodes) {
if (node.data.id) {
fake = false
break
}
if (node.data.content?.some(e => {
return !MessageEncoder.support.includes(e.type)
})) {
fake = false
break
}
}
if (fake && this.ctx.app.native.activated) {
return await this.handleFakeForwardNode(peer, nodes)
} else {
return await this.handleForwardNode(peer, nodes)
}
}
private parseNodeContent(nodes: OB11MessageNode[]) {
return nodes.map(e => {
return {
type: e.type,
data: {
...e.data,
content: e.data.content ? message2List(e.data.content) : undefined
}
}
})
}
private async handleFakeForwardNode(peer: Peer, nodes: OB11MessageNode[]): Promise<Response> {
const encoder = new MessageEncoder(this.ctx, peer)
const raw = await encoder.generate(nodes)
const transmit = Msg.PbMultiMsgTransmit.encode({ pbItemList: raw.multiMsgItems }).finish()
const resid = await this.ctx.app.native.uploadForward(peer, transmit.subarray(1))
const uuid = crypto.randomUUID()
try {
const msg = await this.ctx.ntMsgApi.sendMsg(peer, [{
elementType: 10,
elementId: '',
arkElement: {
bytesData: JSON.stringify({
app: 'com.tencent.multimsg',
config: {
autosize: 1,
forward: 1,
round: 1,
type: 'normal',
width: 300
},
desc: '[聊天记录]',
extra: JSON.stringify({
filename: uuid,
tsum: raw.tsum,
}),
meta: {
detail: {
news: raw.news,
resid,
source: raw.source,
summary: raw.summary,
uniseq: uuid,
}
},
prompt: '[聊天记录]',
ver: '0.0.0.5',
view: 'contact'
})
}
}], 1800)
const msgShortId = this.ctx.store.createMsgShortId({
chatType: msg!.chatType,
peerUid: msg!.peerUid
}, msg!.msgId)
return { message_id: msgShortId, forward_id: resid }
} catch (e) {
this.ctx.logger.error('合并转发失败', e)
throw new Error(`发送伪造合并转发消息失败 (res_id: ${resid} `)
}
} }
private async cloneMsg(msg: RawMessage): Promise<RawMessage | undefined> { private async cloneMsg(msg: RawMessage): Promise<RawMessage | undefined> {
@@ -154,7 +71,7 @@ export class SendForwardMsg extends BaseAction<Payload, Response> {
} }
// 返回一个合并转发的消息id // 返回一个合并转发的消息id
private async handleForwardNode(destPeer: Peer, messageNodes: OB11MessageNode[]): Promise<Response> { private async handleForwardNode(destPeer: Peer, messageNodes: OB11MessageNode[]) {
const selfPeer = { const selfPeer = {
chatType: ChatType.C2C, chatType: ChatType.C2C,
peerUid: selfInfo.uid, peerUid: selfInfo.uid,
@@ -179,7 +96,7 @@ export class SendForwardMsg extends BaseAction<Payload, Response> {
try { try {
const { sendElements, deleteAfterSentFiles } = await createSendElements( const { sendElements, deleteAfterSentFiles } = await createSendElements(
this.ctx, this.ctx,
messageNode.data.content as OB11MessageData[], convertMessage2List(messageNode.data.content),
destPeer destPeer
) )
this.ctx.logger.info('开始生成转发节点', sendElements) this.ctx.logger.info('开始生成转发节点', sendElements)
@@ -246,13 +163,8 @@ export class SendForwardMsg extends BaseAction<Payload, Response> {
if (retMsgIds.length === 0) { if (retMsgIds.length === 0) {
throw Error('转发消息失败,节点为空') throw Error('转发消息失败,节点为空')
} }
const msg = await this.ctx.ntMsgApi.multiForwardMsg(srcPeer!, destPeer, retMsgIds) const returnMsg = await this.ctx.ntMsgApi.multiForwardMsg(srcPeer!, destPeer, retMsgIds)
const resid = JSON.parse(msg.elements[0].arkElement!.bytesData).meta.detail.resid return returnMsg
const msgShortId = this.ctx.store.createMsgShortId({
chatType: msg.chatType,
peerUid: msg.peerUid
}, msg.msgId)
return { message_id: msgShortId, forward_id: resid }
} }
} }

View File

@@ -20,7 +20,7 @@ class GetGroupMemberInfo extends BaseAction<Payload, OB11GroupMember> {
protected async _handle(payload: Payload) { protected async _handle(payload: Payload) {
const groupCode = payload.group_id.toString() const groupCode = payload.group_id.toString()
const uid = await this.ctx.ntUserApi.getUidByUin(payload.user_id.toString(), groupCode) const uid = await this.ctx.ntUserApi.getUidByUin(payload.user_id.toString())
if (!uid) throw new Error('无法获取用户信息') if (!uid) throw new Error('无法获取用户信息')
const member = await this.ctx.ntGroupApi.getGroupMember(groupCode, uid, payload.no_cache) const member = await this.ctx.ntGroupApi.getGroupMember(groupCode, uid, payload.no_cache)
if (member) { if (member) {

View File

@@ -76,8 +76,6 @@ import { DeleteFriend } from './go-cqhttp/DeleteFriend'
import { OCRImage } from './go-cqhttp/OCRImage' import { OCRImage } from './go-cqhttp/OCRImage'
import { GroupPoke } from './llonebot/GroupPoke' import { GroupPoke } from './llonebot/GroupPoke'
import { FriendPoke } from './llonebot/FriendPoke' import { FriendPoke } from './llonebot/FriendPoke'
import { GetGroupFileSystemInfo } from './go-cqhttp/GetGroupFileSystemInfo'
import { GetCredentials } from './system/GetCredentials'
export function initActionMap(adapter: Adapter) { export function initActionMap(adapter: Adapter) {
const actionHandlers = [ const actionHandlers = [
@@ -130,7 +128,6 @@ export function initActionMap(adapter: Adapter) {
new GetCookies(adapter), new GetCookies(adapter),
new ForwardFriendSingleMsg(adapter), new ForwardFriendSingleMsg(adapter),
new ForwardGroupSingleMsg(adapter), new ForwardGroupSingleMsg(adapter),
new GetCredentials(adapter),
// go-cqhttp // go-cqhttp
new GetEssenceMsgList(adapter), new GetEssenceMsgList(adapter),
new GetGroupHonorInfo(adapter), new GetGroupHonorInfo(adapter),
@@ -160,9 +157,8 @@ export function initActionMap(adapter: Adapter) {
new GetGroupNotice(adapter), new GetGroupNotice(adapter),
new DeleteFriend(adapter), new DeleteFriend(adapter),
new OCRImage(adapter), new OCRImage(adapter),
new GetGroupFileSystemInfo(adapter),
] ]
const actionMap = new Map() const actionMap = new Map<string, BaseAction<any, unknown>>()
for (const action of actionHandlers) { for (const action of actionHandlers) {
actionMap.set(action.actionName, action) actionMap.set(action.actionName, action)
actionMap.set(action.actionName + '_async', action) actionMap.set(action.actionName + '_async', action)

View File

@@ -9,7 +9,7 @@ import {
import { BaseAction } from '../BaseAction' import { BaseAction } from '../BaseAction'
import { ActionName } from '../types' import { ActionName } from '../types'
import { CustomMusicSignPostData, IdMusicSignPostData, MusicSign, MusicSignPostData } from '@/common/utils/sign' import { CustomMusicSignPostData, IdMusicSignPostData, MusicSign, MusicSignPostData } from '@/common/utils/sign'
import { message2List, createSendElements, sendMsg, createPeer, CreatePeerMode } from '../../helper/createMessage' import { convertMessage2List, createSendElements, sendMsg, createPeer, CreatePeerMode } from '../../helper/createMessage'
interface ReturnData { interface ReturnData {
message_id: number message_id: number
@@ -26,14 +26,14 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnData> {
contextMode = CreatePeerMode.Private contextMode = CreatePeerMode.Private
} }
const peer = await createPeer(this.ctx, payload, contextMode) const peer = await createPeer(this.ctx, payload, contextMode)
const messages = message2List( const messages = convertMessage2List(
payload.message, payload.message,
payload.auto_escape === true || payload.auto_escape === 'true', payload.auto_escape === true || payload.auto_escape === 'true',
) )
if (this.getSpecialMsgNum(messages, OB11MessageDataType.Node)) { if (this.getSpecialMsgNum(messages, OB11MessageDataType.node)) {
throw new Error('请使用 /send_group_forward_msg 或 /send_private_forward_msg 进行合并转发') throw new Error('请使用 /send_group_forward_msg 或 /send_private_forward_msg 进行合并转发')
} }
else if (this.getSpecialMsgNum(messages, OB11MessageDataType.Music)) { else if (this.getSpecialMsgNum(messages, OB11MessageDataType.music)) {
const music = messages[0] as OB11MessageMusic const music = messages[0] as OB11MessageMusic
if (music) { if (music) {
const { musicSignUrl } = this.adapter.config const { musicSignUrl } = this.adapter.config
@@ -78,7 +78,7 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnData> {
throw `签名音乐消息失败:${e}` throw `签名音乐消息失败:${e}`
} }
messages[0] = { messages[0] = {
type: OB11MessageDataType.Json, type: OB11MessageDataType.json,
data: { data: jsonContent }, data: { data: jsonContent },
} as OB11MessageJson } as OB11MessageJson
} }

View File

@@ -1,26 +0,0 @@
import { BaseAction, Schema } from '../BaseAction'
import { ActionName } from '../types'
interface Payload {
domain: string
}
interface Response {
cookies: string
csrf_token: number
}
export class GetCredentials extends BaseAction<Payload, Response> {
actionName = ActionName.GetCredentials
payloadSchema = Schema.object({
domain: Schema.string().required()
})
protected async _handle(payload: Payload) {
const cookiesObject = await this.ctx.ntUserApi.getCookies(payload.domain)
//把获取到的cookiesObject转换成 k=v; 格式字符串拼接在一起
const cookies = Object.entries(cookiesObject).map(([key, value]) => `${key}=${value}`).join('; ')
const bkn = cookiesObject.skey ? this.ctx.ntWebApi.genBkn(cookiesObject.skey) : ''
return { cookies, csrf_token: +bkn }
}
}

View File

@@ -61,7 +61,6 @@ export enum ActionName {
GetCookies = 'get_cookies', GetCookies = 'get_cookies',
ForwardFriendSingleMsg = 'forward_friend_single_msg', ForwardFriendSingleMsg = 'forward_friend_single_msg',
ForwardGroupSingleMsg = 'forward_group_single_msg', ForwardGroupSingleMsg = 'forward_group_single_msg',
GetCredentials = 'get_credentials',
// go-cqhttp // go-cqhttp
GoCQHTTP_SendGroupForwardMsg = 'send_group_forward_msg', GoCQHTTP_SendGroupForwardMsg = 'send_group_forward_msg',
GoCQHTTP_SendPrivateForwardMsg = 'send_private_forward_msg', GoCQHTTP_SendPrivateForwardMsg = 'send_private_forward_msg',
@@ -90,5 +89,4 @@ export enum ActionName {
GoCQHTTP_GetGroupNotice = '_get_group_notice', GoCQHTTP_GetGroupNotice = '_get_group_notice',
GoCQHTTP_DeleteFriend = 'delete_friend', GoCQHTTP_DeleteFriend = 'delete_friend',
GoCQHTTP_OCRImage = 'ocr_image', GoCQHTTP_OCRImage = 'ocr_image',
GoCQHTTP_GetGroupFileSystemInfo = 'get_group_file_system_info',
} }

View File

@@ -1,22 +1,22 @@
import { BaseAction, Schema } from '../BaseAction' import { BaseAction } from '../BaseAction'
import { ActionName } from '../types' import { ActionName } from '../types'
interface Payload {
domain: string
}
interface Response { interface Response {
cookies: string cookies: string
bkn: string bkn: string
} }
interface Payload {
domain: string
}
export class GetCookies extends BaseAction<Payload, Response> { export class GetCookies extends BaseAction<Payload, Response> {
actionName = ActionName.GetCookies actionName = ActionName.GetCookies
payloadSchema = Schema.object({
domain: Schema.string().required()
})
protected async _handle(payload: Payload) { protected async _handle(payload: Payload) {
if (!payload.domain) {
throw '缺少参数 domain'
}
const cookiesObject = await this.ctx.ntUserApi.getCookies(payload.domain) const cookiesObject = await this.ctx.ntUserApi.getCookies(payload.domain)
//把获取到的cookiesObject转换成 k=v; 格式字符串拼接在一起 //把获取到的cookiesObject转换成 k=v; 格式字符串拼接在一起
const cookies = Object.entries(cookiesObject).map(([key, value]) => `${key}=${value}`).join('; ') const cookies = Object.entries(cookiesObject).map(([key, value]) => `${key}=${value}`).join('; ')

View File

@@ -9,19 +9,20 @@ import {
} from '../ntqqapi/types' } from '../ntqqapi/types'
import { OB11GroupRequestEvent } from './event/request/OB11GroupRequest' import { OB11GroupRequestEvent } from './event/request/OB11GroupRequest'
import { OB11FriendRequestEvent } from './event/request/OB11FriendRequest' import { OB11FriendRequestEvent } from './event/request/OB11FriendRequest'
import { OB11GroupDecreaseEvent } from './event/notice/OB11GroupDecreaseEvent' import { GroupDecreaseSubType, OB11GroupDecreaseEvent } from './event/notice/OB11GroupDecreaseEvent'
import { selfInfo } from '../common/globalVars' import { selfInfo } from '../common/globalVars'
import { OB11Config, Config as LLOBConfig } from '../common/types' import { OB11Config, Config as LLOBConfig } from '../common/types'
import { OB11WebSocket, OB11WebSocketReverseManager } from './connect/ws' import { OB11WebSocket, OB11WebSocketReverseManager } from './connect/ws'
import { OB11Http, OB11HttpPost } from './connect/http' import { OB11Http, OB11HttpPost } from './connect/http'
import { OB11BaseEvent } from './event/OB11BaseEvent' import { OB11BaseEvent } from './event/OB11BaseEvent'
import { OB11Message } from './types'
import { OB11BaseMetaEvent } from './event/meta/OB11BaseMetaEvent' import { OB11BaseMetaEvent } from './event/meta/OB11BaseMetaEvent'
import { postHttpEvent } from './helper/eventForHttp' import { postHttpEvent } from './helper/eventForHttp'
import { initActionMap } from './action' import { initActionMap } from './action'
import { llonebotError } from '../common/globalVars' import { llonebotError } from '../common/globalVars'
import { OB11GroupAdminNoticeEvent } from './event/notice/OB11GroupAdminNoticeEvent' import { OB11GroupAdminNoticeEvent } from './event/notice/OB11GroupAdminNoticeEvent'
import { OB11ProfileLikeEvent } from './event/notice/OB11ProfileLikeEvent' import { OB11ProfileLikeEvent } from './event/notice/OB11ProfileLikeEvent'
import { Msg, SysMsg } from '@/ntqqapi/proto/compiled' import { SysMsg } from '@/ntqqapi/proto/compiled'
import { OB11GroupIncreaseEvent } from './event/notice/OB11GroupIncreaseEvent' import { OB11GroupIncreaseEvent } from './event/notice/OB11GroupIncreaseEvent'
declare module 'cordis' { declare module 'cordis' {
@@ -71,7 +72,7 @@ class OneBot11Adapter extends Service {
}) })
} }
public dispatch(event: OB11BaseEvent) { public dispatch(event: OB11BaseEvent | OB11Message) {
if (this.config.enableWs) { if (this.config.enableWs) {
this.ob11WebSocket.emitEvent(event) this.ob11WebSocket.emitEvent(event)
} }
@@ -87,23 +88,30 @@ class OneBot11Adapter extends Service {
} }
} }
private async handleGroupNotify(notify: GroupNotify, doubt: boolean) { private async handleGroupNotify(notify: GroupNotify) {
try { try {
const flag = `${notify.group.groupCode}|${notify.seq}|${notify.type}|${doubt === true ? '1' : '0'}` const flag = notify.group.groupCode + '|' + notify.seq + '|' + notify.type
if ([GroupNotifyType.MemberLeaveNotifyAdmin, GroupNotifyType.KickMemberNotifyAdmin].includes(notify.type)) { if ([GroupNotifyType.MemberLeaveNotifyAdmin, GroupNotifyType.KickMemberNotifyAdmin].includes(notify.type)) {
this.ctx.logger.info('有成员退出通知', notify)
const member1Uin = await this.ctx.ntUserApi.getUinByUid(notify.user1.uid)
let operatorId = member1Uin
let subType: GroupDecreaseSubType = 'leave'
if (notify.user2.uid) { if (notify.user2.uid) {
this.ctx.logger.info('有群成员被踢', notify.group.groupCode, notify.user1.uid, notify.user2.uid) // 是被踢的
const memberUin = await this.ctx.ntUserApi.getUinByUid(notify.user1.uid) const member2Uin = await this.ctx.ntUserApi.getUinByUid(notify.user2.uid)
const adminUin = await this.ctx.ntUserApi.getUinByUid(notify.user2.uid) if (member2Uin) {
operatorId = member2Uin
}
subType = 'kick'
}
const event = new OB11GroupDecreaseEvent( const event = new OB11GroupDecreaseEvent(
parseInt(notify.group.groupCode), parseInt(notify.group.groupCode),
parseInt(memberUin), parseInt(member1Uin),
parseInt(adminUin), parseInt(operatorId),
'kick', subType,
) )
this.dispatch(event) this.dispatch(event)
} }
}
else if (notify.type === GroupNotifyType.RequestJoinNeedAdminiStratorPass && notify.status === GroupNotifyStatus.Unhandle) { else if (notify.type === GroupNotifyType.RequestJoinNeedAdminiStratorPass && notify.status === GroupNotifyStatus.Unhandle) {
this.ctx.logger.info('有加群请求') this.ctx.logger.info('有加群请求')
const requestUin = await this.ctx.ntUserApi.getUinByUid(notify.user1.uid) const requestUin = await this.ctx.ntUserApi.getUinByUid(notify.user1.uid)
@@ -337,17 +345,16 @@ class OneBot11Adapter extends Service {
this.handleMsg(input) this.handleMsg(input)
}) })
this.ctx.on('nt/group-notify', input => { this.ctx.on('nt/group-notify', input => {
const { doubt, notify } = input this.handleGroupNotify(input)
this.handleGroupNotify(notify, doubt)
}) })
this.ctx.on('nt/friend-request', input => { this.ctx.on('nt/friend-request', input => {
this.handleFriendRequest(input) this.handleFriendRequest(input)
}) })
this.ctx.on('nt/system-message-created', async input => { this.ctx.on('nt/system-message-created', async input => {
const sysMsg = Msg.Message.decode(input) const sysMsg = SysMsg.SystemMessage.decode(input)
const { msgType, subType } = sysMsg.contentHead ?? {} const { msgType, subType, subSubType } = sysMsg.msgSpec[0] ?? {}
if (msgType === 528 && subType === 39) { if (msgType === 528 && subType === 39 && subSubType === 39) {
const tip = SysMsg.ProfileLikeTip.decode(sysMsg.body!.msgContent!) const tip = SysMsg.ProfileLikeTip.decode(sysMsg.bodyWrapper!.body!)
if (tip.msgType !== 0 || tip.subType !== 203) return if (tip.msgType !== 0 || tip.subType !== 203) return
const detail = tip.content?.msg?.detail const detail = tip.content?.msg?.detail
if (!detail) return if (!detail) return
@@ -355,21 +362,13 @@ class OneBot11Adapter extends Service {
const event = new OB11ProfileLikeEvent(detail.uin!, detail.nickname!, +times) const event = new OB11ProfileLikeEvent(detail.uin!, detail.nickname!, +times)
this.dispatch(event) this.dispatch(event)
} else if (msgType === 33) { } else if (msgType === 33) {
const tip = SysMsg.GroupMemberChange.decode(sysMsg.body!.msgContent!) const tip = SysMsg.GroupMemberIncrease.decode(sysMsg.bodyWrapper!.body!)
if (tip.type !== 130) return if (tip.type !== 130) return
this.ctx.logger.info('群成员增加', tip) this.ctx.logger.info('群成员增加', tip)
const memberUin = await this.ctx.ntUserApi.getUinByUid(tip.memberUid) const memberUin = await this.ctx.ntUserApi.getUinByUid(tip.memberUid)
const operatorUin = await this.ctx.ntUserApi.getUinByUid(tip.adminUid) const operatorUin = await this.ctx.ntUserApi.getUinByUid(tip.adminUid)
const event = new OB11GroupIncreaseEvent(tip.groupCode, +memberUin, +operatorUin) const event = new OB11GroupIncreaseEvent(tip.groupCode, +memberUin, +operatorUin)
this.dispatch(event) this.dispatch(event)
} else if (msgType === 34) {
const tip = SysMsg.GroupMemberChange.decode(sysMsg.body!.msgContent!)
if (tip.type !== 130) return // adminUid: 0
this.ctx.logger.info('群成员减少', tip)
const memberUin = await this.ctx.ntUserApi.getUinByUid(tip.memberUid)
const userId = Number(memberUin)
const event = new OB11GroupDecreaseEvent(tip.groupCode, userId, userId)
this.dispatch(event)
} }
}) })
} }

View File

@@ -154,7 +154,7 @@ class OB11HttpPost {
this.disposeInterval?.() this.disposeInterval?.()
} }
public async emitEvent(event: OB11BaseEvent) { public async emitEvent(event: OB11BaseEvent | OB11Message) {
if (!this.activated || !this.config.hosts.length) { if (!this.activated || !this.config.hosts.length) {
return return
} }
@@ -177,8 +177,7 @@ class OB11HttpPost {
}).then( }).then(
async (res) => { async (res) => {
if (event.post_type) { if (event.post_type) {
const eventName = event.post_type + '.' + event[event.post_type + '_type'] this.ctx.logger.info(`HTTP 事件上报: ${host}`, event.post_type, res.status)
this.ctx.logger.info(`HTTP 事件上报: ${host}`, eventName, res.status)
} }
try { try {
const resJson = await res.json() const resJson = await res.json()

View File

@@ -57,12 +57,11 @@ class OB11WebSocket {
}) })
} }
public async emitEvent(event: OB11BaseEvent) { public async emitEvent(event: OB11BaseEvent | OB11Message) {
this.wsClients.forEach(({ socket, emitEvent }) => { this.wsClients.forEach(({ socket, emitEvent }) => {
if (emitEvent && socket.readyState === WebSocket.OPEN) { if (emitEvent && socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(event)) socket.send(JSON.stringify(event))
const eventName = event.post_type + '.' + event[event.post_type + '_type'] this.ctx.logger.info('WebSocket 事件上报', socket.url ?? '', event.post_type)
this.ctx.logger.info('WebSocket 事件上报', socket.url ?? '', eventName)
} }
}) })
} }
@@ -194,11 +193,10 @@ class OB11WebSocketReverse {
this.wsClient?.close() this.wsClient?.close()
} }
public emitEvent(event: OB11BaseEvent) { public emitEvent(event: OB11BaseEvent | OB11Message) {
if (this.wsClient && this.wsClient.readyState === WebSocket.OPEN) { if (this.wsClient && this.wsClient.readyState === WebSocket.OPEN) {
this.wsClient.send(JSON.stringify(event)) this.wsClient.send(JSON.stringify(event))
const eventName = event.post_type + '.' + event[event.post_type + '_type'] this.ctx.logger.info('WebSocket 事件上报', this.wsClient.url ?? '', event.post_type)
this.ctx.logger.info('WebSocket 事件上报', this.wsClient.url ?? '', eventName)
} }
} }

View File

@@ -1,3 +1,4 @@
import { XMLParser } from 'fast-xml-parser'
import { import {
OB11Group, OB11Group,
OB11GroupMember, OB11GroupMember,
@@ -121,7 +122,7 @@ export namespace OB11Entities {
name = content.replace('@', '') name = content.replace('@', '')
} }
messageSegment = { messageSegment = {
type: OB11MessageDataType.At, type: OB11MessageDataType.at,
data: { data: {
qq, qq,
name name
@@ -134,7 +135,7 @@ export namespace OB11Entities {
continue continue
} }
messageSegment = { messageSegment = {
type: OB11MessageDataType.Text, type: OB11MessageDataType.text,
data: { data: {
text text
} }
@@ -170,7 +171,7 @@ export namespace OB11Entities {
throw new Error('回复消息验证失败') throw new Error('回复消息验证失败')
} }
messageSegment = { messageSegment = {
type: OB11MessageDataType.Reply, type: OB11MessageDataType.reply,
data: { data: {
id: ctx.store.createMsgShortId(peer, replyMsg ? replyMsg.msgId : records.msgId).toString() id: ctx.store.createMsgShortId(peer, replyMsg ? replyMsg.msgId : records.msgId).toString()
} }
@@ -184,7 +185,7 @@ export namespace OB11Entities {
const { picElement } = element const { picElement } = element
const fileSize = picElement.fileSize ?? '0' const fileSize = picElement.fileSize ?? '0'
messageSegment = { messageSegment = {
type: OB11MessageDataType.Image, type: OB11MessageDataType.image,
data: { data: {
file: picElement.fileName, file: picElement.fileName,
subType: picElement.picSubType, subType: picElement.picSubType,
@@ -212,7 +213,7 @@ export namespace OB11Entities {
}, msg.msgId, element.elementId) }, msg.msgId, element.elementId)
const fileSize = videoElement.fileSize ?? '0' const fileSize = videoElement.fileSize ?? '0'
messageSegment = { messageSegment = {
type: OB11MessageDataType.Video, type: OB11MessageDataType.video,
data: { data: {
file: videoElement.fileName, file: videoElement.fileName,
url: videoUrl || pathToFileURL(videoElement.filePath).href, url: videoUrl || pathToFileURL(videoElement.filePath).href,
@@ -236,7 +237,7 @@ export namespace OB11Entities {
const { fileElement } = element const { fileElement } = element
const fileSize = fileElement.fileSize ?? '0' const fileSize = fileElement.fileSize ?? '0'
messageSegment = { messageSegment = {
type: OB11MessageDataType.File, type: OB11MessageDataType.file,
data: { data: {
file: fileElement.fileName, file: fileElement.fileName,
url: pathToFileURL(fileElement.filePath).href, url: pathToFileURL(fileElement.filePath).href,
@@ -261,7 +262,7 @@ export namespace OB11Entities {
const { pttElement } = element const { pttElement } = element
const fileSize = pttElement.fileSize ?? '0' const fileSize = pttElement.fileSize ?? '0'
messageSegment = { messageSegment = {
type: OB11MessageDataType.Record, type: OB11MessageDataType.voice,
data: { data: {
file: pttElement.fileName, file: pttElement.fileName,
url: pathToFileURL(pttElement.filePath).href, url: pathToFileURL(pttElement.filePath).href,
@@ -284,7 +285,7 @@ export namespace OB11Entities {
else if (element.arkElement) { else if (element.arkElement) {
const { arkElement } = element const { arkElement } = element
messageSegment = { messageSegment = {
type: OB11MessageDataType.Json, type: OB11MessageDataType.json,
data: { data: {
data: arkElement.bytesData data: arkElement.bytesData
} }
@@ -295,14 +296,14 @@ export namespace OB11Entities {
const { faceIndex, pokeType } = faceElement const { faceIndex, pokeType } = faceElement
if (faceIndex === FaceIndex.Dice) { if (faceIndex === FaceIndex.Dice) {
messageSegment = { messageSegment = {
type: OB11MessageDataType.Dice, type: OB11MessageDataType.dice,
data: { data: {
result: faceElement.resultId! result: faceElement.resultId!
} }
} }
} else if (faceIndex === FaceIndex.RPS) { } else if (faceIndex === FaceIndex.RPS) {
messageSegment = { messageSegment = {
type: OB11MessageDataType.Rps, type: OB11MessageDataType.RPS,
data: { data: {
result: faceElement.resultId! result: faceElement.resultId!
} }
@@ -314,7 +315,7 @@ export namespace OB11Entities {
}*/ }*/
} else { } else {
messageSegment = { messageSegment = {
type: OB11MessageDataType.Face, type: OB11MessageDataType.face,
data: { data: {
id: faceIndex.toString() id: faceIndex.toString()
} }
@@ -330,7 +331,7 @@ export namespace OB11Entities {
// const url = `https://p.qpic.cn/CDN_STATIC/0/data/imgcache/htdocs/club/item/parcel/item/${dir}/${md5}/300x300.gif?max_age=31536000` // const url = `https://p.qpic.cn/CDN_STATIC/0/data/imgcache/htdocs/club/item/parcel/item/${dir}/${md5}/300x300.gif?max_age=31536000`
const url = `https://gxh.vip.qq.com/club/item/parcel/item/${dir}/${emojiId}/raw300.gif` const url = `https://gxh.vip.qq.com/club/item/parcel/item/${dir}/${emojiId}/raw300.gif`
messageSegment = { messageSegment = {
type: OB11MessageDataType.Mface, type: OB11MessageDataType.mface,
data: { data: {
summary: marketFaceElement.faceName!, summary: marketFaceElement.faceName!,
url, url,
@@ -343,15 +344,15 @@ export namespace OB11Entities {
else if (element.markdownElement) { else if (element.markdownElement) {
const { markdownElement } = element const { markdownElement } = element
messageSegment = { messageSegment = {
type: OB11MessageDataType.Markdown, type: OB11MessageDataType.markdown,
data: { data: {
content: markdownElement.content data: markdownElement.content
} }
} }
} }
else if (element.multiForwardMsgElement) { else if (element.multiForwardMsgElement) {
messageSegment = { messageSegment = {
type: OB11MessageDataType.Forward, type: OB11MessageDataType.forward,
data: { data: {
id: msg.msgId id: msg.msgId
} }
@@ -423,8 +424,6 @@ export namespace OB11Entities {
for (const element of msg.elements) { for (const element of msg.elements) {
const grayTipElement = element.grayTipElement const grayTipElement = element.grayTipElement
const groupElement = grayTipElement?.groupElement const groupElement = grayTipElement?.groupElement
const xmlElement = grayTipElement?.xmlElement
if (groupElement) { if (groupElement) {
if (groupElement.type === TipGroupElementType.Ban) { if (groupElement.type === TipGroupElementType.Ban) {
ctx.logger.info('收到群成员禁言提示', groupElement) ctx.logger.info('收到群成员禁言提示', groupElement)
@@ -478,13 +477,6 @@ export namespace OB11Entities {
) )
} }
} }
else if (groupElement.type === TipGroupElementType.MemberIncrease) {
const { memberUid, adminUid } = groupElement
if (memberUid !== selfInfo.uid) return
ctx.logger.info('收到群成员增加消息', groupElement)
const adminUin = adminUid ? await ctx.ntUserApi.getUinByUid(adminUid) : selfInfo.uin
return new OB11GroupIncreaseEvent(+msg.peerUid, +selfInfo.uin, +adminUin)
}
} }
else if (element.fileElement) { else if (element.fileElement) {
return new OB11GroupUploadNoticeEvent(+msg.peerUid, +msg.senderUin!, { return new OB11GroupUploadNoticeEvent(+msg.peerUid, +msg.senderUin!, {
@@ -494,47 +486,65 @@ export namespace OB11Entities {
busid: element.fileElement.fileBizId || 0, busid: element.fileElement.fileBizId || 0,
}) })
} }
else if (xmlElement) {
if (xmlElement.templId === '10382') { if (grayTipElement) {
ctx.logger.info('收到表情回应我的消息', xmlElement.templParam) const xmlElement = grayTipElement.xmlElement
if (xmlElement?.templId === '10382') {
const emojiLikeData = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: '',
}).parse(xmlElement.content)
ctx.logger.info('收到表情回应我的消息', emojiLikeData)
try { try {
const senderUin = xmlElement.templParam.get('jp_uin') const senderUin: string = emojiLikeData.gtip.qq.jp
const msgSeq = xmlElement.templParam.get('msg_seq') const msgSeq: string = emojiLikeData.gtip.url.msgseq
const emojiId = xmlElement.templParam.get('face_id') const emojiId: string = emojiLikeData.gtip.face.id
const peer = { const peer = {
chatType: ChatType.Group, chatType: ChatType.Group,
guildId: '', guildId: '',
peerUid: msg.peerUid, peerUid: msg.peerUid,
} }
const replyMsgList = (await ctx.ntMsgApi.queryFirstMsgBySeq(peer, msgSeq!)).msgList const replyMsgList = (await ctx.ntMsgApi.queryFirstMsgBySeq(peer, msgSeq)).msgList
if (!replyMsgList?.length) { if (!replyMsgList?.length) {
return return
} }
const shortId = ctx.store.createMsgShortId(peer, replyMsgList[0].msgId) const shortId = ctx.store.createMsgShortId(peer, replyMsgList[0].msgId)
return new OB11GroupMsgEmojiLikeEvent( return new OB11GroupMsgEmojiLikeEvent(
parseInt(msg.peerUid), parseInt(msg.peerUid),
parseInt(senderUin!), parseInt(senderUin),
shortId, shortId,
[{ [{
emoji_id: emojiId!, emoji_id: emojiId,
count: 1, count: 1,
}] }]
) )
} catch (e) { } catch (e) {
ctx.logger.error('解析表情回应消息失败', (e as Error).stack) ctx.logger.error('解析表情回应消息失败', (e as Error).stack)
} }
} else if (xmlElement.templId == '10179') { }
ctx.logger.info('收到新人被邀请进群消息', xmlElement)
const invitor = xmlElement.templParam.get('invitor') if (
const invitee = xmlElement.templParam.get('invitee') grayTipElement.subElementType == GrayTipElementSubType.XmlMsg &&
if (invitor && invitee) { xmlElement?.templId == '10179'
) {
ctx.logger.info('收到新人被邀请进群消息', grayTipElement)
if (xmlElement?.content) {
const regex = /jp="(\d+)"/g
const matches: string[] = []
let match: RegExpExecArray | null = null
while ((match = regex.exec(xmlElement.content)) !== null) {
matches.push(match[1])
}
if (matches.length === 2) {
const [invitor, invitee] = matches
return new OB11GroupIncreaseEvent(+msg.peerUid, +invitee, +invitor, 'invite') return new OB11GroupIncreaseEvent(+msg.peerUid, +invitee, +invitor, 'invite')
} }
} }
} }
else if (grayTipElement.subElementType == GrayTipElementSubType.JSON) {
if (grayTipElement) {
if (grayTipElement.subElementType == GrayTipElementSubType.JSON) {
const json = JSON.parse(grayTipElement.jsonGrayTipElement!.jsonStr) const json = JSON.parse(grayTipElement.jsonGrayTipElement!.jsonStr)
if (grayTipElement.jsonGrayTipElement?.busiId === '1061') { if (grayTipElement.jsonGrayTipElement?.busiId === '1061') {
const param = grayTipElement.jsonGrayTipElement.xmlToJsonParam const param = grayTipElement.jsonGrayTipElement.xmlToJsonParam
@@ -655,10 +665,9 @@ export namespace OB11Entities {
export function sex(sex: Sex): OB11UserSex { export function sex(sex: Sex): OB11UserSex {
const sexMap = { const sexMap = {
[Sex.Unknown]: OB11UserSex.Unknown, [Sex.male]: OB11UserSex.Male,
[Sex.Male]: OB11UserSex.Male, [Sex.female]: OB11UserSex.Female,
[Sex.Female]: OB11UserSex.Female, [Sex.unknown]: OB11UserSex.Unknown,
[Sex.Hidden]: OB11UserSex.Unknown
} }
return sexMap[sex] ?? OB11UserSex.Unknown return sexMap[sex] ?? OB11UserSex.Unknown
} }
@@ -688,6 +697,19 @@ export namespace OB11Entities {
} }
} }
export function stranger(user: User): OB11User {
return {
...user,
user_id: parseInt(user.uin),
nickname: user.nick,
sex: sex(user.sex!),
age: 0,
qid: user.qid,
login_days: 0,
level: (user.qqLevel && calcQQLevel(user.qqLevel)) || 0,
}
}
export function group(group: Group): OB11Group { export function group(group: Group): OB11Group {
return { return {
group_id: parseInt(group.groupCode), group_id: parseInt(group.groupCode),

View File

@@ -9,7 +9,6 @@ export enum EventType {
} }
export abstract class OB11BaseEvent { export abstract class OB11BaseEvent {
[index: string]: any
time = Math.floor(Date.now() / 1000) time = Math.floor(Date.now() / 1000)
self_id = parseInt(selfInfo.uin) self_id = parseInt(selfInfo.uin)
abstract post_type: EventType abstract post_type: EventType

View File

@@ -12,7 +12,7 @@ export class OB11GroupDecreaseEvent extends OB11GroupNoticeEvent {
constructor(groupId: number, userId: number, operatorId: number, subType: GroupDecreaseSubType = 'leave') { constructor(groupId: number, userId: number, operatorId: number, subType: GroupDecreaseSubType = 'leave') {
super() super()
this.group_id = groupId this.group_id = groupId
this.operator_id = operatorId this.operator_id = operatorId // 实际上不应该这么实现,但是现在还没有办法识别用户是被踢出的,还是自己主动退出的
this.user_id = userId this.user_id = userId
this.sub_type = subType this.sub_type = subType
} }

View File

@@ -33,14 +33,14 @@ export async function createSendElements(
continue continue
} }
switch (sendMsg.type) { switch (sendMsg.type) {
case OB11MessageDataType.Text: { case OB11MessageDataType.text: {
const text = sendMsg.data?.text const text = sendMsg.data?.text
if (text) { if (text) {
sendElements.push(SendElement.text(sendMsg.data!.text)) sendElements.push(SendElement.text(sendMsg.data!.text))
} }
} }
break break
case OB11MessageDataType.At: { case OB11MessageDataType.at: {
if (!peer) { if (!peer) {
continue continue
} }
@@ -76,7 +76,7 @@ export async function createSendElements(
} }
} }
break break
case OB11MessageDataType.Reply: { case OB11MessageDataType.reply: {
if (sendMsg.data?.id) { if (sendMsg.data?.id) {
const info = await ctx.store.getMsgInfoByShortId(+sendMsg.data.id) const info = await ctx.store.getMsgInfoByShortId(+sendMsg.data.id)
if (!info) { if (!info) {
@@ -90,14 +90,14 @@ export async function createSendElements(
} }
} }
break break
case OB11MessageDataType.Face: { case OB11MessageDataType.face: {
const faceId = sendMsg.data?.id const faceId = sendMsg.data?.id
if (faceId) { if (faceId) {
sendElements.push(SendElement.face(parseInt(faceId))) sendElements.push(SendElement.face(parseInt(faceId)))
} }
} }
break break
case OB11MessageDataType.Mface: { case OB11MessageDataType.mface: {
sendElements.push( sendElements.push(
SendElement.mface( SendElement.mface(
+sendMsg.data.emoji_package_id, +sendMsg.data.emoji_package_id,
@@ -108,10 +108,10 @@ export async function createSendElements(
) )
} }
break break
case OB11MessageDataType.Image: { case OB11MessageDataType.image: {
const res = await SendElement.pic( const res = await SendElement.pic(
ctx, ctx,
(await handleOb11RichMedia(ctx, sendMsg, deleteAfterSentFiles)).path, (await handleOb11FileLikeMessage(ctx, sendMsg, { deleteAfterSentFiles })).path,
sendMsg.data.summary || '', sendMsg.data.summary || '',
sendMsg.data.subType || 0, sendMsg.data.subType || 0,
sendMsg.data.type === 'flash' sendMsg.data.type === 'flash'
@@ -120,13 +120,13 @@ export async function createSendElements(
sendElements.push(res) sendElements.push(res)
} }
break break
case OB11MessageDataType.File: { case OB11MessageDataType.file: {
const { path, fileName } = await handleOb11RichMedia(ctx, sendMsg, deleteAfterSentFiles) const { path, fileName } = await handleOb11FileLikeMessage(ctx, sendMsg, { deleteAfterSentFiles })
sendElements.push(await SendElement.file(ctx, path, fileName)) sendElements.push(await SendElement.file(ctx, path, fileName))
} }
break break
case OB11MessageDataType.Video: { case OB11MessageDataType.video: {
const { path, fileName } = await handleOb11RichMedia(ctx, sendMsg, deleteAfterSentFiles) const { path, fileName } = await handleOb11FileLikeMessage(ctx, sendMsg, { deleteAfterSentFiles })
let thumb = sendMsg.data.thumb let thumb = sendMsg.data.thumb
if (thumb) { if (thumb) {
const uri2LocalRes = await uri2local(ctx, thumb) const uri2LocalRes = await uri2local(ctx, thumb)
@@ -137,32 +137,32 @@ export async function createSendElements(
sendElements.push(res) sendElements.push(res)
} }
break break
case OB11MessageDataType.Record: { case OB11MessageDataType.voice: {
const { path } = await handleOb11RichMedia(ctx, sendMsg, deleteAfterSentFiles) const { path } = await handleOb11FileLikeMessage(ctx, sendMsg, { deleteAfterSentFiles })
sendElements.push(await SendElement.ptt(ctx, path)) sendElements.push(await SendElement.ptt(ctx, path))
} }
break break
case OB11MessageDataType.Json: { case OB11MessageDataType.json: {
sendElements.push(SendElement.ark(sendMsg.data.data)) sendElements.push(SendElement.ark(sendMsg.data.data))
} }
break break
case OB11MessageDataType.Dice: { case OB11MessageDataType.dice: {
const resultId = sendMsg.data?.result const resultId = sendMsg.data?.result
sendElements.push(SendElement.dice(resultId)) sendElements.push(SendElement.dice(resultId))
} }
break break
case OB11MessageDataType.Rps: { case OB11MessageDataType.RPS: {
const resultId = sendMsg.data?.result const resultId = sendMsg.data?.result
sendElements.push(SendElement.rps(resultId)) sendElements.push(SendElement.rps(resultId))
} }
break break
case OB11MessageDataType.Contact: { case OB11MessageDataType.contact: {
const { type, id } = sendMsg.data const { type, id } = sendMsg.data
const data = type === 'qq' ? ctx.ntFriendApi.getBuddyRecommendContact(id) : ctx.ntGroupApi.getGroupRecommendContact(id) const data = type === 'qq' ? ctx.ntFriendApi.getBuddyRecommendContact(id) : ctx.ntGroupApi.getGroupRecommendContact(id)
sendElements.push(SendElement.ark(await data)) sendElements.push(SendElement.ark(await data))
} }
break break
case OB11MessageDataType.Shake: { case OB11MessageDataType.shake: {
sendElements.push(SendElement.shake()) sendElements.push(SendElement.shake())
} }
break break
@@ -175,22 +175,51 @@ export async function createSendElements(
} }
} }
export function message2List(message: OB11MessageMixType, autoEscape = false) { // forked from https://github.com/NapNeko/NapCatQQ/blob/6f6b258f22d7563f15d84e7172c4d4cbb547f47e/src/onebot11/action/msg/SendMsg/create-send-elements.ts#L26
async function handleOb11FileLikeMessage(
ctx: Context,
{ data: inputdata }: OB11MessageFileBase,
{ deleteAfterSentFiles }: { deleteAfterSentFiles: string[] },
) {
//有的奇怪的框架将url作为参数 而不是file 此时优先url 同时注意可能传入的是非file://开头的目录 By Mlikiowa
const {
path,
isLocal,
fileName,
errMsg,
success,
} = (await uri2local(ctx, inputdata.url || inputdata.file))
if (!success) {
ctx.logger.error(errMsg)
throw Error(errMsg)
}
if (!isLocal) { // 只删除http和base64转过来的文件
deleteAfterSentFiles.push(path)
}
return { path, fileName: inputdata.name || fileName }
}
export function convertMessage2List(message: OB11MessageMixType, autoEscape = false) {
if (typeof message === 'string') { if (typeof message === 'string') {
if (autoEscape === true) { if (autoEscape === true) {
return [ message = [
{ {
type: OB11MessageDataType.Text, type: OB11MessageDataType.text,
data: { data: {
text: message, text: message,
}, },
}, },
] as OB11MessageData[] ]
} else {
return decodeCQCode(message)
} }
} else if (!Array.isArray(message)) { else {
return [message] message = decodeCQCode(message.toString())
}
}
else if (!Array.isArray(message)) {
message = [message]
} }
return message return message
} }
@@ -272,18 +301,3 @@ export async function createPeer(ctx: Context, payload: CreatePeerPayload, mode
} }
throw new Error('请指定 group_id 或 user_id') throw new Error('请指定 group_id 或 user_id')
} }
export async function handleOb11RichMedia(ctx: Context, segment: OB11MessageFileBase, deleteAfterSentFiles: string[]) {
const res = await uri2local(ctx, segment.data.url || segment.data.file)
if (!res.success) {
ctx.logger.error(res.errMsg)
throw Error(res.errMsg)
}
if (!res.isLocal) {
deleteAfterSentFiles.push(res.path)
}
return { path: res.path, fileName: segment.data.name || res.fileName }
}

View File

@@ -1,239 +0,0 @@
import { Context } from 'cordis'
import { OB11MessageData, OB11MessageDataType } from '../types'
import { Msg, RichMedia } from '@/ntqqapi/proto/compiled'
import { handleOb11RichMedia } from './createMessage'
import { selfInfo } from '@/common/globalVars'
import { Peer, RichMediaUploadCompleteNotify } from '@/ntqqapi/types'
import { deflateSync } from 'node:zlib'
import faceConfig from '@/ntqqapi/helper/face_config.json'
export class MessageEncoder {
static support = ['text', 'face', 'image', 'markdown', 'forward']
results: Msg.Message[]
children: Msg.Elem[]
deleteAfterSentFiles: string[]
isGroup: boolean
seq: number
tsum: number
preview: string
news: { text: string }[]
name?: string
uin?: number
constructor(private ctx: Context, private peer: Peer) {
this.results = []
this.children = []
this.deleteAfterSentFiles = []
this.isGroup = peer.chatType === 2
this.seq = Math.trunc(Math.random() * 65430)
this.tsum = 0
this.preview = ''
this.news = []
}
async flush() {
if (this.children.length === 0) return
const nick = this.name || selfInfo.nick || 'QQ用户'
if (this.news.length < 4) {
this.news.push({
text: `${nick}: ${this.preview}`
})
}
this.results.push({
routingHead: {
fromUin: this.uin ?? +selfInfo.uin ?? 1094950020,
c2c: this.isGroup ? undefined : {
friendName: nick
},
group: this.isGroup ? {
groupCode: 284840486,
groupCard: nick
} : undefined
},
contentHead: {
msgType: this.isGroup ? 82 : 9,
random: Math.floor(Math.random() * 4294967290),
msgSeq: this.seq,
msgTime: Math.trunc(Date.now() / 1000),
pkgNum: 1,
pkgIndex: 0,
divSeq: 0,
field15: {
field1: 0,
field2: 0,
field3: 0,
field4: '',
field5: ''
}
},
body: {
richText: {
elems: this.children
}
}
})
this.seq++
this.tsum++
this.children = []
this.preview = ''
}
async packImage(data: RichMediaUploadCompleteNotify, busiType: number) {
const imageSize = await this.ctx.ntFileApi.getImageSize(data.filePath)
return {
commonElem: {
serviceType: 48,
pbElem: RichMedia.MsgInfo.encode({
msgInfoBody: [{
index: {
info: {
fileSize: +data.commonFileInfo.fileSize,
md5HexStr: data.commonFileInfo.md5,
sha1HexStr: data.commonFileInfo.sha,
fileName: data.commonFileInfo.fileName,
fileType: {
type: 1,
picFormat: imageSize.type === 'gif' ? 2000 : 1000
},
width: imageSize.width,
height: imageSize.height,
time: 0,
original: 1
},
fileUuid: data.fileId,
storeID: 1,
expire: 2678400
},
pic: {
urlPath: `/download?appid=${this.isGroup ? 1407 : 1406}&fileid=${data.fileId}`,
ext: {
originalParam: '&spec=0',
bigParam: '&spec=720',
thumbParam: '&spec=198'
},
domain: 'multimedia.nt.qq.com.cn'
},
fileExist: true
}],
extBizInfo: {
pic: {
bizType: 0,
summary: ''
},
busiType
}
}).finish(),
businessType: this.isGroup ? 20 : 10
}
}
}
packForwardMessage(resid: string) {
const uuid = crypto.randomUUID()
const content = JSON.stringify({
app: 'com.tencent.multimsg',
config: {
autosize: 1,
forward: 1,
round: 1,
type: 'normal',
width: 300
},
desc: '[聊天记录]',
extra: JSON.stringify({
filename: uuid,
tsum: 0,
}),
meta: {
detail: {
news: [{
text: '查看转发消息'
}],
resid,
source: '聊天记录',
summary: '查看转发消息',
uniseq: uuid,
}
},
prompt: '[聊天记录]',
ver: '0.0.0.5',
view: 'contact'
})
return {
lightApp: {
data: Buffer.concat([Buffer.from([1]), deflateSync(Buffer.from(content, 'utf-8'))])
}
}
}
async visit(segment: OB11MessageData) {
const { type, data } = segment
if (type === OB11MessageDataType.Node) {
await this.render(data.content as OB11MessageData[])
const id = data.uin ?? data.user_id
this.uin = id ? +id : undefined
this.name = data.name ?? data.nickname
await this.flush()
} else if (type === OB11MessageDataType.Text) {
this.children.push({
text: {
str: data.text
}
})
this.preview += data.text
} else if (type === OB11MessageDataType.Face) {
this.children.push({
face: {
index: +data.id
}
})
const face = faceConfig.sysface.find(e => e.QSid === String(data.id))
if (face) {
this.preview += face.QDes
}
} else if (type === OB11MessageDataType.Image) {
const { path } = await handleOb11RichMedia(this.ctx, segment, this.deleteAfterSentFiles)
const data = await this.ctx.ntFileApi.uploadRMFileWithoutMsg(path, this.isGroup ? 4 : 3, this.peer.peerUid)
const busiType = Number(segment.data.subType) || 0
this.children.push(await this.packImage(data, busiType))
this.preview += busiType === 1 ? '[动画表情]' : '[图片]'
} else if (type === OB11MessageDataType.Markdown) {
this.children.push({
commonElem: {
serviceType: 45,
pbElem: Msg.MarkdownElem.encode(data).finish(),
businessType: 1
}
})
} else if (type === OB11MessageDataType.Forward) {
this.children.push(this.packForwardMessage(data.id))
this.preview += '[聊天记录]'
}
}
async render(segments: OB11MessageData[]) {
for (const segment of segments) {
await this.visit(segment)
}
}
async generate(content: any[]) {
await this.render(content)
return {
multiMsgItems: [{
fileName: 'MultiMsg',
buffer: {
msg: this.results
}
}],
tsum: this.tsum,
source: this.isGroup ? '群聊的聊天记录' : '聊天记录',
summary: `查看${this.tsum}条转发消息`,
news: this.news
}
}
}

View File

@@ -2,7 +2,7 @@ import { OB11Message, OB11MessageData, OB11MessageDataType } from '../types'
import { OB11FriendRequestEvent } from '../event/request/OB11FriendRequest' import { OB11FriendRequestEvent } from '../event/request/OB11FriendRequest'
import { OB11GroupRequestEvent } from '../event/request/OB11GroupRequest' import { OB11GroupRequestEvent } from '../event/request/OB11GroupRequest'
import { GroupRequestOperateTypes } from '@/ntqqapi/types' import { GroupRequestOperateTypes } from '@/ntqqapi/types'
import { message2List, createSendElements, sendMsg, createPeer, CreatePeerMode } from '../helper/createMessage' import { convertMessage2List, createSendElements, sendMsg, createPeer, CreatePeerMode } from '../helper/createMessage'
import { isNullable } from 'cosmokit' import { isNullable } from 'cosmokit'
import { Context } from 'cordis' import { Context } from 'cordis'
@@ -65,7 +65,7 @@ async function handleMsg(ctx: Context, msg: OB11Message, quickAction: QuickOpera
if (reply) { if (reply) {
let replyMessage: OB11MessageData[] = [] let replyMessage: OB11MessageData[] = []
replyMessage.push({ replyMessage.push({
type: OB11MessageDataType.Reply, type: OB11MessageDataType.reply,
data: { data: {
id: msg.message_id.toString(), id: msg.message_id.toString(),
}, },
@@ -74,14 +74,14 @@ async function handleMsg(ctx: Context, msg: OB11Message, quickAction: QuickOpera
if (msg.message_type == 'group') { if (msg.message_type == 'group') {
if ((quickAction as QuickOperationGroupMessage).at_sender) { if ((quickAction as QuickOperationGroupMessage).at_sender) {
replyMessage.push({ replyMessage.push({
type: OB11MessageDataType.At, type: OB11MessageDataType.at,
data: { data: {
qq: msg.user_id.toString(), qq: msg.user_id.toString(),
}, },
}) })
} }
} }
replyMessage = replyMessage.concat(message2List(reply, quickAction.auto_escape)) replyMessage = replyMessage.concat(convertMessage2List(reply, quickAction.auto_escape))
const { sendElements, deleteAfterSentFiles } = await createSendElements(ctx, replyMessage, peer) const { sendElements, deleteAfterSentFiles } = await createSendElements(ctx, replyMessage, peer)
sendMsg(ctx, peer, sendElements, deleteAfterSentFiles).catch(e => ctx.logger.error(e)) sendMsg(ctx, peer, sendElements, deleteAfterSentFiles).catch(e => ctx.logger.error(e))
} }

View File

@@ -77,7 +77,7 @@ export enum OB11MessageType {
export interface OB11Message { export interface OB11Message {
target_id?: number // 自己发送的消息才有此字段 target_id?: number // 自己发送的消息才有此字段
self_id: number self_id?: number
time: number time: number
message_id: number message_id: number
message_seq: number // go-cqhttp字段实际上是message_id message_seq: number // go-cqhttp字段实际上是message_id
@@ -91,7 +91,7 @@ export interface OB11Message {
message_format: 'array' | 'string' message_format: 'array' | 'string'
raw_message: string raw_message: string
font: number font: number
post_type: EventType post_type?: EventType
raw?: RawMessage raw?: RawMessage
temp_source?: 0 | 1 | 2 | 3 | 4 | 6 | 7 | 8 | 9 temp_source?: 0 | 1 | 2 | 3 | 4 | 6 | 7 | 8 | 9
} }
@@ -117,30 +117,30 @@ export interface OB11Return<DataType> {
} }
export enum OB11MessageDataType { export enum OB11MessageDataType {
Text = 'text', text = 'text',
Image = 'image', image = 'image',
Music = 'music', music = 'music',
Video = 'video', video = 'video',
Record = 'record', voice = 'record',
File = 'file', file = 'file',
At = 'at', at = 'at',
Reply = 'reply', reply = 'reply',
Json = 'json', json = 'json',
Face = 'face', face = 'face',
Mface = 'mface', // 商城表情 mface = 'mface', // 商城表情
Markdown = 'markdown', markdown = 'markdown',
Node = 'node', // 合并转发消息节点 node = 'node', // 合并转发消息节点
Forward = 'forward', // 合并转发消息,用于上报 forward = 'forward', // 合并转发消息,用于上报
Xml = 'xml', xml = 'xml',
Poke = 'poke', poke = 'poke',
Dice = 'dice', dice = 'dice',
Rps = 'rps', RPS = 'rps',
Contact = 'contact', contact = 'contact',
Shake = 'shake', shake = 'shake',
} }
export interface OB11MessageMFace { export interface OB11MessageMFace {
type: OB11MessageDataType.Mface type: OB11MessageDataType.mface
data: { data: {
emoji_package_id: number emoji_package_id: number
emoji_id: string emoji_id: string
@@ -151,27 +151,27 @@ export interface OB11MessageMFace {
} }
export interface OB11MessageDice { export interface OB11MessageDice {
type: OB11MessageDataType.Dice type: OB11MessageDataType.dice
data: { data: {
result: number /* intended */ | string /* in fact */ result: number /* intended */ | string /* in fact */
} }
} }
export interface OB11MessageRPS { export interface OB11MessageRPS {
type: OB11MessageDataType.Rps type: OB11MessageDataType.RPS
data: { data: {
result: number | string result: number | string
} }
} }
export interface OB11MessageText { export interface OB11MessageText {
type: OB11MessageDataType.Text type: OB11MessageDataType.text
data: { data: {
text: string // 纯文本 text: string // 纯文本
} }
} }
export interface OB11MessagePoke { export interface OB11MessagePoke {
type: OB11MessageDataType.Poke type: OB11MessageDataType.poke
data: { data: {
qq?: number qq?: number
id?: number id?: number
@@ -189,7 +189,7 @@ export interface OB11MessageFileBase {
} }
export interface OB11MessageImage extends OB11MessageFileBase { export interface OB11MessageImage extends OB11MessageFileBase {
type: OB11MessageDataType.Image type: OB11MessageDataType.image
data: OB11MessageFileBase['data'] & { data: OB11MessageFileBase['data'] & {
summary?: string // 图片摘要 summary?: string // 图片摘要
subType?: PicSubType subType?: PicSubType
@@ -198,14 +198,14 @@ export interface OB11MessageImage extends OB11MessageFileBase {
} }
export interface OB11MessageRecord extends OB11MessageFileBase { export interface OB11MessageRecord extends OB11MessageFileBase {
type: OB11MessageDataType.Record type: OB11MessageDataType.voice
data: OB11MessageFileBase['data'] & { data: OB11MessageFileBase['data'] & {
path?: string //扩展 path?: string //扩展
} }
} }
export interface OB11MessageFile extends OB11MessageFileBase { export interface OB11MessageFile extends OB11MessageFileBase {
type: OB11MessageDataType.File type: OB11MessageDataType.file
data: OB11MessageFileBase['data'] & { data: OB11MessageFileBase['data'] & {
file_id?: string file_id?: string
path?: string path?: string
@@ -213,14 +213,14 @@ export interface OB11MessageFile extends OB11MessageFileBase {
} }
export interface OB11MessageVideo extends OB11MessageFileBase { export interface OB11MessageVideo extends OB11MessageFileBase {
type: OB11MessageDataType.Video type: OB11MessageDataType.video
data: OB11MessageFileBase['data'] & { data: OB11MessageFileBase['data'] & {
path?: string //扩展 path?: string //扩展
} }
} }
export interface OB11MessageAt { export interface OB11MessageAt {
type: OB11MessageDataType.At type: OB11MessageDataType.at
data: { data: {
qq: string | 'all' qq: string | 'all'
name?: string name?: string
@@ -228,14 +228,14 @@ export interface OB11MessageAt {
} }
export interface OB11MessageReply { export interface OB11MessageReply {
type: OB11MessageDataType.Reply type: OB11MessageDataType.reply
data: { data: {
id: string id: string
} }
} }
export interface OB11MessageFace { export interface OB11MessageFace {
type: OB11MessageDataType.Face type: OB11MessageDataType.face
data: { data: {
id: string id: string
} }
@@ -244,50 +244,48 @@ export interface OB11MessageFace {
export type OB11MessageMixType = OB11MessageData[] | string | OB11MessageData export type OB11MessageMixType = OB11MessageData[] | string | OB11MessageData
export interface OB11MessageNode { export interface OB11MessageNode {
type: OB11MessageDataType.Node type: OB11MessageDataType.node
data: { data: {
id?: number | string id?: string
content?: OB11MessageMixType user_id?: number
user_id?: number // ob11 nickname: string
nickname?: string // ob11 content: OB11MessageMixType
name?: string // gocq
uin?: number | string // gocq
} }
} }
export interface OB11MessageIdMusic { export interface OB11MessageIdMusic {
type: OB11MessageDataType.Music type: OB11MessageDataType.music
data: IdMusicSignPostData data: IdMusicSignPostData
} }
export interface OB11MessageCustomMusic { export interface OB11MessageCustomMusic {
type: OB11MessageDataType.Music type: OB11MessageDataType.music
data: Omit<CustomMusicSignPostData, 'singer'> & { content?: string } data: Omit<CustomMusicSignPostData, 'singer'> & { content?: string }
} }
export type OB11MessageMusic = OB11MessageIdMusic | OB11MessageCustomMusic export type OB11MessageMusic = OB11MessageIdMusic | OB11MessageCustomMusic
export interface OB11MessageJson { export interface OB11MessageJson {
type: OB11MessageDataType.Json type: OB11MessageDataType.json
data: { data: string /* , config: { token: string } */ } data: { data: string /* , config: { token: string } */ }
} }
export interface OB11MessageMarkdown { export interface OB11MessageMarkdown {
type: OB11MessageDataType.Markdown type: OB11MessageDataType.markdown
data: { data: {
content: string data: string
} }
} }
export interface OB11MessageForward { export interface OB11MessageForward {
type: OB11MessageDataType.Forward type: OB11MessageDataType.forward
data: { data: {
id: string id: string
} }
} }
export interface OB11MessageContact { export interface OB11MessageContact {
type: OB11MessageDataType.Contact type: OB11MessageDataType.contact
data: { data: {
type: 'qq' | 'group' type: 'qq' | 'group'
id: string id: string
@@ -295,7 +293,7 @@ export interface OB11MessageContact {
} }
export interface OB11MessageShake { export interface OB11MessageShake {
type: OB11MessageDataType.Shake type: OB11MessageDataType.shake
data: Record<string, never> data: Record<string, never>
} }

View File

@@ -43,13 +43,6 @@ async function onSettingWindowCreated(view: Element) {
SettingButton('请稍候', 'llonebot-update-button', 'secondary'), SettingButton('请稍候', 'llonebot-update-button', 'secondary'),
), ),
]), ]),
SettingList([
SettingItem(
'是否启用 LLOneBot重启 QQ 后生效',
null,
SettingSwitch('enableLLOB', config.enableLLOB, { 'control-display-id': 'config-enableLLOB' }),
)
]),
SettingList([ SettingList([
SettingItem( SettingItem(
'是否启用 Satori 协议', '是否启用 Satori 协议',
@@ -456,11 +449,9 @@ async function onSettingWindowCreated(view: Element) {
} }
window.llonebot.checkVersion().then(checkVersionFunc) window.llonebot.checkVersion().then(checkVersionFunc)
window.addEventListener('beforeunload', () => { window.addEventListener('beforeunload', () => {
window.llonebot.getConfig().then(oldConfig=>{ if (JSON.stringify(ob11Config) === JSON.stringify(config.ob11)) return
if(JSON.stringify(oldConfig) !== JSON.stringify(config)){ config.ob11 = ob11Config
window.llonebot.setConfig(true, config) window.llonebot.setConfig(true, config)
}
})
}) })
} }

View File

@@ -99,7 +99,7 @@ class SatoriAdapter extends Service {
} }
} }
async handleGroupNotify(input: NT.GroupNotify, doubt: boolean) { async handleGroupNotify(input: NT.GroupNotify) {
if ( if (
input.type === NT.GroupNotifyType.InvitedByMember && input.type === NT.GroupNotifyType.InvitedByMember &&
input.status === NT.GroupNotifyStatus.Unhandle input.status === NT.GroupNotifyStatus.Unhandle
@@ -119,14 +119,14 @@ class SatoriAdapter extends Service {
input.status === NT.GroupNotifyStatus.Unhandle input.status === NT.GroupNotifyStatus.Unhandle
) { ) {
// 他人主动申请,需管理员同意 // 他人主动申请,需管理员同意
return await parseGuildMemberRequest(this, input, doubt) return await parseGuildMemberRequest(this, input)
} }
else if ( else if (
input.type === NT.GroupNotifyType.InvitedNeedAdminiStratorPass && input.type === NT.GroupNotifyType.InvitedNeedAdminiStratorPass &&
input.status === NT.GroupNotifyStatus.Unhandle input.status === NT.GroupNotifyStatus.Unhandle
) { ) {
// 他人被邀请,需管理员同意 // 他人被邀请,需管理员同意
return await parseGuildMemberRequest(this, input, doubt) return await parseGuildMemberRequest(this, input)
} }
} }
@@ -140,8 +140,7 @@ class SatoriAdapter extends Service {
}) })
this.ctx.on('nt/group-notify', async input => { this.ctx.on('nt/group-notify', async input => {
const { doubt, notify } = input const event = await this.handleGroupNotify(input)
const event = await this.handleGroupNotify(notify, doubt)
.catch(e => this.ctx.logger.error(e)) .catch(e => this.ctx.logger.error(e))
event && this.server.dispatch(event) event && this.server.dispatch(event)
}) })

View File

@@ -46,9 +46,9 @@ export async function parseGuildMemberRemoved(bot: SatoriAdapter, input: GroupNo
}) })
} }
export async function parseGuildMemberRequest(bot: SatoriAdapter, input: GroupNotify, doubt: boolean) { export async function parseGuildMemberRequest(bot: SatoriAdapter, input: GroupNotify) {
const groupCode = input.group.groupCode const groupCode = input.group.groupCode
const flag = `${groupCode}|${input.seq}|${input.type}|${doubt === true ? '1' : '0'}` const flag = groupCode + '|' + input.seq + '|' + input.type
return bot.event('guild-member-request', { return bot.event('guild-member-request', {
guild: decodeGuild(input.group), guild: decodeGuild(input.group),

View File

@@ -1 +1 @@
export const version = '4.1.3' export const version = '4.0.12'