mirror of
https://github.com/LLOneBot/LLOneBot.git
synced 2024-11-22 01:56:33 +00:00
Compare commits
87 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
a7d75f84cb | ||
![]() |
9bb69058c2 | ||
![]() |
89971dd2e4 | ||
![]() |
aea67db27c | ||
![]() |
c4b45f8298 | ||
![]() |
1a77abfc62 | ||
![]() |
eb32ecb79b | ||
![]() |
ccf91f4a94 | ||
![]() |
282b2a0da0 | ||
![]() |
b28b812396 | ||
![]() |
1936671cb3 | ||
![]() |
6a8d67a8ae | ||
![]() |
64c4798117 | ||
![]() |
daca59d27d | ||
![]() |
b29134f40b | ||
![]() |
2727795b20 | ||
![]() |
edcf3f2592 | ||
![]() |
0a8e25c121 | ||
![]() |
2d5d1c69c1 | ||
![]() |
1c92f37188 | ||
![]() |
c510f4acdc | ||
![]() |
43fbcb819a | ||
![]() |
8d2353a524 | ||
![]() |
d08601505b | ||
![]() |
f9c376f6c5 | ||
![]() |
5e64df0eaa | ||
![]() |
2c55d84b9f | ||
![]() |
3c4db1d9d9 | ||
![]() |
9698c6d81c | ||
![]() |
1b04cd4843 | ||
![]() |
dbd72c952b | ||
![]() |
a4e97bfea5 | ||
![]() |
9411993d8a | ||
![]() |
e545d8d1cd | ||
![]() |
7fd37fe137 | ||
![]() |
dcaa07dc1c | ||
![]() |
5194c279d8 | ||
![]() |
b830cfbfa0 | ||
![]() |
ce25c9752f | ||
![]() |
5e00aee176 | ||
![]() |
a25c1b24fc | ||
![]() |
afed1b8575 | ||
![]() |
0fe58c1965 | ||
![]() |
b3cae5f1c6 | ||
![]() |
d09fc78747 | ||
![]() |
19d7ecd4f0 | ||
![]() |
070eee6c1c | ||
![]() |
fe5e0ea4e0 | ||
![]() |
7ba7af13a8 | ||
![]() |
fae61fbbde | ||
![]() |
a249139fe0 | ||
![]() |
ebc3968c4e | ||
![]() |
b3981f22f2 | ||
![]() |
1554f1b08e | ||
![]() |
08eb49ba67 | ||
![]() |
0fd8da0696 | ||
![]() |
3d03aec976 | ||
![]() |
083d3ddf67 | ||
![]() |
1c6ec56c81 | ||
![]() |
0ecacde730 | ||
![]() |
fd2be2feda | ||
![]() |
f272aeb28f | ||
![]() |
a8e249d8e6 | ||
![]() |
ac227f8335 | ||
![]() |
19dfc06822 | ||
![]() |
8083ae4091 | ||
![]() |
465b7eaf6e | ||
![]() |
0a6a67738e | ||
![]() |
f9a3b60192 | ||
![]() |
15ea558721 | ||
![]() |
35c9ffc0b0 | ||
![]() |
7dde7cbc2b | ||
![]() |
515fc8afb4 | ||
![]() |
f341e9f6e1 | ||
![]() |
bfdb2835c6 | ||
![]() |
05c4d693e0 | ||
![]() |
5c04f73f89 | ||
![]() |
8f7886e1ee | ||
![]() |
5bbbe77ad0 | ||
![]() |
0a3ae76b89 | ||
![]() |
ddd60a6a79 | ||
![]() |
6364f90b20 | ||
![]() |
e4d8c5e72e | ||
![]() |
907c9053c7 | ||
![]() |
6d33fb8b14 | ||
![]() |
2350e4dc75 | ||
![]() |
600addbf82 |
20
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
20
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: Bug反馈
|
||||
about: 报个Bug
|
||||
title: ''
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
QQ版本:
|
||||
|
||||
LLOneBot版本:
|
||||
|
||||
调用LLOneBot的方式或者应用端(如postman直接调用,或NoneBot2、Koishi):
|
||||
|
||||
BUG描述:
|
||||
|
||||
复现步骤:
|
||||
|
||||
LLOneBot日志:
|
36
.github/workflows/publish.yml
vendored
Normal file
36
.github/workflows/publish.yml
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
name: "publish"
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
|
||||
jobs:
|
||||
build-and-publish:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: setup node
|
||||
uses: actions/setup-node@v2
|
||||
with:
|
||||
node-version: 18
|
||||
|
||||
- name: install dependenies
|
||||
run: npm install
|
||||
|
||||
- name: build
|
||||
run: npm run build
|
||||
|
||||
- name: zip
|
||||
run: |
|
||||
sudo apt install zip -y
|
||||
cp manifest.json ./dist/manifest.json
|
||||
zip LLOneBot.zip ./dist/* -j
|
||||
|
||||
- name: publish
|
||||
uses: ncipollo/release-action@v1
|
||||
with:
|
||||
artifacts: "LLOneBot.zip"
|
||||
draft: true
|
||||
token: ${{ secrets.RELEASE_TOKEN }}
|
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,3 +1,4 @@
|
||||
node_modules/
|
||||
dist/
|
||||
.idea/
|
||||
.idea/
|
||||
.DS_Store
|
82
README.md
82
README.md
@@ -1,30 +1,31 @@
|
||||
# LLOneBot API
|
||||
|
||||
将NTQQLiteLoaderAPI封装成OneBot11/12标准的API, V12没有完整测试
|
||||
LiteLoaderQQNT的OneBot11协议插件
|
||||
|
||||
*注意:本文档对应的是 LiteLoader 1.0.0及以上版本,如果你使用的是旧版本请切换到本项目v1分支查看文档*
|
||||
|
||||
*V3之后不再需要LLAPI*
|
||||
|
||||
## 安装方法
|
||||
|
||||
1.安装[NTQQLiteLoader](https://github.com/LiteLoaderQQNT/LiteLoaderQQNT)
|
||||
1.安装[LiteLoaderQQNT](https://liteloaderqqnt.github.io/guide/install.html)
|
||||
|
||||
2.安装修改后的[LiteLoaderQQNT-Plugin-LLAPI](https://github.com/linyuchen/LiteLoaderQQNT-Plugin-LLAPI),原版的功能有缺陷
|
||||
2.安装本项目插件[OneBotApi](https://github.com/linyuchen/LiteLoaderQQNT-OneBotApi/releases/), 注意本插件2.0以下的版本不支持LiteLoader 1.0.0及以上版本
|
||||
|
||||
3.安装本项目插件[OneBotApi](https://github.com/linyuchen/LiteLoaderQQNT-OneBotApi/releases/)
|
||||
*关于插件的安装方法: 下载后解压复制到插件目录*
|
||||
|
||||
*关于插件的安装方法: 上述的两个插件都没有上架NTQQLiteLoader插件市场,需要自己下载源码复制到插件目录*
|
||||
|
||||
*Windows插件目录:`%USERPROFILE%/Documents/LiteLoaderQQNT/plugins`*
|
||||
|
||||
*Mac插件目录:`~/Library/Containers/com.tencent.qq/Data/Documents/LiteLoaderQQNT/plugins`*
|
||||
*插件目录:`LiteLoaderQQNT/plugins`*
|
||||
|
||||
## 支持的API
|
||||
|
||||
目前只支持http协议POST方法,不支持websocket,事件上报也是http协议
|
||||
目前只支持http协议,不支持websocket,事件上报也是http协议
|
||||
|
||||
主要功能:
|
||||
- [x] 发送好友消息
|
||||
- [x] 发送群消息
|
||||
- [x] 获取好友列表
|
||||
- [x] 获取群列表
|
||||
- [x] 获取群成员列表
|
||||
- [x] 获取好友列表
|
||||
- [x] 发送群消息
|
||||
- [x] 发送好友消息
|
||||
- [x] 撤回消息
|
||||
- [x] 上报好友消息
|
||||
- [x] 上报群消息
|
||||
@@ -34,7 +35,9 @@
|
||||
- [x] 图片
|
||||
- [x] 引用消息
|
||||
- [x] @群成员
|
||||
- [x] 发送语音(只测试了silk编码的amr)
|
||||
- [x] 语音
|
||||
- [x] json消息(只上报)
|
||||
- [ ] 红包
|
||||
- [ ] 转发消息记录
|
||||
- [ ] xml
|
||||
|
||||
@@ -45,14 +48,59 @@
|
||||
- [x] send_private_msg
|
||||
- [x] delete_msg
|
||||
- [x] get_group_list
|
||||
- [x] get_group_info
|
||||
- [x] get_group_member_list
|
||||
- [x] get_group_member_info
|
||||
- [x] get_friend_list
|
||||
|
||||
**自己发送成功的消息也会上报,可以用于获取需要撤回消息的id**
|
||||
- [x] get_msg
|
||||
|
||||
## 示例
|
||||
|
||||

|
||||
|
||||
*暂时不支持`"message": "hello"`这种message为字符串的形式*
|
||||
## 一些坑
|
||||
|
||||
<details>
|
||||
<summary>下载了插件但是没有看到在NTQQ中生效</summary>
|
||||
<br/>
|
||||
检查是否下载的是插件release的版本,如果是源码的话需要自行编译。依然不生效请查阅<a href="https://liteloaderqqnt.github.io/guide/plugins.html">LiteLoaderQQNT的文档</a>
|
||||
</details>
|
||||
<br/>
|
||||
|
||||
<details>
|
||||
<summary>调用接口报404</summary>
|
||||
<br/>
|
||||
目前没有支持全部的onebot规范接口,请检查是否调用了不支持的接口
|
||||
</details>
|
||||
<br/>
|
||||
|
||||
<details>
|
||||
<summary>发送不了图片和语音</summary>
|
||||
<br/>
|
||||
检查当前操作用户是否有LiteLoaderQQNT/data/LLOneBot的写入权限,如Windows把QQ上安装到C盘有可能会出现无权限导致发送失败
|
||||
</details>
|
||||
<br/>
|
||||
|
||||
<details>
|
||||
<summary>不支持cq码</summary>
|
||||
<br/>
|
||||
cq码已经过时了,没有支持的打算(主要是我不用这玩意儿,加上我懒)
|
||||
</details>
|
||||
<br/>
|
||||
|
||||
<details>
|
||||
<summary>QQ变得很卡</summary>
|
||||
<br/>
|
||||
这是你的群特别多导致的,因为启动后会批量获取群成员列表,获取完之后就正常了
|
||||
</details>
|
||||
<br/>
|
||||
|
||||
|
||||
## TODO
|
||||
- [x] 重构摆脱LLAPI,目前调用LLAPI只能在renderer进程调用,需重构成在main进程调用
|
||||
- [ ] 转发消息记录
|
||||
- [ ] 好友点赞api
|
||||
- [ ] 支持websocket,等个有缘人提PR实现
|
||||
|
||||
## onebot11文档
|
||||
<https://11.onebot.dev/>
|
||||
|
@@ -1,23 +1,23 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"manifest_version": 4,
|
||||
"type": "extension",
|
||||
"name": "LLOneBot",
|
||||
"slug": "LLOneBot",
|
||||
"description": "LiteLoaderQQNT的OneBotApi",
|
||||
"version": "1.2.5",
|
||||
"version": "3.0.8",
|
||||
"thumbnail": "./icon.png",
|
||||
"author": {
|
||||
"authors": [{
|
||||
"name": "linyuchen",
|
||||
"link": "https://github.com/linyuchen"
|
||||
},
|
||||
}],
|
||||
"repository": {
|
||||
"repo": "linyuchen/LLOneBot",
|
||||
"branch": "main",
|
||||
"use_release": {
|
||||
"tag": "latest",
|
||||
"name": "LLOneBot.zip"
|
||||
}
|
||||
},
|
||||
"repo": "linyuchen/LiteLoaderQQNT-OneBotApi",
|
||||
"branch": "main",
|
||||
"release": {
|
||||
"tag": "latest",
|
||||
"name": "LLOneBot.zip"
|
||||
}
|
||||
},
|
||||
"platform": [
|
||||
"win32",
|
||||
"linux",
|
||||
|
778
package-lock.json
generated
778
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
13
package.json
13
package.json
@@ -5,28 +5,31 @@
|
||||
"main": "dist/main.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"postinstall": "ELECTRON_SKIP_BINARY_DOWNLOAD=1 npm install electron --no-save",
|
||||
"build": "npm run build-main && npm run build-preload && npm run build-renderer",
|
||||
"build-main": "webpack --config webpack.main.config.js",
|
||||
"build-preload": "webpack --config webpack.preload.config.js",
|
||||
"build-renderer": "webpack --config webpack.renderer.config.js",
|
||||
"build-mac": "npm run build && cp manifest.json dist/ && npm run deploy-mac",
|
||||
"deploy-mac": "cp dist/* ~/Library/Containers/com.tencent.qq/Data/Documents/LiteLoaderQQNT/plugins/LLOnebot/",
|
||||
"deploy-mac": "cp dist/* ~/Library/Containers/com.tencent.qq/Data/LiteLoaderQQNT/plugins/LLOnebot/",
|
||||
"build-win": "npm run build && cp manifest.json dist/ && npm run deploy-win",
|
||||
"deploy-win": "cmd /c \"copy dist\\* %USERPROFILE%\\documents\\LiteLoaderQQNT\\plugins\\LLOnebot\\\""
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"express": "^4.18.2"
|
||||
"express": "^4.18.2",
|
||||
"json-bigint": "^1.0.0",
|
||||
"uuid": "^9.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"electron": "^27.0.2",
|
||||
"@babel/preset-env": "^7.23.2",
|
||||
"@types/express": "^4.17.20",
|
||||
"@types/uuid": "^9.0.8",
|
||||
"babel-loader": "^9.1.3",
|
||||
"ts-loader": "^9.5.0",
|
||||
"typescript": "^5.2.2",
|
||||
"webpack": "^5.89.0",
|
||||
"webpack-cli": "^5.1.4",
|
||||
"typescript": "^5.2.2"
|
||||
"webpack-cli": "^5.1.4"
|
||||
}
|
||||
}
|
||||
|
@@ -1,12 +0,0 @@
|
||||
export const CHANNEL_SEND_MSG = "llonebot_send_msg"
|
||||
export const CHANNEL_RECALL_MSG = "llonebot_recall_msg"
|
||||
export const CHANNEL_GET_CONFIG = "llonebot_get_config"
|
||||
export const CHANNEL_SET_CONFIG = "llonebot_set_config"
|
||||
export const CHANNEL_START_HTTP_SERVER = "llonebot_start_http_server"
|
||||
export const CHANNEL_UPDATE_GROUPS = "llonebot_update_groups"
|
||||
export const CHANNEL_UPDATE_FRIENDS = "llonebot_update_friends"
|
||||
export const CHANNEL_LOG = "llonebot_log"
|
||||
export const CHANNEL_POST_ONEBOT_DATA = "llonebot_post_onebot_data"
|
||||
export const CHANNEL_SET_SELF_INFO= "llonebot_set_self_info"
|
||||
export const CHANNEL_DOWNLOAD_FILE= "llonebot_download_file"
|
||||
export const CHANNEL_DELETE_FILE= "llonebot_delete_file"
|
3
src/common/channels.ts
Normal file
3
src/common/channels.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export const CHANNEL_GET_CONFIG = "llonebot_get_config"
|
||||
export const CHANNEL_SET_CONFIG = "llonebot_set_config"
|
||||
export const CHANNEL_LOG = "llonebot_log"
|
@@ -1,4 +1,4 @@
|
||||
import {Config} from "../common/types";
|
||||
import {Config} from "./types";
|
||||
|
||||
const fs = require("fs")
|
||||
|
89
src/common/data.ts
Normal file
89
src/common/data.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import { NTQQApi } from '../ntqqapi/ntcall';
|
||||
import { Friend, Group, GroupMember, RawMessage, SelfInfo } from "../ntqqapi/types";
|
||||
import { log } from "./utils";
|
||||
|
||||
export let groups: Group[] = []
|
||||
export let friends: Friend[] = []
|
||||
export let msgHistory: Record<string, RawMessage> = {} // msgId: RawMessage
|
||||
|
||||
let globalMsgId = Date.now()
|
||||
|
||||
export function addHistoryMsg(msg: RawMessage): boolean{
|
||||
let existMsg = msgHistory[msg.msgId]
|
||||
if (existMsg){
|
||||
Object.assign(existMsg, msg)
|
||||
msg.msgShortId = existMsg.msgShortId;
|
||||
return false
|
||||
}
|
||||
msg.msgShortId = ++globalMsgId
|
||||
msgHistory[msg.msgId] = msg
|
||||
return true
|
||||
}
|
||||
|
||||
export function getHistoryMsgByShortId(shortId: number | string){
|
||||
// log("getHistoryMsgByShortId", shortId, Object.values(msgHistory).map(m=>m.msgShortId))
|
||||
return Object.values(msgHistory).find(msg => msg.msgShortId.toString() == shortId.toString())
|
||||
}
|
||||
|
||||
|
||||
export async function getFriend(qq: string): Promise<Friend | undefined> {
|
||||
let friend = friends.find(friend => friend.uin === qq)
|
||||
// if (!friend){
|
||||
// friends = (await NTQQApi.getFriends(true))
|
||||
// friend = friends.find(friend => friend.uin === qq)
|
||||
// }
|
||||
return friend
|
||||
}
|
||||
|
||||
export async function getGroup(qq: string): Promise<Group | undefined> {
|
||||
let group = groups.find(group => group.groupCode === qq)
|
||||
// if (!group){
|
||||
// groups = await NTQQApi.getGroups(true);
|
||||
// group = groups.find(group => group.groupCode === qq)
|
||||
// }
|
||||
return group
|
||||
}
|
||||
|
||||
export async function getGroupMember(groupQQ: string, memberQQ: string=null, memberUid: string=null) {
|
||||
const group = await getGroup(groupQQ)
|
||||
if (group) {
|
||||
let filterFunc: (member: GroupMember) => boolean
|
||||
if (memberQQ){
|
||||
filterFunc = member => member.uin === memberQQ
|
||||
}
|
||||
else if (memberUid){
|
||||
filterFunc = member => member.uid === memberUid
|
||||
}
|
||||
let member = group.members?.find(filterFunc)
|
||||
if (!member){
|
||||
const _members = await NTQQApi.getGroupMembers(groupQQ)
|
||||
if (_members.length){
|
||||
group.members = _members
|
||||
}
|
||||
member = group.members?.find(filterFunc)
|
||||
}
|
||||
return member
|
||||
}
|
||||
}
|
||||
|
||||
export let selfInfo: SelfInfo = {
|
||||
uid: "",
|
||||
uin: "",
|
||||
nick: "",
|
||||
}
|
||||
|
||||
|
||||
export function getHistoryMsgBySeq(seq: string) {
|
||||
return Object.values(msgHistory).find(msg => msg.msgSeq === seq)
|
||||
}
|
||||
|
||||
|
||||
export let uidMaps:Record<string, Friend> = {} // 一串加密的字符串(uid) -> qq号
|
||||
|
||||
export function getStrangerByUin(uin: string) {
|
||||
for (const key in uidMaps) {
|
||||
if (uidMaps[key].uin === uin) {
|
||||
return uidMaps[key];
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,160 +1,9 @@
|
||||
export enum AtType {
|
||||
notAt = 0,
|
||||
atUser = 2
|
||||
export interface Config {
|
||||
port: number
|
||||
hosts: string[]
|
||||
enableBase64?: boolean
|
||||
debug?: boolean
|
||||
reportSelfMessage?: boolean
|
||||
log?: boolean
|
||||
}
|
||||
|
||||
export type GroupMemberInfo = {
|
||||
avatarPath: string;
|
||||
cardName: string;
|
||||
cardType: number;
|
||||
isDelete: boolean;
|
||||
nick: string;
|
||||
qid: string;
|
||||
remark: string;
|
||||
role: number; // 群主:4, 管理员:3,群员:2
|
||||
shutUpTime: number; // 禁言时间,单位是什么暂时不清楚
|
||||
uid: string; // 加密的字符串
|
||||
uin: string; // QQ号
|
||||
}
|
||||
|
||||
export const OnebotGroupMemberRole = {
|
||||
4: 'owner',
|
||||
3: 'admin',
|
||||
2: 'member'
|
||||
}
|
||||
|
||||
|
||||
export type SelfInfo = {
|
||||
user_id: string;
|
||||
nickname: string;
|
||||
}
|
||||
|
||||
export type User = {
|
||||
avatarUrl?: string;
|
||||
bio?: string; // 签名
|
||||
nickName: string;
|
||||
uid?: string; // 加密的字符串
|
||||
uin: string; // QQ号
|
||||
}
|
||||
|
||||
export type Group = {
|
||||
uid: string; // 群号
|
||||
name: string;
|
||||
members?: GroupMemberInfo[];
|
||||
}
|
||||
|
||||
export type Peer = {
|
||||
chatType: "private" | "group"
|
||||
name: string
|
||||
uid: string // qq号
|
||||
}
|
||||
|
||||
export type MessageElement = {
|
||||
raw: {
|
||||
msgId: string,
|
||||
msgSeq: string,
|
||||
elements: {
|
||||
replyElement: {
|
||||
senderUid: string, // 原消息发送者QQ号
|
||||
sourceMsgIsIncPic: boolean; // 原消息是否有图片
|
||||
sourceMsgText: string;
|
||||
replayMsgSeq: string; // 源消息的msgSeq,可以通过这个找到源消息的msgId
|
||||
},
|
||||
textElement: {
|
||||
atType: AtType
|
||||
atUid: string,
|
||||
content: string,
|
||||
atNtUid: string
|
||||
},
|
||||
picElement: {
|
||||
sourcePath: string // 图片本地路径
|
||||
picWidth: number
|
||||
picHeight: number
|
||||
fileSize: number
|
||||
fileName: string
|
||||
fileUuid: string
|
||||
},
|
||||
pttElement: {
|
||||
canConvert2Text: boolean
|
||||
duration: number // 秒数
|
||||
fileBizId: null
|
||||
fileId: number // 0
|
||||
fileName: string // "e4d09c784d5a2abcb2f9980bdc7acfe6.amr"
|
||||
filePath: string // "/Users/C5366155/Library/Containers/com.tencent.qq/Data/Library/Application Support/QQ/nt_qq_a6b15c9820595d25a56c1633ce19ad40/nt_data/Ptt/2023-11/Ori/e4d09c784d5a2abcb2f9980bdc7acfe6.amr"
|
||||
fileSize: string // "4261"
|
||||
fileSubId: string // "0"
|
||||
fileUuid: string // "90j3z7rmRphDPrdVgP9udFBaYar#oK0TWZIV"
|
||||
formatType: string // 1
|
||||
invalidState: number // 0
|
||||
md5HexStr: string // "e4d09c784d5a2abcb2f9980bdc7acfe6"
|
||||
playState: number // 0
|
||||
progress: number // 0
|
||||
text: string // ""
|
||||
transferStatus: number // 0
|
||||
translateStatus: number // 0
|
||||
voiceChangeType: number // 0
|
||||
voiceType: number // 0
|
||||
waveAmplitudes: number[]
|
||||
}
|
||||
}[]
|
||||
}
|
||||
|
||||
peer: Peer,
|
||||
sender: {
|
||||
uid: string // 一串加密的字符串
|
||||
memberName: string
|
||||
nickname: string
|
||||
}
|
||||
}
|
||||
|
||||
export type SendMessage = {
|
||||
type: "text",
|
||||
content: string,
|
||||
data?: {
|
||||
text: string, // 纯文本
|
||||
}
|
||||
} | {
|
||||
type: "image" | "voice",
|
||||
file: string, // 本地路径
|
||||
data?: {
|
||||
file: string // 本地路径
|
||||
}
|
||||
} | {
|
||||
type: "at",
|
||||
atType?: AtType,
|
||||
content?: string,
|
||||
atUid?: string,
|
||||
atNtUid?: string,
|
||||
data?: {
|
||||
qq: string // at的qq号
|
||||
}
|
||||
} | {
|
||||
type: "reply",
|
||||
msgId: string,
|
||||
msgSeq: string,
|
||||
senderUin: string,
|
||||
data: {
|
||||
id: string,
|
||||
}
|
||||
}
|
||||
|
||||
export type PostDataAction = "send_private_msg" | "send_group_msg" | "get_group_list"
|
||||
| "get_friend_list" | "delete_msg" | "get_login_info" | "get_group_member_list" | "get_group_member_info"
|
||||
|
||||
export type PostDataSendMsg = {
|
||||
action: PostDataAction
|
||||
message_type?: "private" | "group"
|
||||
params?: {
|
||||
user_id: string,
|
||||
group_id: string,
|
||||
message: SendMessage[];
|
||||
},
|
||||
user_id: string,
|
||||
group_id: string,
|
||||
message: SendMessage[];
|
||||
}
|
||||
|
||||
export type Config = {
|
||||
port: number,
|
||||
hosts: string[],
|
||||
}
|
||||
|
96
src/common/utils.ts
Normal file
96
src/common/utils.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import * as path from "path";
|
||||
import {selfInfo} from "./data";
|
||||
import {ConfigUtil} from "./config";
|
||||
import util from "util";
|
||||
import { sendLog } from '../main/ipcsend';
|
||||
|
||||
const fs = require('fs');
|
||||
|
||||
export const CONFIG_DIR = global.LiteLoader.plugins["LLOneBot"].path.data;
|
||||
|
||||
export function getConfigUtil() {
|
||||
const configFilePath = path.join(CONFIG_DIR, `config_${selfInfo.uin}.json`)
|
||||
return new ConfigUtil(configFilePath)
|
||||
}
|
||||
|
||||
export function log(...msg: any[]) {
|
||||
if (!getConfigUtil().getConfig().log){
|
||||
return
|
||||
}
|
||||
let currentDateTime = new Date().toLocaleString();
|
||||
const date = new Date();
|
||||
const year = date.getFullYear();
|
||||
const month = date.getMonth() + 1;
|
||||
const day = date.getDate();
|
||||
const currentDate = `${year}-${month}-${day}`;
|
||||
const userInfo = selfInfo.uin ? `${selfInfo.nick}(${selfInfo.uin})` : ""
|
||||
let logMsg = "";
|
||||
for (let msgItem of msg){
|
||||
// 判断是否是对象
|
||||
if (typeof msgItem === "object"){
|
||||
logMsg += JSON.stringify(msgItem) + " ";
|
||||
continue;
|
||||
}
|
||||
logMsg += msgItem + " ";
|
||||
}
|
||||
logMsg = `${currentDateTime} ${userInfo}: ${logMsg}\n`
|
||||
// sendLog(...msg);
|
||||
// console.log(msg)
|
||||
fs.appendFile(path.join(CONFIG_DIR , `llonebot-${currentDate}.log`), logMsg, (err: any) => {
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
export function isGIF(path: string) {
|
||||
const buffer = Buffer.alloc(4);
|
||||
const fd = fs.openSync(path, 'r');
|
||||
fs.readSync(fd, buffer, 0, 4, 0);
|
||||
fs.closeSync(fd);
|
||||
return buffer.toString() === 'GIF8'
|
||||
}
|
||||
|
||||
|
||||
// 定义一个异步函数来检查文件是否存在
|
||||
export function checkFileReceived(path: string, timeout: number=3000): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const startTime = Date.now();
|
||||
|
||||
function check() {
|
||||
if (fs.existsSync(path)) {
|
||||
resolve();
|
||||
} else if (Date.now() - startTime > timeout) {
|
||||
reject(new Error(`文件不存在: ${path}`));
|
||||
} else {
|
||||
setTimeout(check, 100);
|
||||
}
|
||||
}
|
||||
|
||||
check();
|
||||
});
|
||||
}
|
||||
|
||||
export async function file2base64(path: string){
|
||||
const readFile = util.promisify(fs.readFile);
|
||||
let result = {
|
||||
err: "",
|
||||
data: ""
|
||||
}
|
||||
try {
|
||||
// 读取文件内容
|
||||
// if (!fs.existsSync(path)){
|
||||
// path = path.replace("\\Ori\\", "\\Thumb\\");
|
||||
// }
|
||||
try {
|
||||
await checkFileReceived(path, 5000);
|
||||
} catch (e: any) {
|
||||
result.err = e.toString();
|
||||
return result;
|
||||
}
|
||||
const data = await readFile(path);
|
||||
// 转换为Base64编码
|
||||
result.data = data.toString('base64');
|
||||
} catch (err) {
|
||||
result.err = err.toString();
|
||||
}
|
||||
return result;
|
||||
}
|
43
src/global.d.ts
vendored
43
src/global.d.ts
vendored
@@ -1,55 +1,14 @@
|
||||
import {
|
||||
Config,
|
||||
Group,
|
||||
GroupMemberInfo,
|
||||
MessageElement,
|
||||
Peer,
|
||||
PostDataSendMsg,
|
||||
SelfInfo,
|
||||
SendMessage,
|
||||
User
|
||||
} from "./common/types";
|
||||
|
||||
|
||||
declare var LLAPI: {
|
||||
on(event: "new-messages" | "new-send-messages", callback: (data: MessageElement[]) => void): void;
|
||||
on(event: "context-msg-menu", callback: (event: any, target: any, msgIds:any) => void): void;
|
||||
getAccountInfo(): Promise<{
|
||||
uid: string // 一串加密的字符串
|
||||
uin: string // qq
|
||||
}>
|
||||
|
||||
getUserInfo(uid: string): Promise<User>; // uid是一串加密的字符串
|
||||
sendMessage(peer: Peer, message: SendMessage[]): Promise<any>;
|
||||
recallMessage(peer: Peer, msgIds: string[]): Promise<void>;
|
||||
getGroupsList(forced: boolean): Promise<Group[]>
|
||||
getFriendsList(forced: boolean): Promise<User[]>
|
||||
getGroupMemberList(group_id: string, num: number): Promise<{result: { infos: Map<string, GroupMemberInfo> }}>
|
||||
getPeer(): Promise<Peer>
|
||||
add_qmenu(func: (qContextMenu: Node)=>void): void
|
||||
|
||||
};
|
||||
import { Config } from "./common/types";
|
||||
|
||||
|
||||
declare var llonebot: {
|
||||
postData: (data: any) => void
|
||||
listenSendMessage: (handle: (msg: PostDataSendMsg) => void) => void
|
||||
listenRecallMessage: (handle: (msg: {message_id: string}) => void) => void
|
||||
updateGroups: (groups: Group[]) => void
|
||||
updateFriends: (friends: User[]) => void
|
||||
updateGroupMembers: (data: { groupMembers: User[], group_id: string }) => void
|
||||
startExpress: () => void
|
||||
log(data: any): void,
|
||||
setConfig(config: Config):void;
|
||||
getConfig():Promise<Config>;
|
||||
setSelfInfo(selfInfo: SelfInfo):void;
|
||||
downloadFile(arg: {uri: string, localFilePath: string}):Promise<string>;
|
||||
deleteFile(path: string[]):Promise<void>;
|
||||
};
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
LLAPI: typeof LLAPI;
|
||||
llonebot: typeof llonebot;
|
||||
LiteLoader: any;
|
||||
}
|
||||
|
@@ -1,196 +0,0 @@
|
||||
const express = require("express");
|
||||
const bodyParser = require('body-parser');
|
||||
import {sendIPCRecallQQMsg, sendIPCSendQQMsg} from "./IPCSend";
|
||||
import {OnebotGroupMemberRole, PostDataAction, PostDataSendMsg, SendMessage} from "../common/types";
|
||||
import {friends, groups, selfInfo} from "./data";
|
||||
|
||||
// @SiberianHusky 2021-08-15
|
||||
function checkSendMessage(sendMsgList: SendMessage[]) {
|
||||
function checkUri(uri: string): boolean {
|
||||
const pattern = /^(file:\/\/|http:\/\/|https:\/\/|base64:\/\/)/;
|
||||
return pattern.test(uri);
|
||||
}
|
||||
|
||||
for (let msg of sendMsgList) {
|
||||
if (msg["type"] && msg["data"]) {
|
||||
let type = msg["type"];
|
||||
let data = msg["data"];
|
||||
if (type === "text" && !data["text"]) {
|
||||
return 400;
|
||||
} else if (["image", "voice"].includes(type)) {
|
||||
if (!data["file"]) {
|
||||
return 400;
|
||||
}
|
||||
else{
|
||||
if (checkUri(data["file"])) {
|
||||
return 200;
|
||||
}
|
||||
else{
|
||||
return 400;
|
||||
}
|
||||
}
|
||||
|
||||
} else if (type === "at" && !data["qq"]) {
|
||||
return 400;
|
||||
} else if (type === "reply" && !data["id"]) {
|
||||
return 400;
|
||||
}
|
||||
}
|
||||
else{
|
||||
return 400
|
||||
}
|
||||
}
|
||||
return 200;
|
||||
}
|
||||
// ==end==
|
||||
|
||||
function handlePost(jsonData: any) {
|
||||
if (!jsonData.params) {
|
||||
jsonData.params = jsonData
|
||||
|
||||
}
|
||||
let resData = {
|
||||
status: 0,
|
||||
retcode: 0,
|
||||
data: {},
|
||||
message: ''
|
||||
}
|
||||
if (jsonData.action == "get_login_info") {
|
||||
resData["data"] = selfInfo
|
||||
} else if (jsonData.action == "send_private_msg" || jsonData.action == "send_group_msg") {
|
||||
if (jsonData.action == "send_private_msg") {
|
||||
jsonData.message_type = "private"
|
||||
} else {
|
||||
jsonData.message_type = "group"
|
||||
}
|
||||
// @SiberianHuskY 2021-10-20 22:00:00
|
||||
resData.status = checkSendMessage(jsonData.message);
|
||||
if (resData.status == 200) {
|
||||
resData.message = "发送成功";
|
||||
resData.data = jsonData.message;
|
||||
sendIPCSendQQMsg(jsonData);
|
||||
} else {
|
||||
resData.message = "发送失败, 请检查消息格式";
|
||||
resData.data = jsonData.message;
|
||||
}
|
||||
// == end ==
|
||||
} else if (jsonData.action == "get_group_list") {
|
||||
resData["data"] = groups.map(group => {
|
||||
return {
|
||||
group_id: group.uid,
|
||||
group_name: group.name,
|
||||
member_count: group.members.length,
|
||||
group_members: group.members.map(member => {
|
||||
return {
|
||||
user_id: member.uin,
|
||||
user_name: member.cardName || member.nick,
|
||||
user_display_name: member.cardName || member.nick
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
} else if (jsonData.action == "get_group_info") {
|
||||
let group = groups.find(group => group.uid == jsonData.params.group_id)
|
||||
if (group) {
|
||||
resData["data"] = {
|
||||
group_id: group.uid,
|
||||
group_name: group.name,
|
||||
member_count: group.members.length,
|
||||
}
|
||||
}
|
||||
} else if (jsonData.action == "get_group_member_info") {
|
||||
let member = groups.find(group => group.uid == jsonData.params.group_id)?.members?.find(member => member.uin == jsonData.params.user_id)
|
||||
resData["data"] = {
|
||||
user_id: member.uin,
|
||||
user_name: member.nick,
|
||||
user_display_name: member.cardName || member.nick,
|
||||
nickname: member.nick,
|
||||
card: member.cardName,
|
||||
role: OnebotGroupMemberRole[member.role],
|
||||
}
|
||||
} else if (jsonData.action == "get_group_member_list") {
|
||||
let group = groups.find(group => group.uid == jsonData.params.group_id)
|
||||
if (group) {
|
||||
resData["data"] = group?.members?.map(member => {
|
||||
return {
|
||||
user_id: member.uin,
|
||||
user_name: member.nick,
|
||||
user_display_name: member.cardName || member.nick,
|
||||
nickname: member.nick,
|
||||
card: member.cardName,
|
||||
role: OnebotGroupMemberRole[member.role],
|
||||
}
|
||||
|
||||
}) || []
|
||||
} else {
|
||||
resData["data"] = []
|
||||
}
|
||||
} else if (jsonData.action == "get_friend_list") {
|
||||
resData["data"] = friends.map(friend => {
|
||||
return {
|
||||
user_id: friend.uin,
|
||||
user_name: friend.nickName,
|
||||
}
|
||||
})
|
||||
} else if (jsonData.action == "delete_msg") {
|
||||
sendIPCRecallQQMsg(jsonData.message_id)
|
||||
}
|
||||
return resData
|
||||
}
|
||||
|
||||
|
||||
export function startExpress(port: number) {
|
||||
const app = express();
|
||||
// 中间件,用于解析POST请求的请求体
|
||||
app.use(express.urlencoded({extended: true, limit: "500mb"}));
|
||||
app.use(bodyParser({limit: '500mb'}))
|
||||
app.use(express.json());
|
||||
|
||||
function parseToOnebot12(action: PostDataAction) {
|
||||
app.post('/' + action, (req: any, res: any) => {
|
||||
let jsonData: PostDataSendMsg = req.body;
|
||||
jsonData.action = action
|
||||
let resData = handlePost(jsonData)
|
||||
res.send(resData)
|
||||
});
|
||||
}
|
||||
|
||||
const actionList: PostDataAction[] = ["get_login_info", "send_private_msg", "send_group_msg",
|
||||
"get_group_list", "get_friend_list", "delete_msg", "get_group_member_list", "get_group_member_info"]
|
||||
|
||||
for (const action of actionList) {
|
||||
parseToOnebot12(action as PostDataAction)
|
||||
}
|
||||
|
||||
app.get('/', (req: any, res: any) => {
|
||||
res.send('llonebot已启动');
|
||||
})
|
||||
|
||||
|
||||
// 处理POST请求的路由
|
||||
app.post('/', (req: any, res: any) => {
|
||||
let jsonData: PostDataSendMsg = req.body;
|
||||
let resData = handlePost(jsonData)
|
||||
res.send(resData)
|
||||
});
|
||||
app.post('/send_msg', (req: any, res: any) => {
|
||||
let jsonData: PostDataSendMsg = req.body;
|
||||
if (jsonData.message_type == "private") {
|
||||
jsonData.action = "send_private_msg"
|
||||
} else if (jsonData.message_type == "group") {
|
||||
jsonData.action = "send_group_msg"
|
||||
} else {
|
||||
if (jsonData.params.group_id) {
|
||||
jsonData.action = "send_group_msg"
|
||||
} else {
|
||||
jsonData.action = "send_private_msg"
|
||||
}
|
||||
}
|
||||
let resData = handlePost(jsonData)
|
||||
res.send(resData)
|
||||
})
|
||||
|
||||
app.listen(port, "0.0.0.0", () => {
|
||||
console.log(`服务器已启动,监听端口 ${port}`);
|
||||
});
|
||||
}
|
@@ -1,22 +0,0 @@
|
||||
import {ipcMain, webContents} from 'electron';
|
||||
import {PostDataSendMsg} from "../common/types";
|
||||
import {CHANNEL_RECALL_MSG, CHANNEL_SEND_MSG} from "../common/IPCChannel";
|
||||
|
||||
function sendIPCMsg(channel: string, data: any) {
|
||||
let contents = webContents.getAllWebContents();
|
||||
for (const content of contents) {
|
||||
try {
|
||||
content.send(channel, data)
|
||||
} catch (e) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export function sendIPCSendQQMsg(postData: PostDataSendMsg) {
|
||||
sendIPCMsg(CHANNEL_SEND_MSG, postData);
|
||||
}
|
||||
|
||||
export function sendIPCRecallQQMsg(message_id: string) {
|
||||
sendIPCMsg(CHANNEL_RECALL_MSG, {message_id});
|
||||
}
|
@@ -1,9 +0,0 @@
|
||||
import {Group, SelfInfo, User} from "../common/types";
|
||||
|
||||
export let groups: Group[] = []
|
||||
export let friends: User[] = []
|
||||
|
||||
export let selfInfo: SelfInfo = {
|
||||
user_id: "",
|
||||
nickname: ""
|
||||
}
|
18
src/main/ipcsend.ts
Normal file
18
src/main/ipcsend.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import {webContents} from 'electron';
|
||||
import { CHANNEL_LOG } from '../common/channels';
|
||||
|
||||
|
||||
function sendIPCMsg(channel: string, ...data: any) {
|
||||
let contents = webContents.getAllWebContents();
|
||||
for (const content of contents) {
|
||||
try {
|
||||
content.send(channel, ...data)
|
||||
} catch (e) {
|
||||
console.log("llonebot send ipc msg to render error:", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function sendLog(...args){
|
||||
sendIPCMsg(CHANNEL_LOG, ...args)
|
||||
}
|
212
src/main/main.ts
212
src/main/main.ts
@@ -1,144 +1,146 @@
|
||||
// 运行在 Electron 主进程 下的插件入口
|
||||
|
||||
import * as path from "path";
|
||||
import {ipcMain} from 'electron';
|
||||
import { BrowserWindow, ipcMain } from 'electron';
|
||||
import * as util from 'util';
|
||||
|
||||
import {Config, Group, SelfInfo, User} from "../common/types";
|
||||
import { Config } from "../common/types";
|
||||
import {
|
||||
CHANNEL_DOWNLOAD_FILE,
|
||||
CHANNEL_GET_CONFIG,
|
||||
CHANNEL_SET_SELF_INFO,
|
||||
CHANNEL_LOG,
|
||||
CHANNEL_POST_ONEBOT_DATA,
|
||||
CHANNEL_SET_CONFIG,
|
||||
CHANNEL_START_HTTP_SERVER,
|
||||
CHANNEL_UPDATE_FRIENDS,
|
||||
CHANNEL_UPDATE_GROUPS, CHANNEL_DELETE_FILE
|
||||
} from "../common/IPCChannel";
|
||||
import {ConfigUtil} from "./config";
|
||||
import {startExpress} from "./HttpServer";
|
||||
import {log} from "./utils";
|
||||
import {friends, groups, selfInfo} from "./data";
|
||||
} from "../common/channels";
|
||||
import { postMsg, startExpress } from "../onebot11/server";
|
||||
import { CONFIG_DIR, getConfigUtil, log } from "../common/utils";
|
||||
import { addHistoryMsg, msgHistory, selfInfo } from "../common/data";
|
||||
import { hookNTQQApiReceive, ReceiveCmd, registerReceiveHook } from "../ntqqapi/hook";
|
||||
import { OB11Constructor } from "../onebot11/constructor";
|
||||
import { NTQQApi } from "../ntqqapi/ntcall";
|
||||
import { Group, RawMessage, SelfInfo } from "../ntqqapi/types";
|
||||
|
||||
const fs = require('fs');
|
||||
|
||||
let running = false;
|
||||
|
||||
|
||||
// 加载插件时触发
|
||||
function onLoad(plugin: any) {
|
||||
function onLoad() {
|
||||
log("llonebot main onLoad");
|
||||
|
||||
function getConfigUtil() {
|
||||
const configFilePath = path.join(plugin.path.data, `config_${selfInfo.user_id}.json`)
|
||||
return new ConfigUtil(configFilePath)
|
||||
}
|
||||
// const config_dir = browserWindow.LiteLoader.plugins["LLOneBot"].path.data;
|
||||
|
||||
if (!fs.existsSync(plugin.path.data)) {
|
||||
fs.mkdirSync(plugin.path.data, {recursive: true});
|
||||
|
||||
if (!fs.existsSync(CONFIG_DIR)) {
|
||||
fs.mkdirSync(CONFIG_DIR, {recursive: true});
|
||||
}
|
||||
ipcMain.handle(CHANNEL_GET_CONFIG, (event: any, arg: any) => {
|
||||
return getConfigUtil().getConfig()
|
||||
})
|
||||
ipcMain.handle(CHANNEL_DOWNLOAD_FILE, async (event: any, arg: {uri: string, localFilePath: string}) => {
|
||||
let url = new URL(arg.uri);
|
||||
if (url.protocol == "base64:"){
|
||||
// base64转成文件
|
||||
let base64Data = arg.uri.split("base64://")[1]
|
||||
const buffer = Buffer.from(base64Data, 'base64');
|
||||
|
||||
fs.writeFileSync(arg.localFilePath, buffer);
|
||||
}
|
||||
else if (url.protocol == "http:" || url.protocol == "https:") {
|
||||
// 下载文件
|
||||
let res = await fetch(url)
|
||||
let blob = await res.blob();
|
||||
let buffer = await blob.arrayBuffer();
|
||||
fs.writeFileSync(arg.localFilePath, Buffer.from(buffer));
|
||||
}
|
||||
// todo: 需要识别gif格式
|
||||
return arg.localFilePath;
|
||||
})
|
||||
ipcMain.on(CHANNEL_SET_CONFIG, (event: any, arg: Config) => {
|
||||
getConfigUtil().setConfig(arg)
|
||||
})
|
||||
|
||||
ipcMain.on(CHANNEL_START_HTTP_SERVER, (event: any, arg: any) => {
|
||||
startExpress(getConfigUtil().getConfig().port)
|
||||
})
|
||||
|
||||
ipcMain.on(CHANNEL_UPDATE_GROUPS, (event: any, arg: Group[]) => {
|
||||
for (const group of arg) {
|
||||
let existGroup = groups.find(g => g.uid == group.uid)
|
||||
if (existGroup) {
|
||||
if (!existGroup.members) {
|
||||
existGroup.members = []
|
||||
}
|
||||
existGroup.name = group.name
|
||||
for (const member of group.members || []) {
|
||||
let existMember = existGroup.members?.find(m => m.uin == member.uin)
|
||||
if (existMember) {
|
||||
existMember.nick = member.nick
|
||||
existMember.cardName = member.cardName
|
||||
} else {
|
||||
existGroup.members?.push(member)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
groups.push(group)
|
||||
}
|
||||
}
|
||||
groups.length = 0
|
||||
groups.push(...arg)
|
||||
})
|
||||
|
||||
ipcMain.on(CHANNEL_UPDATE_FRIENDS, (event: any, arg: User[]) => {
|
||||
friends.length = 0
|
||||
friends.push(...arg)
|
||||
})
|
||||
|
||||
ipcMain.on(CHANNEL_POST_ONEBOT_DATA, (event: any, arg: any) => {
|
||||
for(const host of getConfigUtil().getConfig().hosts) {
|
||||
try {
|
||||
fetch(host, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-self-id": selfInfo.user_id
|
||||
},
|
||||
body: JSON.stringify(arg)
|
||||
}).then((res: any) => {
|
||||
log("新消息事件上传");
|
||||
}, (err: any) => {
|
||||
log("新消息事件上传失败:" + err + JSON.stringify(arg));
|
||||
});
|
||||
} catch (e: any) {
|
||||
log(e.toString())
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.on(CHANNEL_LOG, (event: any, arg: any) => {
|
||||
log(arg)
|
||||
})
|
||||
|
||||
ipcMain.handle(CHANNEL_SET_SELF_INFO, (event: any, arg: SelfInfo) => {
|
||||
selfInfo.user_id = arg.user_id;
|
||||
selfInfo.nickname = arg.nickname;
|
||||
})
|
||||
|
||||
ipcMain.on(CHANNEL_DELETE_FILE, (event: any, arg: string[]) => {
|
||||
for (const path of arg) {
|
||||
fs.unlinkSync(path);
|
||||
function postRawMsg(msgList: RawMessage[]) {
|
||||
const {debug, reportSelfMessage} = getConfigUtil().getConfig();
|
||||
for (let message of msgList) {
|
||||
message.msgShortId = msgHistory[message.msgId]?.msgShortId
|
||||
if (!message.msgShortId) {
|
||||
addHistoryMsg(message)
|
||||
}
|
||||
OB11Constructor.message(message).then((msg) => {
|
||||
if (debug) {
|
||||
msg.raw = message;
|
||||
}
|
||||
if (msg.user_id == selfInfo.uin && !reportSelfMessage) {
|
||||
return
|
||||
}
|
||||
postMsg(msg);
|
||||
// log("post msg", msg)
|
||||
}).catch(e => log("constructMessage error: ", e.toString()));
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
function start() {
|
||||
log("llonebot start")
|
||||
registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.NEW_MSG, (payload) => {
|
||||
try {
|
||||
// log("received msg length", payload.msgList.length);
|
||||
postRawMsg(payload.msgList);
|
||||
} catch (e) {
|
||||
log("report message error: ", e.toString())
|
||||
}
|
||||
})
|
||||
|
||||
registerReceiveHook<{ msgRecord: RawMessage }>(ReceiveCmd.SELF_SEND_MSG, (payload) => {
|
||||
const {reportSelfMessage} = getConfigUtil().getConfig()
|
||||
if (!reportSelfMessage) {
|
||||
return
|
||||
}
|
||||
// log("reportSelfMessage", payload)
|
||||
try {
|
||||
postRawMsg([payload.msgRecord]);
|
||||
} catch (e) {
|
||||
log("report self message error: ", e.toString())
|
||||
}
|
||||
})
|
||||
NTQQApi.getGroups(true).then()
|
||||
startExpress(getConfigUtil().getConfig().port)
|
||||
}
|
||||
|
||||
const init = async () => {
|
||||
try {
|
||||
const _ = await NTQQApi.getSelfInfo()
|
||||
Object.assign(selfInfo, _)
|
||||
selfInfo.nick = selfInfo.uin
|
||||
log("get self simple info", _)
|
||||
} catch (e) {
|
||||
log("retry get self info")
|
||||
}
|
||||
if (selfInfo.uin) {
|
||||
try {
|
||||
const userInfo = (await NTQQApi.getUserInfo(selfInfo.uid))
|
||||
log("self info", userInfo);
|
||||
if (userInfo) {
|
||||
selfInfo.nick = userInfo.nick
|
||||
} else {
|
||||
return setTimeout(init, 1000)
|
||||
}
|
||||
} catch (e) {
|
||||
log("get self nickname failed", e.toString())
|
||||
return setTimeout(init, 1000)
|
||||
}
|
||||
start();
|
||||
}
|
||||
else{
|
||||
setTimeout(init, 1000)
|
||||
}
|
||||
}
|
||||
setTimeout(init, 1000)
|
||||
}
|
||||
|
||||
|
||||
// 创建窗口时触发
|
||||
function onBrowserWindowCreated(window: any, plugin: any) {
|
||||
|
||||
function onBrowserWindowCreated(window: BrowserWindow) {
|
||||
try {
|
||||
hookNTQQApiReceive(window);
|
||||
} catch (e) {
|
||||
log("llonebot hook error: ", e.toString())
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
onLoad();
|
||||
} catch (e: any) {
|
||||
console.log(e.toString())
|
||||
}
|
||||
|
||||
// 这两个函数都是可选的
|
||||
export {
|
||||
onLoad, onBrowserWindowCreated
|
||||
onBrowserWindowCreated
|
||||
}
|
@@ -1,8 +0,0 @@
|
||||
const fs = require('fs');
|
||||
|
||||
export function log(msg: any) {
|
||||
let currentDateTime = new Date().toLocaleString();
|
||||
fs.appendFile("./llonebot.log", currentDateTime + ":" + msg + "\n", (err: any) => {
|
||||
|
||||
})
|
||||
}
|
97
src/ntqqapi/constructor.ts
Normal file
97
src/ntqqapi/constructor.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import {ElementType, SendPicElement, SendPttElement, SendReplyElement, SendTextElement, AtType} from "./types";
|
||||
import {NTQQApi} from "./ntcall";
|
||||
|
||||
|
||||
export class SendMsgElementConstructor {
|
||||
static text(content: string): SendTextElement {
|
||||
return {
|
||||
elementType: ElementType.TEXT,
|
||||
elementId: "",
|
||||
textElement: {
|
||||
content,
|
||||
atType: AtType.notAt,
|
||||
atUid: "",
|
||||
atTinyId: "",
|
||||
atNtUid: "",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
static at(atUid: string, atNtUid: string, atType: AtType, atName: string): SendTextElement {
|
||||
return {
|
||||
elementType: ElementType.TEXT,
|
||||
elementId: "",
|
||||
textElement: {
|
||||
content: `@${atName}`,
|
||||
atType,
|
||||
atUid,
|
||||
atTinyId: "",
|
||||
atNtUid,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
static reply(msgSeq: string, msgId: string, senderUin: string, senderUinStr: string): SendReplyElement {
|
||||
return {
|
||||
elementType: ElementType.REPLY,
|
||||
elementId: "",
|
||||
replyElement: {
|
||||
replayMsgSeq: msgSeq, // raw.msgSeq
|
||||
replayMsgId: msgId, // raw.msgId
|
||||
senderUin: senderUin,
|
||||
senderUinStr: senderUinStr,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async pic(picPath: string): Promise<SendPicElement>{
|
||||
const {md5, fileName, path, fileSize} = await NTQQApi.uploadFile(picPath);
|
||||
const imageSize = await NTQQApi.getImageSize(picPath);
|
||||
const picElement = {
|
||||
md5HexStr: md5,
|
||||
fileSize: fileSize,
|
||||
picWidth: imageSize.width,
|
||||
picHeight: imageSize.height,
|
||||
fileName: fileName,
|
||||
sourcePath: path,
|
||||
original: true,
|
||||
picType: 1001,
|
||||
picSubType: 0,
|
||||
fileUuid: "",
|
||||
fileSubId: "",
|
||||
thumbFileSize: 0,
|
||||
summary: "",
|
||||
};
|
||||
|
||||
return {
|
||||
elementType: ElementType.PIC,
|
||||
elementId: "",
|
||||
picElement
|
||||
};
|
||||
}
|
||||
|
||||
static async ptt(pttPath: string):Promise<SendPttElement> {
|
||||
const {md5, fileName, path, fileSize} = await NTQQApi.uploadFile(pttPath);
|
||||
return {
|
||||
elementType: ElementType.PTT,
|
||||
elementId: "",
|
||||
pttElement: {
|
||||
fileName: fileName,
|
||||
filePath: path,
|
||||
md5HexStr: md5,
|
||||
fileSize: fileSize,
|
||||
duration: Math.max(1, Math.round(fileSize / 1024 / 3)), // 一秒钟大概是3kb大小, 小于1秒的按1秒算
|
||||
formatType: 1,
|
||||
voiceType: 1,
|
||||
voiceChangeType: 0,
|
||||
canConvert2Text: true,
|
||||
waveAmplitudes: [
|
||||
0, 18, 9, 23, 16, 17, 16, 15, 44, 17, 24, 20, 14, 15, 17,
|
||||
],
|
||||
fileSubId: "",
|
||||
playState: 1,
|
||||
autoConvertText: 0,
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
161
src/ntqqapi/hook.ts
Normal file
161
src/ntqqapi/hook.ts
Normal file
@@ -0,0 +1,161 @@
|
||||
import { BrowserWindow } from 'electron';
|
||||
import { getConfigUtil, log } from "../common/utils";
|
||||
import { NTQQApi, NTQQApiClass, sendMessagePool } from "./ntcall";
|
||||
import { Group, User } from "./types";
|
||||
import { RawMessage } from "./types";
|
||||
import { addHistoryMsg, friends, groups, msgHistory } from "../common/data";
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
export let hookApiCallbacks: Record<string, (apiReturn: any) => void> = {}
|
||||
|
||||
export enum ReceiveCmd {
|
||||
UPDATE_MSG = "nodeIKernelMsgListener/onMsgInfoListUpdate",
|
||||
NEW_MSG = "nodeIKernelMsgListener/onRecvMsg",
|
||||
SELF_SEND_MSG = "nodeIKernelMsgListener/onAddSendMsg",
|
||||
USER_INFO = "nodeIKernelProfileListener/onProfileSimpleChanged",
|
||||
GROUPS = "nodeIKernelGroupListener/onGroupListUpdate",
|
||||
GROUPS_UNIX = "onGroupListUpdate",
|
||||
FRIENDS = "onBuddyListChange"
|
||||
}
|
||||
|
||||
interface NTQQApiReturnData<PayloadType = unknown> extends Array<any> {
|
||||
0: {
|
||||
"type": "request",
|
||||
"eventName": NTQQApiClass,
|
||||
"callbackId"?: string
|
||||
},
|
||||
1:
|
||||
{
|
||||
cmdName: ReceiveCmd,
|
||||
cmdType: "event",
|
||||
payload: PayloadType
|
||||
}[]
|
||||
}
|
||||
|
||||
let receiveHooks: Array<{
|
||||
method: ReceiveCmd,
|
||||
hookFunc: (payload: any) => void,
|
||||
id: string
|
||||
}> = []
|
||||
|
||||
export function hookNTQQApiReceive(window: BrowserWindow) {
|
||||
const originalSend = window.webContents.send;
|
||||
const patchSend = (channel: string, ...args: NTQQApiReturnData) => {
|
||||
// log(`received ntqq api message: ${channel}`, JSON.stringify(args))
|
||||
if (args?.[1] instanceof Array) {
|
||||
for (let receiveData of args?.[1]) {
|
||||
const ntQQApiMethodName = receiveData.cmdName;
|
||||
// log(`received ntqq api message: ${channel} ${ntQQApiMethodName}`, JSON.stringify(receiveData))
|
||||
for (let hook of receiveHooks) {
|
||||
if (hook.method === ntQQApiMethodName) {
|
||||
new Promise((resolve, reject) => {
|
||||
try {
|
||||
hook.hookFunc(receiveData.payload);
|
||||
} catch (e) {
|
||||
log("hook error", e, receiveData.payload)
|
||||
}
|
||||
}).then()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (args[0]?.callbackId) {
|
||||
// log("hookApiCallback", hookApiCallbacks, args)
|
||||
const callbackId = args[0].callbackId;
|
||||
if (hookApiCallbacks[callbackId]) {
|
||||
// log("callback found")
|
||||
new Promise((resolve, reject) => {
|
||||
hookApiCallbacks[callbackId](args[1]);
|
||||
}).then()
|
||||
delete hookApiCallbacks[callbackId];
|
||||
}
|
||||
}
|
||||
return originalSend.call(window.webContents, channel, ...args);
|
||||
}
|
||||
window.webContents.send = patchSend;
|
||||
}
|
||||
|
||||
export function registerReceiveHook<PayloadType>(method: ReceiveCmd, hookFunc: (payload: PayloadType) => void): string {
|
||||
const id = uuidv4()
|
||||
receiveHooks.push({
|
||||
method,
|
||||
hookFunc,
|
||||
id
|
||||
})
|
||||
return id;
|
||||
}
|
||||
|
||||
export function removeReceiveHook(id: string) {
|
||||
const index = receiveHooks.findIndex(h => h.id === id)
|
||||
receiveHooks.splice(index, 1);
|
||||
}
|
||||
|
||||
async function updateGroups(_groups: Group[]) {
|
||||
for (let group of _groups) {
|
||||
let existGroup = groups.find(g => g.groupCode == group.groupCode)
|
||||
if (!existGroup) {
|
||||
NTQQApi.getGroupMembers(group.groupCode).then(members => {
|
||||
if (members) {
|
||||
group.members = members
|
||||
}
|
||||
})
|
||||
groups.push(group)
|
||||
log("update group members", group.members)
|
||||
} else {
|
||||
Object.assign(existGroup, group)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registerReceiveHook<{ groupList: Group[] }>(ReceiveCmd.GROUPS, (payload) => updateGroups(payload.groupList).then())
|
||||
registerReceiveHook<{ groupList: Group[] }>(ReceiveCmd.GROUPS_UNIX, (payload) => updateGroups(payload.groupList).then())
|
||||
registerReceiveHook<{
|
||||
data: { categoryId: number, categroyName: string, categroyMbCount: number, buddyList: User[] }[]
|
||||
}>(ReceiveCmd.FRIENDS, payload => {
|
||||
for (const fData of payload.data) {
|
||||
const _friends = fData.buddyList;
|
||||
for (let friend of _friends) {
|
||||
let existFriend = friends.find(f => f.uin == friend.uin)
|
||||
if (!existFriend) {
|
||||
friends.push(friend)
|
||||
} else {
|
||||
Object.assign(existFriend, friend)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// registerReceiveHook<any>(ReceiveCmd.USER_INFO, (payload)=>{
|
||||
// log("user info", payload);
|
||||
// })
|
||||
|
||||
registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.UPDATE_MSG, (payload) => {
|
||||
for (const message of payload.msgList) {
|
||||
addHistoryMsg(message)
|
||||
}
|
||||
})
|
||||
|
||||
registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.NEW_MSG, (payload) => {
|
||||
for (const message of payload.msgList) {
|
||||
// log("收到新消息,push到历史记录", message)
|
||||
addHistoryMsg(message)
|
||||
}
|
||||
const msgIds = Object.keys(msgHistory);
|
||||
if (msgIds.length > 30000) {
|
||||
delete msgHistory[msgIds.sort()[0]]
|
||||
}
|
||||
})
|
||||
|
||||
registerReceiveHook<{ msgRecord: RawMessage }>(ReceiveCmd.SELF_SEND_MSG, ({msgRecord}) => {
|
||||
const message = msgRecord;
|
||||
const peerUid = message.peerUid;
|
||||
// log("收到自己发送成功的消息", Object.keys(sendMessagePool), message);
|
||||
const sendCallback = sendMessagePool[peerUid];
|
||||
if (sendCallback) {
|
||||
try {
|
||||
sendCallback(message);
|
||||
} catch (e) {
|
||||
log("receive self msg error", e.stack)
|
||||
}
|
||||
}
|
||||
})
|
339
src/ntqqapi/ntcall.ts
Normal file
339
src/ntqqapi/ntcall.ts
Normal file
@@ -0,0 +1,339 @@
|
||||
import { ipcMain } from "electron";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { ReceiveCmd, hookApiCallbacks, registerReceiveHook, removeReceiveHook } from "./hook";
|
||||
import { log } from "../common/utils";
|
||||
import { ChatType, Friend, PicElement, SelfInfo, User } from "./types";
|
||||
import { Group } from "./types";
|
||||
import { GroupMember } from "./types";
|
||||
import { RawMessage } from "./types";
|
||||
import { SendMessageElement } from "./types";
|
||||
import * as fs from "fs";
|
||||
|
||||
interface IPCReceiveEvent {
|
||||
eventName: string
|
||||
callbackId: string
|
||||
}
|
||||
|
||||
export type IPCReceiveDetail = [
|
||||
{
|
||||
cmdName: NTQQApiMethod
|
||||
payload: unknown
|
||||
},
|
||||
]
|
||||
|
||||
export enum NTQQApiClass {
|
||||
NT_API = "ns-ntApi",
|
||||
FS_API = "ns-FsApi",
|
||||
GLOBAL_DATA = "ns-GlobalDataApi"
|
||||
}
|
||||
|
||||
export enum NTQQApiMethod {
|
||||
LIKE_FRIEND = "nodeIKernelProfileLikeService/setBuddyProfileLike",
|
||||
UPDATE_MSG = "nodeIKernelMsgListener/onMsgInfoListUpdate",
|
||||
SELF_INFO = "fetchAuthData",
|
||||
FRIENDS = "nodeIKernelBuddyService/getBuddyList",
|
||||
GROUPS = "nodeIKernelGroupService/getGroupList",
|
||||
GROUP_MEMBER_SCENE = "nodeIKernelGroupService/createMemberListScene",
|
||||
GROUP_MEMBERS = "nodeIKernelGroupService/getNextMemberList",
|
||||
USER_INFO = "nodeIKernelProfileService/getUserSimpleInfo",
|
||||
FILE_TYPE = "getFileType",
|
||||
FILE_MD5 = "getFileMd5",
|
||||
FILE_COPY = "copyFile",
|
||||
IMAGE_SIZE = "getImageSizeFromPath",
|
||||
FILE_SIZE = "getFileSize",
|
||||
MEDIA_FILE_PATH = "nodeIKernelMsgService/getRichMediaFilePathForGuild",
|
||||
RECALL_MSG = "nodeIKernelMsgService/recallMsg",
|
||||
SEND_MSG = "nodeIKernelMsgService/sendMsg",
|
||||
DOWNLOAD_MEDIA = "nodeIKernelMsgService/downloadRichMedia"
|
||||
}
|
||||
|
||||
enum NTQQApiChannel {
|
||||
IPC_UP_2 = "IPC_UP_2",
|
||||
IPC_UP_3 = "IPC_UP_3",
|
||||
IPC_UP_1 = "IPC_UP_1",
|
||||
}
|
||||
|
||||
export interface Peer {
|
||||
chatType: ChatType
|
||||
peerUid: string // 如果是群聊uid为群号,私聊uid就是加密的字符串
|
||||
guildId?: ""
|
||||
}
|
||||
|
||||
enum CallBackType {
|
||||
UUID,
|
||||
METHOD
|
||||
}
|
||||
|
||||
|
||||
function callNTQQApi<ReturnType>(channel: NTQQApiChannel, className: NTQQApiClass, methodName: NTQQApiMethod, args: unknown[] = [], cbCmd: ReceiveCmd | null = null, timeout = 5) {
|
||||
const uuid = uuidv4();
|
||||
// log("callNTQQApi", channel, className, methodName, args, uuid)
|
||||
return new Promise((resolve: (data: ReturnType) => void, reject) => {
|
||||
// log("callNTQQApiPromise", channel, className, methodName, args, uuid)
|
||||
const _timeout = timeout * 1000
|
||||
let success = false
|
||||
if (!cbCmd) {
|
||||
// QQ后端会返回结果,并且可以插根据uuid识别
|
||||
hookApiCallbacks[uuid] = (r: ReturnType) => {
|
||||
success = true
|
||||
resolve(r)
|
||||
};
|
||||
} else {
|
||||
// 这里的callback比较特殊,QQ后端先返回是否调用成功,再返回一条结果数据
|
||||
hookApiCallbacks[uuid] = (result: GeneralCallResult) => {
|
||||
log(`${methodName} callback`, result)
|
||||
if (result.result == 0) {
|
||||
const hookId = registerReceiveHook<ReturnType>(cbCmd, (payload) => {
|
||||
log(methodName, "second callback", cbCmd, payload);
|
||||
removeReceiveHook(hookId);
|
||||
success = true
|
||||
resolve(payload);
|
||||
})
|
||||
} else {
|
||||
success = true
|
||||
reject(`ntqq api call failed, ${result.errMsg}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
setTimeout(() => {
|
||||
// log("ntqq api timeout", success, channel, className, methodName)
|
||||
if (!success) {
|
||||
log(`ntqq api timeout ${channel}, ${className}, ${methodName}`)
|
||||
reject(`ntqq api timeout ${channel}, ${className}, ${methodName}`)
|
||||
}
|
||||
}, _timeout)
|
||||
|
||||
ipcMain.emit(
|
||||
channel,
|
||||
{},
|
||||
{type: 'request', callbackId: uuid, eventName: className + "-" + channel[channel.length - 1]},
|
||||
[methodName, ...args],
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
export let sendMessagePool: Record<string, ((sendSuccessMsg: RawMessage) => void) | null> = {}// peerUid: callbackFunnc
|
||||
|
||||
interface GeneralCallResult {
|
||||
result: number, // 0: success
|
||||
errMsg: string
|
||||
}
|
||||
|
||||
|
||||
export class NTQQApi {
|
||||
// static likeFriend = defineNTQQApi<void>(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.LIKE_FRIEND)
|
||||
static likeFriend(uid: string, count = 1) {
|
||||
return callNTQQApi(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.LIKE_FRIEND, [{
|
||||
doLikeUserInfo: {
|
||||
friendUid: uid,
|
||||
sourceId: 71,
|
||||
doLikeCount: count,
|
||||
doLikeTollCount: 0
|
||||
}
|
||||
},
|
||||
null])
|
||||
}
|
||||
|
||||
static getSelfInfo() {
|
||||
return callNTQQApi<SelfInfo>(NTQQApiChannel.IPC_UP_2, NTQQApiClass.GLOBAL_DATA, NTQQApiMethod.SELF_INFO, [], null, 2)
|
||||
|
||||
}
|
||||
|
||||
static async getUserInfo(uid: string) {
|
||||
const result = await callNTQQApi<{
|
||||
profiles: Map<string, User>
|
||||
}>(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.USER_INFO,
|
||||
[{force: true, uids: [uid]}, undefined], ReceiveCmd.USER_INFO)
|
||||
return result.profiles.get(uid)
|
||||
}
|
||||
|
||||
static async getFriends(forced = false) {
|
||||
const data = await callNTQQApi<{
|
||||
data: { categoryId: number, categroyName: string, categroyMbCount: number, buddyList: Friend[] }[]
|
||||
}>(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.FRIENDS, [{force_update: forced}, undefined], ReceiveCmd.FRIENDS)
|
||||
let _friends: Friend[] = [];
|
||||
for (const fData of data.data) {
|
||||
_friends.push(...fData.buddyList)
|
||||
}
|
||||
return _friends
|
||||
}
|
||||
|
||||
static async getGroups(forced = false) {
|
||||
let cbCmd = ReceiveCmd.GROUPS
|
||||
if (process.platform != "win32") {
|
||||
cbCmd = ReceiveCmd.GROUPS_UNIX
|
||||
}
|
||||
const result = await callNTQQApi<{
|
||||
updateType: number,
|
||||
groupList: Group[]
|
||||
}>(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.GROUPS, [{force_update: forced}, undefined], cbCmd)
|
||||
return result.groupList
|
||||
}
|
||||
|
||||
static async getGroupMembers(groupQQ: string, num = 3000) {
|
||||
const sceneId = await callNTQQApi(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.GROUP_MEMBER_SCENE, [{
|
||||
groupCode: groupQQ,
|
||||
scene: "groupMemberList_MainWindow"
|
||||
}])
|
||||
// log("get group member sceneId", sceneId);
|
||||
try {
|
||||
const result = await callNTQQApi<{
|
||||
result: { infos: any }
|
||||
}>(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.GROUP_MEMBERS,
|
||||
[{
|
||||
sceneId: sceneId,
|
||||
num: num
|
||||
},
|
||||
null
|
||||
])
|
||||
// log("members info", typeof result.result.infos, Object.keys(result.result.infos))
|
||||
let values = result.result.infos.values()
|
||||
|
||||
values = Array.from(values) as GroupMember[]
|
||||
// log("members info", values);
|
||||
return values
|
||||
} catch (e) {
|
||||
log(`get group ${groupQQ} members failed`, e)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static getFileType(filePath: string) {
|
||||
return callNTQQApi<{
|
||||
ext: string
|
||||
}>(NTQQApiChannel.IPC_UP_2, NTQQApiClass.FS_API, NTQQApiMethod.FILE_TYPE, [filePath])
|
||||
}
|
||||
|
||||
static getFileMd5(filePath: string) {
|
||||
return callNTQQApi<string>(NTQQApiChannel.IPC_UP_2, NTQQApiClass.FS_API, NTQQApiMethod.FILE_MD5, [filePath])
|
||||
}
|
||||
|
||||
static copyFile(filePath: string, destPath: string) {
|
||||
return callNTQQApi<string>(NTQQApiChannel.IPC_UP_2, NTQQApiClass.FS_API, NTQQApiMethod.FILE_COPY, [{
|
||||
fromPath: filePath,
|
||||
toPath: destPath
|
||||
}])
|
||||
}
|
||||
|
||||
static getImageSize(filePath: string) {
|
||||
return callNTQQApi<{
|
||||
width: number,
|
||||
height: number
|
||||
}>(NTQQApiChannel.IPC_UP_2, NTQQApiClass.FS_API, NTQQApiMethod.IMAGE_SIZE, [filePath])
|
||||
}
|
||||
|
||||
static getFileSize(filePath: string) {
|
||||
return callNTQQApi<number>(NTQQApiChannel.IPC_UP_2, NTQQApiClass.FS_API, NTQQApiMethod.FILE_SIZE, [filePath])
|
||||
}
|
||||
|
||||
// 上传文件到QQ的文件夹
|
||||
static async uploadFile(filePath: string) {
|
||||
const md5 = await NTQQApi.getFileMd5(filePath);
|
||||
let ext = (await NTQQApi.getFileType(filePath))?.ext
|
||||
if (ext) {
|
||||
ext = "." + ext
|
||||
}
|
||||
else{
|
||||
ext = ""
|
||||
}
|
||||
const fileName = `${md5}${ext}`;
|
||||
const mediaPath = await callNTQQApi<string>(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.MEDIA_FILE_PATH, [{
|
||||
path_info: {
|
||||
md5HexStr: md5,
|
||||
fileName: fileName,
|
||||
elementType: 2,
|
||||
elementSubType: 0,
|
||||
thumbSize: 0,
|
||||
needCreate: true,
|
||||
downloadType: 1,
|
||||
file_uuid: ""
|
||||
}
|
||||
}])
|
||||
log("media path", mediaPath)
|
||||
await NTQQApi.copyFile(filePath, mediaPath);
|
||||
const fileSize = await NTQQApi.getFileSize(filePath);
|
||||
return {
|
||||
md5,
|
||||
fileName,
|
||||
path: mediaPath,
|
||||
fileSize
|
||||
}
|
||||
}
|
||||
|
||||
static async downloadMedia(msgId: string, chatType: ChatType, peerUid: string, elementId: string, thumbPath: string, sourcePath: string) {
|
||||
// 用于下载收到的消息中的图片等
|
||||
if (fs.existsSync(sourcePath)) {
|
||||
return sourcePath
|
||||
}
|
||||
const apiParams = [
|
||||
{
|
||||
getReq: {
|
||||
msgId: msgId,
|
||||
chatType: chatType,
|
||||
peerUid: peerUid,
|
||||
elementId: elementId,
|
||||
thumbSize: 0,
|
||||
downloadType: 1,
|
||||
filePath: thumbPath,
|
||||
},
|
||||
},
|
||||
undefined,
|
||||
]
|
||||
await callNTQQApi(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.DOWNLOAD_MEDIA, apiParams)
|
||||
return sourcePath
|
||||
}
|
||||
|
||||
static recallMsg(peer: Peer, msgIds: string[]) {
|
||||
return callNTQQApi(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.RECALL_MSG, [{
|
||||
peer,
|
||||
msgIds
|
||||
}, null])
|
||||
}
|
||||
|
||||
static sendMsg(peer: Peer, msgElements: SendMessageElement[]) {
|
||||
const sendTimeout = 10 * 1000
|
||||
|
||||
return new Promise<RawMessage>((resolve, reject) => {
|
||||
const peerUid = peer.peerUid;
|
||||
let usingTime = 0;
|
||||
let success = false;
|
||||
|
||||
const checkSuccess = () => {
|
||||
if (!success) {
|
||||
sendMessagePool[peerUid] = null;
|
||||
reject("发送超时")
|
||||
}
|
||||
}
|
||||
setTimeout(checkSuccess, sendTimeout);
|
||||
|
||||
const checkLastSend = () => {
|
||||
let lastSending = sendMessagePool[peerUid]
|
||||
if (sendTimeout < usingTime) {
|
||||
sendMessagePool[peerUid] = null;
|
||||
reject("发送超时")
|
||||
}
|
||||
if (!!lastSending) {
|
||||
// log("有正在发送的消息,等待中...")
|
||||
usingTime += 100;
|
||||
setTimeout(checkLastSend, 100);
|
||||
} else {
|
||||
log("可以进行发送消息,设置发送成功回调", sendMessagePool)
|
||||
sendMessagePool[peerUid] = (rawMessage: RawMessage) => {
|
||||
success = true;
|
||||
sendMessagePool[peerUid] = null;
|
||||
resolve(rawMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
checkLastSend()
|
||||
callNTQQApi(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.SEND_MSG, [{
|
||||
msgId: "0",
|
||||
peer, msgElements,
|
||||
msgAttributeInfos: new Map(),
|
||||
}, null]).then()
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
}
|
224
src/ntqqapi/types.ts
Normal file
224
src/ntqqapi/types.ts
Normal file
@@ -0,0 +1,224 @@
|
||||
export interface User {
|
||||
uid: string; // 加密的字符串
|
||||
uin: string; // QQ号
|
||||
nick: string;
|
||||
avatarUrl?: string;
|
||||
longNick?: string; // 签名
|
||||
remark?: string
|
||||
}
|
||||
|
||||
export interface SelfInfo extends User{
|
||||
|
||||
}
|
||||
|
||||
export interface Friend extends User{}
|
||||
|
||||
export interface Group{
|
||||
groupCode: string,
|
||||
maxMember: number,
|
||||
memberCount: number,
|
||||
groupName: string,
|
||||
groupStatus: 0,
|
||||
memberRole: 2,
|
||||
isTop: boolean,
|
||||
toppedTimestamp: "0",
|
||||
privilegeFlag: number, //65760
|
||||
isConf: boolean,
|
||||
hasModifyConfGroupFace: boolean,
|
||||
hasModifyConfGroupName: boolean,
|
||||
remarkName: string,
|
||||
hasMemo: boolean,
|
||||
groupShutupExpireTime: string, //"0",
|
||||
personShutupExpireTime: string, //"0",
|
||||
discussToGroupUin: string, //"0",
|
||||
discussToGroupMaxMsgSeq: number,
|
||||
discussToGroupTime: number,
|
||||
groupFlagExt: number, //1073938496,
|
||||
authGroupType: number, //0,
|
||||
groupCreditLevel: number, //0,
|
||||
groupFlagExt3: number, //0,
|
||||
groupOwnerId: {
|
||||
"memberUin": string, //"0",
|
||||
"memberUid": string, //"u_fbf8N7aeuZEnUiJAbQ9R8Q"
|
||||
},
|
||||
members: GroupMember[] // 原始数据是没有这个的,为了方便自己加了这个字段
|
||||
}
|
||||
|
||||
export interface GroupMember {
|
||||
avatarPath: string;
|
||||
cardName: string;
|
||||
cardType: number;
|
||||
isDelete: boolean;
|
||||
nick: string;
|
||||
qid: string;
|
||||
remark: string;
|
||||
role: number; // 群主:4, 管理员:3,群员:2
|
||||
shutUpTime: number; // 禁言时间,单位是什么暂时不清楚
|
||||
uid: string; // 加密的字符串
|
||||
uin: string; // QQ号
|
||||
}
|
||||
|
||||
export enum ElementType {
|
||||
TEXT = 1,
|
||||
PIC = 2,
|
||||
PTT = 4,
|
||||
REPLY = 7,
|
||||
}
|
||||
|
||||
export interface SendTextElement {
|
||||
elementType: ElementType.TEXT,
|
||||
elementId: "",
|
||||
textElement: {
|
||||
content: string,
|
||||
atType: number,
|
||||
atUid: string,
|
||||
atTinyId: string,
|
||||
atNtUid: string,
|
||||
}
|
||||
}
|
||||
export interface SendPttElement {
|
||||
elementType: ElementType.PTT,
|
||||
elementId: "",
|
||||
pttElement: {
|
||||
fileName: string,
|
||||
filePath: string,
|
||||
md5HexStr: string,
|
||||
fileSize: number,
|
||||
duration: number,
|
||||
formatType: number,
|
||||
voiceType: number,
|
||||
voiceChangeType: number,
|
||||
canConvert2Text: boolean,
|
||||
waveAmplitudes: number[],
|
||||
fileSubId: "",
|
||||
playState: number,
|
||||
autoConvertText: number,
|
||||
}
|
||||
}
|
||||
|
||||
export interface SendPicElement {
|
||||
elementType: ElementType.PIC,
|
||||
elementId: "",
|
||||
picElement: {
|
||||
md5HexStr: string,
|
||||
fileSize: number,
|
||||
picWidth: number,
|
||||
picHeight: number,
|
||||
fileName: string,
|
||||
sourcePath: string,
|
||||
original: boolean,
|
||||
picType: number,
|
||||
picSubType: number,
|
||||
fileUuid: string,
|
||||
fileSubId: string,
|
||||
thumbFileSize: number,
|
||||
summary: string,
|
||||
}
|
||||
}
|
||||
|
||||
export interface SendReplyElement {
|
||||
elementType: ElementType.REPLY,
|
||||
elementId: "",
|
||||
replyElement: {
|
||||
replayMsgSeq: string,
|
||||
replayMsgId: string,
|
||||
senderUin: string,
|
||||
senderUinStr: string,
|
||||
}
|
||||
}
|
||||
|
||||
export type SendMessageElement = SendTextElement | SendPttElement | SendPicElement | SendReplyElement
|
||||
|
||||
export enum AtType {
|
||||
notAt = 0,
|
||||
atAll = 1,
|
||||
atUser = 2
|
||||
}
|
||||
|
||||
export enum ChatType {
|
||||
friend = 1,
|
||||
group = 2,
|
||||
temp = 100
|
||||
}
|
||||
export interface PttElement {
|
||||
canConvert2Text: boolean;
|
||||
duration: number; // 秒数
|
||||
fileBizId: null;
|
||||
fileId: number; // 0
|
||||
fileName: string; // "e4d09c784d5a2abcb2f9980bdc7acfe6.amr"
|
||||
filePath: string; // "/Users//Library/Containers/com.tencent.qq/Data/Library/Application Support/QQ/nt_qq_a6b15c9820595d25a56c1633ce19ad40/nt_data/Ptt/2023-11/Ori/e4d09c784d5a2abcb2f9980bdc7acfe6.amr"
|
||||
fileSize: string; // "4261"
|
||||
fileSubId: string; // "0"
|
||||
fileUuid: string; // "90j3z7rmRphDPrdVgP9udFBaYar#oK0TWZIV"
|
||||
formatType: string; // 1
|
||||
invalidState: number; // 0
|
||||
md5HexStr: string; // "e4d09c784d5a2abcb2f9980bdc7acfe6"
|
||||
playState: number; // 0
|
||||
progress: number; // 0
|
||||
text: string; // ""
|
||||
transferStatus: number; // 0
|
||||
translateStatus: number; // 0
|
||||
voiceChangeType: number; // 0
|
||||
voiceType: number; // 0
|
||||
waveAmplitudes: number[];
|
||||
}
|
||||
|
||||
export interface ArkElement {
|
||||
bytesData: string;
|
||||
}
|
||||
|
||||
export const IMAGE_HTTP_HOST = "https://gchat.qpic.cn"
|
||||
|
||||
export interface PicElement {
|
||||
originImageUrl: string; // http url, 没有host,host是https://gchat.qpic.cn/
|
||||
sourcePath: string; // 图片本地路径
|
||||
thumbPath: Map<number, string>;
|
||||
picWidth: number;
|
||||
picHeight: number;
|
||||
fileSize: number;
|
||||
fileName: string;
|
||||
fileUuid: string;
|
||||
}
|
||||
|
||||
export interface RawMessage {
|
||||
msgId: string;
|
||||
msgShortId?: number; // 自己维护的消息id
|
||||
msgTime: string;
|
||||
msgSeq: string;
|
||||
senderUin: string; // 发送者QQ号
|
||||
peerUid: string; // 群号 或者 QQ uid
|
||||
peerUin: string; // 群号 或者 发送者QQ号
|
||||
sendNickName: string;
|
||||
sendMemberName?: string; // 发送者群名片
|
||||
chatType: ChatType;
|
||||
elements: {
|
||||
elementId: string,
|
||||
replyElement: {
|
||||
senderUid: string; // 原消息发送者QQ号
|
||||
sourceMsgIsIncPic: boolean; // 原消息是否有图片
|
||||
sourceMsgText: string;
|
||||
replayMsgSeq: string; // 源消息的msgSeq,可以通过这个找到源消息的msgId
|
||||
};
|
||||
textElement: {
|
||||
atType: AtType;
|
||||
atUid: string; // QQ号
|
||||
content: string;
|
||||
atNtUid: string; // uid号
|
||||
};
|
||||
picElement: PicElement;
|
||||
pttElement: PttElement;
|
||||
arkElement: ArkElement;
|
||||
}[];
|
||||
}
|
||||
|
||||
export interface MessageElement {
|
||||
raw: RawMessage;
|
||||
peer: any;
|
||||
sender: {
|
||||
uid: string; // 一串加密的字符串
|
||||
memberName: string;
|
||||
nickname: string;
|
||||
};
|
||||
}
|
||||
|
||||
|
31
src/onebot11/actions/BaseAction.ts
Normal file
31
src/onebot11/actions/BaseAction.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import {ActionName, BaseCheckResult} from "./types"
|
||||
import { OB11Response } from "./utils"
|
||||
import { OB11Return } from "../types";
|
||||
|
||||
class BaseAction<PayloadType, ReturnDataType> {
|
||||
actionName: ActionName
|
||||
protected async check(payload: PayloadType): Promise<BaseCheckResult> {
|
||||
return {
|
||||
valid: true,
|
||||
}
|
||||
}
|
||||
|
||||
public async handle(payload: PayloadType): Promise<OB11Return<ReturnDataType | null>> {
|
||||
const result = await this.check(payload)
|
||||
if (!result.valid) {
|
||||
return OB11Response.error(result.message)
|
||||
}
|
||||
try {
|
||||
const resData = await this._handle(payload)
|
||||
return OB11Response.ok(resData)
|
||||
}catch (e) {
|
||||
return OB11Response.error(e.toString())
|
||||
}
|
||||
}
|
||||
|
||||
protected async _handle(payload: PayloadType): Promise<ReturnDataType> {
|
||||
throw `pleas override ${this.actionName} _handle`
|
||||
}
|
||||
}
|
||||
|
||||
export default BaseAction
|
22
src/onebot11/actions/DeleteMsg.ts
Normal file
22
src/onebot11/actions/DeleteMsg.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { ActionName } from "./types";
|
||||
import BaseAction from "./BaseAction";
|
||||
import { NTQQApi } from "../../ntqqapi/ntcall";
|
||||
import { getHistoryMsgByShortId, msgHistory } from "../../common/data";
|
||||
|
||||
interface Payload {
|
||||
message_id: number
|
||||
}
|
||||
|
||||
class DeleteMsg extends BaseAction<Payload, void> {
|
||||
actionName = ActionName.DeleteMsg
|
||||
|
||||
protected async _handle(payload:Payload){
|
||||
let msg = getHistoryMsgByShortId(payload.message_id)
|
||||
await NTQQApi.recallMsg({
|
||||
chatType: msg.chatType,
|
||||
peerUid: msg.peerUid
|
||||
}, [msg.msgId])
|
||||
}
|
||||
}
|
||||
|
||||
export default DeleteMsg
|
16
src/onebot11/actions/GetFriendList.ts
Normal file
16
src/onebot11/actions/GetFriendList.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { OB11User } from '../types';
|
||||
import { OB11Constructor } from "../constructor";
|
||||
import { friends } from "../../common/data";
|
||||
import BaseAction from "./BaseAction";
|
||||
import { ActionName } from "./types";
|
||||
|
||||
|
||||
class GetFriendList extends BaseAction<null, OB11User[]> {
|
||||
actionName = ActionName.GetFriendList
|
||||
|
||||
protected async _handle(payload: null){
|
||||
return OB11Constructor.friends(friends);
|
||||
}
|
||||
}
|
||||
|
||||
export default GetFriendList
|
24
src/onebot11/actions/GetGroupInfo.ts
Normal file
24
src/onebot11/actions/GetGroupInfo.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { OB11Group } from '../types';
|
||||
import { getGroup, groups } from "../../common/data";
|
||||
import { OB11Constructor } from "../constructor";
|
||||
import BaseAction from "./BaseAction";
|
||||
import { ActionName } from "./types";
|
||||
|
||||
interface PayloadType {
|
||||
group_id: number
|
||||
}
|
||||
|
||||
class GetGroupInfo extends BaseAction<PayloadType, OB11Group[]> {
|
||||
actionName = ActionName.GetGroupInfo
|
||||
|
||||
protected async _handle(payload: PayloadType) {
|
||||
const group = await getGroup(payload.group_id.toString())
|
||||
if (group) {
|
||||
return OB11Constructor.groups(groups)
|
||||
} else {
|
||||
throw `群${payload.group_id}不存在`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default GetGroupInfo
|
17
src/onebot11/actions/GetGroupList.ts
Normal file
17
src/onebot11/actions/GetGroupList.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { OB11Group } from '../types';
|
||||
import { OB11Constructor } from "../constructor";
|
||||
import { groups } from "../../common/data";
|
||||
import BaseAction from "./BaseAction";
|
||||
import { ActionName } from "./types";
|
||||
|
||||
|
||||
|
||||
class GetGroupList extends BaseAction<null, OB11Group[]> {
|
||||
actionName = ActionName.GetGroupList
|
||||
|
||||
protected async _handle(payload: null){
|
||||
return OB11Constructor.groups(groups);
|
||||
}
|
||||
}
|
||||
|
||||
export default GetGroupList
|
27
src/onebot11/actions/GetGroupMemberInfo.ts
Normal file
27
src/onebot11/actions/GetGroupMemberInfo.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { OB11GroupMember } from '../types';
|
||||
import { getGroupMember } from "../../common/data";
|
||||
import { OB11Constructor } from "../constructor";
|
||||
import BaseAction from "./BaseAction";
|
||||
import { ActionName } from "./types";
|
||||
|
||||
|
||||
export interface PayloadType {
|
||||
group_id: number
|
||||
user_id: number
|
||||
}
|
||||
|
||||
class GetGroupMemberInfo extends BaseAction<PayloadType, OB11GroupMember> {
|
||||
actionName = ActionName.GetGroupMemberInfo
|
||||
|
||||
protected async _handle(payload: PayloadType){
|
||||
const member = await getGroupMember(payload.group_id.toString(), payload.user_id.toString())
|
||||
if (member) {
|
||||
return OB11Constructor.groupMember(payload.group_id.toString(), member)
|
||||
}
|
||||
else {
|
||||
throw(`群成员${payload.user_id}不存在`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default GetGroupMemberInfo
|
30
src/onebot11/actions/GetGroupMemberList.ts
Normal file
30
src/onebot11/actions/GetGroupMemberList.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { OB11GroupMember } from '../types';
|
||||
import { getGroup } from "../../common/data";
|
||||
import { NTQQApi } from "../../ntqqapi/ntcall";
|
||||
import { OB11Constructor } from "../constructor";
|
||||
import BaseAction from "./BaseAction";
|
||||
import { ActionName } from "./types";
|
||||
|
||||
export interface PayloadType {
|
||||
group_id: number
|
||||
}
|
||||
|
||||
|
||||
class GetGroupMemberList extends BaseAction<PayloadType, OB11GroupMember[]> {
|
||||
actionName = ActionName.GetGroupMemberList
|
||||
|
||||
protected async _handle(payload: PayloadType){
|
||||
const group = await getGroup(payload.group_id.toString());
|
||||
if (group) {
|
||||
if (!group.members?.length) {
|
||||
group.members = await NTQQApi.getGroupMembers(payload.group_id.toString())
|
||||
}
|
||||
return OB11Constructor.groupMembers(group);
|
||||
}
|
||||
else {
|
||||
throw (`群${payload.group_id}不存在`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default GetGroupMemberList
|
16
src/onebot11/actions/GetLoginInfo.ts
Normal file
16
src/onebot11/actions/GetLoginInfo.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { OB11User } from '../types';
|
||||
import { OB11Constructor } from "../constructor";
|
||||
import { selfInfo } from "../../common/data";
|
||||
import BaseAction from "./BaseAction";
|
||||
import { ActionName } from "./types";
|
||||
|
||||
|
||||
class GetLoginInfo extends BaseAction<null, OB11User> {
|
||||
actionName = ActionName.GetLoginInfo
|
||||
|
||||
protected async _handle(payload: null){
|
||||
return OB11Constructor.selfInfo(selfInfo);
|
||||
}
|
||||
}
|
||||
|
||||
export default GetLoginInfo
|
30
src/onebot11/actions/GetMsg.ts
Normal file
30
src/onebot11/actions/GetMsg.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { getHistoryMsgByShortId, msgHistory } from "../../common/data";
|
||||
import { OB11Message } from '../types';
|
||||
import { OB11Constructor } from "../constructor";
|
||||
import { log } from "../../common/utils";
|
||||
import BaseAction from "./BaseAction";
|
||||
import { ActionName } from "./types";
|
||||
|
||||
|
||||
export interface PayloadType {
|
||||
message_id: number
|
||||
}
|
||||
|
||||
export type ReturnDataType = OB11Message
|
||||
|
||||
class GetMsg extends BaseAction<PayloadType, OB11Message> {
|
||||
actionName = ActionName.GetMsg
|
||||
|
||||
protected async _handle(payload: PayloadType){
|
||||
// log("history msg ids", Object.keys(msgHistory));
|
||||
const msg = getHistoryMsgByShortId(payload.message_id)
|
||||
if (msg) {
|
||||
const msgData = await OB11Constructor.message(msg);
|
||||
return msgData
|
||||
} else {
|
||||
throw("消息不存在")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default GetMsg
|
9
src/onebot11/actions/SendGroupMsg.ts
Normal file
9
src/onebot11/actions/SendGroupMsg.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import SendMsg from "./SendMsg";
|
||||
import { ActionName } from "./types";
|
||||
|
||||
|
||||
class SendGroupMsg extends SendMsg{
|
||||
actionName = ActionName.SendGroupMsg
|
||||
}
|
||||
|
||||
export default SendGroupMsg
|
137
src/onebot11/actions/SendMsg.ts
Normal file
137
src/onebot11/actions/SendMsg.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
import { AtType, ChatType, Group } from "../../ntqqapi/types";
|
||||
import {
|
||||
addHistoryMsg,
|
||||
friends,
|
||||
getGroup,
|
||||
getHistoryMsgByShortId,
|
||||
getStrangerByUin,
|
||||
} from "../../common/data";
|
||||
import { OB11MessageData, OB11MessageDataType, OB11PostSendMsg } from '../types';
|
||||
import { NTQQApi } from "../../ntqqapi/ntcall";
|
||||
import { Peer } from "../../ntqqapi/ntcall";
|
||||
import { SendMessageElement } from "../../ntqqapi/types";
|
||||
import { SendMsgElementConstructor } from "../../ntqqapi/constructor";
|
||||
import { uri2local } from "../utils";
|
||||
import { v4 as uuid4 } from 'uuid';
|
||||
import { log } from "../../common/utils";
|
||||
import BaseAction from "./BaseAction";
|
||||
import { ActionName } from "./types";
|
||||
import * as fs from "fs";
|
||||
|
||||
export interface ReturnDataType {
|
||||
message_id: number
|
||||
}
|
||||
|
||||
class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
|
||||
actionName = ActionName.SendMsg
|
||||
|
||||
protected async _handle(payload: OB11PostSendMsg){
|
||||
const peer: Peer = {
|
||||
chatType: ChatType.friend,
|
||||
peerUid: ""
|
||||
}
|
||||
let deleteAfterSentFiles: string[] = []
|
||||
let group: Group | undefined = undefined;
|
||||
if (payload?.group_id) {
|
||||
group = await getGroup(payload.group_id.toString())
|
||||
if (!group) {
|
||||
throw (`群${payload.group_id}不存在`)
|
||||
}
|
||||
peer.chatType = ChatType.group
|
||||
// peer.name = group.name
|
||||
peer.peerUid = group.groupCode
|
||||
}
|
||||
else if (payload?.user_id) {
|
||||
const friend = friends.find(f => f.uin == payload.user_id.toString())
|
||||
if (friend) {
|
||||
// peer.name = friend.nickName
|
||||
peer.peerUid = friend.uid
|
||||
}
|
||||
else {
|
||||
peer.chatType = ChatType.temp
|
||||
const tempUser = getStrangerByUin(payload.user_id.toString())
|
||||
if (!tempUser) {
|
||||
throw(`找不到私聊对象${payload.user_id}`)
|
||||
}
|
||||
// peer.name = tempUser.nickName
|
||||
peer.peerUid = tempUser.uid
|
||||
}
|
||||
}
|
||||
if (typeof payload.message === "string") {
|
||||
payload.message = [{
|
||||
type: OB11MessageDataType.text,
|
||||
data: {
|
||||
text: payload.message
|
||||
}
|
||||
}] as OB11MessageData[]
|
||||
}
|
||||
else if (!Array.isArray(payload.message)) {
|
||||
payload.message = [payload.message]
|
||||
}
|
||||
const sendElements: SendMessageElement[] = []
|
||||
for (let sendMsg of payload.message) {
|
||||
switch (sendMsg.type) {
|
||||
case OB11MessageDataType.text: {
|
||||
const text = sendMsg.data?.text;
|
||||
if (text) {
|
||||
sendElements.push(SendMsgElementConstructor.text(sendMsg.data!.text))
|
||||
}
|
||||
} break;
|
||||
case OB11MessageDataType.at: {
|
||||
let atQQ = sendMsg.data?.qq;
|
||||
if (atQQ) {
|
||||
atQQ = atQQ.toString()
|
||||
if (atQQ === "all") {
|
||||
sendElements.push(SendMsgElementConstructor.at(atQQ, atQQ, AtType.atAll, "全体成员"))
|
||||
}
|
||||
else {
|
||||
const atMember = group?.members.find(m => m.uin == atQQ)
|
||||
if (atMember) {
|
||||
sendElements.push(SendMsgElementConstructor.at(atQQ, atMember.uid, AtType.atUser, atMember.cardName || atMember.nick))
|
||||
}
|
||||
}
|
||||
}
|
||||
} break;
|
||||
case OB11MessageDataType.reply: {
|
||||
let replyMsgId = sendMsg.data.id;
|
||||
if (replyMsgId) {
|
||||
replyMsgId = replyMsgId.toString()
|
||||
const replyMsg = getHistoryMsgByShortId(replyMsgId)
|
||||
if (replyMsg) {
|
||||
sendElements.push(SendMsgElementConstructor.reply(replyMsg.msgSeq, replyMsg.msgId, replyMsg.senderUin, replyMsg.senderUin))
|
||||
}
|
||||
}
|
||||
} break;
|
||||
case OB11MessageDataType.image:
|
||||
case OB11MessageDataType.voice: {
|
||||
const file = sendMsg.data?.file
|
||||
if (file) {
|
||||
const {path, isLocal} = (await uri2local(uuid4(), file))
|
||||
if (path) {
|
||||
if (!isLocal){ // 只删除http和base64转过来的文件
|
||||
deleteAfterSentFiles.push(path)
|
||||
}
|
||||
if (sendMsg.type === OB11MessageDataType.image){
|
||||
sendElements.push(await SendMsgElementConstructor.pic(path))
|
||||
}
|
||||
else {
|
||||
sendElements.push(await SendMsgElementConstructor.ptt(path))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// log("send msg:", peer, sendElements)
|
||||
try {
|
||||
const returnMsg = await NTQQApi.sendMsg(peer, sendElements)
|
||||
addHistoryMsg(returnMsg)
|
||||
deleteAfterSentFiles.map(f=>fs.unlink(f, ()=>{}))
|
||||
return { message_id: returnMsg.msgShortId }
|
||||
} catch (e) {
|
||||
throw(e.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default SendMsg
|
8
src/onebot11/actions/SendPrivateMsg.ts
Normal file
8
src/onebot11/actions/SendPrivateMsg.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import SendMsg from "./SendMsg";
|
||||
import { ActionName } from "./types";
|
||||
|
||||
class SendPrivateMsg extends SendMsg {
|
||||
actionName = ActionName.SendPrivateMsg
|
||||
}
|
||||
|
||||
export default SendPrivateMsg
|
20
src/onebot11/actions/index.ts
Normal file
20
src/onebot11/actions/index.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import GetMsg from './GetMsg'
|
||||
import GetLoginInfo from './GetLoginInfo'
|
||||
import GetFriendList from './GetFriendList'
|
||||
import GetGroupList from './GetGroupList'
|
||||
import GetGroupInfo from './GetGroupInfo'
|
||||
import GetGroupMemberList from './GetGroupMemberList'
|
||||
import GetGroupMemberInfo from './GetGroupMemberInfo'
|
||||
import SendGroupMsg from './SendGroupMsg'
|
||||
import SendPrivateMsg from './SendPrivateMsg'
|
||||
import SendMsg from './SendMsg'
|
||||
import DeleteMsg from "./DeleteMsg";
|
||||
|
||||
export const actionHandlers = [
|
||||
new GetMsg(),
|
||||
new GetLoginInfo(),
|
||||
new GetFriendList(),
|
||||
new GetGroupList(), new GetGroupInfo(), new GetGroupMemberList(), new GetGroupMemberInfo(),
|
||||
new SendGroupMsg(), new SendPrivateMsg(), new SendMsg(),
|
||||
new DeleteMsg()
|
||||
]
|
26
src/onebot11/actions/types.ts
Normal file
26
src/onebot11/actions/types.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
export type BaseCheckResult = ValidCheckResult | InvalidCheckResult
|
||||
|
||||
export interface ValidCheckResult {
|
||||
valid: true
|
||||
[k: string | number]: any
|
||||
}
|
||||
|
||||
export interface InvalidCheckResult {
|
||||
valid: false
|
||||
message: string
|
||||
[k: string | number]: any
|
||||
}
|
||||
|
||||
export enum ActionName{
|
||||
GetLoginInfo = "get_login_info",
|
||||
GetFriendList = "get_friend_list",
|
||||
GetGroupInfo = "get_group_info",
|
||||
GetGroupList = "get_group_list",
|
||||
GetGroupMemberInfo = "get_group_member_info",
|
||||
GetGroupMemberList = "get_group_member_list",
|
||||
GetMsg = "get_msg",
|
||||
SendMsg = "send_msg",
|
||||
SendGroupMsg = "send_group_msg",
|
||||
SendPrivateMsg = "send_private_msg",
|
||||
DeleteMsg = "delete_msg"
|
||||
}
|
18
src/onebot11/actions/utils.ts
Normal file
18
src/onebot11/actions/utils.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { OB11Return } from '../types';
|
||||
|
||||
export class OB11Response {
|
||||
static res<T>(data: T, status: number = 0, message: string = ""): OB11Return<T> {
|
||||
return {
|
||||
status: status,
|
||||
retcode: status,
|
||||
data: data,
|
||||
message: message
|
||||
}
|
||||
}
|
||||
static ok<T>(data: T) {
|
||||
return OB11Response.res<T>(data)
|
||||
}
|
||||
static error(err: string) {
|
||||
return OB11Response.res(null, -1, err)
|
||||
}
|
||||
}
|
188
src/onebot11/constructor.ts
Normal file
188
src/onebot11/constructor.ts
Normal file
@@ -0,0 +1,188 @@
|
||||
import {
|
||||
OB11MessageDataType,
|
||||
OB11GroupMemberRole,
|
||||
OB11Message,
|
||||
OB11Group,
|
||||
OB11GroupMember,
|
||||
OB11User
|
||||
} from "./types";
|
||||
import { AtType, ChatType, Group, GroupMember, IMAGE_HTTP_HOST, RawMessage, SelfInfo, User } from '../ntqqapi/types';
|
||||
import { getFriend, getGroupMember, getHistoryMsgBySeq, msgHistory, selfInfo } from '../common/data';
|
||||
import { file2base64, getConfigUtil, log } from "../common/utils";
|
||||
import { NTQQApi } from "../ntqqapi/ntcall";
|
||||
|
||||
|
||||
export class OB11Constructor {
|
||||
static async message(msg: RawMessage): Promise<OB11Message> {
|
||||
|
||||
const {enableBase64} = getConfigUtil().getConfig()
|
||||
const message_type = msg.chatType == ChatType.group ? "group" : "private";
|
||||
const resMsg: OB11Message = {
|
||||
self_id: selfInfo.uin,
|
||||
user_id: msg.senderUin,
|
||||
time: parseInt(msg.msgTime) || 0,
|
||||
message_id: msg.msgShortId,
|
||||
real_id: msg.msgId,
|
||||
message_type: msg.chatType == ChatType.group ? "group" : "private",
|
||||
sender: {
|
||||
user_id: msg.senderUin,
|
||||
nickname: msg.sendNickName,
|
||||
card: msg.sendMemberName || "",
|
||||
},
|
||||
raw_message: "",
|
||||
font: 14,
|
||||
sub_type: "friend",
|
||||
message: [],
|
||||
post_type: "message",
|
||||
}
|
||||
if (msg.chatType == ChatType.group) {
|
||||
resMsg.sub_type = "normal"
|
||||
resMsg.group_id = msg.peerUin
|
||||
const member = await getGroupMember(msg.peerUin, msg.senderUin);
|
||||
if (member) {
|
||||
resMsg.sender.role = OB11Constructor.groupMemberRole(member.role);
|
||||
}
|
||||
} else if (msg.chatType == ChatType.friend) {
|
||||
resMsg.sub_type = "friend"
|
||||
const friend = await getFriend(msg.senderUin);
|
||||
if (friend) {
|
||||
resMsg.sender.nickname = friend.nick;
|
||||
}
|
||||
} else if (msg.chatType == ChatType.temp) {
|
||||
resMsg.sub_type = "group"
|
||||
}
|
||||
|
||||
for (let element of msg.elements) {
|
||||
let message_data: any = {
|
||||
data: {},
|
||||
type: "unknown"
|
||||
}
|
||||
if (element.textElement && element.textElement?.atType !== AtType.notAt) {
|
||||
message_data["type"] = OB11MessageDataType.at
|
||||
if (element.textElement.atType == AtType.atAll) {
|
||||
message_data["data"]["mention"] = "all"
|
||||
message_data["data"]["qq"] = "all"
|
||||
} else {
|
||||
let atUid = element.textElement.atNtUid
|
||||
let atQQ = element.textElement.atUid
|
||||
if (!atQQ || atQQ === "0") {
|
||||
const atMember = await getGroupMember(msg.peerUin, null, atUid)
|
||||
if (atMember) {
|
||||
atQQ = atMember.uin
|
||||
}
|
||||
}
|
||||
if (atQQ) {
|
||||
message_data["data"]["mention"] = atQQ
|
||||
message_data["data"]["qq"] = atQQ
|
||||
}
|
||||
}
|
||||
} else if (element.textElement) {
|
||||
message_data["type"] = "text"
|
||||
message_data["data"]["text"] = element.textElement.content
|
||||
} else if (element.picElement) {
|
||||
message_data["type"] = "image"
|
||||
message_data["data"]["file_id"] = element.picElement.fileUuid
|
||||
message_data["data"]["path"] = element.picElement.sourcePath
|
||||
message_data["data"]["file"] = element.picElement.sourcePath
|
||||
try {
|
||||
await NTQQApi.downloadMedia(msg.msgId, msg.chatType, msg.peerUid,
|
||||
element.elementId, element.picElement.thumbPath.get(0), element.picElement.sourcePath)
|
||||
} catch (e) {
|
||||
message_data["data"]["http_file"] = IMAGE_HTTP_HOST + element.picElement.originImageUrl
|
||||
}
|
||||
} else if (element.replyElement) {
|
||||
message_data["type"] = "reply"
|
||||
const replyMsg = getHistoryMsgBySeq(element.replyElement.replayMsgSeq)
|
||||
if (replyMsg) {
|
||||
message_data["data"]["id"] = replyMsg.msgShortId
|
||||
} else {
|
||||
continue
|
||||
}
|
||||
} else if (element.pttElement) {
|
||||
message_data["type"] = OB11MessageDataType.voice;
|
||||
message_data["data"]["file"] = element.pttElement.filePath
|
||||
message_data["data"]["file_id"] = element.pttElement.fileUuid
|
||||
// console.log("收到语音消息", message.raw.msgId, message.peer, element.pttElement)
|
||||
// window.LLAPI.Ptt2Text(message.raw.msgId, message.peer, messages).then(text => {
|
||||
// console.log("语音转文字结果", text);
|
||||
// }).catch(err => {
|
||||
// console.log("语音转文字失败", err);
|
||||
// })
|
||||
} else if (element.arkElement) {
|
||||
message_data["type"] = OB11MessageDataType.json;
|
||||
message_data["data"]["data"] = element.arkElement.bytesData;
|
||||
}
|
||||
if (message_data.data.http_file) {
|
||||
message_data.data.file = message_data.data.http_file
|
||||
} else if (message_data.data.file) {
|
||||
let filePath: string = message_data.data.file;
|
||||
message_data.data.file = "file://" + filePath
|
||||
if (enableBase64) {
|
||||
let {err, data} = await file2base64(filePath);
|
||||
if (err) {
|
||||
console.log("文件转base64失败", err)
|
||||
} else {
|
||||
message_data.data.file = "base64://" + data
|
||||
}
|
||||
}
|
||||
}
|
||||
if (message_data.type !== "unknown" && message_data.data) {
|
||||
resMsg.message.push(message_data);
|
||||
}
|
||||
}
|
||||
return resMsg;
|
||||
}
|
||||
|
||||
static friend(friend: User): OB11User {
|
||||
return {
|
||||
user_id: friend.uin,
|
||||
nickname: friend.nick,
|
||||
remark: friend.remark
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static selfInfo(selfInfo: SelfInfo): OB11User {
|
||||
return {
|
||||
user_id: selfInfo.uin,
|
||||
nickname: selfInfo.nick
|
||||
}
|
||||
}
|
||||
|
||||
static friends(friends: User[]): OB11User[] {
|
||||
return friends.map(OB11Constructor.friend)
|
||||
}
|
||||
|
||||
static groupMemberRole(role: number): OB11GroupMemberRole | undefined {
|
||||
return {
|
||||
4: OB11GroupMemberRole.owner,
|
||||
3: OB11GroupMemberRole.admin,
|
||||
2: OB11GroupMemberRole.member
|
||||
}[role]
|
||||
}
|
||||
|
||||
static groupMember(group_id: string, member: GroupMember): OB11GroupMember {
|
||||
return {
|
||||
group_id,
|
||||
user_id: member.uin,
|
||||
nickname: member.nick,
|
||||
card: member.cardName
|
||||
}
|
||||
}
|
||||
|
||||
static groupMembers(group: Group): OB11GroupMember[] {
|
||||
log("construct ob11 group members", group)
|
||||
return group.members.map(m => OB11Constructor.groupMember(group.groupCode, m))
|
||||
}
|
||||
|
||||
static group(group: Group): OB11Group {
|
||||
return {
|
||||
group_id: group.groupCode,
|
||||
group_name: group.groupName
|
||||
}
|
||||
}
|
||||
|
||||
static groups(groups: Group[]): OB11Group[] {
|
||||
return groups.map(OB11Constructor.group)
|
||||
}
|
||||
}
|
161
src/onebot11/server.ts
Normal file
161
src/onebot11/server.ts
Normal file
@@ -0,0 +1,161 @@
|
||||
import { getConfigUtil, log } from "../common/utils";
|
||||
|
||||
const express = require("express");
|
||||
import { Request } from 'express';
|
||||
import { Response } from 'express';
|
||||
|
||||
const JSONbig = require('json-bigint')({ storeAsString: true });
|
||||
import { selfInfo } from "../common/data";
|
||||
import { OB11Message, OB11Return, OB11MessageData } from './types';
|
||||
import { actionHandlers } from "./actions";
|
||||
|
||||
|
||||
// @SiberianHusky 2021-08-15
|
||||
function checkSendMessage(sendMsgList: OB11MessageData[]) {
|
||||
function checkUri(uri: string): boolean {
|
||||
const pattern = /^(file:\/\/|http:\/\/|https:\/\/|base64:\/\/)/;
|
||||
return pattern.test(uri);
|
||||
}
|
||||
|
||||
for (let msg of sendMsgList) {
|
||||
if (msg["type"] && msg["data"]) {
|
||||
let type = msg["type"];
|
||||
let data = msg["data"];
|
||||
if (type === "text" && !data["text"]) {
|
||||
return 400;
|
||||
} else if (["image", "voice", "record"].includes(type)) {
|
||||
if (!data["file"]) {
|
||||
return 400;
|
||||
} else {
|
||||
if (checkUri(data["file"])) {
|
||||
return 200;
|
||||
} else {
|
||||
return 400;
|
||||
}
|
||||
}
|
||||
|
||||
} else if (type === "at" && !data["qq"]) {
|
||||
return 400;
|
||||
} else if (type === "reply" && !data["id"]) {
|
||||
return 400;
|
||||
}
|
||||
} else {
|
||||
return 400
|
||||
}
|
||||
}
|
||||
return 200;
|
||||
}
|
||||
|
||||
// ==end==
|
||||
|
||||
|
||||
class OB11Response {
|
||||
static res<T>(data: T, status: number = 0, message: string = ""): OB11Return<T> {
|
||||
return {
|
||||
status: status,
|
||||
retcode: status,
|
||||
data: data,
|
||||
message: message
|
||||
}
|
||||
}
|
||||
static ok<T>(data: T) {
|
||||
return OB11Response.res<T>(data)
|
||||
}
|
||||
static error(err: string) {
|
||||
return OB11Response.res(null, -1, err)
|
||||
}
|
||||
}
|
||||
|
||||
const expressAPP = express();
|
||||
expressAPP.use(express.urlencoded({ extended: true, limit: "500mb" }));
|
||||
|
||||
expressAPP.use((req, res, next) => {
|
||||
let data = '';
|
||||
req.on('data', chunk => {
|
||||
data += chunk.toString();
|
||||
});
|
||||
req.on('end', () => {
|
||||
if (data) {
|
||||
try {
|
||||
// log("receive raw", data)
|
||||
req.body = JSONbig.parse(data);
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
}
|
||||
next();
|
||||
});
|
||||
});
|
||||
// expressAPP.use(express.json({
|
||||
// limit: '500mb',
|
||||
// verify: (req: any, res: any, buf: any, encoding: any) => {
|
||||
// req.rawBody = buf;
|
||||
// }
|
||||
// }));
|
||||
|
||||
export function startExpress(port: number) {
|
||||
|
||||
expressAPP.get('/', (req: Request, res: Response) => {
|
||||
res.send('llonebot已启动');
|
||||
})
|
||||
|
||||
expressAPP.listen(port, "0.0.0.0", () => {
|
||||
console.log(`llonebot started 0.0.0.0:${port}`);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
export function postMsg(msg: OB11Message) {
|
||||
const { reportSelfMessage } = getConfigUtil().getConfig()
|
||||
if (!reportSelfMessage) {
|
||||
if (msg.user_id == selfInfo.uin) {
|
||||
return
|
||||
}
|
||||
}
|
||||
for (const host of getConfigUtil().getConfig().hosts) {
|
||||
fetch(host, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-self-id": selfInfo.uin
|
||||
},
|
||||
body: JSON.stringify(msg)
|
||||
}).then((res: any) => {
|
||||
log(`新消息事件上报成功: ${host} ` + JSON.stringify(msg));
|
||||
}, (err: any) => {
|
||||
log(`新消息事件上报失败: ${host} ` + err + JSON.stringify(msg));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let routers: Record<string, (payload: any) => Promise<OB11Return<any>>> = {};
|
||||
|
||||
function registerRouter(action: string, handle: (payload: any) => Promise<any>) {
|
||||
let url = action.toString()
|
||||
if (!action.startsWith("/")) {
|
||||
url = "/" + action
|
||||
}
|
||||
async function _handle(res: Response, payload: any) {
|
||||
log("receive post data", url, payload)
|
||||
try {
|
||||
const result = await handle(payload)
|
||||
res.send(result)
|
||||
}
|
||||
catch (e) {
|
||||
log(e.stack);
|
||||
res.send(OB11Response.error(e.stack.toString()))
|
||||
}
|
||||
}
|
||||
|
||||
expressAPP.post(url, (req: Request, res: Response) => {
|
||||
_handle(res, req.body).then()
|
||||
});
|
||||
expressAPP.get(url, (req: Request, res: Response) => {
|
||||
_handle(res, req.query as any).then()
|
||||
});
|
||||
routers[url] = handle
|
||||
}
|
||||
|
||||
for (const action of actionHandlers) {
|
||||
registerRouter(action.actionName, (payload) => action.handle(payload))
|
||||
}
|
142
src/onebot11/types.ts
Normal file
142
src/onebot11/types.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import { AtType } from "../ntqqapi/types";
|
||||
import { RawMessage } from "../ntqqapi/types";
|
||||
|
||||
export interface OB11User{
|
||||
user_id: string;
|
||||
nickname: string;
|
||||
remark?: string
|
||||
}
|
||||
|
||||
export enum OB11UserSex{
|
||||
male = "male",
|
||||
female = "female",
|
||||
unknown = "unknown"
|
||||
}
|
||||
|
||||
export enum OB11GroupMemberRole{
|
||||
owner = "owner",
|
||||
admin = "admin",
|
||||
member = "member",
|
||||
}
|
||||
|
||||
export interface OB11GroupMember {
|
||||
group_id: string
|
||||
user_id: string
|
||||
nickname: string
|
||||
card?: string
|
||||
sex?: OB11UserSex
|
||||
age?: number
|
||||
join_time?: number
|
||||
last_sent_time?: number
|
||||
level?: number
|
||||
role?: OB11GroupMemberRole
|
||||
title?: string
|
||||
}
|
||||
|
||||
export interface OB11Group{
|
||||
group_id: string
|
||||
group_name: string
|
||||
member_count?: number
|
||||
max_member_count?: number
|
||||
}
|
||||
|
||||
interface OB11Sender {
|
||||
user_id: string,
|
||||
nickname: string,
|
||||
sex?: OB11UserSex,
|
||||
age?: number,
|
||||
card?: string, // 群名片
|
||||
level?: string, // 群等级
|
||||
role?: OB11GroupMemberRole
|
||||
}
|
||||
|
||||
export enum OB11MessageType {
|
||||
private = "private",
|
||||
group = "group"
|
||||
}
|
||||
|
||||
export interface OB11Message {
|
||||
self_id?: string,
|
||||
time: number,
|
||||
message_id: number,
|
||||
real_id: string,
|
||||
user_id: string,
|
||||
group_id?: string,
|
||||
message_type: "private" | "group",
|
||||
sub_type?: "friend" | "group" | "normal",
|
||||
sender: OB11Sender,
|
||||
message: OB11MessageData[],
|
||||
raw_message: string,
|
||||
font: number,
|
||||
post_type?: "message",
|
||||
raw?: RawMessage
|
||||
}
|
||||
|
||||
export type OB11ApiName =
|
||||
"send_msg"
|
||||
| "send_private_msg"
|
||||
| "send_group_msg"
|
||||
| "get_group_list"
|
||||
| "get_group_info"
|
||||
| "get_friend_list"
|
||||
| "delete_msg"
|
||||
| "get_login_info"
|
||||
| "get_group_member_list"
|
||||
| "get_group_member_info"
|
||||
| "get_msg"
|
||||
|
||||
export interface OB11Return<DataType> {
|
||||
status: number
|
||||
retcode: number
|
||||
data: DataType
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface OB11SendMsgReturn extends OB11Return<{message_id: string}>{}
|
||||
|
||||
export enum OB11MessageDataType {
|
||||
text = "text",
|
||||
image = "image",
|
||||
voice = "record",
|
||||
at = "at",
|
||||
reply = "reply",
|
||||
json = "json"
|
||||
}
|
||||
|
||||
export type OB11MessageData = {
|
||||
type: OB11MessageDataType.text,
|
||||
content: string,
|
||||
data?: {
|
||||
text: string, // 纯文本
|
||||
}
|
||||
} | {
|
||||
type: "image" | "voice" | "record",
|
||||
file: string, // 本地路径
|
||||
data?: {
|
||||
file: string // 本地路径
|
||||
}
|
||||
} | {
|
||||
type: OB11MessageDataType.at,
|
||||
atType?: AtType,
|
||||
content?: string,
|
||||
atUid?: string,
|
||||
atNtUid?: string,
|
||||
data?: {
|
||||
qq: string // at的qq号
|
||||
}
|
||||
} | {
|
||||
type: OB11MessageDataType.reply,
|
||||
msgId: string,
|
||||
msgSeq: string,
|
||||
senderUin: string,
|
||||
data: {
|
||||
id: string,
|
||||
}
|
||||
}
|
||||
|
||||
export interface OB11PostSendMsg {
|
||||
message_type?: "private" | "group"
|
||||
user_id: string,
|
||||
group_id?: string,
|
||||
message: OB11MessageData[] | string | OB11MessageData;
|
||||
}
|
62
src/onebot11/utils.ts
Normal file
62
src/onebot11/utils.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { CONFIG_DIR, isGIF } from "../common/utils";
|
||||
import * as path from 'path';
|
||||
import { NTQQApi } from '../ntqqapi/ntcall';
|
||||
const fs = require("fs").promises;
|
||||
|
||||
export async function uri2local(fileName: string, uri: string){
|
||||
let filePath = path.join(CONFIG_DIR, fileName)
|
||||
let url = new URL(uri);
|
||||
let res = {
|
||||
success: false,
|
||||
errMsg: "",
|
||||
path: "",
|
||||
isLocal: false
|
||||
}
|
||||
if (url.protocol == "base64:") {
|
||||
// base64转成文件
|
||||
let base64Data = uri.split("base64://")[1]
|
||||
try {
|
||||
const buffer = Buffer.from(base64Data, 'base64');
|
||||
await fs.writeFile(filePath, buffer);
|
||||
} catch (e: any) {
|
||||
res.errMsg = `base64文件下载失败,` + e.toString()
|
||||
return res
|
||||
}
|
||||
} else if (url.protocol == "http:" || url.protocol == "https:") {
|
||||
// 下载文件
|
||||
let fetchRes = await fetch(url)
|
||||
if (!fetchRes.ok) {
|
||||
res.errMsg = `${url}下载失败,` + fetchRes.statusText
|
||||
return res
|
||||
}
|
||||
let blob = await fetchRes.blob();
|
||||
let buffer = await blob.arrayBuffer();
|
||||
try {
|
||||
await fs.writeFile(filePath, Buffer.from(buffer));
|
||||
} catch (e: any) {
|
||||
res.errMsg = `${url}下载失败,` + e.toString()
|
||||
return res
|
||||
}
|
||||
} else if (url.protocol === "file:"){
|
||||
// await fs.copyFile(url.pathname, filePath);
|
||||
let pathname = decodeURIComponent(url.pathname)
|
||||
if (process.platform === "win32"){
|
||||
filePath = pathname.slice(1)
|
||||
}
|
||||
else{
|
||||
filePath = pathname
|
||||
}
|
||||
res.isLocal = true
|
||||
}
|
||||
else{
|
||||
res.errMsg = `不支持的file协议,` + url.protocol
|
||||
return res
|
||||
}
|
||||
if (isGIF(filePath) && !res.isLocal) {
|
||||
await fs.rename(filePath, filePath + ".gif");
|
||||
filePath += ".gif";
|
||||
}
|
||||
res.success = true
|
||||
res.path = filePath
|
||||
return res
|
||||
}
|
@@ -1,13 +1,11 @@
|
||||
// Electron 主进程 与 渲染进程 交互的桥梁
|
||||
|
||||
import {Config, Group, PostDataSendMsg, SelfInfo, User} from "./common/types";
|
||||
import {Config} from "./common/types";
|
||||
import {
|
||||
CHANNEL_DOWNLOAD_FILE,
|
||||
CHANNEL_GET_CONFIG, CHANNEL_SET_SELF_INFO, CHANNEL_LOG, CHANNEL_POST_ONEBOT_DATA,
|
||||
CHANNEL_RECALL_MSG, CHANNEL_SEND_MSG,
|
||||
CHANNEL_GET_CONFIG,
|
||||
CHANNEL_LOG,
|
||||
CHANNEL_SET_CONFIG,
|
||||
CHANNEL_START_HTTP_SERVER, CHANNEL_UPDATE_FRIENDS, CHANNEL_UPDATE_GROUPS, CHANNEL_DELETE_FILE
|
||||
} from "./common/IPCChannel";
|
||||
} from "./common/channels";
|
||||
|
||||
|
||||
const {contextBridge} = require("electron");
|
||||
@@ -15,29 +13,6 @@ const {ipcRenderer} = require('electron');
|
||||
|
||||
// 在window对象下导出只读对象
|
||||
contextBridge.exposeInMainWorld("llonebot", {
|
||||
|
||||
postData: (data: any) => {
|
||||
ipcRenderer.send(CHANNEL_POST_ONEBOT_DATA, data);
|
||||
},
|
||||
updateGroups: (groups: Group[]) => {
|
||||
ipcRenderer.send(CHANNEL_UPDATE_GROUPS, groups);
|
||||
},
|
||||
updateFriends: (friends: User[]) => {
|
||||
ipcRenderer.send(CHANNEL_UPDATE_FRIENDS, friends);
|
||||
},
|
||||
listenSendMessage: (handle: (jsonData: PostDataSendMsg) => void) => {
|
||||
ipcRenderer.on(CHANNEL_SEND_MSG, (event: any, args: PostDataSendMsg) => {
|
||||
handle(args)
|
||||
})
|
||||
},
|
||||
listenRecallMessage: (handle: (jsonData: {message_id: string}) => void) => {
|
||||
ipcRenderer.on(CHANNEL_RECALL_MSG, (event: any, args: {message_id: string}) => {
|
||||
handle(args)
|
||||
})
|
||||
},
|
||||
startExpress: () => {
|
||||
ipcRenderer.send(CHANNEL_START_HTTP_SERVER);
|
||||
},
|
||||
log: (data: any) => {
|
||||
ipcRenderer.send(CHANNEL_LOG, data);
|
||||
},
|
||||
@@ -47,14 +22,4 @@ contextBridge.exposeInMainWorld("llonebot", {
|
||||
getConfig: async () => {
|
||||
return ipcRenderer.invoke(CHANNEL_GET_CONFIG);
|
||||
},
|
||||
setSelfInfo(selfInfo: SelfInfo){
|
||||
ipcRenderer.invoke(CHANNEL_SET_SELF_INFO, selfInfo)
|
||||
},
|
||||
downloadFile: (arg: {uri: string, localFilePath: string}) => {
|
||||
return ipcRenderer.invoke(CHANNEL_DOWNLOAD_FILE, arg);
|
||||
},
|
||||
deleteFile: async (localFilePath: string[]) => {
|
||||
ipcRenderer.send(CHANNEL_DELETE_FILE, localFilePath);
|
||||
}
|
||||
// startExpress,
|
||||
});
|
542
src/renderer.ts
542
src/renderer.ts
@@ -1,449 +1,91 @@
|
||||
/// <reference path="./global.d.ts" />
|
||||
|
||||
// import express from "express";
|
||||
// const { ipcRenderer } = require('electron');
|
||||
import {AtType, Group, MessageElement, OnebotGroupMemberRole, Peer, PostDataSendMsg, User} from "./common/types";
|
||||
import * as stream from "stream";
|
||||
|
||||
let self_qq: string = ""
|
||||
let groups: Group[] = []
|
||||
let friends: User[] = []
|
||||
let msgHistory: MessageElement[] = []
|
||||
let uid_maps: Record<string, User> = {} // 一串加密的字符串 -> qq号
|
||||
async function getUserInfo(uid: string): Promise<User> {
|
||||
let user = uid_maps[uid]
|
||||
if (!user) {
|
||||
// 从服务器获取用户信息
|
||||
user = await window.LLAPI.getUserInfo(uid)
|
||||
uid_maps[uid] = user
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
async function getFriends() {
|
||||
let _friends = await window.LLAPI.getFriendsList(false)
|
||||
for (let friend of _friends) {
|
||||
let existFriend = friends.find(f => f.uin == friend.uin)
|
||||
if (!existFriend) {
|
||||
friends.push(friend)
|
||||
}
|
||||
}
|
||||
window.llonebot.updateFriends(friends)
|
||||
return friends
|
||||
}
|
||||
|
||||
async function getFriend(qq: string) {
|
||||
let friend = friends.find(friend => friend.uin == qq)
|
||||
if (!friend) {
|
||||
await getFriends();
|
||||
friend = friends.find(friend => friend.uin == qq);
|
||||
}
|
||||
return friend;
|
||||
}
|
||||
|
||||
async function getGroup(qq: string) {
|
||||
let group = groups.find(group => group.uid == qq)
|
||||
if (!group) {
|
||||
await getGroups();
|
||||
group = groups.find(group => group.uid == qq)
|
||||
}
|
||||
return group
|
||||
}
|
||||
|
||||
async function getGroups() {
|
||||
let __groups = await window.LLAPI.getGroupsList(false)
|
||||
for (let group of __groups) {
|
||||
group.members = [];
|
||||
let existGroup = groups.find(g => g.uid == group.uid)
|
||||
if (!existGroup) {
|
||||
// console.log("更新群列表", groups)
|
||||
groups.push(group)
|
||||
}
|
||||
}
|
||||
window.llonebot.updateGroups(groups)
|
||||
return groups
|
||||
}
|
||||
|
||||
async function getGroupMembers(group_qq: string, forced: boolean = false) {
|
||||
let group = await getGroup(group_qq)
|
||||
if (!group?.members || group!.members!.length == 0 || forced) {
|
||||
let res = (await window.LLAPI.getGroupMemberList(group_qq, 5000))
|
||||
// console.log(`更新群${group}成员列表 await`, _res)
|
||||
// window.LLAPI.getGroupMemberList(group_qq + "_groupMemberList_MainWindow", 5000).then(res =>{
|
||||
let members = res.result.infos.values();
|
||||
console.log("getGroupMemberList api response:", res)
|
||||
if (members && forced) {
|
||||
group.members = []
|
||||
}
|
||||
for (const member of members) {
|
||||
if (!group!.members!.find(m => m.uid == member.uid)) {
|
||||
group!.members!.push(member)
|
||||
}
|
||||
}
|
||||
window.llonebot.updateGroups(groups)
|
||||
console.log(`更新群${group.name}成员列表`, group)
|
||||
// })
|
||||
}
|
||||
return group?.members
|
||||
}
|
||||
|
||||
async function getGroupMember(group_qq: string, member_uid: string) {
|
||||
let members = await getGroupMembers(group_qq)
|
||||
if (members) {
|
||||
let member = members.find(member => member.uid == member_uid)
|
||||
if (!member) {
|
||||
members = await getGroupMembers(group_qq, true)
|
||||
member = members?.find(member => member.uid == member_uid)
|
||||
}
|
||||
return member
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function handleNewMessage(messages: MessageElement[]) {
|
||||
for (let message of messages) {
|
||||
let onebot_message_data: any = {
|
||||
self: {
|
||||
platform: "qq",
|
||||
user_id: self_qq
|
||||
},
|
||||
self_id: self_qq,
|
||||
time: 0,
|
||||
type: "message",
|
||||
post_type: "message",
|
||||
message_type: message.peer.chatType,
|
||||
detail_type: message.peer.chatType,
|
||||
message_id: message.raw.msgId,
|
||||
sub_type: "",
|
||||
message: []
|
||||
}
|
||||
if (message.peer.chatType == "group") {
|
||||
let group_id = message.peer.uid
|
||||
let group = (await getGroup(group_id))!
|
||||
onebot_message_data["group_id"] = message.peer.uid
|
||||
let groupMember = await getGroupMember(group_id, message.sender.uid)
|
||||
onebot_message_data["user_id"] = groupMember!.uin
|
||||
onebot_message_data.sender = {
|
||||
user_id: groupMember!.uin,
|
||||
nickname: groupMember!.nick,
|
||||
card: groupMember!.cardName,
|
||||
role: OnebotGroupMemberRole[groupMember!.role]
|
||||
}
|
||||
console.log("收到群消息", onebot_message_data)
|
||||
} else if (message.peer.chatType == "private") {
|
||||
onebot_message_data["user_id"] = message.peer.uid
|
||||
let friend = await getFriend(message.sender.uid)
|
||||
onebot_message_data.sender = {
|
||||
user_id: friend!.uin,
|
||||
nickname: friend!.nickName
|
||||
}
|
||||
}
|
||||
for (let element of message.raw.elements) {
|
||||
let message_data: any = {
|
||||
data: {},
|
||||
type: "unknown"
|
||||
}
|
||||
if (element.textElement?.atType == AtType.atUser) {
|
||||
message_data["type"] = "at"
|
||||
if (element.textElement.atUid != "0") {
|
||||
message_data["data"]["mention"] = element.textElement.atUid
|
||||
} else {
|
||||
let uid = element.textElement.atNtUid
|
||||
let atMember = await getGroupMember(message.peer.uid, uid)
|
||||
message_data["data"]["mention"] = atMember!.uin
|
||||
message_data["data"]["qq"] = atMember!.uin
|
||||
}
|
||||
} else if (element.textElement) {
|
||||
message_data["type"] = "text"
|
||||
message_data["data"]["text"] = element.textElement.content
|
||||
} else if (element.picElement) {
|
||||
message_data["type"] = "image"
|
||||
message_data["data"]["file_id"] = element.picElement.fileUuid
|
||||
message_data["data"]["path"] = element.picElement.sourcePath
|
||||
let startS = "file://"
|
||||
if (!element.picElement.sourcePath.startsWith("/")) {
|
||||
startS += "/"
|
||||
}
|
||||
message_data["data"]["file"] = startS + element.picElement.sourcePath
|
||||
} else if (element.replyElement) {
|
||||
message_data["type"] = "reply"
|
||||
message_data["data"]["id"] = msgHistory.find(msg => msg.raw.msgSeq == element.replyElement.replayMsgSeq)?.raw.msgId
|
||||
}
|
||||
onebot_message_data.message.push(message_data)
|
||||
}
|
||||
msgHistory.push(message)
|
||||
console.log("发送上传消息给ipc main", onebot_message_data)
|
||||
window.llonebot.postData(onebot_message_data);
|
||||
}
|
||||
}
|
||||
|
||||
async function listenSendMessage(postData: PostDataSendMsg) {
|
||||
if (postData.action == "send_private_msg" || postData.action == "send_group_msg") {
|
||||
let peer: Peer | null = null;
|
||||
if (!postData.params) {
|
||||
postData.params = {
|
||||
message: postData.message,
|
||||
user_id: postData.user_id,
|
||||
group_id: postData.group_id
|
||||
}
|
||||
}
|
||||
if (postData.action == "send_private_msg") {
|
||||
let friend = await getFriend(postData.params.user_id)
|
||||
if (friend) {
|
||||
peer = {
|
||||
chatType: "private",
|
||||
name: friend.nickName,
|
||||
uid: friend.uid
|
||||
}
|
||||
}
|
||||
} else if (postData.action == "send_group_msg") {
|
||||
let group = await getGroup(postData.params.group_id)
|
||||
if (group) {
|
||||
peer = {
|
||||
chatType: "group",
|
||||
name: group.name,
|
||||
uid: group.uid
|
||||
}
|
||||
|
||||
} else {
|
||||
console.log("未找到群, 发送群消息失败", postData)
|
||||
}
|
||||
}
|
||||
if (peer) {
|
||||
let sendFiles: string[] = [];
|
||||
for (let message of postData.params.message) {
|
||||
if (message.type == "at") {
|
||||
// @ts-ignore
|
||||
message.type = "text"
|
||||
message.atType = AtType.atUser
|
||||
let atUid = message.data?.qq || message.atUid
|
||||
let group = await getGroup(postData.params.group_id)
|
||||
let atMember = group.members.find(member => member.uin == atUid)
|
||||
message.atNtUid = atMember.uid
|
||||
message.atUid = atUid
|
||||
message.content = `@${atMember.cardName || atMember.nick}`
|
||||
} else if (message.type == "text") {
|
||||
message.content = message.data?.text || message.content
|
||||
} else if (message.type == "image" || message.type == "voice") {
|
||||
// todo: 收到的应该是uri格式的,需要转成本地的, uri格式有三种,http, file, base64
|
||||
let url = message.data?.file || message.file
|
||||
let uri = new URL(url);
|
||||
let ext: string;
|
||||
if (message.type == "image") {
|
||||
// todo: 需要识别gif格式
|
||||
ext = ".png"
|
||||
}
|
||||
if (message.type == "voice") {
|
||||
ext = ".amr"
|
||||
}
|
||||
let localFilePath = `${Date.now()}${ext}`
|
||||
if (uri.protocol == "file:") {
|
||||
localFilePath = url.split("file://")[1]
|
||||
} else {
|
||||
await window.llonebot.downloadFile({uri: url, localFilePath: localFilePath})
|
||||
}
|
||||
message.file = localFilePath
|
||||
sendFiles.push(localFilePath);
|
||||
} else if (message.type == "reply") {
|
||||
let msgId = message.data?.id || message.msgId
|
||||
let replyMessage = msgHistory.find(msg => msg.raw.msgId == msgId)
|
||||
message.msgId = msgId
|
||||
message.msgSeq = replyMessage?.raw.msgSeq || ""
|
||||
}
|
||||
}
|
||||
console.log("发送消息", postData)
|
||||
window.LLAPI.sendMessage(peer, postData.params.message).then(res => {
|
||||
console.log("消息发送成功:", peer, postData.params.message)
|
||||
window.llonebot.deleteFile(sendFiles);
|
||||
},
|
||||
err => console.log("消息发送失败", postData, err))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function recallMessage(msgId: string) {
|
||||
let msg = msgHistory.find(msg => msg.raw.msgId == msgId)
|
||||
window.LLAPI.recallMessage(msg.peer, [msgId]).then()
|
||||
}
|
||||
|
||||
let chatListEle: HTMLCollectionOf<Element>
|
||||
|
||||
function onLoad() {
|
||||
|
||||
window.llonebot.listenSendMessage((postData: PostDataSendMsg) => {
|
||||
listenSendMessage(postData).then().catch(err => console.log("listenSendMessage err", err))
|
||||
})
|
||||
window.llonebot.listenRecallMessage((arg: { message_id: string }) => {
|
||||
recallMessage(arg.message_id)
|
||||
})
|
||||
|
||||
async function getGroupsMembers(groupsArg: Group[]) {
|
||||
// 批量获取群成员列表
|
||||
let failedGroups: Group[] = []
|
||||
for (const group of groupsArg) {
|
||||
let handledGroup = await getGroupMembers(group.uid, true)
|
||||
if (handledGroup.length == 0) {
|
||||
failedGroups.push(group)
|
||||
}
|
||||
}
|
||||
if (failedGroups.length > 0) {
|
||||
console.log("获取群成员列表失败,重试", failedGroups.map(group => group.name))
|
||||
setTimeout(() => {
|
||||
getGroupsMembers(failedGroups).then()
|
||||
}, 1000)
|
||||
} else {
|
||||
console.log("全部群成员获取完毕", groups)
|
||||
}
|
||||
}
|
||||
|
||||
function onNewMessages(messages: MessageElement[]) {
|
||||
async function func(messages: MessageElement[]) {
|
||||
console.log("收到新消息", messages)
|
||||
if (!self_qq) {
|
||||
self_qq = (await window.LLAPI.getAccountInfo()).uin
|
||||
}
|
||||
await handleNewMessage(messages);
|
||||
}
|
||||
|
||||
func(messages).then(() => {
|
||||
})
|
||||
console.log("chatListEle", chatListEle)
|
||||
}
|
||||
|
||||
getFriends().then();
|
||||
getGroups().then(() => {
|
||||
getGroupsMembers(groups).then(() => {
|
||||
window.LLAPI.on("new-messages", onNewMessages);
|
||||
window.LLAPI.on("new-send-messages", onNewMessages);
|
||||
})
|
||||
})
|
||||
|
||||
window.LLAPI.getAccountInfo().then(accountInfo => {
|
||||
window.LLAPI.getUserInfo(accountInfo.uid).then(userInfo => {
|
||||
window.llonebot.setSelfInfo({
|
||||
user_id: accountInfo.uin,
|
||||
nickname: userInfo.nickName
|
||||
});
|
||||
window.llonebot.startExpress();
|
||||
})
|
||||
})
|
||||
|
||||
window.LLAPI.add_qmenu((qContextMenu: Node) => {
|
||||
let btn = document.createElement("a")
|
||||
btn.className = "q-context-menu-item q-context-menu-item--normal vue-component"
|
||||
btn.setAttribute("aria-disabled", "false")
|
||||
btn.setAttribute("role", "menuitem")
|
||||
btn.setAttribute("tabindex", "-1")
|
||||
btn.onclick = () => {
|
||||
// window.LLAPI.getPeer().then(peer => {
|
||||
// // console.log("current peer", peer)
|
||||
// if (peer && peer.chatType == "group") {
|
||||
// getGroupMembers(peer.uid, true).then(()=> {
|
||||
// console.log("获取群成员列表成功", groups);
|
||||
// alert("获取群成员列表成功")
|
||||
// })
|
||||
// }
|
||||
// })
|
||||
async function func() {
|
||||
for (const group of groups) {
|
||||
await getGroupMembers(group.uid, true)
|
||||
}
|
||||
}
|
||||
|
||||
func().then(() => {
|
||||
console.log("获取群成员列表结果", groups);
|
||||
// 找到members数量为空的群
|
||||
groups.map(group => {
|
||||
if (group.members.length == 0) {
|
||||
console.log(`${group.name}群成员为空`)
|
||||
}
|
||||
})
|
||||
window.llonebot.updateGroups(groups)
|
||||
})
|
||||
}
|
||||
btn.innerText = "获取群成员列表"
|
||||
console.log(qContextMenu)
|
||||
// qContextMenu.appendChild(btn)
|
||||
})
|
||||
|
||||
window.LLAPI.on("context-msg-menu", (event, target, msgIds) => {
|
||||
console.log("msg menu", event, target, msgIds);
|
||||
})
|
||||
|
||||
// console.log("getAccountInfo", LLAPI.getAccountInfo());
|
||||
function getChatListEle() {
|
||||
chatListEle = document.getElementsByClassName("viewport-list__inner")
|
||||
console.log("chatListEle", chatListEle)
|
||||
if (chatListEle.length == 0) {
|
||||
setTimeout(getChatListEle, 500)
|
||||
} else {
|
||||
try {
|
||||
// 选择要观察的目标节点
|
||||
const targetNode = chatListEle[0];
|
||||
|
||||
// 创建一个观察器实例并传入回调函数
|
||||
const observer = new MutationObserver(function (mutations) {
|
||||
mutations.forEach(function (mutation) {
|
||||
// console.log("chat list changed", mutation.type); // 输出 mutation 的类型
|
||||
// 获得当前聊天窗口
|
||||
window.LLAPI.getPeer().then(peer => {
|
||||
// console.log("current peer", peer)
|
||||
if (peer && peer.chatType == "group") {
|
||||
getGroupMembers(peer.uid, false).then()
|
||||
}
|
||||
})
|
||||
});
|
||||
});
|
||||
|
||||
// 配置观察选项
|
||||
const config = {attributes: true, childList: true, subtree: true};
|
||||
|
||||
// 传入目标节点和观察选项
|
||||
observer.observe(targetNode, config);
|
||||
|
||||
} catch (e) {
|
||||
window.llonebot.log(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// getChatListEle();
|
||||
}
|
||||
|
||||
// 打开设置界面时触发
|
||||
async function onConfigView(view: any) {
|
||||
const {port, hosts} = await window.llonebot.getConfig()
|
||||
async function onSettingWindowCreated(view: Element) {
|
||||
window.llonebot.log("setting window created");
|
||||
let config = await window.llonebot.getConfig()
|
||||
|
||||
function creatHostEleStr(host: string) {
|
||||
let eleStr = `
|
||||
<div class="hostItem vertical-list-item">
|
||||
<setting-item data-direction="row" class="hostItem vertical-list-item">
|
||||
<h2>事件上报地址(http)</h2>
|
||||
<input class="host" type="text" value="${host}"
|
||||
<input class="host input-text" type="text" value="${host}"
|
||||
style="width:60%;padding: 5px"
|
||||
placeholder="不支持localhost,如果是本机请填写局域网ip"/>
|
||||
</div>
|
||||
placeholder="如果localhost上报失败试试局域网ip"/>
|
||||
</setting-item>
|
||||
|
||||
`
|
||||
return eleStr
|
||||
}
|
||||
|
||||
let hostsEleStr = ""
|
||||
for (const host of hosts) {
|
||||
for (const host of config.hosts) {
|
||||
hostsEleStr += creatHostEleStr(host);
|
||||
}
|
||||
const html = `
|
||||
<section class="wrap">
|
||||
<div class="vertical-list-item">
|
||||
<h2>监听端口</h2>
|
||||
<input id="port" type="number" value="${port}"/>
|
||||
</div>
|
||||
<div>
|
||||
<button id="addHost" class="q-button">添加上报地址</button>
|
||||
</div>
|
||||
<div id="hostItems">
|
||||
${hostsEleStr}
|
||||
</div>
|
||||
<button id="save" class="q-button">保存(监听端口重启QQ后生效)</button>
|
||||
</section>
|
||||
let html = `
|
||||
<div class="config_view llonebot">
|
||||
<setting-section>
|
||||
<setting-panel>
|
||||
<setting-list class="wrap">
|
||||
<setting-item class="vertical-list-item" data-direction="row">
|
||||
<setting-text>监听端口</setting-text>
|
||||
<input id="port" type="number" value="${config.port}"/>
|
||||
</setting-item>
|
||||
<div>
|
||||
<button id="addHost" class="q-button">添加上报地址</button>
|
||||
</div>
|
||||
<div id="hostItems">
|
||||
${hostsEleStr}
|
||||
</div>
|
||||
<button id="save" class="q-button">保存(监听端口重启QQ后生效)</button>
|
||||
</setting-list>
|
||||
</setting-panel>
|
||||
<setting-panel>
|
||||
<setting-item data-direction="row" class="hostItem vertical-list-item">
|
||||
<div>
|
||||
<div>上报文件进行base64编码</div>
|
||||
<div class="tips">不开启时,上报文件将以本地路径形式发送</div>
|
||||
</div>
|
||||
<setting-switch id="switchBase64" ${config.enableBase64 ? "is-active" : ""}></setting-switch>
|
||||
</setting-item>
|
||||
<setting-item data-direction="row" class="hostItem vertical-list-item">
|
||||
<div>
|
||||
<div>debug模式</div>
|
||||
<div class="tips">开启后上报消息添加raw字段附带原始消息</div>
|
||||
</div>
|
||||
<setting-switch id="debug" ${config.debug ? "is-active" : ""}></setting-switch>
|
||||
</setting-item>
|
||||
<setting-item data-direction="row" class="hostItem vertical-list-item">
|
||||
<div>
|
||||
<div>上报自身消息</div>
|
||||
<div class="tips">开启后上报自己发出的消息</div>
|
||||
</div>
|
||||
<setting-switch id="reportSelfMessage" ${config.reportSelfMessage ? "is-active" : ""}></setting-switch>
|
||||
</setting-item>
|
||||
<setting-item data-direction="row" class="hostItem vertical-list-item">
|
||||
<div>
|
||||
<div>日志</div>
|
||||
<div class="tips">日志目录:${window.LiteLoader.plugins["LLOneBot"].path.data}</div>
|
||||
</div>
|
||||
<setting-switch id="log" ${config.log ? "is-active" : ""}></setting-switch>
|
||||
</setting-item>
|
||||
</setting-panel>
|
||||
</setting-section>
|
||||
</div>
|
||||
<style>
|
||||
setting-panel {
|
||||
padding: 10px;
|
||||
}
|
||||
.tips {
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
@media (prefers-color-scheme: dark){
|
||||
.llonebot input {
|
||||
color: white;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
`
|
||||
|
||||
const parser = new DOMParser();
|
||||
@@ -452,7 +94,7 @@ async function onConfigView(view: any) {
|
||||
|
||||
function addHostEle(initValue: string = "") {
|
||||
let addressDoc = parser.parseFromString(creatHostEleStr(initValue), "text/html");
|
||||
let addressEle = addressDoc.querySelector("div")
|
||||
let addressEle = addressDoc.querySelector("setting-item")
|
||||
let hostItemsEle = document.getElementById("hostItems");
|
||||
hostItemsEle.appendChild(addressEle);
|
||||
}
|
||||
@@ -460,6 +102,25 @@ async function onConfigView(view: any) {
|
||||
|
||||
doc.getElementById("addHost").addEventListener("click", () => addHostEle())
|
||||
|
||||
function switchClick(eleId: string, configKey: string) {
|
||||
doc.getElementById(eleId)?.addEventListener("click", (e) => {
|
||||
const switchEle = e.target as HTMLInputElement
|
||||
if (config[configKey]) {
|
||||
config[configKey] = false
|
||||
switchEle.removeAttribute("is-active")
|
||||
} else {
|
||||
config[configKey] = true
|
||||
switchEle.setAttribute("is-active", "")
|
||||
}
|
||||
window.llonebot.setConfig(config)
|
||||
})
|
||||
}
|
||||
|
||||
switchClick("debug", "debug");
|
||||
switchClick("switchBase64", "enableBase64");
|
||||
switchClick("reportSelfMessage", "reportSelfMessage");
|
||||
switchClick("log", "log");
|
||||
|
||||
doc.getElementById("save")?.addEventListener("click",
|
||||
() => {
|
||||
const portEle: HTMLInputElement = document.getElementById("port") as HTMLInputElement
|
||||
@@ -474,18 +135,21 @@ async function onConfigView(view: any) {
|
||||
hosts.push(hostEle.value);
|
||||
}
|
||||
}
|
||||
window.llonebot.setConfig({
|
||||
port: parseInt(port),
|
||||
hosts: hosts
|
||||
})
|
||||
config.port = parseInt(port);
|
||||
config.hosts = hosts;
|
||||
window.llonebot.setConfig(config);
|
||||
alert("保存成功");
|
||||
})
|
||||
doc.querySelectorAll("section").forEach((node) => view.appendChild(node));
|
||||
|
||||
|
||||
doc.body.childNodes.forEach(node => {
|
||||
view.appendChild(node);
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
export {
|
||||
onLoad,
|
||||
onConfigView
|
||||
}
|
||||
onSettingWindowCreated
|
||||
}
|
||||
|
@@ -50,7 +50,7 @@ module.exports = {
|
||||
]
|
||||
},
|
||||
optimization: {
|
||||
minimize: true,
|
||||
minimize: false,
|
||||
minimizer: [
|
||||
new TerserPlugin({
|
||||
extractComments: false,
|
||||
|
Reference in New Issue
Block a user