Compare commits

...

85 Commits

Author SHA1 Message Date
linyuchen
9453b71943 refactor: remove nc packet api 2024-11-19 00:47:48 +08:00
linyuchen
0fb30df1bc chore: version 4.3.1 2024-11-17 15:22:06 +08:00
linyuchen
62e23614fb Merge branch 'dev' 2024-11-17 15:20:45 +08:00
linyuchen
5514bf0bb8 chore: bump version 2024-11-17 15:20:22 +08:00
linyuchen
f5d093cc45 fix: 调用发包接口时检查 QQ 版本,兼容 27333 - 27597 的戳一戳 2024-11-17 15:19:48 +08:00
linyuchen
44c6debd01 Merge branch 'dev' 2024-11-16 23:03:01 +08:00
linyuchen
2c1d12e04b Merge remote-tracking branch 'origin/dev' into dev 2024-11-16 23:01:39 +08:00
linyuchen
110193ea15 fix: 调用发包接口时检查QQ版本 2024-11-16 23:01:24 +08:00
idranme
fafcf058b1 refactor 2024-11-16 19:39:14 +08:00
linyuchen
825c7c8e29 Merge branch 'dev' 2024-11-16 14:49:13 +08:00
linyuchen
c8d5eebe5d feat: new api set_friend_remark, set_friend_category, set_group_remark, set_group_msg_mask, set_restart 2024-11-16 14:48:45 +08:00
linyuchen
466a3e4d66 Merge branch 'dev'
# Conflicts:
#	manifest.json
#	src/version.ts
2024-11-15 11:01:52 +08:00
linyuchen
f6263375f1 chore: version 4.2.2 2024-11-15 11:01:25 +08:00
linyuchen
f79581d97e 🐛修复 hook ipc 时获取不到 callbackId 导致其他插件 ipc 通信失败 2024-11-15 10:58:35 +08:00
linyuchen
56f26e9aa8 chore: version 4.2.1 2024-11-14 20:00:36 +08:00
linyuchen
9e03071629 Merge branch 'dev' 2024-11-14 19:58:27 +08:00
idranme
1f02c98c8f chore 2024-11-14 15:24:46 +08:00
linyuchen
e1e5c278b9 🐛修复 hook ipc 时获取不到 eventName 导致其他插件 ipc 通信失败 2024-11-14 14:51:01 +08:00
idranme
104839f7ea fix 2024-11-14 12:34:48 +08:00
idranme
bb8771a5b4 refactor 2024-11-14 11:40:19 +08:00
linyuchen
4a2523463b Merge remote-tracking branch 'origin/main' 2024-11-13 19:35:04 +08:00
linyuchen
a23a99310a Merge branch 'dev' 2024-11-13 19:34:18 +08:00
linyuchen
5c5105ce88 chore: version 4.2.0 2024-11-13 19:33:29 +08:00
linyuchen
1bf5e41bdc chore: 协议包支持 macOS 2024-11-13 19:27:50 +08:00
linyuchen
cd679cc041 refactor: 设置群员头衔的时候检查是否群主 2024-11-13 19:27:21 +08:00
linyuchen
eabee466bb refactor: 使用 napcat packet 实现戳一戳、群头衔、群打卡 2024-11-12 22:09:50 +08:00
idranme
d3f93257ce feat: get_stranger_info API adds city field 2024-11-10 16:59:58 +08:00
idranme
33f340ca81 chore 2024-11-10 14:18:09 +08:00
idranme
0d27ef7ebc Merge pull request #502 from LLOneBot/dev
release: 4.1.4
2024-11-09 22:29:16 +08:00
idranme
479e8c9d25 optimize 2024-11-09 22:21:04 +08:00
linyuchen
e3dffa24f8 Merge branch 'dev' 2024-11-09 21:40:06 +08:00
linyuchen
30b8793ee1 fix: 修复 IPC 超时 2024-11-09 21:37:41 +08:00
linyuchen
edf7a97269 Merge branch 'dev' 2024-11-08 18:27:06 +08:00
linyuchen
47b068737d chore: bump version, add author 2024-11-08 06:05:17 +08:00
linyuchen
bfb67188ce fix: DownloadFile接口参数url和base64二选一即可 2024-11-08 05:45:21 +08:00
linyuchen
7ad384d407 fix: 发送文件路径包含#%时发送失败 2024-11-08 05:44:55 +08:00
idranme
66335ddf9b Merge pull request #492 from LLOneBot/dev
release: 4.1.2
2024-10-27 12:11:50 +08:00
idranme
f7926c2e1b chore: bump versions 2024-10-27 12:07:21 +08:00
idranme
b669e28038 fix 2024-10-27 12:06:33 +08:00
idranme
70b3005005 Merge pull request #489 from LLOneBot/dev
release: 4.1.1
2024-10-26 00:19:15 +08:00
idranme
94f1d84dd8 chore: bump versions 2024-10-26 00:16:18 +08:00
idranme
aa2b4a160d fix 2024-10-26 00:15:48 +08:00
idranme
9be43de04b fix: forward 2024-10-26 00:14:27 +08:00
idranme
ac5fe4d275 Merge pull request #485 from LLOneBot/dev
release: 4.1.0
2024-10-24 22:11:38 +08:00
idranme
78f04f0ba2 chore: bump versions 2024-10-24 22:09:33 +08:00
idranme
f1027ec0d9 fix 2024-10-24 22:09:12 +08:00
idranme
f1b0be710a refactor 2024-10-24 20:46:21 +08:00
idranme
91ca4e96c4 fix 2024-10-24 17:40:35 +08:00
idranme
c9e39769dd feat: support for fake forward message 2024-10-23 23:30:27 +08:00
linyuchen
8b04833a6a 退出设置界面时检查配置是否改动并提示用户保存配置 2024-10-23 17:10:33 +08:00
linyuchen
4aadcd5288 Update README.md contributors 2024-10-21 17:14:54 +08:00
idranme
2f74de667e Merge pull request #481 from LLOneBot/dev
release: 4.0.13
2024-10-19 18:21:27 +08:00
idranme
2a67ffae24 chore: bump versions 2024-10-19 18:12:07 +08:00
idranme
78def9ebf8 fix 2024-10-19 18:09:33 +08:00
idranme
c6dddcd664 refactor 2024-10-19 18:09:23 +08:00
idranme
5b90a25f8f refactor 2024-10-19 15:57:58 +08:00
idranme
364dfe8b93 feat: get_group_file_system_info API 2024-10-19 10:31:14 +08:00
idranme
0fe725eb32 fix 2024-10-19 10:07:59 +08:00
idranme
8b89fd7a0b Merge pull request #479 from LLOneBot/dev
release: 4.0.12
2024-10-18 21:16:46 +08:00
idranme
1b0c9ad57c chore: bump versions 2024-10-18 21:10:57 +08:00
idranme
2910b8f4e6 optimize 2024-10-18 21:09:51 +08:00
idranme
2453509734 refactor 2024-10-18 00:03:23 +08:00
idranme
8239e9a243 Merge pull request #477 from LLOneBot/dev
release: 4.0.11
2024-10-16 11:44:43 +08:00
idranme
50e5f89f4f chore: bump versions 2024-10-16 11:43:14 +08:00
idranme
be2119a1e6 feat: add save button 2024-10-16 11:32:50 +08:00
idranme
951afea794 Merge pull request #475 from LLOneBot/dev
release: 4.0.10
2024-10-15 21:09:42 +08:00
idranme
0946d9652e chore: bump versions 2024-10-15 20:54:57 +08:00
idranme
a66e48dfb0 optimize 2024-10-15 20:53:25 +08:00
idranme
029842ca08 fix(onebot): group_increase event 2024-10-15 20:22:39 +08:00
idranme
39fda24799 fix: config hot update 2024-10-15 11:51:00 +08:00
idranme
a4beeba528 Merge pull request #474 from LLOneBot/dev
release: 4.0.9
2024-10-13 23:51:30 +08:00
idranme
c837e970df chore: bump versions 2024-10-13 23:48:50 +08:00
idranme
4ced7fa3cf fix 2024-10-13 23:48:22 +08:00
idranme
dbd71d4376 chore 2024-10-13 23:42:01 +08:00
idranme
d43612b2a3 feat(satori): support for receiving llonebot:ark element 2024-10-13 20:31:20 +08:00
idranme
31ad0195d8 fix(onebot): get_group_msg_history API 2024-10-13 19:52:29 +08:00
idranme
9b32140f87 Merge pull request #470 from LLOneBot/dev
release: 4.0.8
2024-10-13 16:36:12 +08:00
idranme
dc5982c6b2 chore: bump versions 2024-10-13 16:34:35 +08:00
idranme
ce46c99330 fix 2024-10-13 16:32:39 +08:00
idranme
d3abaf806f optimize 2024-10-13 16:32:18 +08:00
idranme
e10a67ce05 Merge pull request #468 from LLOneBot/dev
release: 4.0.7
2024-10-13 01:30:01 +08:00
idranme
c8e897abdb chore: bump versions 2024-10-13 01:29:19 +08:00
idranme
e07c06f3e9 Merge pull request #467 from LLOneBot/dev
...
2024-10-13 01:17:06 +08:00
idranme
9c694a11b5 fix: poke 2024-10-13 01:12:12 +08:00
idranme
6e3bb7c9cf fix 2024-10-13 01:10:39 +08:00
80 changed files with 8743 additions and 1567 deletions

7
.gitattributes vendored
View File

@@ -1,7 +0,0 @@
* text eol=lf
*.png -text
*.jpg -text
*.ico -text
*.gif -text
*.webp -text

View File

@@ -23,6 +23,10 @@ TG 群:<https://t.me/+nLZEnpne-pQ1OWFl>
[![Stargazers over time](https://starchart.cc/LLOneBot/LLOneBot.svg?variant=adaptive)](https://starchart.cc/LLOneBot/LLOneBot) [![Stargazers over time](https://starchart.cc/LLOneBot/LLOneBot.svg?variant=adaptive)](https://starchart.cc/LLOneBot/LLOneBot)
## 贡献者
[![Contributors](https://contributors-img.web.app/image?repo=LLOneBot/LLOneBot)](https://github.com/LOneBot/LLOneBot/graphs/contributors)
## 鸣谢 ## 鸣谢
- [NapCatQQ](https://github.com/NapNeko/NapCatQQ) - [NapCatQQ](https://github.com/NapNeko/NapCatQQ)

View File

@@ -39,6 +39,7 @@ const config: ElectronViteConfig = {
...external.map(genCpModule), ...external.map(genCpModule),
{ src: './manifest.json', dest: 'dist' }, { src: './manifest.json', dest: 'dist' },
{ src: './icon.webp', dest: 'dist' }, { src: './icon.webp', dest: 'dist' },
{ src: './src/ntqqapi/native/napcat-protocol-packet/Moehoo/*', dest: 'dist/main/Moehoo' },
], ],
}), }),
], ],

View File

@@ -4,12 +4,16 @@
"name": "LLOneBot", "name": "LLOneBot",
"slug": "LLOneBot", "slug": "LLOneBot",
"description": "实现 OneBot 11 和 Satori 协议,用于 QQ 机器人开发", "description": "实现 OneBot 11 和 Satori 协议,用于 QQ 机器人开发",
"version": "4.0.6", "version": "4.3.1",
"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-encode --no-verify -t static-module -w es6 -p src/ntqqapi/proto -o src/ntqqapi/proto/compiled.js systemMessage.proto profileLikeTip.proto && pbts -o src/ntqqapi/proto/compiled.d.ts src/ntqqapi/proto/compiled.js" "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"
}, },
"author": "", "author": "",
"license": "MIT", "license": "MIT",
@@ -25,26 +25,25 @@
"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.1",
"protobufjs": "^7.4.0", "protobufjs": "^7.4.0",
"silk-wasm": "^3.6.1", "silk-wasm": "^3.6.3",
"ts-case-convert": "^2.1.0", "ts-case-convert": "^2.1.0",
"ws": "^8.18.0" "ws": "^8.18.0"
}, },
"devDependencies": { "devDependencies": {
"@types/cors": "^2.8.17", "@types/cors": "^2.8.17",
"@types/express": "^5.0.0", "@types/express": "^5.0.0",
"@types/fluent-ffmpeg": "^2.1.26", "@types/fluent-ffmpeg": "^2.1.27",
"@types/node": "^20.14.15", "@types/node": "^20.14.15",
"@types/ws": "^8.5.12", "@types/ws": "^8.5.13",
"electron": "^31.4.0", "electron": "^31.4.0",
"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.8", "vite": "^5.4.10",
"vite-plugin-cp": "^4.0.8" "vite-plugin-cp": "^4.0.8"
}, },
"packageManager": "yarn@4.5.0" "packageManager": "yarn@4.5.1"
} }

View File

@@ -13,6 +13,10 @@ const manifest = {
{ {
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

@@ -1,6 +1,5 @@
export const CHANNEL_GET_CONFIG = 'llonebot_get_config' export const CHANNEL_GET_CONFIG = 'llonebot_get_config'
export const CHANNEL_SET_CONFIG = 'llonebot_set_config' export const CHANNEL_SET_CONFIG = 'llonebot_set_config'
export const CHANNEL_SET_CONFIG_CONFIRMED = 'llonebot_set_config_confirmed'
export const CHANNEL_LOG = 'llonebot_log' export const CHANNEL_LOG = 'llonebot_log'
export const CHANNEL_ERROR = 'llonebot_error' export const CHANNEL_ERROR = 'llonebot_error'
export const CHANNEL_UPDATE = 'llonebot_update' export const CHANNEL_UPDATE = 'llonebot_update'

View File

@@ -44,13 +44,14 @@ 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,
token: '', token: '',
enableLocalFile2Url: false, enableLocalFile2Url: false,
debug: false, debug: false,
log: false, log: true,
autoDeleteFile: false, autoDeleteFile: false,
autoDeleteFileSecond: 60, autoDeleteFileSecond: 60,
musicSignUrl: '', musicSignUrl: '',

View File

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

View File

@@ -27,9 +27,10 @@ export function checkFileReceived(path: string, timeout: number = 3000): Promise
export function calculateFileMD5(filePath: string): Promise<string> { export function calculateFileMD5(filePath: string): Promise<string> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const hash = createHash('md5')
// 创建一个流式读取器 // 创建一个流式读取器
const stream = fs.createReadStream(filePath) const stream = fs.createReadStream(filePath)
const hash = createHash('md5')
stream.on('data', (data: Buffer) => { stream.on('data', (data: Buffer) => {
// 当读取到数据时,更新哈希对象的状态 // 当读取到数据时,更新哈希对象的状态
@@ -122,8 +123,11 @@ 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 filePath = fileURLToPath(uri) const fileUri = uri.replace('%', '%25').replace('#', '%23')
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

@@ -0,0 +1,9 @@
import { BrowserWindow } from 'electron'
import { log } from '@/common/utils'
export function getAllWindowIds(): number[] {
const allWindows = BrowserWindow.getAllWindows();
const ids = allWindows.map(window => window.id);
log('getAllWindowIds', ids);
return ids;
}

View File

@@ -15,8 +15,7 @@ import {
CHANNEL_LOG, CHANNEL_LOG,
CHANNEL_SELECT_FILE, CHANNEL_SELECT_FILE,
CHANNEL_SET_CONFIG, CHANNEL_SET_CONFIG,
CHANNEL_UPDATE, CHANNEL_UPDATE
CHANNEL_SET_CONFIG_CONFIRMED
} from '../common/channels' } from '../common/channels'
import { startHook } from '../ntqqapi/hook' import { startHook } from '../ntqqapi/hook'
import { checkNewVersion, upgradeLLOneBot } from '../common/utils/upgrade' import { checkNewVersion, upgradeLLOneBot } from '../common/utils/upgrade'
@@ -35,8 +34,8 @@ import {
NTQQWebApi, NTQQWebApi,
NTQQWindowApi NTQQWindowApi
} from '../ntqqapi/api' } from '../ntqqapi/api'
import { mkdir } from 'node:fs/promises'
import { existsSync, mkdirSync } from 'node:fs' import { existsSync, mkdirSync } from 'node:fs'
import { NTQQSystemApi } from '@/ntqqapi/api/system'
declare module 'cordis' { declare module 'cordis' {
interface Events { interface Events {
@@ -56,6 +55,30 @@ function onLoad() {
mkdirSync(LOG_DIR) mkdirSync(LOG_DIR)
} }
if (!existsSync(TEMP_DIR)) {
mkdirSync(TEMP_DIR)
}
const dbDir = path.join(DATA_DIR, 'database')
if (!existsSync(dbDir)) {
mkdirSync(dbDir)
}
const ctx = new Context()
ctx.plugin(NTQQFileApi)
ctx.plugin(NTQQFileCacheApi)
ctx.plugin(NTQQFriendApi)
ctx.plugin(NTQQGroupApi)
ctx.plugin(NTQQMsgApi)
ctx.plugin(NTQQUserApi)
ctx.plugin(NTQQWebApi)
ctx.plugin(NTQQWindowApi)
ctx.plugin(Database)
ctx.plugin(NTQQSystemApi)
let started = false
ipcMain.handle(CHANNEL_CHECK_VERSION, async () => { ipcMain.handle(CHANNEL_CHECK_VERSION, async () => {
return checkNewVersion() return checkNewVersion()
}) })
@@ -114,7 +137,9 @@ function onLoad() {
if (!ask) { if (!ask) {
getConfigUtil().setConfig(config) getConfigUtil().setConfig(config)
log('配置已更新', config) log('配置已更新', config)
checkFfmpeg(config.ffmpeg).then() if (started) {
ctx.parallel('llob/config-updated', config)
}
resolve(true) resolve(true)
return return
} }
@@ -131,7 +156,9 @@ function onLoad() {
if (result.response === 0) { if (result.response === 0) {
getConfigUtil().setConfig(config) getConfigUtil().setConfig(config)
log('配置已更新', config) log('配置已更新', config)
checkFfmpeg(config.ffmpeg).then() if (started) {
ctx.parallel('llob/config-updated', config)
}
resolve(true) resolve(true)
} }
}) })
@@ -146,62 +173,7 @@ function onLoad() {
log(arg) log(arg)
}) })
async function start() { const intervalId = setInterval(async () => {
log('process pid', process.pid)
const config = getConfigUtil().getConfig()
if (!existsSync(TEMP_DIR)) {
await mkdir(TEMP_DIR)
}
const dbDir = path.join(DATA_DIR, 'database')
if (!existsSync(dbDir)) {
await mkdir(dbDir)
}
const ctx = new Context()
ctx.plugin(Log, {
enable: config.log!,
filename: logFileName
})
ctx.plugin(NTQQFileApi)
ctx.plugin(NTQQFileCacheApi)
ctx.plugin(NTQQFriendApi)
ctx.plugin(NTQQGroupApi)
ctx.plugin(NTQQMsgApi)
ctx.plugin(NTQQUserApi)
ctx.plugin(NTQQWebApi)
ctx.plugin(NTQQWindowApi)
ctx.plugin(Core, config)
ctx.plugin(Database)
ctx.plugin(SQLiteDriver, {
path: path.join(dbDir, `${selfInfo.uin}.db`)
})
ctx.plugin(Store, {
msgCacheExpire: config.msgCacheExpire! * 1000
})
if (config.ob11.enable) {
ctx.plugin(OneBot11Adapter, {
...config.ob11,
heartInterval: config.heartInterval,
token: config.token!,
debug: config.debug!,
musicSignUrl: config.musicSignUrl,
enableLocalFile2Url: config.enableLocalFile2Url!,
ffmpeg: config.ffmpeg,
})
}
if (config.satori.enable) {
ctx.plugin(SatoriAdapter, {
...config.satori,
ffmpeg: config.ffmpeg,
})
}
ctx.start()
llonebotError.otherError = ''
ipcMain.on(CHANNEL_SET_CONFIG_CONFIRMED, (event, config: LLOBConfig) => {
ctx.parallel('llob/config-updated', config)
})
}
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,
@@ -209,18 +181,62 @@ function onLoad() {
}) })
if (self.uin) { if (self.uin) {
clearInterval(intervalId) clearInterval(intervalId)
start() log('process pid', process.pid)
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, {
enable: config.log!,
filename: logFileName
})
ctx.plugin(SQLiteDriver, {
path: path.join(dbDir, `${selfInfo.uin}.db`)
})
ctx.plugin(Store, {
msgCacheExpire: config.msgCacheExpire! * 1000
})
ctx.plugin(Core, config)
if (config.ob11.enable) {
ctx.plugin(OneBot11Adapter, {
...config.ob11,
heartInterval: config.heartInterval,
token: config.token!,
debug: config.debug!,
musicSignUrl: config.musicSignUrl,
enableLocalFile2Url: config.enableLocalFile2Url!,
ffmpeg: config.ffmpeg,
})
}
if (config.satori.enable) {
ctx.plugin(SatoriAdapter, {
...config.satori,
ffmpeg: config.ffmpeg,
})
}
ctx.start()
started = true
llonebotError.otherError = ''
} }
}, 600) }, 500)
} }
// 创建窗口时触发 // 创建窗口时触发
function onBrowserWindowCreated(window: BrowserWindow) { function onBrowserWindowCreated(window: BrowserWindow) {
if (window.id === 2) {
mainWindow = window
}
} }
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, Peer } from '@/ntqqapi/types/msg' import { RichMediaDownloadCompleteNotify, RichMediaUploadCompleteNotify, RMBizType, 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,
params: { exParams: {
downSourceType: 1, downSourceType: 1,
triggerType: 1 triggerType: 1
} }
@@ -211,6 +211,28 @@ 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

@@ -58,7 +58,7 @@ export class NTQQFriendApi extends Service {
return Object.values(data.userSimpleInfos).filter(v => uids.includes(v.uid!)) return Object.values(data.userSimpleInfos).filter(v => uids.includes(v.uid!))
} }
/** uid => uin */ /** uid -> uin */
async getBuddyIdMap(refresh = false): Promise<Map<string, string>> { async getBuddyIdMap(refresh = false): Promise<Map<string, string>> {
const retMap: Map<string, string> = new Map() const retMap: Map<string, string> = new Map()
const data = await invoke<{ const data = await invoke<{
@@ -107,7 +107,7 @@ export class NTQQFriendApi extends Service {
return ret.arkMsg return ret.arkMsg
} }
async setBuddyRemark(uid: string, remark: string) { async setBuddyRemark(uid: string, remark = '') {
return await invoke('nodeIKernelBuddyService/setBuddyRemark', [{ return await invoke('nodeIKernelBuddyService/setBuddyRemark', [{
remarkParams: { uid, remark } remarkParams: { uid, remark }
}]) }])
@@ -122,4 +122,8 @@ export class NTQQFriendApi extends Service {
} }
}]) }])
} }
async setBuddyCategory(uid: string, categoryId: number) {
return await invoke('nodeIKernelBuddyService/setBuddyCategory', [{ uid, categoryId }])
}
} }

View File

@@ -9,7 +9,8 @@ import {
PublishGroupBulletinReq, PublishGroupBulletinReq,
GroupAllInfo, GroupAllInfo,
GroupFileInfo, GroupFileInfo,
GroupBulletinListResult GroupBulletinListResult,
GroupMsgMask
} from '../types' } from '../types'
import { invoke, NTClass, NTMethod } from '../ntcall' import { invoke, NTClass, NTMethod } from '../ntcall'
import { GeneralCallResult } from '../services' import { GeneralCallResult } from '../services'
@@ -45,8 +46,11 @@ export class NTQQGroupApi extends Service {
return result.groupList return result.groupList
} }
async getGroupMembers(groupCode: string, num = 3000): Promise<Map<string, GroupMember>> { async getGroupMembers(groupCode: string, num = 3000) {
const sceneId = await invoke(NTMethod.GROUP_MEMBER_SCENE, [{ groupCode, scene: 'groupMemberList_MainWindow' }]) const sceneId = await invoke(NTMethod.GROUP_MEMBER_SCENE, [{
groupCode,
scene: 'groupMemberList_MainWindow'
}])
const data = await invoke(NTMethod.GROUP_MEMBERS, [{ sceneId, num }]) const data = await invoke(NTMethod.GROUP_MEMBERS, [{ sceneId, num }])
if (data.errCode !== 0) { if (data.errCode !== 0) {
throw new Error('获取群成员列表出错,' + data.errMsg) throw new Error('获取群成员列表出错,' + data.errMsg)
@@ -80,7 +84,7 @@ export class NTQQGroupApi extends Service {
} }
async getGroupIgnoreNotifies() { async getGroupIgnoreNotifies() {
await this.getSingleScreenNotifies(14) await this.getSingleScreenNotifies(false, 14)
return await this.ctx.ntWindowApi.openWindow<GeneralCallResult & GroupNotifies>( return await this.ctx.ntWindowApi.openWindow<GeneralCallResult & GroupNotifies>(
NTQQWindows.GroupNotifyFilterWindow, NTQQWindows.GroupNotifyFilterWindow,
[], [],
@@ -88,17 +92,18 @@ export class NTQQGroupApi extends Service {
) )
} }
async getSingleScreenNotifies(number: number, startSeq = '') { async getSingleScreenNotifies(doubt: boolean, number: number, startSeq = '') {
invoke(ReceiveCmdS.GROUP_NOTIFY, [], { registerEvent: true }) await invoke(ReceiveCmdS.GROUP_NOTIFY, [], { registerEvent: true })
return (await invoke<GroupNotifies>( const data = await invoke<GroupNotifies>(
'nodeIKernelGroupService/getSingleScreenNotifies', 'nodeIKernelGroupService/getSingleScreenNotifies',
[{ doubt: false, startSeq, number }], [{ doubt, 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) {
@@ -106,8 +111,9 @@ 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: false, doubt,
operateMsg: { operateMsg: {
operateType, operateType,
targetMsg: { targetMsg: {
@@ -322,4 +328,26 @@ 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 }]
)
}
async setGroupMsgMask(groupCode: string, msgMask: GroupMsgMask) {
return await invoke('nodeIKernelGroupService/setGroupMsgMask', [{ groupCode, msgMask }])
}
async setGroupRemark(groupCode: string, groupRemark = '') {
return await invoke('nodeIKernelGroupService/modifyGroupRemark', [{ groupCode, groupRemark }])
}
} }

View File

@@ -52,7 +52,7 @@ export class NTQQMsgApi extends Service {
} }
async getMsgHistory(peer: Peer, msgId: string, cnt: number, queryOrder = false) { async getMsgHistory(peer: Peer, msgId: string, cnt: number, queryOrder = false) {
// 默认情况下消息时间从旧到 // 默认情况下消息时间从新到旧
return await invoke(NTMethod.HISTORY_MSG, [{ peer, msgId, cnt, queryOrder }]) return await invoke(NTMethod.HISTORY_MSG, [{ peer, msgId, cnt, queryOrder }])
} }
@@ -62,21 +62,35 @@ export class NTQQMsgApi extends Service {
async sendMsg(peer: Peer, msgElements: SendMessageElement[], timeout = 10000) { async sendMsg(peer: Peer, msgElements: SendMessageElement[], timeout = 10000) {
const uniqueId = await this.generateMsgUniqueId(peer.chatType) const uniqueId = await this.generateMsgUniqueId(peer.chatType)
peer.guildId = uniqueId const msgAttributeInfos = new Map()
msgAttributeInfos.set(0, {
attrType: 0,
attrId: uniqueId,
vasMsgInfo: {
msgNamePlateInfo: {},
bubbleInfo: {},
avatarPendantInfo: {},
vasFont: {},
iceBreakInfo: {}
}
})
let sentMsgId: string
const data = await invoke<{ msgList: RawMessage[] }>( const data = await invoke<{ msgList: RawMessage[] }>(
'nodeIKernelMsgService/sendMsg', 'nodeIKernelMsgService/sendMsg',
[{ [{
msgId: '0', msgId: '0',
peer, peer,
msgElements, msgElements,
msgAttributeInfos: new Map() msgAttributeInfos
}], }],
{ {
cbCmd: 'nodeIKernelMsgListener/onMsgInfoListUpdate', cbCmd: 'nodeIKernelMsgListener/onMsgInfoListUpdate',
afterFirstCmd: false, afterFirstCmd: false,
cmdCB: payload => { cmdCB: payload => {
for (const msgRecord of payload.msgList) { for (const msgRecord of payload.msgList) {
if (msgRecord.guildId === uniqueId && msgRecord.sendStatus === 2) { if (msgRecord.msgAttrs.get(0)?.attrId === uniqueId && msgRecord.sendStatus === 2) {
sentMsgId = msgRecord.msgId
return true return true
} }
} }
@@ -85,15 +99,15 @@ export class NTQQMsgApi extends Service {
timeout timeout
} }
) )
delete peer.guildId
return data.msgList.find(msgRecord => msgRecord.guildId === uniqueId) return data.msgList.find(msgRecord => msgRecord.msgId === sentMsgId)
} }
async forwardMsg(srcPeer: Peer, destPeer: Peer, msgIds: string[]) { async forwardMsg(srcPeer: Peer, destPeer: Peer, msgIds: string[]) {
const uniqueId = await this.generateMsgUniqueId(destPeer.chatType) const uniqueId = await this.generateMsgUniqueId(destPeer.chatType)
destPeer.guildId = uniqueId destPeer.guildId = uniqueId
const data = await invoke<{ msgList: RawMessage[] }>( const data = await invoke<{ msgList: RawMessage[] }>(
'nodeIKernelMsgService/forwardMsg', 'nodeIKernelMsgService/forwardMsgWithComment',
[{ [{
msgIds, msgIds,
srcContact: srcPeer, srcContact: srcPeer,
@@ -111,7 +125,8 @@ export class NTQQMsgApi extends Service {
} }
} }
return false return false
} },
timeout: 3000
} }
) )
delete destPeer.guildId delete destPeer.guildId
@@ -138,7 +153,17 @@ 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 (msgRecord.peerUid === destPeer.peerUid && msgRecord.senderUid === selfUid) { if (
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
} }
} }
@@ -146,20 +171,12 @@ export class NTQQMsgApi extends Service {
} }
} }
) )
for (const msg of data.msgList) { return data.msgList.find(msgRecord => {
const arkElement = msg.elements.find(ele => ele.arkElement) const { arkElement } = msgRecord.elements[0]
if (!arkElement) { if (arkElement?.bytesData.includes('com.tencent.multimsg')) {
continue return true
} }
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) {

38
src/ntqqapi/api/system.ts Normal file
View File

@@ -0,0 +1,38 @@
import { Context, Service } from 'cordis'
import { invoke, NTClass } from '@/ntqqapi/ntcall'
declare module 'cordis' {
interface Context {
ntSystemApi: NTQQSystemApi
}
}
export class NTQQSystemApi extends Service {
constructor(protected ctx: Context) {
super(ctx, 'ntSystemApi', true)
}
async restart() {
// todo: 调用此接口后会将 NTQQ 设置里面的自动登录和无需手机确认打开,重启后将状态恢复到之前的状态
// 设置自动登录
await this.setSettingAutoLogin(true)
// 退出账号
invoke('quitAccount', [], {
className: NTClass.BUSINESS_API
}).then()
invoke('notifyQQClose', [{ type: 1 }], { className: NTClass.QQ_EX_API }).then()
// 等待登录界面,模拟点击登录按钮?还是直接调用登录方法?
}
async getSettingAutoLogin() {
// 查询是否自动登录
return invoke('nodeIKernelNodeMiscService/queryAutoRun', [])
}
async setSettingAutoLogin(state: boolean) {
await invoke('nodeIKernelSettingService/setNeedConfirmSwitch', [{ state: 1 }]) // 1不需要手机确认2需要手机确认
await invoke('nodeIKernelSettingService/setAutoLoginSwitch', [{ state }])
}
}

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 } from '../ntcall' import { invoke, NTClass } 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'
@@ -118,7 +118,7 @@ export class NTQQUserApi extends Service {
await this.ctx.sleep(30) await this.ctx.sleep(30)
member = await this.ctx.ntGroupApi.searchMember(groupCode, uin) member = await this.ctx.ntGroupApi.searchMember(groupCode, uin)
} }
uid = member.values().find(e => e.uin === uin)?.uid uid = Array.from(member.values()).find(e => e.uin === uin)?.uid
} }
if (!uid) { if (!uid) {
const unveifyUid = (await this.getUserDetailInfoByUin(uin)).info.uid const unveifyUid = (await this.getUserDetailInfoByUin(uin)).info.uid
@@ -173,12 +173,12 @@ 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) return uin if (uin && uin !== '0') 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)
if (uin) return uin if (uin) return uin
uin = (await this.ctx.ntFriendApi.getBuddyIdMap(true)).get(uid) uin = (await this.ctx.ntFriendApi.getBuddyIdMap()).get(uid)
if (uin) return uin if (uin) return uin
uin = (await this.getUserDetailInfo(uid)).uin uin = (await this.getUserDetailInfo(uid)).uin
return uin return uin
@@ -288,4 +288,14 @@ 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,10 +16,10 @@ import {
BuddyReqType, BuddyReqType,
GrayTipElementSubType GrayTipElementSubType
} from './types' } from './types'
import { selfInfo, llonebotError } from '../common/globalVars' import { selfInfo } 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/crychic'
declare module 'cordis' { declare module 'cordis' {
interface Context { interface Context {
@@ -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: GroupNotify) => void 'nt/group-notify': (input: { notify: GroupNotify, doubt: boolean }) => 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,11 +47,6 @@ 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}`)
@@ -173,9 +168,10 @@ class Core extends Service {
}) })
registerReceiveHook<{ msgList: RawMessage[] }>([ReceiveCmdS.NEW_MSG, ReceiveCmdS.NEW_ACTIVE_MSG], payload => { registerReceiveHook<{ msgList: RawMessage[] }>([ReceiveCmdS.NEW_MSG, ReceiveCmdS.NEW_ACTIVE_MSG], payload => {
const startTime = this.startTime / 1000
for (const message of payload.msgList) { for (const message of payload.msgList) {
// 过滤启动之前的消息 // 过滤启动之前的消息
if (parseInt(message.msgTime) < this.startTime / 1000) { if (parseInt(message.msgTime) < startTime) {
continue continue
} }
if (message.senderUin && message.senderUin !== '0') { if (message.senderUin && message.senderUin !== '0') {
@@ -201,8 +197,10 @@ 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)) {
sentMsgIds.delete(msg.msgId) if (msg.sendStatus === 2) {
this.ctx.parallel('nt/message-sent', msg) sentMsgIds.delete(msg.msgId)
this.ctx.parallel('nt/message-sent', msg)
}
} }
} }
}) })
@@ -211,7 +209,7 @@ class Core extends Service {
sentMsgIds.set(payload.msgRecord.msgId, true) sentMsgIds.set(payload.msgRecord.msgId, true)
}) })
const groupNotifyFlags: string[] = [] const groupNotifyIgnore: string[] = []
registerReceiveHook<{ registerReceiveHook<{
doubt: boolean doubt: boolean
oldestUnreadSeq: string oldestUnreadSeq: string
@@ -220,19 +218,17 @@ 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.unreadCount) notifies = await this.ctx.ntGroupApi.getSingleScreenNotifies(payload.doubt, payload.unreadCount)
} catch (e) { } catch (e) {
return return
} }
for (const notify of notifies) { for (const notify of notifies) {
const flag = notify.group.groupCode + '|' + notify.seq + '|' + notify.type const notifyTime = Math.trunc(+notify.seq / 1000)
const notifyTime = parseInt(notify.seq) / 1000 if (groupNotifyIgnore.includes(notify.seq) || notifyTime < this.startTime) {
if (groupNotifyFlags.includes(flag) || notifyTime < this.startTime) {
continue continue
} }
groupNotifyFlags.shift() groupNotifyIgnore.push(notify.seq)
groupNotifyFlags.push(flag) this.ctx.parallel('nt/group-notify', { notify, doubt: payload.doubt })
this.ctx.parallel('nt/group-notify', notify)
} }
} }
}) })

View File

@@ -2,6 +2,7 @@ import { NTMethod } from './ntcall'
import { log } from '@/common/utils' import { log } from '@/common/utils'
import { randomUUID } from 'node:crypto' import { randomUUID } from 'node:crypto'
import { ipcMain } from 'electron' import { ipcMain } from 'electron'
import { Dict } from 'cosmokit'
export const hookApiCallbacks: Record<string, (res: any) => void> = {} export const hookApiCallbacks: Record<string, (res: any) => void> = {}
@@ -29,11 +30,10 @@ export enum ReceiveCmdS {
const logHook = false const logHook = false
const receiveHooks: Array<{ const receiveHooks: Map<string, {
method: ReceiveCmdS[] method: ReceiveCmdS[]
hookFunc: (payload: any) => void | Promise<void> hookFunc: (payload: any) => void | Promise<void>
id: string }> = new Map()
}> = []
const callHooks: Array<{ const callHooks: Array<{
method: NTMethod[] method: NTMethod[]
@@ -41,40 +41,43 @@ const callHooks: Array<{
}> = [] }> = []
export function startHook() { export function startHook() {
log('start hook')
const senderExclude = Symbol() const senderExclude = Symbol()
ipcMain.emit = new Proxy(ipcMain.emit, { ipcMain.emit = new Proxy(ipcMain.emit, {
apply(target, thisArg, args: [eventName: string, ...args: any]) { apply(target, thisArg, args: [channel: string, ...args: any]) {
if (args[2]?.eventName.startsWith('ns-LoggerApi')) { if (args[2]?.eventName?.startsWith('ns-LoggerApi')) {
return target.apply(thisArg, args) return target.apply(thisArg, args)
} }
if (logHook) { if (logHook) {
log('request', args) log('request', args)
} }
const event = args[1] const event = args[1]
if (event.sender && !event.sender[senderExclude]) { if (event.sender && !event.sender[senderExclude]) {
event.sender[senderExclude] = true event.sender[senderExclude] = true
event.sender.send = new Proxy(event.sender.send, { event.sender.send = new Proxy(event.sender.send, {
apply(target, thisArg, args: any[]) { apply(target, thisArg, args: [channel: string, meta: Dict, data: Dict[]]) {
if (args[1].eventName?.startsWith('ns-LoggerApi')) { if (args[1]?.eventName?.startsWith('ns-LoggerApi')) {
return target.apply(thisArg, args) return target.apply(thisArg, args)
} }
if (logHook) { if (logHook) {
log('received', args) log('received', args)
} }
const callbackId = args[1].callbackId const callbackId = args[1]?.callbackId
if (callbackId) { if (callbackId) {
if (hookApiCallbacks[callbackId]) { if (hookApiCallbacks[callbackId]) {
Promise.resolve(hookApiCallbacks[callbackId](args[2])) Promise.resolve(hookApiCallbacks[callbackId](args[2]))
delete hookApiCallbacks[callbackId] delete hookApiCallbacks[callbackId]
} }
} else if (args[2]) { } else if (args[2]) {
for (const receiveData of args[2]) { if (['IPC_DOWN_2', 'IPC_DOWN_3'].includes(args[0])) {
for (const hook of receiveHooks) { for (const receiveData of args[2]) {
if (hook.method.includes(receiveData.cmdName)) { for (const hook of receiveHooks.values()) {
Promise.resolve(hook.hookFunc(receiveData.payload)) if (hook.method.includes(receiveData.cmdName)) {
Promise.resolve(hook.hookFunc(receiveData.payload))
}
} }
} }
} }
@@ -94,7 +97,7 @@ export function startHook() {
} }
} }
return target.apply(thisArg, args) return target.apply(thisArg, args)
} },
}) })
} }
@@ -106,10 +109,9 @@ export function registerReceiveHook<PayloadType>(
if (!Array.isArray(method)) { if (!Array.isArray(method)) {
method = [method] method = [method]
} }
receiveHooks.push({ receiveHooks.set(id, {
method: method as ReceiveCmdS[], method: method as ReceiveCmdS[],
hookFunc, hookFunc,
id,
}) })
return id return id
} }
@@ -128,6 +130,5 @@ export function registerCallHook(
} }
export function removeReceiveHook(id: string) { export function removeReceiveHook(id: string) {
const index = receiveHooks.findIndex((h) => h.id === id) receiveHooks.delete(id)
receiveHooks.splice(index, 1)
} }

View File

@@ -0,0 +1,99 @@
import { Context } from 'cordis'
import { Dict } from 'cosmokit'
import { getBuildVersion } from '../../../common/utils/misc'
import { TEMP_DIR } from '../../../common/globalVars'
import { copyFile } from 'fs/promises'
import { ChatType, Peer } from '../../types'
import path from 'node:path'
import addon from './external/crychic-win32-x64.node?asset'
export class Native {
public activated = false
private crychic?: Dict
private seq = 0
private cb: Map<number, (res: any) => void> = new Map()
constructor(private ctx: Context) {
ctx.on('ready', () => {
this.start()
})
}
checkPlatform() {
return process.platform === 'win32' && process.arch === 'x64'
}
checkVersion() {
const version = getBuildVersion()
// 27333—27597
return version >= 27333 && version < 28060
}
async start() {
if (this.crychic) {
return
}
if (!this.checkPlatform()) {
return
}
if (!this.checkVersion()) {
return
}
const handler = async (name: string, ...e: unknown[]) => {
if (name === 'cb') {
this.cb.get(e[0] as number)?.(e[1])
}
}
try {
const fileName = path.basename(addon)
const dest = path.join(TEMP_DIR, fileName)
try {
await copyFile(addon, dest)
} catch (e) {
// resource busy or locked?
this.ctx.logger.warn(e)
}
this.crychic = require(dest)
this.crychic!.setCryHandler(handler)
this.crychic!.init()
this.activated = true
} catch (e) {
this.ctx.logger.warn('crychic 加载失败', e)
}
}
async sendFriendPoke(uin: number) {
if (!this.crychic) return
this.crychic.sendFriendPoke(uin)
await this.ctx.ntMsgApi.fetchUnitedCommendConfig(['100243'])
}
async sendGroupPoke(groupCode: number, memberUin: number) {
if (!this.crychic) return
this.crychic.sendGroupPoke(memberUin, groupCode)
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,55 +0,0 @@
import { Context } from 'cordis'
import { Dict } from 'cosmokit'
import { getBuildVersion } from '@/common/utils/misc'
// @ts-expect-error: Unreachable code error
import addon from './external/crychic-win32-x64.node?asset'
export class Native {
private crychic?: Dict
constructor(private ctx: Context) {
ctx.on('ready', () => {
this.start()
})
}
checkPlatform() {
return process.platform === 'win32' && process.arch === 'x64'
}
checkVersion() {
const version = getBuildVersion()
// 27187—27597
return version >= 27187 && version < 28060
}
start() {
if (this.crychic) {
return
}
if (!this.checkPlatform()) {
return
}
if (!this.checkVersion()) {
return
}
try {
this.crychic = require(addon)
this.crychic.init()
} catch (e) {
this.ctx.logger.warn('crychic 加载失败', e)
}
}
async sendFriendPoke(uin: number) {
if (!this.crychic) return
this.crychic.sendFriendPoke(uin)
await this.ctx.ntMsgApi.fetchUnitedCommendConfig(['100243'])
}
async sendGroupPoke(groupCode: number, memberUin: number) {
if (!this.crychic) return
this.crychic.sendGroupPoke(memberUin, groupCode)
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 { log } from '../common/utils/legacyLog' import { log } from '../common/utils'
import { randomUUID } from 'node:crypto' import { randomUUID } from 'node:crypto'
import { import {
GeneralCallResult, GeneralCallResult,
@@ -29,7 +29,8 @@ export enum NTClass {
SKEY_API = 'ns-SkeyApi', SKEY_API = 'ns-SkeyApi',
GROUP_HOME_WORK = 'ns-GroupHomeWork', GROUP_HOME_WORK = 'ns-GroupHomeWork',
GROUP_ESSENCE = 'ns-GroupEssence', GROUP_ESSENCE = 'ns-GroupEssence',
NODE_STORE_API = 'ns-NodeStoreApi' NODE_STORE_API = 'ns-NodeStoreApi',
QQ_EX_API = 'ns-QQEXApi',
} }
export enum NTMethod { export enum NTMethod {
@@ -108,13 +109,26 @@ interface InvokeOptions<ReturnType> {
timeout?: number timeout?: number
} }
let channel: NTChannel
function getChannel() {
if (channel) {
return channel
}
if (ipcMain.eventNames().includes(NTChannel.IPC_UP_2)) {
return channel = NTChannel.IPC_UP_2
} else {
return channel = NTChannel.IPC_UP_3
}
}
export function invoke< export function invoke<
R extends Awaited<ReturnType<Extract<NTService[S][M], (...args: any) => unknown>>>, R extends Awaited<ReturnType<Extract<NTService[S][M], (...args: any) => unknown>>>,
S extends keyof NTService = any, S extends keyof NTService = any,
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 ?? NTChannel.IPC_UP_2 const channel = options.channel ?? getChannel()
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]
@@ -124,7 +138,12 @@ export function invoke<
return new Promise<R>((resolve, reject) => { return new Promise<R>((resolve, reject) => {
const apiArgs = [method, ...args] const apiArgs = [method, ...args]
const callbackId = randomUUID() const callbackId = randomUUID()
let eventId: string
const timeoutId = setTimeout(() => { const timeoutId = setTimeout(() => {
if (eventId) {
removeReceiveHook(eventId)
}
log(`ntqq api timeout ${channel}, ${eventName}, ${method}`, args) log(`ntqq api timeout ${channel}, ${eventName}, ${method}`, args)
reject(`ntqq api timeout ${channel}, ${eventName}, ${method}, ${JSON.stringify(args)}`) reject(`ntqq api timeout ${channel}, ${eventName}, ${method}, ${JSON.stringify(args)}`)
}, timeout) }, timeout)
@@ -140,19 +159,15 @@ export function invoke<
let result: unknown let result: unknown
// 这里的callback比较特殊QQ后端先返回是否调用成功再返回一条结果数据 // 这里的callback比较特殊QQ后端先返回是否调用成功再返回一条结果数据
const secondCallback = () => { const secondCallback = () => {
const hookId = registerReceiveHook<R>(options.cbCmd!, (payload) => { eventId = registerReceiveHook<R>(options.cbCmd!, (payload) => {
if (options.cmdCB) { if (options.cmdCB) {
if (options.cmdCB(payload, result)) { if (!options.cmdCB(payload, result)) {
removeReceiveHook(hookId) return
clearTimeout(timeoutId)
resolve(payload)
} }
} }
else { removeReceiveHook(eventId)
removeReceiveHook(hookId) clearTimeout(timeoutId)
clearTimeout(timeoutId) resolve(payload)
resolve(payload)
}
}) })
} }
!afterFirstCmd && secondCallback() !afterFirstCmd && secondCallback()
@@ -162,9 +177,12 @@ export function invoke<
afterFirstCmd && secondCallback() afterFirstCmd && secondCallback()
} }
else { else {
log('ntqq api call failed,', method, args, res)
clearTimeout(timeoutId) clearTimeout(timeoutId)
reject(`ntqq api call failed, ${method}, ${res?.errMsg}`) if (eventId) {
removeReceiveHook(eventId)
}
log('ntqq api call failed,', method, args, res)
reject(`ntqq api call failed, ${method}, ${JSON.stringify(res)}`)
} }
} }
} }

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,14 @@
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

@@ -0,0 +1,134 @@
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

@@ -0,0 +1,76 @@
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

@@ -1,30 +0,0 @@
syntax = "proto3";
package SysMsg;
message SystemMessage {
repeated SystemMessageHeader header = 1;
repeated SystemMessageMsgSpec msgSpec = 2;
SystemMessageBodyWrapper bodyWrapper = 3;
}
message SystemMessageHeader {
uint32 peerNumber = 1;
string peerString = 2;
uint32 uin = 5;
optional string uid = 6;
}
message SystemMessageMsgSpec {
uint32 msgType = 1;
uint32 subType = 2;
uint32 subSubType = 3;
uint32 msgSeq = 5;
uint32 time = 6;
//uint64 msgId = 12;
uint32 other = 13;
}
message SystemMessageBodyWrapper {
bytes body = 2;
// Find the first [08], or ignore the first 7 bytes?
}

View File

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

View File

@@ -12,4 +12,6 @@ export interface NodeIKernelNodeMiscService {
score: '' score: ''
}[] }[]
}> }>
queryAutoRun(): Promise<boolean>
} }

View File

@@ -39,5 +39,21 @@ 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

@@ -1,10 +1,3 @@
export enum GroupListUpdateType {
REFRESHALL,
GETALL,
MODIFIED,
REMOVE
}
export interface Group { export interface Group {
groupCode: string groupCode: string
maxMember: number maxMember: number
@@ -188,3 +181,10 @@ export interface GroupBulletinListResult {
nextIndex: number nextIndex: number
jointime: string jointime: string
} }
export enum GroupMsgMask {
AllowNotify = 1, // 允许提醒
AllowNotNotify = 4, // 接受消息不提醒
BoxNotNotify = 2, // 收进群助手不提醒
NotAllow = 3, // 屏蔽
}

View File

@@ -80,7 +80,7 @@ export interface SendVideoElement {
export interface SendArkElement { export interface SendArkElement {
elementType: ElementType.Ark elementType: ElementType.Ark
elementId: '' elementId: ''
arkElement: ArkElement arkElement: Partial<ArkElement>
} }
export type SendMessageElement = export type SendMessageElement =
@@ -294,6 +294,9 @@ export interface GrayTipElement {
jsonGrayTipElement?: { jsonGrayTipElement?: {
busiId: string busiId: string
jsonStr: string jsonStr: string
xmlToJsonParam?: {
templParam: Map<string, string>
}
} }
} }
@@ -435,6 +438,11 @@ export interface RawMessage {
likesCnt: string likesCnt: string
isClicked: boolean isClicked: boolean
}[] }[]
msgAttrs: Map<number, {
attrType: number
attrId: string
}>
isOnlineMsg: boolean
} }
export interface Peer { export interface Peer {
@@ -580,3 +588,31 @@ 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,7 +1,8 @@
export enum Sex { export enum Sex {
male = 0, Unknown = 0,
female = 2, Male = 1,
unknown = 255, Female = 2,
Hidden = 255
} }
export interface QQLevel { export interface QQLevel {
@@ -101,7 +102,7 @@ export interface BaseInfo {
birthday_month: number birthday_month: number
birthday_day: number birthday_day: number
age: number age: number
sex: number sex: Sex
eMail: string eMail: string
phoneNum: string phoneNum: string
categoryId: number categoryId: number
@@ -296,7 +297,7 @@ export interface UserDetailInfoByUin {
birthday_year: number birthday_year: number
birthday_month: number birthday_month: number
birthday_day: number birthday_day: number
sex: number //0 sex: number
topTime: string topTime: string
constellation: number constellation: number
shengXiao: number shengXiao: 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: String, url: Schema.string(),
base64: String, base64: Schema.string(),
headers: Schema.union([String, Schema.array(String)]) headers: Schema.union([String, Schema.array(String)])
}) })

View File

@@ -0,0 +1,32 @@
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

@@ -30,12 +30,12 @@ export class GetGroupMsgHistory extends BaseAction<Payload, Response> {
const { count, reverseOrder } = payload const { count, reverseOrder } = payload
const peer = { chatType: ChatType.Group, peerUid: payload.group_id.toString() } const peer = { chatType: ChatType.Group, peerUid: payload.group_id.toString() }
let msgList: RawMessage[] let msgList: RawMessage[]
if (!payload.message_seq || payload.message_seq === '0') { if (!payload.message_seq || +payload.message_seq === 0) {
msgList = (await this.ctx.ntMsgApi.getAioFirstViewLatestMsgs(peer, +count)).msgList msgList = (await this.ctx.ntMsgApi.getAioFirstViewLatestMsgs(peer, +count)).msgList
} else { } else {
const startMsgId = (await this.ctx.store.getMsgInfoByShortId(+payload.message_seq))?.msgId const startMsgId = (await this.ctx.store.getMsgInfoByShortId(+payload.message_seq))?.msgId
if (!startMsgId) throw new Error(`消息${payload.message_seq}不存在`) if (!startMsgId) throw new Error(`消息${payload.message_seq}不存在`)
msgList = (await this.ctx.ntMsgApi.getMsgHistory(peer, startMsgId, +count)).msgList msgList = (await this.ctx.ntMsgApi.getMsgHistory(peer, startMsgId, +count, true)).msgList
} }
if (!msgList?.length) throw new Error('未找到消息') if (!msgList?.length) throw new Error('未找到消息')
if (reverseOrder) msgList.reverse() if (reverseOrder) msgList.reverse()

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(10) const singleScreenNotifies = await this.ctx.ntGroupApi.getSingleScreenNotifies(false, 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

@@ -3,59 +3,54 @@ import { OB11User } from '../../types'
import { OB11Entities } from '../../entities' import { OB11Entities } from '../../entities'
import { ActionName } from '../types' import { ActionName } from '../types'
import { getBuildVersion } from '@/common/utils' import { getBuildVersion } from '@/common/utils'
import { OB11UserSex } from '../../types'
import { calcQQLevel } from '@/common/utils/misc' import { calcQQLevel } from '@/common/utils/misc'
interface Payload { interface Payload {
user_id: number | string user_id: number | string
} }
export class GetStrangerInfo extends BaseAction<Payload, OB11User> { interface Response extends OB11User {
reg_time: number
long_nick: string
city: string
}
export class GetStrangerInfo extends BaseAction<Payload, Response> {
actionName = ActionName.GoCQHTTP_GetStrangerInfo actionName = ActionName.GoCQHTTP_GetStrangerInfo
payloadSchema = Schema.object({ payloadSchema = Schema.object({
user_id: Schema.union([Number, String]).required() user_id: Schema.union([Number, String]).required()
}) })
protected async _handle(payload: Payload): Promise<OB11User> { protected async _handle(payload: Payload) {
if (!(getBuildVersion() >= 26702)) { const uin = payload.user_id.toString()
const user_id = payload.user_id.toString() if (getBuildVersion() >= 26702) {
const extendData = await this.ctx.ntUserApi.getUserDetailInfoByUin(user_id) const data = await this.ctx.ntUserApi.getUserDetailInfoByUinV2(uin)
const uid = (await this.ctx.ntUserApi.getUidByUin(user_id))! return {
if (!uid || uid.indexOf('*') != -1) { user_id: parseInt(data.detail.uin) || 0,
const ret = { nickname: data.detail.simpleInfo.coreInfo.nick,
...extendData, sex: OB11Entities.sex(data.detail.simpleInfo.baseInfo.sex),
user_id: parseInt(extendData.info.uin) || 0, age: data.detail.simpleInfo.baseInfo.age,
nickname: extendData.info.nick, qid: data.detail.simpleInfo.baseInfo.qid,
sex: OB11UserSex.Unknown, level: data.detail.commonExt.qqLevel && calcQQLevel(data.detail.commonExt.qqLevel) || 0,
age: (extendData.info.birthday_year == 0) ? 0 : new Date().getFullYear() - extendData.info.birthday_year, login_days: 0,
qid: extendData.info.qid, reg_time: data.detail.commonExt.regTime,
level: extendData.info.qqLevel && calcQQLevel(extendData.info.qqLevel) || 0, long_nick: data.detail.simpleInfo.baseInfo.longNick,
login_days: 0, city: data.detail.commonExt.city
uid: ''
}
return ret
} }
const data = { ...extendData, ...(await this.ctx.ntUserApi.getUserDetailInfo(uid)) }
return OB11Entities.stranger(data)
} else { } else {
const user_id = payload.user_id.toString() const data = await this.ctx.ntUserApi.getUserDetailInfoByUin(uin)
const extendData = await this.ctx.ntUserApi.getUserDetailInfoByUinV2(user_id) return {
const uid = (await this.ctx.ntUserApi.getUidByUin(user_id))! user_id: parseInt(data.info.uin) || 0,
if (!uid || uid.indexOf('*') != -1) { nickname: data.info.nick,
const ret = { sex: OB11Entities.sex(data.info.sex),
...extendData, age: data.info.birthday_year === 0 ? 0 : new Date().getFullYear() - data.info.birthday_year,
user_id: parseInt(extendData.detail.uin) || 0, qid: data.info.qid,
nickname: extendData.detail.simpleInfo.coreInfo.nick, level: data.info.qqLevel && calcQQLevel(data.info.qqLevel) || 0,
sex: OB11UserSex.Unknown, login_days: 0,
age: 0, reg_time: data.info.regTime,
level: extendData.detail.commonExt.qqLevel && calcQQLevel(extendData.detail.commonExt.qqLevel) || 0, long_nick: data.info.longNick,
login_days: 0, city: data.info.city
uid: ''
}
return ret
} }
const data = { ...extendData, ...(await this.ctx.ntUserApi.getUserDetailInfo(uid)) }
return OB11Entities.stranger(data)
} }
} }
} }

View File

@@ -1,11 +1,13 @@
import { unlink } from 'node:fs/promises' import { unlink } from 'node:fs/promises'
import { OB11MessageNode } from '../../types' import { OB11MessageData, 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 { convertMessage2List, createSendElements, sendMsg, createPeer, CreatePeerMode } from '../../helper/createMessage' import { message2List, 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
@@ -17,7 +19,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> {
@@ -42,9 +44,90 @@ 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 msgShortId = this.ctx.store.createMsgShortId({ chatType: msg.chatType, peerUid: msg.peerUid }, msg.msgId) const nodes = this.parseNodeContent(messages)
return { message_id: msgShortId } let fake = true
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> {
@@ -71,7 +154,7 @@ export class SendForwardMsg extends BaseAction<Payload, Response> {
} }
// 返回一个合并转发的消息id // 返回一个合并转发的消息id
private async handleForwardNode(destPeer: Peer, messageNodes: OB11MessageNode[]) { private async handleForwardNode(destPeer: Peer, messageNodes: OB11MessageNode[]): Promise<Response> {
const selfPeer = { const selfPeer = {
chatType: ChatType.C2C, chatType: ChatType.C2C,
peerUid: selfInfo.uid, peerUid: selfInfo.uid,
@@ -96,7 +179,7 @@ export class SendForwardMsg extends BaseAction<Payload, Response> {
try { try {
const { sendElements, deleteAfterSentFiles } = await createSendElements( const { sendElements, deleteAfterSentFiles } = await createSendElements(
this.ctx, this.ctx,
convertMessage2List(messageNode.data.content), messageNode.data.content as OB11MessageData[],
destPeer destPeer
) )
this.ctx.logger.info('开始生成转发节点', sendElements) this.ctx.logger.info('开始生成转发节点', sendElements)
@@ -163,8 +246,13 @@ export class SendForwardMsg extends BaseAction<Payload, Response> {
if (retMsgIds.length === 0) { if (retMsgIds.length === 0) {
throw Error('转发消息失败,节点为空') throw Error('转发消息失败,节点为空')
} }
const returnMsg = await this.ctx.ntMsgApi.multiForwardMsg(srcPeer!, destPeer, retMsgIds) const msg = await this.ctx.ntMsgApi.multiForwardMsg(srcPeer!, destPeer, retMsgIds)
return returnMsg const resid = JSON.parse(msg.elements[0].arkElement!.bytesData).meta.detail.resid
const msgShortId = this.ctx.store.createMsgShortId({
chatType: msg.chatType,
peerUid: msg.peerUid
}, msg.msgId)
return { message_id: msgShortId, forward_id: resid }
} }
} }

View File

@@ -0,0 +1,19 @@
import { BaseAction, Schema } from '../BaseAction'
import { ActionName } from '../types'
import { selfInfo } from '@/common/globalVars'
interface Payload {
group_id: number | string
}
export class SendGroupSign extends BaseAction<Payload, null> {
actionName = ActionName.GoCQHTTP_SendGroupSign
payloadSchema = Schema.object({
group_id: Schema.union([Number, String]).required(),
})
async _handle(payload: Payload) {
throw new Error('暂未实现群签到功能')
return null
}
}

View File

@@ -0,0 +1,30 @@
import { BaseAction, Schema } from '../BaseAction'
import { ActionName } from '../types'
import { selfInfo } from '@/common/globalVars'
import { GroupMemberRole } from '@/ntqqapi/types'
interface Payload {
group_id: number | string
user_id: number | string
special_title?: string
}
export class SetGroupSpecialTitle extends BaseAction<Payload, null> {
actionName = ActionName.GoCQHTTP_SetGroupSpecialTitle
payloadSchema = Schema.object({
group_id: Schema.union([Number, String]).required(),
user_id: Schema.union([Number, String]).required(),
special_title: Schema.string()
})
async _handle(payload: Payload) {
const uid = await this.ctx.ntUserApi.getUidByUin(payload.user_id.toString(), payload.group_id.toString())
if (!uid) throw new Error(`用户${payload.user_id}的uid获取失败`)
const self = await this.ctx.ntGroupApi.getGroupMember(payload.group_id.toString(), selfInfo.uid, false)
if (self.role !== GroupMemberRole.Owner){
throw new Error(`不是群${payload.group_id}的群主,无法设置群头衔`)
}
throw new Error('暂未实现设置群头衔功能')
return null
}
}

View File

@@ -27,7 +27,11 @@ export class UploadGroupFile extends BaseAction<Payload, null> {
if (!success) { if (!success) {
throw new Error(errMsg) throw new Error(errMsg)
} }
const file = await SendElement.file(this.ctx, path, payload.name || fileName, payload.folder ?? payload.folder_id) const name = payload.name || fileName
if (name.includes('/') || name.includes('\\')) {
throw new Error(`文件名 ${name} 不合法`)
}
const file = await SendElement.file(this.ctx, path, name, payload.folder ?? payload.folder_id)
const peer = await createPeer(this.ctx, payload, CreatePeerMode.Group) const peer = await createPeer(this.ctx, payload, CreatePeerMode.Group)
await sendMsg(this.ctx, peer, [file], []) await sendMsg(this.ctx, peer, [file], [])
return null return null

View File

@@ -23,7 +23,11 @@ export class UploadPrivateFile extends BaseAction<UploadPrivateFilePayload, null
if (!success) { if (!success) {
throw new Error(errMsg) throw new Error(errMsg)
} }
const sendFileEle = await SendElement.file(this.ctx, path, payload.name || fileName) const name = payload.name || fileName
if (name.includes('/') || name.includes('\\')) {
throw new Error(`文件名 ${name} 不合法`)
}
const sendFileEle = await SendElement.file(this.ctx, path, name)
const peer = await createPeer(this.ctx, payload, CreatePeerMode.Private) const peer = await createPeer(this.ctx, payload, CreatePeerMode.Private)
await sendMsg(this.ctx, peer, [sendFileEle], []) await sendMsg(this.ctx, peer, [sendFileEle], [])
return null return null

View File

@@ -2,33 +2,35 @@ import { BaseAction, Schema } from '../BaseAction'
import { OB11GroupMember } from '../../types' import { OB11GroupMember } from '../../types'
import { OB11Entities } from '../../entities' import { OB11Entities } from '../../entities'
import { ActionName } from '../types' import { ActionName } from '../types'
import { calcQQLevel } from '@/common/utils/misc' import { calcQQLevel, parseBool } from '@/common/utils/misc'
interface Payload { interface Payload {
group_id: number | string group_id: number | string
user_id: number | string user_id: number | string
no_cache: boolean
} }
class GetGroupMemberInfo extends BaseAction<Payload, OB11GroupMember> { class GetGroupMemberInfo extends BaseAction<Payload, OB11GroupMember> {
actionName = ActionName.GetGroupMemberInfo actionName = ActionName.GetGroupMemberInfo
payloadSchema = Schema.object({ payloadSchema = Schema.object({
group_id: Schema.union([Number, String]).required(), group_id: Schema.union([Number, String]).required(),
user_id: Schema.union([Number, String]).required() user_id: Schema.union([Number, String]).required(),
no_cache: Schema.union([Boolean, Schema.transform(String, parseBool)]).default(false)
}) })
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()) const uid = await this.ctx.ntUserApi.getUidByUin(payload.user_id.toString(), groupCode)
if (!uid) throw new Error('无法获取用户信息') if (!uid) throw new Error('无法获取用户信息')
const member = await this.ctx.ntGroupApi.getGroupMember(groupCode, uid) const member = await this.ctx.ntGroupApi.getGroupMember(groupCode, uid, payload.no_cache)
if (member) { if (member) {
const ret = OB11Entities.groupMember(groupCode, member) const ret = OB11Entities.groupMember(+groupCode, member)
const date = Math.round(Date.now() / 1000) const date = Math.trunc(Date.now() / 1000)
ret.last_sent_time ??= date ret.last_sent_time ??= date
ret.join_time ??= date ret.join_time ??= date
const info = await this.ctx.ntUserApi.getUserDetailInfo(member.uid) const info = await this.ctx.ntUserApi.getUserDetailInfo(member.uid)
ret.sex = OB11Entities.sex(info.sex!) ret.sex = OB11Entities.sex(info.sex!)
ret.qq_level = (info.qqLevel && calcQQLevel(info.qqLevel)) || 0 ret.qq_level = info.qqLevel && calcQQLevel(info.qqLevel) || 0
ret.age = info.age ?? 0 ret.age = info.age ?? 0
return ret return ret
} }

View File

@@ -17,19 +17,26 @@ class GetGroupMemberList 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()
let groupMembers = await this.ctx.ntGroupApi.getGroupMembers(groupCode) let groupMembers = await this.ctx.ntGroupApi.getGroupMembers(groupCode)
if (groupMembers.size === 0) { for (let i = 0; i < 5; i++) {
await this.ctx.sleep(100) if (groupMembers.size > 0) {
break
}
await this.ctx.sleep(60)
groupMembers = await this.ctx.ntGroupApi.getGroupMembers(groupCode) groupMembers = await this.ctx.ntGroupApi.getGroupMembers(groupCode)
} }
const groupMembersArr = Array.from(groupMembers.values())
const date = Math.round(Date.now() / 1000)
return groupMembersArr.map(item => { const date = Math.trunc(Date.now() / 1000)
const member = OB11Entities.groupMember(groupCode, item) const groupId = Number(payload.group_id)
const ret: OB11GroupMember[] = []
for (const item of groupMembers.values()) {
const member = OB11Entities.groupMember(groupId, item)
member.join_time ??= date member.join_time ??= date
member.last_sent_time ??= date member.last_sent_time ??= date
return member ret.push(member)
}) }
return ret
} }
} }

View File

@@ -76,6 +76,15 @@ 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'
import { SetGroupSpecialTitle } from '@/onebot11/action/go-cqhttp/SetGroupSpecialTitle'
import { SendGroupSign } from '@/onebot11/action/go-cqhttp/SendGroupSign'
import { SetRestart } from '@/onebot11/action/system/SetRestart'
import { SetFriendCategory } from '@/onebot11/action/llonebot/SetFriendCategory'
import { SetFriendRemark } from '@/onebot11/action/llonebot/SetFriendRemark'
import { SetGroupMsgMask } from '@/onebot11/action/llonebot/SetGroupMsgMask'
import { SetGroupRemark } from '@/onebot11/action/llonebot/SetGroupRemark'
export function initActionMap(adapter: Adapter) { export function initActionMap(adapter: Adapter) {
const actionHandlers = [ const actionHandlers = [
@@ -96,6 +105,10 @@ export function initActionMap(adapter: Adapter) {
new GetRobotUinRange(adapter), new GetRobotUinRange(adapter),
new GroupPoke(adapter), new GroupPoke(adapter),
new FriendPoke(adapter), new FriendPoke(adapter),
new SetFriendCategory(adapter),
new SetFriendRemark(adapter),
new SetGroupMsgMask(adapter),
new SetGroupRemark(adapter),
// onebot11 // onebot11
new SendLike(adapter), new SendLike(adapter),
new GetMsg(adapter), new GetMsg(adapter),
@@ -128,6 +141,8 @@ 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),
new SetRestart(adapter),
// go-cqhttp // go-cqhttp
new GetEssenceMsgList(adapter), new GetEssenceMsgList(adapter),
new GetGroupHonorInfo(adapter), new GetGroupHonorInfo(adapter),
@@ -157,8 +172,11 @@ 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),
new SetGroupSpecialTitle(adapter),
new SendGroupSign(adapter),
] ]
const actionMap = new Map<string, BaseAction<any, unknown>>() const actionMap = new Map()
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

@@ -1,6 +1,6 @@
import { BaseAction, Schema } from '../BaseAction' import { BaseAction, Schema } from '../BaseAction'
import { ActionName } from '../types' import { ActionName } from '../types'
import { getBuildVersion } from '@/common/utils/misc' import { getBuildVersion } from '@/common/utils'
interface Payload { interface Payload {
user_id: number | string user_id: number | string
@@ -13,13 +13,13 @@ export class FriendPoke extends BaseAction<Payload, null> {
}) })
async _handle(payload: Payload) { async _handle(payload: Payload) {
if (!this.ctx.app.native.checkPlatform()) { if (!this.ctx.app.native.checkPlatform() || !this.ctx.app.native.checkVersion()) {
throw new Error('当前系统平台或架构不支持') // await this.ctx.app.packet.sendPokePacket(+payload.user_id)
throw new Error('戳一戳暂时只支持Windows QQ 27333 ~ 275970版本')
} }
if (!this.ctx.app.native.checkVersion()) { else{
throw new Error(`当前 QQ 版本 ${getBuildVersion()} 不支持,可尝试其他版本 27187—27597`) await this.ctx.app.native.sendFriendPoke(+payload.user_id)
} }
await this.ctx.app.native.sendFriendPoke(+payload.user_id)
return null return null
} }
} }

View File

@@ -1,6 +1,6 @@
import { BaseAction, Schema } from '../BaseAction' import { BaseAction, Schema } from '../BaseAction'
import { ActionName } from '../types' import { ActionName } from '../types'
import { getBuildVersion } from '@/common/utils/misc' import { getBuildVersion } from '@/common/utils'
interface Payload { interface Payload {
group_id: number | string group_id: number | string
@@ -15,13 +15,12 @@ export class GroupPoke extends BaseAction<Payload, null> {
}) })
async _handle(payload: Payload) { async _handle(payload: Payload) {
if (!this.ctx.app.native.checkPlatform()) { if (!this.ctx.app.native.checkPlatform() || !this.ctx.app.native.checkVersion()) {
throw new Error('当前系统平台或架构不支持') throw new Error('戳一戳暂时只支持Windows QQ 27333 ~ 275970版本')
} }
if (!this.ctx.app.native.checkVersion()) { else{
throw new Error(`当前 QQ 版本 ${getBuildVersion()} 不支持,可尝试其他版本 27187—27597`) await this.ctx.app.native.sendGroupPoke(+payload.group_id, +payload.user_id)
} }
await this.ctx.app.native.sendGroupPoke(+payload.group_id, +payload.user_id)
return null return null
} }
} }

View File

@@ -0,0 +1,21 @@
import { BaseAction, Schema } from '../BaseAction'
import { ActionName } from '../types'
interface Payload {
user_id: number | string
category_id: number | string
}
export class SetFriendCategory extends BaseAction<Payload, unknown> {
actionName = ActionName.SetFriendCategory
payloadSchema = Schema.object({
user_id: Schema.union([Number, String]).required(),
category_id: Schema.union([Number, String]).required()
})
protected async _handle(payload: Payload) {
const uid = await this.ctx.ntUserApi.getUidByUin(payload.user_id.toString())
if (!uid) throw new Error('无法获取好友信息')
return this.ctx.ntFriendApi.setBuddyCategory(uid, +payload.category_id)
}
}

View File

@@ -0,0 +1,21 @@
import { BaseAction, Schema } from '../BaseAction'
import { ActionName } from '../types'
interface Payload {
user_id: number | string
remark?: string
}
export class SetFriendRemark extends BaseAction<Payload, unknown> {
actionName = ActionName.SetFriendRemark
payloadSchema = Schema.object({
user_id: Schema.union([Number, String]).required(),
remark: Schema.string()
})
protected async _handle(payload: Payload) {
const uid = await this.ctx.ntUserApi.getUidByUin(payload.user_id.toString())
if (!uid) throw new Error('无法获取好友信息')
return this.ctx.ntFriendApi.setBuddyRemark(uid, payload.remark || '')
}
}

View File

@@ -0,0 +1,19 @@
import { BaseAction, Schema } from '../BaseAction'
import { ActionName } from '../types'
interface Payload {
group_id: number | string
mask: number | string // 1, 2, 3, 4
}
export class SetGroupMsgMask extends BaseAction<Payload, unknown> {
actionName = ActionName.SetGroupMsgMask
payloadSchema = Schema.object({
group_id: Schema.union([Number, String]).required(),
mask: Schema.union([Number, String]).required()
})
protected async _handle(payload: Payload) {
return this.ctx.ntGroupApi.setGroupMsgMask(payload.group_id.toString(), +payload.mask)
}
}

View File

@@ -0,0 +1,15 @@
import { BaseAction } from '../BaseAction'
import { ActionName } from '../types'
interface Payload {
group_id: string,
remark?: string
}
export class SetGroupRemark extends BaseAction<Payload, unknown> {
actionName = ActionName.SetGroupRemark
protected async _handle(payload: Payload): Promise<unknown>{
return this.ctx.ntGroupApi.setGroupRemark(payload.group_id.toString(), payload.remark)
}
}

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 { convertMessage2List, createSendElements, sendMsg, createPeer, CreatePeerMode } from '../../helper/createMessage' import { message2List, 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 = convertMessage2List( const messages = message2List(
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

@@ -7,62 +7,52 @@ import { ChatCacheListItemBasic, CacheFileType } from '@/ntqqapi/types'
export default class CleanCache extends BaseAction<void, void> { export default class CleanCache extends BaseAction<void, void> {
actionName = ActionName.CleanCache actionName = ActionName.CleanCache
protected _handle(): Promise<void> { protected async _handle(): Promise<void> {
return new Promise<void>(async (res, rej) => { const cacheFilePaths: string[] = []
try {
// dbUtil.clearCache()
const cacheFilePaths: string[] = []
await this.ctx.ntFileCacheApi.setCacheSilentScan(false) await this.ctx.ntFileCacheApi.setCacheSilentScan(false)
cacheFilePaths.push(await this.ctx.ntFileCacheApi.getHotUpdateCachePath()) cacheFilePaths.push(await this.ctx.ntFileCacheApi.getHotUpdateCachePath())
cacheFilePaths.push(await this.ctx.ntFileCacheApi.getDesktopTmpPath()) cacheFilePaths.push(await this.ctx.ntFileCacheApi.getDesktopTmpPath())
const list = await this.ctx.ntFileCacheApi.getCacheSessionPathList() const list = await this.ctx.ntFileCacheApi.getCacheSessionPathList()
list.forEach((e) => cacheFilePaths.push(e.value)) list.forEach((e) => cacheFilePaths.push(e.value))
// await NTQQApi.addCacheScannedPaths(); // XXX: 调用就崩溃,原因目前还未知 // await NTQQApi.addCacheScannedPaths(); // XXX: 调用就崩溃,原因目前还未知
const cacheScanResult = await this.ctx.ntFileCacheApi.scanCache() const cacheScanResult = await this.ctx.ntFileCacheApi.scanCache()
const cacheSize = parseInt(cacheScanResult.size[6]) const cacheSize = parseInt(cacheScanResult.size[6])
if (cacheScanResult.result !== 0) { if (cacheScanResult.result !== 0) {
throw 'Something went wrong while scanning cache. Code: ' + cacheScanResult.result throw 'Something went wrong while scanning cache. Code: ' + cacheScanResult.result
} }
await this.ctx.ntFileCacheApi.setCacheSilentScan(true) await this.ctx.ntFileCacheApi.setCacheSilentScan(true)
if (cacheSize > 0 && cacheFilePaths.length > 2) { if (cacheSize > 0 && cacheFilePaths.length > 2) {
// 存在缓存文件且大小不为 0 时执行清理动作 // 存在缓存文件且大小不为 0 时执行清理动作
// await NTQQApi.clearCache([ 'tmp', 'hotUpdate', ...cacheScanResult ]) // XXX: 也是调用就崩溃,调用 fs 删除得了 // await NTQQApi.clearCache([ 'tmp', 'hotUpdate', ...cacheScanResult ]) // XXX: 也是调用就崩溃,调用 fs 删除得了
deleteCachePath(cacheFilePaths) deleteCachePath(cacheFilePaths)
} }
// 获取聊天记录列表 // 获取聊天记录列表
// NOTE: 以防有人不需要删除聊天记录,暂时先注释掉,日后加个开关 // NOTE: 以防有人不需要删除聊天记录,暂时先注释掉,日后加个开关
// const privateChatCache = await getCacheList(ChatType.friend); // 私聊消息 // const privateChatCache = await getCacheList(ChatType.friend); // 私聊消息
// const groupChatCache = await getCacheList(ChatType.group); // 群聊消息 // const groupChatCache = await getCacheList(ChatType.group); // 群聊消息
// const chatCacheList = [ ...privateChatCache, ...groupChatCache ]; // const chatCacheList = [ ...privateChatCache, ...groupChatCache ];
const chatCacheList: ChatCacheListItemBasic[] = [] const chatCacheList: ChatCacheListItemBasic[] = []
// 获取聊天缓存文件列表 // 获取聊天缓存文件列表
const cacheFileList: string[] = [] const cacheFileList: string[] = []
for (const name in CacheFileType) { for (const name in CacheFileType) {
if (!isNaN(parseInt(name))) continue if (!isNaN(parseInt(name))) continue
const fileTypeAny: any = CacheFileType[name] const fileType = CacheFileType[name] as unknown as CacheFileType
const fileType: CacheFileType = fileTypeAny
cacheFileList.push(...(await this.ctx.ntFileCacheApi.getFileCacheInfo(fileType)).infos.map((file) => file.fileKey)) cacheFileList.push(...(await this.ctx.ntFileCacheApi.getFileCacheInfo(fileType)).infos.map((file) => file.fileKey))
} }
// 一并清除 // 一并清除
await this.ctx.ntFileCacheApi.clearChatCache(chatCacheList, cacheFileList) await this.ctx.ntFileCacheApi.clearChatCache(chatCacheList, cacheFileList)
res()
} catch (e) {
console.error('清理缓存时发生了错误')
rej(e)
}
})
} }
} }

View File

@@ -0,0 +1,26 @@
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

@@ -0,0 +1,10 @@
import { BaseAction } from '@/onebot11/action/BaseAction'
import { ActionName } from '@/onebot11/action/types'
export class SetRestart extends BaseAction<null, void> {
actionName = ActionName.SetRestart
protected async _handle() {
await this.ctx.ntSystemApi.restart()
}
}

View File

@@ -29,6 +29,10 @@ export enum ActionName {
GetRobotUinRange = 'get_robot_uin_range', GetRobotUinRange = 'get_robot_uin_range',
GroupPoke = 'group_poke', GroupPoke = 'group_poke',
FriendPoke = 'friend_poke', FriendPoke = 'friend_poke',
SetFriendRemark = 'set_friend_remark',
SetFriendCategory = 'set_friend_category',
SetGroupMsgMask = 'set_group_msg_mask',
SetGroupRemark = 'set_group_remark',
// onebot 11 // onebot 11
SendLike = 'send_like', SendLike = 'send_like',
GetLoginInfo = 'get_login_info', GetLoginInfo = 'get_login_info',
@@ -47,6 +51,7 @@ export enum ActionName {
SetGroupLeave = 'set_group_leave', SetGroupLeave = 'set_group_leave',
GetVersionInfo = 'get_version_info', GetVersionInfo = 'get_version_info',
GetStatus = 'get_status', GetStatus = 'get_status',
SetRestart = 'set_restart',
CanSendRecord = 'can_send_record', CanSendRecord = 'can_send_record',
CanSendImage = 'can_send_image', CanSendImage = 'can_send_image',
SetGroupKick = 'set_group_kick', SetGroupKick = 'set_group_kick',
@@ -61,6 +66,7 @@ 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',
@@ -89,4 +95,7 @@ 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',
GoCQHTTP_SetGroupSpecialTitle = 'set_group_special_title',
GoCQHTTP_SendGroupSign = 'send_group_sign',
} }

View File

@@ -1,22 +1,22 @@
import { BaseAction } from '../BaseAction' import { BaseAction, Schema } 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

@@ -23,11 +23,11 @@ export default class SetFriendAddRequest extends BaseAction<Payload, null> {
if (payload.remark) { if (payload.remark) {
await this.ctx.ntFriendApi.setBuddyRemark(uid, payload.remark) await this.ctx.ntFriendApi.setBuddyRemark(uid, payload.remark)
} }
await this.ctx.ntMsgApi.activateChat({ /*await this.ctx.ntMsgApi.activateChat({
peerUid: uid, peerUid: uid,
chatType: ChatType.C2C, chatType: ChatType.C2C,
guildId: '' guildId: ''
}) })*/
return null return null
} }
} }

View File

@@ -9,20 +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 { GroupDecreaseSubType, OB11GroupDecreaseEvent } from './event/notice/OB11GroupDecreaseEvent' import { 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 { SysMsg } from '@/ntqqapi/proto/compiled' import { Msg, SysMsg } from '@/ntqqapi/proto/compiled'
import { OB11GroupIncreaseEvent } from './event/notice/OB11GroupIncreaseEvent'
declare module 'cordis' { declare module 'cordis' {
interface Context { interface Context {
@@ -71,7 +71,7 @@ class OneBot11Adapter extends Service {
}) })
} }
public dispatch(event: OB11BaseEvent | OB11Message) { public dispatch(event: OB11BaseEvent) {
if (this.config.enableWs) { if (this.config.enableWs) {
this.ob11WebSocket.emitEvent(event) this.ob11WebSocket.emitEvent(event)
} }
@@ -87,29 +87,22 @@ class OneBot11Adapter extends Service {
} }
} }
private async handleGroupNotify(notify: GroupNotify) { private async handleGroupNotify(notify: GroupNotify, doubt: boolean) {
try { try {
const flag = notify.group.groupCode + '|' + notify.seq + '|' + notify.type const flag = `${notify.group.groupCode}|${notify.seq}|${notify.type}|${doubt === true ? '1' : '0'}`
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 member2Uin = await this.ctx.ntUserApi.getUinByUid(notify.user2.uid) const memberUin = await this.ctx.ntUserApi.getUinByUid(notify.user1.uid)
if (member2Uin) { const adminUin = await this.ctx.ntUserApi.getUinByUid(notify.user2.uid)
operatorId = member2Uin const event = new OB11GroupDecreaseEvent(
} parseInt(notify.group.groupCode),
subType = 'kick' parseInt(memberUin),
parseInt(adminUin),
'kick',
)
this.dispatch(event)
} }
const event = new OB11GroupDecreaseEvent(
parseInt(notify.group.groupCode),
parseInt(member1Uin),
parseInt(operatorId),
subType,
)
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('有加群请求')
@@ -344,22 +337,39 @@ class OneBot11Adapter extends Service {
this.handleMsg(input) this.handleMsg(input)
}) })
this.ctx.on('nt/group-notify', input => { this.ctx.on('nt/group-notify', input => {
this.handleGroupNotify(input) const { doubt, notify } = 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', input => { this.ctx.on('nt/system-message-created', async input => {
const sysMsg = SysMsg.SystemMessage.decode(input) const sysMsg = Msg.Message.decode(input)
const { msgType, subType, subSubType } = sysMsg.msgSpec[0] ?? {} const { msgType, subType } = sysMsg.contentHead ?? {}
if (msgType === 528 && subType === 39 && subSubType === 39) { if (msgType === 528 && subType === 39) {
const tip = SysMsg.ProfileLikeTip.decode(sysMsg.bodyWrapper!.body!) const tip = SysMsg.ProfileLikeTip.decode(sysMsg.body!.msgContent!)
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
const [times] = detail.txt?.match(/\d+/) ?? ['0'] const [times] = detail.txt?.match(/\d+/) ?? ['0']
const profileLikeEvent = new OB11ProfileLikeEvent(detail.uin!, detail.nickname!, +times) const event = new OB11ProfileLikeEvent(detail.uin!, detail.nickname!, +times)
this.dispatch(profileLikeEvent) this.dispatch(event)
} else if (msgType === 33) {
const tip = SysMsg.GroupMemberChange.decode(sysMsg.body!.msgContent!)
if (tip.type !== 130) return
this.ctx.logger.info('群成员增加', tip)
const memberUin = await this.ctx.ntUserApi.getUinByUid(tip.memberUid)
const operatorUin = await this.ctx.ntUserApi.getUinByUid(tip.adminUid)
const event = new OB11GroupIncreaseEvent(tip.groupCode, +memberUin, +operatorUin)
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

@@ -134,11 +134,13 @@ namespace OB11Http {
class OB11HttpPost { class OB11HttpPost {
private disposeInterval?: () => void private disposeInterval?: () => void
private activated = false
constructor(protected ctx: Context, public config: OB11HttpPost.Config) { constructor(protected ctx: Context, public config: OB11HttpPost.Config) {
} }
public start() { public start() {
this.activated = true
if (this.config.enableHttpHeart && !this.disposeInterval) { if (this.config.enableHttpHeart && !this.disposeInterval) {
this.disposeInterval = this.ctx.setInterval(() => { this.disposeInterval = this.ctx.setInterval(() => {
// ws的心跳是ws自己维护的 // ws的心跳是ws自己维护的
@@ -148,10 +150,14 @@ class OB11HttpPost {
} }
public stop() { public stop() {
this.activated = false
this.disposeInterval?.() this.disposeInterval?.()
} }
public async emitEvent(event: OB11BaseEvent | OB11Message) { public async emitEvent(event: OB11BaseEvent) {
if (!this.activated || !this.config.hosts.length) {
return
}
const msgStr = JSON.stringify(event) const msgStr = JSON.stringify(event)
const headers: Dict = { const headers: Dict = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@@ -171,7 +177,8 @@ class OB11HttpPost {
}).then( }).then(
async (res) => { async (res) => {
if (event.post_type) { if (event.post_type) {
this.ctx.logger.info(`HTTP 事件上报: ${host}`, event.post_type, res.status) const eventName = event.post_type + '.' + event[event.post_type + '_type']
this.ctx.logger.info(`HTTP 事件上报: ${host}`, eventName, res.status)
} }
try { try {
const resJson = await res.json() const resJson = await res.json()

View File

@@ -57,11 +57,12 @@ class OB11WebSocket {
}) })
} }
public async emitEvent(event: OB11BaseEvent | OB11Message) { public async emitEvent(event: OB11BaseEvent) {
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))
this.ctx.logger.info('WebSocket 事件上报', socket.url ?? '', event.post_type) const eventName = event.post_type + '.' + event[event.post_type + '_type']
this.ctx.logger.info('WebSocket 事件上报', socket.url ?? '', eventName)
} }
}) })
} }
@@ -193,10 +194,11 @@ class OB11WebSocketReverse {
this.wsClient?.close() this.wsClient?.close()
} }
public emitEvent(event: OB11BaseEvent | OB11Message) { public emitEvent(event: OB11BaseEvent) {
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))
this.ctx.logger.info('WebSocket 事件上报', this.wsClient.url ?? '', event.post_type) const eventName = event.post_type + '.' + event[event.post_type + '_type']
this.ctx.logger.info('WebSocket 事件上报', this.wsClient.url ?? '', eventName)
} }
} }

View File

@@ -1,4 +1,3 @@
import { XMLParser } from 'fast-xml-parser'
import { import {
OB11Group, OB11Group,
OB11GroupMember, OB11GroupMember,
@@ -71,7 +70,7 @@ export namespace OB11Entities {
sub_type: 'friend', sub_type: 'friend',
message: messagePostFormat === 'string' ? '' : [], message: messagePostFormat === 'string' ? '' : [],
message_format: messagePostFormat === 'string' ? 'string' : 'array', message_format: messagePostFormat === 'string' ? 'string' : 'array',
post_type: selfUin == msg.senderUin ? EventType.MESSAGE_SENT : EventType.MESSAGE, post_type: selfUin === msg.senderUin ? EventType.MESSAGE_SENT : EventType.MESSAGE,
} }
if (debug) { if (debug) {
resMsg.raw = msg resMsg.raw = msg
@@ -79,11 +78,14 @@ export namespace OB11Entities {
if (msg.chatType === ChatType.Group) { if (msg.chatType === ChatType.Group) {
resMsg.sub_type = 'normal' resMsg.sub_type = 'normal'
resMsg.group_id = parseInt(msg.peerUin) resMsg.group_id = parseInt(msg.peerUin)
const member = await ctx.ntGroupApi.getGroupMember(msg.peerUin, msg.senderUid) // 284840486: 合并转发内部
if (member) { if (msg.peerUin !== '284840486') {
resMsg.sender.role = groupMemberRole(member.role) const member = await ctx.ntGroupApi.getGroupMember(msg.peerUin, msg.senderUid)
resMsg.sender.nickname = member.nick if (member) {
resMsg.sender.title = member.memberSpecialTitle ?? '' resMsg.sender.role = groupMemberRole(member.role)
resMsg.sender.nickname = member.nick
resMsg.sender.title = member.memberSpecialTitle ?? ''
}
} }
} }
else if (msg.chatType === ChatType.C2C) { else if (msg.chatType === ChatType.C2C) {
@@ -119,7 +121,7 @@ export namespace OB11Entities {
name = content.replace('@', '') name = content.replace('@', '')
} }
messageSegment = { messageSegment = {
type: OB11MessageDataType.at, type: OB11MessageDataType.At,
data: { data: {
qq, qq,
name name
@@ -132,7 +134,7 @@ export namespace OB11Entities {
continue continue
} }
messageSegment = { messageSegment = {
type: OB11MessageDataType.text, type: OB11MessageDataType.Text,
data: { data: {
text text
} }
@@ -168,7 +170,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()
} }
@@ -182,7 +184,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,
@@ -210,7 +212,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,
@@ -234,7 +236,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,
@@ -259,7 +261,7 @@ export namespace OB11Entities {
const { pttElement } = element const { pttElement } = element
const fileSize = pttElement.fileSize ?? '0' const fileSize = pttElement.fileSize ?? '0'
messageSegment = { messageSegment = {
type: OB11MessageDataType.voice, type: OB11MessageDataType.Record,
data: { data: {
file: pttElement.fileName, file: pttElement.fileName,
url: pathToFileURL(pttElement.filePath).href, url: pathToFileURL(pttElement.filePath).href,
@@ -282,7 +284,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
} }
@@ -293,14 +295,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!
} }
@@ -312,7 +314,7 @@ export namespace OB11Entities {
}*/ }*/
} else { } else {
messageSegment = { messageSegment = {
type: OB11MessageDataType.face, type: OB11MessageDataType.Face,
data: { data: {
id: faceIndex.toString() id: faceIndex.toString()
} }
@@ -328,7 +330,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,
@@ -341,15 +343,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: {
data: markdownElement.content content: 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
} }
@@ -373,11 +375,23 @@ export namespace OB11Entities {
if (msg.chatType !== ChatType.C2C) { if (msg.chatType !== ChatType.C2C) {
return return
} }
if (msg.msgType !== 5) {
return
}
for (const element of msg.elements) { for (const element of msg.elements) {
if (element.grayTipElement) { if (element.grayTipElement) {
const { grayTipElement } = element const { grayTipElement } = element
if (grayTipElement.jsonGrayTipElement?.busiId === '1061') { if (grayTipElement.jsonGrayTipElement?.busiId === '1061') {
const json = JSON.parse(grayTipElement.jsonGrayTipElement.jsonStr) const json = JSON.parse(grayTipElement.jsonGrayTipElement.jsonStr)
const param = grayTipElement.jsonGrayTipElement.xmlToJsonParam
if (param) {
return new OB11FriendPokeEvent(
Number(param.templParam.get('uin_str1')),
Number(param.templParam.get('uin_str2')),
json.items
)
}
const pokedetail: Dict[] = json.items const pokedetail: Dict[] = json.items
//筛选item带有uid的元素 //筛选item带有uid的元素
const poke_uid = pokedetail.filter(item => item.uid) const poke_uid = pokedetail.filter(item => item.uid)
@@ -402,31 +416,17 @@ export namespace OB11Entities {
if (msg.chatType !== ChatType.Group) { if (msg.chatType !== ChatType.Group) {
return return
} }
/**if (msg.senderUin) { if (msg.msgType !== 5 && msg.msgType !== 3) {
const member = await ctx.ntGroupApi.getGroupMember(msg.peerUid, msg.senderUin) return
if (member && member.cardName !== msg.sendMemberName) { }
const event = new OB11GroupCardEvent(
parseInt(msg.peerUid),
parseInt(msg.senderUin),
msg.sendMemberName!,
member.cardName,
)
member.cardName = msg.sendMemberName!
return event
}
}*/
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.MemberIncrease) { if (groupElement.type === TipGroupElementType.Ban) {
ctx.logger.info('收到群成员增加消息', groupElement)
const { memberUid, adminUid } = groupElement
const memberUin = await ctx.ntUserApi.getUinByUid(memberUid)
const operatorUin = adminUid ? await ctx.ntUserApi.getUinByUid(adminUid) : memberUin
return new OB11GroupIncreaseEvent(+msg.peerUid, +memberUin, +operatorUin)
}
else if (groupElement.type === TipGroupElementType.Ban) {
ctx.logger.info('收到群成员禁言提示', groupElement) ctx.logger.info('收到群成员禁言提示', groupElement)
const memberUid = groupElement.shutUp?.member.uid const memberUid = groupElement.shutUp?.member.uid
const adminUid = groupElement.shutUp?.admin.uid const adminUid = groupElement.shutUp?.admin.uid
@@ -478,6 +478,13 @@ 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!, {
@@ -487,75 +494,66 @@ export namespace OB11Entities {
busid: element.fileElement.fileBizId || 0, busid: element.fileElement.fileBizId || 0,
}) })
} }
else if (xmlElement) {
if (grayTipElement) { if (xmlElement.templId === '10382') {
const xmlElement = grayTipElement.xmlElement ctx.logger.info('收到表情回应我的消息', xmlElement.templParam)
if (xmlElement?.templId === '10382') {
const emojiLikeData = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: '',
}).parse(xmlElement.content)
ctx.logger.info('收到表情回应我的消息', emojiLikeData)
try { try {
const senderUin: string = emojiLikeData.gtip.qq.jp const senderUin = xmlElement.templParam.get('jp_uin')
const msgSeq: string = emojiLikeData.gtip.url.msgseq const msgSeq = xmlElement.templParam.get('msg_seq')
const emojiId: string = emojiLikeData.gtip.face.id const emojiId = xmlElement.templParam.get('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)
if ( const invitor = xmlElement.templParam.get('invitor')
grayTipElement.subElementType == GrayTipElementSubType.XmlMsg && const invitee = xmlElement.templParam.get('invitee')
xmlElement?.templId == '10179' if (invitor && invitee) {
) { return new OB11GroupIncreaseEvent(+msg.peerUid, +invitee, +invitor, 'invite')
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')
}
} }
} }
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
if (param) {
return new OB11GroupPokeEvent(
Number(msg.peerUid),
Number(param.templParam.get('uin_str1')),
Number(param.templParam.get('uin_str2')),
json.items
)
}
const pokedetail: Dict[] = json.items const pokedetail: Dict[] = json.items
//筛选item带有uid的元素 //筛选item带有uid的元素
const poke_uid = pokedetail.filter(item => item.uid) const poke_uid = pokedetail.filter(item => item.uid)
if (poke_uid.length == 2) { if (poke_uid.length == 2) {
return new OB11GroupPokeEvent( return new OB11GroupPokeEvent(
parseInt(msg.peerUid), Number(msg.peerUid),
parseInt(await ctx.ntUserApi.getUinByUid(poke_uid[0].uid) ?? 0), Number(await ctx.ntUserApi.getUinByUid(poke_uid[0].uid) ?? 0),
parseInt(await ctx.ntUserApi.getUinByUid(poke_uid[1].uid) ?? 0), Number(await ctx.ntUserApi.getUinByUid(poke_uid[1].uid) ?? 0),
pokedetail pokedetail
) )
} }
@@ -657,19 +655,22 @@ export namespace OB11Entities {
export function sex(sex: Sex): OB11UserSex { export function sex(sex: Sex): OB11UserSex {
const sexMap = { const sexMap = {
[Sex.male]: OB11UserSex.Male, [Sex.Unknown]: OB11UserSex.Unknown,
[Sex.female]: OB11UserSex.Female, [Sex.Male]: OB11UserSex.Male,
[Sex.unknown]: OB11UserSex.Unknown, [Sex.Female]: OB11UserSex.Female,
[Sex.Hidden]: OB11UserSex.Unknown
} }
return sexMap[sex] || OB11UserSex.Unknown return sexMap[sex] ?? OB11UserSex.Unknown
} }
export function groupMember(group_id: string, member: GroupMember): OB11GroupMember { export function groupMember(groupId: number, member: GroupMember): OB11GroupMember {
const titleExpireTime = +member.specialTitleExpireTime
const int32Max = 2147483647
return { return {
group_id: parseInt(group_id), group_id: groupId,
user_id: parseInt(member.uin), user_id: parseInt(member.uin),
nickname: member.nick, nickname: member.nick,
card: member.cardName, card: member.cardName || member.nick,
sex: OB11UserSex.Unknown, sex: OB11UserSex.Unknown,
age: 0, age: 0,
area: '', area: '',
@@ -677,7 +678,7 @@ export namespace OB11Entities {
qq_level: 0, qq_level: 0,
join_time: member.joinTime, join_time: member.joinTime,
last_sent_time: member.lastSpeakTime, last_sent_time: member.lastSpeakTime,
title_expire_time: +member.specialTitleExpireTime, title_expire_time: titleExpireTime > int32Max ? 0 : titleExpireTime,
unfriendly: false, unfriendly: false,
card_changeable: true, card_changeable: true,
is_robot: member.isRobot, is_robot: member.isRobot,
@@ -687,19 +688,6 @@ 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,6 +9,7 @@ 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 handleOb11FileLikeMessage(ctx, sendMsg, { deleteAfterSentFiles })).path, (await handleOb11RichMedia(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 handleOb11FileLikeMessage(ctx, sendMsg, { deleteAfterSentFiles }) const { path, fileName } = await handleOb11RichMedia(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 handleOb11FileLikeMessage(ctx, sendMsg, { deleteAfterSentFiles }) const { path, fileName } = await handleOb11RichMedia(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.voice: { case OB11MessageDataType.Record: {
const { path } = await handleOb11FileLikeMessage(ctx, sendMsg, { deleteAfterSentFiles }) const { path } = await handleOb11RichMedia(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,51 +175,22 @@ export async function createSendElements(
} }
} }
// forked from https://github.com/NapNeko/NapCatQQ/blob/6f6b258f22d7563f15d84e7172c4d4cbb547f47e/src/onebot11/action/msg/SendMsg/create-send-elements.ts#L26 export function message2List(message: OB11MessageMixType, autoEscape = false) {
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) {
message = [ return [
{ {
type: OB11MessageDataType.text, type: OB11MessageDataType.Text,
data: { data: {
text: message, text: message,
}, },
}, },
] ] as OB11MessageData[]
} else {
return decodeCQCode(message)
} }
else { } else if (!Array.isArray(message)) {
message = decodeCQCode(message.toString()) return [message]
}
}
else if (!Array.isArray(message)) {
message = [message]
} }
return message return message
} }
@@ -301,3 +272,18 @@ 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

@@ -0,0 +1,239 @@
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: OB11MessageData[]) {
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 { convertMessage2List, createSendElements, sendMsg, createPeer, CreatePeerMode } from '../helper/createMessage' import { message2List, 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(convertMessage2List(reply, quickAction.auto_escape)) replyMessage = replyMessage.concat(message2List(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

@@ -11,8 +11,6 @@ export interface OB11User {
age?: number age?: number
qid?: string qid?: string
login_days?: number login_days?: number
categroyName?: string
categoryId?: number
} }
export enum OB11UserSex { export enum OB11UserSex {
@@ -79,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
@@ -93,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
} }
@@ -119,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',
voice = 'record', Record = '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
@@ -153,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
@@ -191,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
@@ -200,14 +198,14 @@ export interface OB11MessageImage extends OB11MessageFileBase {
} }
export interface OB11MessageRecord extends OB11MessageFileBase { export interface OB11MessageRecord extends OB11MessageFileBase {
type: OB11MessageDataType.voice type: OB11MessageDataType.Record
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
@@ -215,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
@@ -230,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
} }
@@ -246,48 +244,50 @@ 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?: string id?: number | string
user_id?: number content?: OB11MessageMixType
nickname: string user_id?: number // ob11
content: OB11MessageMixType nickname?: string // ob11
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: {
data: string content: 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 +295,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

@@ -7,11 +7,8 @@ import {
CHANNEL_SELECT_FILE, CHANNEL_SELECT_FILE,
CHANNEL_SET_CONFIG, CHANNEL_SET_CONFIG,
CHANNEL_UPDATE, CHANNEL_UPDATE,
CHANNEL_SET_CONFIG_CONFIRMED,
} from './common/channels' } from './common/channels'
import { contextBridge, ipcRenderer } from 'electron'
const { contextBridge } = require('electron')
const { ipcRenderer } = require('electron')
const llonebot = { const llonebot = {
log: (data: unknown) => { log: (data: unknown) => {
@@ -24,8 +21,7 @@ const llonebot = {
return ipcRenderer.invoke(CHANNEL_UPDATE) return ipcRenderer.invoke(CHANNEL_UPDATE)
}, },
setConfig: async (ask: boolean, config: Config) => { setConfig: async (ask: boolean, config: Config) => {
const isSuccess = await ipcRenderer.invoke(CHANNEL_SET_CONFIG, ask, config) return ipcRenderer.invoke(CHANNEL_SET_CONFIG, ask, config)
if (isSuccess) ipcRenderer.send(CHANNEL_SET_CONFIG_CONFIRMED, config)
}, },
getConfig: async (): Promise<Config> => { getConfig: async (): Promise<Config> => {
return ipcRenderer.invoke(CHANNEL_GET_CONFIG) return ipcRenderer.invoke(CHANNEL_GET_CONFIG)

View File

@@ -11,6 +11,10 @@ function isEmpty(value: unknown) {
} }
async function onSettingWindowCreated(view: Element) { async function onSettingWindowCreated(view: Element) {
console.log(view)
if (!view){
return
}
const config = await window.llonebot.getConfig() const config = await window.llonebot.getConfig()
const ob11Config = { ...config.ob11 } const ob11Config = { ...config.ob11 }
@@ -25,9 +29,6 @@ async function onSettingWindowCreated(view: Element) {
} else { } else {
Object.assign(config, { [key]: value }) Object.assign(config, { [key]: value })
} }
if (!['heartInterval', 'token', 'ffmpeg'].includes(key)) {
window.llonebot.setConfig(false, config)
}
} }
} }
@@ -46,6 +47,13 @@ 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 协议',
@@ -178,6 +186,7 @@ async function onSettingWindowCreated(view: Element) {
'调用 /get_image、/get_record、/get_file 时,没有 url 时添加 Base64 字段', '调用 /get_image、/get_record、/get_file 时,没有 url 时添加 Base64 字段',
SettingSwitch('enableLocalFile2Url', config.enableLocalFile2Url), SettingSwitch('enableLocalFile2Url', config.enableLocalFile2Url),
), ),
SettingItem('', null, SettingButton('保存', 'config-ob11-save-2', 'primary')),
]), ]),
SettingList([ SettingList([
SettingItem( SettingItem(
@@ -217,6 +226,7 @@ async function onSettingWindowCreated(view: Element) {
'单位为秒,可用于获取撤回的消息', '单位为秒,可用于获取撤回的消息',
`<div class="q-input"><input class="q-input__inner" data-config-key="msgCacheExpire" type="number" min="1" value="${config.msgCacheExpire}" placeholder="${config.msgCacheExpire}" /></div>`, `<div class="q-input"><input class="q-input__inner" data-config-key="msgCacheExpire" type="number" min="1" value="${config.msgCacheExpire}" placeholder="${config.msgCacheExpire}" /></div>`,
), ),
SettingItem('', null, SettingButton('保存', 'config-ob11-save-3', 'primary')),
]), ]),
SettingList([ SettingList([
SettingItem('GitHub 仓库', `https://github.com/LLOneBot/LLOneBot`, SettingButton('点个星星', 'open-github')), SettingItem('GitHub 仓库', `https://github.com/LLOneBot/LLOneBot`, SettingButton('点个星星', 'open-github')),
@@ -241,7 +251,9 @@ async function onSettingWindowCreated(view: Element) {
} else { } else {
errDom?.classList.add('show') errDom?.classList.add('show')
} }
errCodeDom!.innerHTML = errMsg if (errCodeDom) {
errCodeDom.innerHTML = errMsg
}
} }
showError().then() showError().then()
@@ -395,6 +407,22 @@ async function onSettingWindowCreated(view: Element) {
alert('保存成功') alert('保存成功')
}) })
doc.querySelector('#config-ob11-save-2')?.addEventListener('click', () => {
config.ob11 = ob11Config
window.llonebot.setConfig(false, config)
showError().then()
alert('保存成功')
})
doc.querySelector('#config-ob11-save-3')?.addEventListener('click', () => {
config.ob11 = ob11Config
window.llonebot.setConfig(false, config)
showError().then()
alert('保存成功')
})
doc.body.childNodes.forEach((node) => { doc.body.childNodes.forEach((node) => {
view.appendChild(node) view.appendChild(node)
}) })
@@ -434,9 +462,11 @@ async function onSettingWindowCreated(view: Element) {
} }
window.llonebot.checkVersion().then(checkVersionFunc) window.llonebot.checkVersion().then(checkVersionFunc)
window.addEventListener('beforeunload', () => { window.addEventListener('beforeunload', () => {
if (JSON.stringify(ob11Config) === JSON.stringify(config.ob11)) return window.llonebot.getConfig().then(oldConfig => {
config.ob11 = ob11Config if (JSON.stringify(oldConfig) !== JSON.stringify(config)) {
window.llonebot.setConfig(true, config) window.llonebot.setConfig(true, config)
}
})
}) })
} }

View File

@@ -91,7 +91,7 @@ class SatoriAdapter extends Service {
input.subMsgType === 12 && input.subMsgType === 12 &&
input.elements[0]?.grayTipElement?.xmlElement?.templId === '10382' input.elements[0]?.grayTipElement?.xmlElement?.templId === '10382'
) { ) {
// 机器人被表情回应
} }
else { else {
// 普通的消息 // 普通的消息
@@ -99,7 +99,7 @@ class SatoriAdapter extends Service {
} }
} }
async handleGroupNotify(input: NT.GroupNotify) { async handleGroupNotify(input: NT.GroupNotify, doubt: boolean) {
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) return await parseGuildMemberRequest(this, input, doubt)
} }
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) return await parseGuildMemberRequest(this, input, doubt)
} }
} }
@@ -140,7 +140,8 @@ class SatoriAdapter extends Service {
}) })
this.ctx.on('nt/group-notify', async input => { this.ctx.on('nt/group-notify', async input => {
const event = await this.handleGroupNotify(input) const { doubt, notify } = 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) { export async function parseGuildMemberRequest(bot: SatoriAdapter, input: GroupNotify, doubt: boolean) {
const groupCode = input.group.groupCode const groupCode = input.group.groupCode
const flag = groupCode + '|' + input.seq + '|' + input.type const flag = `${groupCode}|${input.seq}|${input.type}|${doubt === true ? '1' : '0'}`
return bot.event('guild-member-request', { return bot.event('guild-member-request', {
guild: decodeGuild(input.group), guild: decodeGuild(input.group),

View File

@@ -99,6 +99,15 @@ export class SatoriServer {
} }
public async stop() { public async stop() {
if (this.wsClients.length > 0) {
for (const socket of this.wsClients) {
try {
if (socket.readyState === WebSocket.OPEN) {
socket.close(1000)
}
} catch { }
}
}
if (this.wsServer) { if (this.wsServer) {
const close = promisify(this.wsServer.close) const close = promisify(this.wsServer.close)
await close.call(this.wsServer) await close.call(this.wsServer)

View File

@@ -129,6 +129,11 @@ async function decodeElement(ctx: Context, data: NT.RawMessage, quoted = false)
type: String(faceType), type: String(faceType),
platform: 'llonebot' platform: 'llonebot'
})) }))
} else if (v.arkElement) {
// llonebot:ark
buffer.push(h('llonebot:ark', {
data: v.arkElement.bytesData
}))
} }
} }
return buffer return buffer

View File

@@ -1 +1 @@
export const version = '4.0.6' export const version = '4.3.1'

View File

@@ -1,6 +1,6 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "ESNext", "target": "ES2023",
"module": "CommonJS", "module": "CommonJS",
"outDir": "./dist", "outDir": "./dist",
"strict": true, "strict": true,
@@ -20,7 +20,10 @@
"./src/ntqqapi/*" "./src/ntqqapi/*"
] ]
}, },
"noEmit": true "noEmit": true,
"types": [
"electron-vite/node"
]
}, },
"include": [ "include": [
"src", "src",