Compare commits

..

43 Commits

Author SHA1 Message Date
linyuchen
fd2be2feda Merge branch 'dev'
# Conflicts:
#	src/renderer.ts
2024-01-31 11:33:41 +08:00
linyuchen
f272aeb28f ver: 2.1.0 2024-01-31 11:32:29 +08:00
linyuchen
a8e249d8e6 ver: 2.1.0 2024-01-31 11:23:57 +08:00
linyuchen
ac227f8335 docs: Q&A 2024-01-31 06:48:57 +08:00
linyuchen
19dfc06822 refactor: log path 2024-01-30 17:26:00 +08:00
linyuchen
8083ae4091 Merge branch 'dev'
# Conflicts:
#	manifest.json
2024-01-30 04:11:43 +08:00
linyuchen
465b7eaf6e chore: ver 2.0.4 2024-01-30 04:11:01 +08:00
linyuchen
0a6a67738e fix: cant not get sender info from friend message 2024-01-30 03:46:31 +08:00
linyuchen
f9a3b60192 ver: 2.0.3 2024-01-28 10:54:57 +08:00
linyuchen
15ea558721 doc update 2024-01-28 10:54:26 +08:00
linyuchen
35c9ffc0b0 Merge branch 'dev' 2024-01-28 10:42:46 +08:00
linyuchen
7dde7cbc2b fix: 发送file://文件时会误删除原文件 2024-01-28 10:41:48 +08:00
linyuchen
515fc8afb4 Merge pull request #7 from Rotten-LKZ/dev
feat: github actions for automatically publishing releases
2024-01-28 10:37:06 +08:00
Rotten-LKZ
f341e9f6e1 fix: cannot start with GITHUB 2024-01-28 03:42:11 +08:00
Rotten-LKZ
bfdb2835c6 feat: github actions for automatically publishing releases 2024-01-28 03:22:01 +08:00
linyuchen
05c4d693e0 fix: 上报消息添加raw_message和font字段 2024-01-25 14:42:44 +08:00
linyuchen
5c04f73f89 fix Linux无法加载
fix 样式
2024-01-25 08:10:39 +08:00
linyuchen
8f7886e1ee Merge branch 'v2'
# Conflicts:
#	manifest.json
2024-01-21 00:09:34 +08:00
linyuchen
5bbbe77ad0 doc update 2024-01-20 23:53:38 +08:00
linyuchen
0a3ae76b89 v1.2.7 2024-01-20 23:24:49 +08:00
linyuchen
ddd60a6a79 fix voice record type 2024-01-20 23:24:24 +08:00
linyuchen
6364f90b20 fix voice record type 2024-01-20 23:22:44 +08:00
linyuchen
e4d8c5e72e Merge remote-tracking branch 'origin/main' 2024-01-20 22:28:03 +08:00
linyuchen
907c9053c7 fix config path 2024-01-20 14:37:03 +08:00
linyuchen
6d33fb8b14 check gif 2024-01-20 08:38:14 +08:00
linyuchen
2350e4dc75 Update README.md 2024-01-13 18:27:30 +08:00
linyuchen
600addbf82 fix: 打开插件设置界面导致插件多次监听 2023-12-14 02:10:30 +08:00
linyuchen
f07f0111cd perf: auto remove send files 2023-12-12 20:45:54 +08:00
linyuchen
923f72e5d3 perf: message data checker 2023-12-09 16:59:16 +08:00
linyuchen
5b4001e411 Merge pull request #2 from YDHusky/main
修改发送消息返回数据
2023-12-09 14:46:16 +08:00
husky
b950f01d51 修改发送消息返回数据 2023-12-08 23:24:22 +08:00
linyuchen
dc38275660 fix: send private msg 2023-12-08 16:52:31 +08:00
linyuchen
3d077550cd doc: example 2023-12-08 15:55:13 +08:00
linyuchen
44fe01f94b Update README.md 2023-12-08 01:13:35 -06:00
linyuchen
5f9679dfbf body size up to 500mb 2023-12-06 17:42:57 +08:00
linyuchen
bffa2d9a31 fix: body too large 2023-12-03 15:52:14 +08:00
linyuchen
0c131ff555 fix: get_group_member_list, send_private_msg, send_group_msg.
feat: auto identify qq to read config
2023-12-02 11:58:50 +08:00
linyuchen
a802e95d89 feat: auto copy manifest 2023-12-01 01:53:48 +08:00
linyuchen
5ae65e1cf8 feat: 支持多个事件上报地址(http) 2023-12-01 01:48:54 +08:00
linyuchen
a826232e96 ver 1.0.0 2023-11-30 22:18:41 +08:00
linyuchen
1bd51d8d7b Merge remote-tracking branch 'origin/main' 2023-11-30 17:31:30 +08:00
linyuchen
3d3974d0c7 feature: image|voice support uri 2023-11-30 17:31:16 +08:00
linyuchen
9a07c8bba1 doc: download link 2023-11-20 18:31:17 +08:00
17 changed files with 966 additions and 313 deletions

36
.github/workflows/publish.yml vendored Normal file
View 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 }}

113
README.md
View File

@@ -1,32 +1,36 @@
# LLOneBot API
将NTQQLiteLoaderAPI封装成OneBot11/12标准的API
将NTQQLiteLoaderAPI封装成OneBot11/12标准的API, V12没有完整测试
*注意:本文档对应的是 LiteLoader 1.0.0及以上版本如果你使用的是旧版本请切换到本项目v1分支查看文档*
## 安装方法
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.安装修改后的[LiteLoaderQQNT-Plugin-LLAPI](https://github.com/linyuchen/LiteLoaderQQNT-Plugin-LLAPI/releases),原版的功能有缺陷
3.安装本项目插件[OneBotApi](https://github.com/linyuchen/LiteLoaderQQNT-OneBotApi)
3.安装本项目插件[OneBotApi](https://github.com/linyuchen/LiteLoaderQQNT-OneBotApi/releases/), 注意本插件2.0以下的版本不支持LiteLoader 1.0.0及以上版本
*关于插件的安装方法: 上述的两个插件都没有上架NTQQLiteLoader插件市场需要自己下载源码复制到插件目录*
*关于插件的安装方法: 上述的两个插件都没有上架NTQQLiteLoader插件市场需要自己下载复制到插件目录*
*Windows插件目录:`%USERPROFILE%/Documents/LiteLoaderQQNT/plugins`*
*Mac插件目录:`~/Library/Containers/com.tencent.qq/Data/Documents/LiteLoaderQQNT/plugins`*
*插件目录:`LiteLoaderQQNT/plugins`*
## 支持的API
目前只支持http协议不支持websocket事件上报也是http协议
目前只支持http协议POST方法不支持websocket事件上报也是http协议
主要功能:
- [x] 发送好友消息
- [x] 发送临时消息
- [x] 发送群消息
- [x] 获取好友列表
- [x] 获取群列表
- [x] 获取群成员列表
- [x] 获取好友列表
- [x] 发送群消息
- [x] 发送好友消息
- [x] 撤回消息
- [x] 上报好友消息
- [x] 上报临时消息
- [x] 上报群消息
消息格式支持:
@@ -38,4 +42,89 @@
- [ ] 转发消息记录
- [ ] xml
支持的api:
- [x] get_login_info
- [x] send_msg
- [x] send_group_msg
- [x] send_private_msg
- [x] delete_msg
- [x] get_group_list
- [x] get_group_member_list
- [x] get_group_member_info
- [x] get_friend_list
**自己发送成功的消息也会上报可以用于获取需要撤回消息的id**
## 示例
![](doc/image/example.jpg)
*暂时不支持`"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规范接口请检查是否调用了不支持的接口并且所有接口都只支持POST方法调用GET方法会报404
</details>
<br/>
<details>
<summary>发送不了图片和语音</summary>
<br/>
检查当前操作用户是否有LiteLoaderQQNT/data/LLOneBot的写入权限如Windows把QQ上安装到C盘有可能会出现无权限导致发送失败
</details>
<br/>
<details>
<summary>不支持cq码</summary>
<br/>
cq码已经过时了没有支持的打算(主要是我不用这玩意儿,加上我懒)
</details>
<br/>
<details>
<summary>onebot 12对接不了</summary>
<br/>
onebot 12只写了部分兼容没有完整测试不保证能用慎用
</details>
<br/>
<details>
<summary>QQ多开时事件没有上报</summary>
<br/>
小概率事件有可能是IPC通信串台了(不确定)重启QQ可解决目前正在想办法修复
</details>
<br/>
<details>
<summary>QQ变得很卡</summary>
<br/>
这是你的群特别多导致的,因为启动后会批量获取群成员列表,获取完之后就正常了
</details>
<br/>
<details>
<summary>如何查看日志</summary>
<br/>
LiteLoaderQQNT/data/LLOneBot/*.log
</details>
<br/>
## TODO
- [x] 接口返回更详细的错误信息,目前消息发不出去也会返回发送成功(这河里吗)
- [ ] 转发消息记录
- [ ] 支持websocket等个有缘人提PR实现
- [ ] 重构摆脱LLAPI目前调用LLAPI只能在renderer进程调用需重构成在main进程调用
## onebot11文档
<https://11.onebot.dev/>

BIN
doc/image/example.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

View File

@@ -1,19 +1,19 @@
{
"manifest_version": 3,
"manifest_version": 4,
"type": "extension",
"name": "LLOneBot",
"slug": "LLOneBot",
"description": "LiteLoaderQQNT的OneBotApi",
"version": "0.1.0",
"version": "2.1.0",
"thumbnail": "./icon.png",
"author": {
"authors": [{
"name": "linyuchen",
"link": "https://github.com/linyuchen"
},
}],
"repository": {
"repo": "linyuchen/LLOneBot",
"repo": "linyuchen/LiteLoaderQQNT-OneBotApi",
"branch": "main",
"use_release": {
"release": {
"tag": "latest",
"name": "LLOneBot.zip"
}

15
package-lock.json generated
View File

@@ -9,7 +9,8 @@
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"express": "^4.18.2"
"express": "^4.18.2",
"uuid": "^9.0.1"
},
"devDependencies": {
"@babel/preset-env": "^7.23.2",
@@ -5213,6 +5214,18 @@
"node": ">= 0.4.0"
}
},
"node_modules/uuid": {
"version": "9.0.1",
"resolved": "https://mirrors.cloud.tencent.com/npm/uuid/-/uuid-9.0.1.tgz",
"integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://mirrors.cloud.tencent.com/npm/vary/-/vary-1.1.2.tgz",

View File

@@ -9,24 +9,25 @@
"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 && npm run deploy-mac",
"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/",
"build-win": "npm run build && npm run deploy-win",
"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",
"uuid": "^9.0.1"
},
"devDependencies": {
"electron": "^27.0.2",
"@babel/preset-env": "^7.23.2",
"@types/express": "^4.17.20",
"babel-loader": "^9.1.3",
"electron": "^27.0.2",
"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"
}
}

View File

@@ -7,3 +7,7 @@ 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"
export const CHANNEL_GET_RUNNING_STATUS= "llonebot_get_running_status"

View File

@@ -3,6 +3,12 @@ export enum AtType {
atUser = 2
}
export enum ChatType {
friend = 1,
group = 2,
temp = 100
}
export type GroupMemberInfo = {
avatarPath: string;
cardName: string;
@@ -17,6 +23,18 @@ export type GroupMemberInfo = {
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; // 签名
@@ -32,7 +50,7 @@ export type Group = {
}
export type Peer = {
chatType: "private" | "group"
chatType: ChatType
name: string
uid: string // qq号
}
@@ -40,7 +58,10 @@ export type Peer = {
export type MessageElement = {
raw: {
msgId: string,
msgTime: string,
msgSeq: string,
senderUin: string; // 发送者QQ号
chatType: ChatType,
elements: {
replyElement: {
senderUid: string, // 原消息发送者QQ号
@@ -86,7 +107,6 @@ export type MessageElement = {
}
}[]
}
peer: Peer,
sender: {
uid: string // 一串加密的字符串
@@ -102,7 +122,7 @@ export type SendMessage = {
text: string, // 纯文本
}
} | {
type: "image" | "voice",
type: "image" | "voice" | "record",
file: string, // 本地路径
data?: {
file: string // 本地路径
@@ -126,8 +146,11 @@ export type SendMessage = {
}
}
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: "send_private_msg" | "send_group_msg" | "get_group_list" | "get_friend_list" | "delete_msg",
action: PostDataAction
message_type?: "private" | "group"
params?: {
user_id: string,
@@ -137,9 +160,17 @@ export type PostDataSendMsg = {
user_id: string,
group_id: string,
message: SendMessage[];
ipc_uuid?: string
}
export type Config = {
port: number,
host: string,
hosts: string[],
}
export type SendMsgResult = {
status: number,
retcode: number,
data: any,
message: string,
}

24
src/global.d.ts vendored
View File

@@ -1,16 +1,25 @@
import {Config, Group, GroupMemberInfo, MessageElement, Peer, PostDataSendMsg, SendMessage, User} from "./common/types";
import {
Config,
Group,
GroupMemberInfo,
MessageElement,
Peer,
PostDataSendMsg,
SelfInfo,
SendMessage, SendMsgResult,
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 // qq
uin: string // 一串加密的字符串
uid: string // 一串加密的字符串
uin: string // qq
}>
// uid是一串加密的字符串
getUserInfo(uid: string): Promise<User>;
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[]>
@@ -33,6 +42,11 @@ declare var llonebot: {
log(data: any): void,
setConfig(config: Config):void;
getConfig():Promise<Config>;
setSelfInfo(selfInfo: SelfInfo):void;
downloadFile(arg: {uri: string, fileName: string}):Promise<{errMsg: string, path: string}>;
deleteFile(path: string[]):Promise<void>;
getRunningStatus(): Promise<boolean>;
sendSendMsgResult(sessionId: string, msgResult: SendMsgResult): void;
};
declare global {

View File

@@ -1,23 +1,89 @@
import {sendIPCRecallQQMsg, sendIPCSendQQMsg} from "./IPCSend";
import {log} from "./utils";
const express = require("express");
import {PostDataSendMsg} from "../common/types";
import {friends, groups} from "./data";
import {sendIPCRecallQQMsg, sendIPCSendQQMsg} from "./IPCSend";
import {OnebotGroupMemberRole, PostDataAction, PostDataSendMsg, SendMessage, SendMsgResult} from "../common/types";
import {friends, groups, selfInfo} from "./data";
function handlePost(jsonData: any) {
// @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", "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==
function handlePost(jsonData: any, handleSendResult: (data: SendMsgResult)=>void) {
log("API receive post:" + JSON.stringify(jsonData))
if (!jsonData.params) {
jsonData.params = JSON.parse(JSON.stringify(jsonData));
delete jsonData.params.params;
}
let resData = {
status: 0,
retcode: 0,
data: {},
message: ''
}
if (jsonData.action == "send_private_msg" || jsonData.action == "send_group_msg") {
sendIPCSendQQMsg(jsonData);
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, handleSendResult);
return;
} 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,
@@ -27,33 +93,36 @@ function handlePost(jsonData: any) {
})
}
})
} 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 => {
let role = "member"
switch (member.role) {
case 4: {
role = "owner"
break;
}
case 3: {
role = "admin"
break
}
case 2: {
role = "member"
break
}
}
return {
user_id: member.uin,
user_name: member.nick,
user_display_name: member.cardName || member.nick,
nickname: member.nick,
card: member.cardName,
role
role: OnebotGroupMemberRole[member.role],
}
}) || []
@@ -76,10 +145,27 @@ function handlePost(jsonData: any) {
export function startExpress(port: number) {
const app = express();
// 中间件用于解析POST请求的请求体
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use(express.urlencoded({extended: true, limit: "500mb"}));
app.use(express.json({limit: '500mb'}));
function parseToOnebot12(action: PostDataAction) {
app.post('/' + action, (req: any, res: any) => {
let jsonData: PostDataSendMsg = req.body;
jsonData.action = action
let resData = handlePost(jsonData, (data:SendMsgResult)=>{res.send(data)})
if (resData){
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已启动');
@@ -89,21 +175,11 @@ export function startExpress(port: number) {
// 处理POST请求的路由
app.post('/', (req: any, res: any) => {
let jsonData: PostDataSendMsg = req.body;
let resData = handlePost(jsonData)
let resData = handlePost(jsonData, (data:SendMsgResult)=>{res.send(data)})
if (resData){
res.send(resData)
}
});
app.post('/send_private_msg', (req: any, res: any) => {
let jsonData: PostDataSendMsg = req.body;
jsonData.action = "send_private_msg"
let resData = handlePost(jsonData)
res.send(resData)
})
app.post('/send_group_msg', (req: any, res: any) => {
let jsonData: PostDataSendMsg = req.body;
jsonData.action = "send_group_msg"
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") {
@@ -117,16 +193,13 @@ export function startExpress(port: number) {
jsonData.action = "send_private_msg"
}
}
let resData = handlePost(jsonData)
res.send(resData)
})
app.post('/delete_msg', (req: any, res: any) => {
let jsonData: PostDataSendMsg = req.body;
jsonData.action = "delete_msg"
let resData = handlePost(jsonData)
let resData = handlePost(jsonData, (data:SendMsgResult)=>{res.send(data)})
if (resData){
res.send(resData)
}
})
app.listen(port, "0.0.0.0", () => {
console.log(`服务器已启动,监听端口 ${port}`);
console.log(`llonebot started 0.0.0.0:${port}`);
});
}

View File

@@ -1,6 +1,8 @@
import {webContents} from 'electron';
import {PostDataSendMsg} from "../common/types";
import {ipcMain, webContents} from 'electron';
import {PostDataSendMsg, SendMsgResult} from "../common/types";
import {CHANNEL_RECALL_MSG, CHANNEL_SEND_MSG} from "../common/IPCChannel";
import {v4 as uuid4} from "uuid";
import {log} from "./utils";
function sendIPCMsg(channel: string, data: any) {
let contents = webContents.getAllWebContents();
@@ -8,12 +10,23 @@ function sendIPCMsg(channel: string, data: any) {
try {
content.send(channel, data)
} catch (e) {
console.log("llonebot send ipc msg to render error:", e)
}
}
}
export function sendIPCSendQQMsg(postData: PostDataSendMsg) {
export function sendIPCSendQQMsg(postData: PostDataSendMsg, handleSendResult: (data: SendMsgResult) => void) {
const onceSessionId = "llonebot_send_msg_" + uuid4();
postData.ipc_uuid = onceSessionId;
ipcMain.once(onceSessionId, (event: any, sendResult: SendMsgResult) => {
// log("llonebot send msg ipcMain.once:" + JSON.stringify(sendResult));
try {
handleSendResult(sendResult)
} catch (e) {
log("llonebot send msg ipcMain.once error:" + JSON.stringify(e))
}
})
sendIPCMsg(CHANNEL_SEND_MSG, postData);
}

View File

@@ -11,10 +11,18 @@ export class ConfigUtil{
getConfig(): Config{
if (!fs.existsSync(this.configPath)) {
return {"port":3000, "host": "http://localhost:5000/"}
return {port:3000, hosts: ["http://192.168.1.2:5000/"]}
} else {
const data = fs.readFileSync(this.configPath, "utf-8");
return JSON.parse(data);
let jsonData =JSON.parse(data);
if (!jsonData.hosts){
jsonData.hosts = []
}
return jsonData;
}
}
setConfig(config: Config){
fs.writeFileSync(this.configPath, JSON.stringify(config, null, 2), "utf-8")
}
}

View File

@@ -1,4 +1,9 @@
import {Group, User} from "../common/types";
import {Group, SelfInfo, User} from "../common/types";
export let groups: Group[] = []
export let friends: User[] = []
export let selfInfo: SelfInfo = {
user_id: "",
nickname: ""
}

View File

@@ -1,42 +1,113 @@
// 运行在 Electron 主进程 下的插件入口
import * as path from "path";
const fs = require('fs');
import {ipcMain} from 'electron';
import {Config, Group, User} from "../common/types";
import {Config, Group, SelfInfo, User} from "../common/types";
import {
CHANNEL_GET_CONFIG, CHANNEL_LOG, CHANNEL_POST_ONEBOT_DATA,
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_START_HTTP_SERVER,
CHANNEL_UPDATE_FRIENDS,
CHANNEL_UPDATE_GROUPS, CHANNEL_DELETE_FILE, CHANNEL_GET_RUNNING_STATUS
} from "../common/IPCChannel";
import {ConfigUtil} from "./config";
import {startExpress} from "./HttpServer";
import {log} from "./utils";
import {friends, groups} from "./data";
import {CONFIG_DIR, isGIF, log} from "./utils";
import {friends, groups, selfInfo} from "./data";
import {} from "../global";
const fs = require('fs');
let running = false;
// 加载插件时触发
function onLoad(plugin: any) {
function onLoad() {
log("main onLoaded");
const configFilePath = path.join(plugin.path.data, "config.json")
let configUtil = new ConfigUtil(configFilePath)
// const config_dir = browserWindow.LiteLoader.plugins["LLOneBot"].path.data;
function getConfigUtil() {
const configFilePath = path.join(CONFIG_DIR, `config_${selfInfo.user_id}.json`)
return new ConfigUtil(configFilePath)
}
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 configUtil.getConfig()
return getConfigUtil().getConfig()
})
ipcMain.handle(CHANNEL_DOWNLOAD_FILE, async (event: any, arg: { uri: string, fileName: string }): Promise<{
success: boolean,
errMsg: string,
path: string
}> => {
let filePath = path.join(CONFIG_DIR, arg.fileName)
let url = new URL(arg.uri);
if (url.protocol == "base64:") {
// base64转成文件
let base64Data = arg.uri.split("base64://")[1]
try {
const buffer = Buffer.from(base64Data, 'base64');
fs.writeFileSync(filePath, buffer);
} catch (e: any) {
return {
success: false,
errMsg: `base64文件下载失败,` + e.toString(),
path: ""
}
}
} else if (url.protocol == "http:" || url.protocol == "https:") {
// 下载文件
let res = await fetch(url)
if (!res.ok) {
return {
success: false,
errMsg: `${url}下载失败,` + res.statusText,
path: ""
}
}
let blob = await res.blob();
let buffer = await blob.arrayBuffer();
try {
fs.writeFileSync(filePath, Buffer.from(buffer));
} catch (e: any) {
return {
success: false,
errMsg: `${url}下载失败,` + e.toString(),
path: ""
}
}
}
else{
return {
success: false,
errMsg: `不支持的file协议,` + url.protocol,
path: ""
}
}
if (isGIF(filePath)) {
fs.renameSync(filePath, filePath + ".gif");
filePath += ".gif";
}
return {
success: true,
errMsg: "",
path: filePath
};
})
ipcMain.on(CHANNEL_SET_CONFIG, (event: any, arg: Config) => {
fs.writeFileSync(configFilePath, JSON.stringify(arg, null, 2), "utf-8")
getConfigUtil().setConfig(arg)
})
ipcMain.on(CHANNEL_START_HTTP_SERVER, (event: any, arg: any) => {
startExpress(configUtil.getConfig().port)
startExpress(getConfigUtil().getConfig().port)
})
ipcMain.on(CHANNEL_UPDATE_GROUPS, (event: any, arg: Group[]) => {
@@ -70,38 +141,60 @@ function onLoad(plugin: any) {
})
ipcMain.on(CHANNEL_POST_ONEBOT_DATA, (event: any, arg: any) => {
for (const host of getConfigUtil().getConfig().hosts) {
try {
fetch(configUtil.getConfig().host, {
fetch(host, {
method: "POST",
headers: {
"Content-Type": "application/json"
"Content-Type": "application/json",
"x-self-id": selfInfo.user_id
},
body: JSON.stringify(arg)
}).then((res: any) => {
log("新消息事件上传");
log(`新消息事件上传成功: ${host} ` + JSON.stringify(arg));
}, (err: any) => {
log("新消息事件上传失败:" + err + JSON.stringify(arg));
log(`新消息事件上传失败: ${host} ` + 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;
running = true;
})
ipcMain.on(CHANNEL_DELETE_FILE, (event: any, arg: string[]) => {
for (const path of arg) {
fs.unlinkSync(path);
}
})
ipcMain.handle(CHANNEL_GET_RUNNING_STATUS, (event: any, arg: any) => {
return running;
})
}
// 创建窗口时触发
function onBrowserWindowCreated(window: any, plugin: any) {
function onBrowserWindowCreated(window: any) {
}
try {
onLoad();
} catch (e: any) {
console.log(e.toString())
}
// 这两个函数都是可选的
export {
onLoad, onBrowserWindowCreated
onBrowserWindowCreated
}

View File

@@ -1,8 +1,28 @@
import * as path from "path";
import {json} from "express";
import {selfInfo} from "./data";
const fs = require('fs');
export const CONFIG_DIR = global.LiteLoader.plugins["LLOneBot"].path.data;
export function log(msg: any) {
let currentDateTime = new Date().toLocaleString();
fs.appendFile("./llonebot.log", currentDateTime + ":" + msg + "\n", (err: any) => {
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.user_id ? `${selfInfo.nickname}(${selfInfo.user_id})` : ""
fs.appendFile(path.join(CONFIG_DIR , `llonebot-${currentDate}.log`), currentDateTime + ` ${userInfo}:` + JSON.stringify(msg) + "\n", (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'
}

View File

@@ -1,11 +1,20 @@
// Electron 主进程 与 渲染进程 交互的桥梁
import {Config, Group, PostDataSendMsg, User} from "./common/types";
import {Config, Group, PostDataSendMsg, SelfInfo, SendMsgResult, User} from "./common/types";
import {
CHANNEL_GET_CONFIG, CHANNEL_LOG, CHANNEL_POST_ONEBOT_DATA,
CHANNEL_RECALL_MSG, CHANNEL_SEND_MSG,
CHANNEL_DOWNLOAD_FILE,
CHANNEL_GET_CONFIG,
CHANNEL_SET_SELF_INFO,
CHANNEL_LOG,
CHANNEL_POST_ONEBOT_DATA,
CHANNEL_RECALL_MSG,
CHANNEL_SEND_MSG,
CHANNEL_SET_CONFIG,
CHANNEL_START_HTTP_SERVER, CHANNEL_UPDATE_FRIENDS, CHANNEL_UPDATE_GROUPS
CHANNEL_START_HTTP_SERVER,
CHANNEL_UPDATE_FRIENDS,
CHANNEL_UPDATE_GROUPS,
CHANNEL_DELETE_FILE,
CHANNEL_GET_RUNNING_STATUS
} from "./common/IPCChannel";
@@ -24,7 +33,11 @@ contextBridge.exposeInMainWorld("llonebot", {
updateFriends: (friends: User[]) => {
ipcRenderer.send(CHANNEL_UPDATE_FRIENDS, friends);
},
sendSendMsgResult: (sessionId: string, msgResult: SendMsgResult)=>{
ipcRenderer.send(sessionId, msgResult);
},
listenSendMessage: (handle: (jsonData: PostDataSendMsg) => void) => {
ipcRenderer.send(CHANNEL_LOG, "发送消息API已注册");
ipcRenderer.on(CHANNEL_SEND_MSG, (event: any, args: PostDataSendMsg) => {
handle(args)
})
@@ -45,6 +58,18 @@ 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);
},
getRunningStatus: () => {
return ipcRenderer.invoke(CHANNEL_GET_RUNNING_STATUS);
}
// startExpress,
});

View File

@@ -2,13 +2,31 @@
// import express from "express";
// const { ipcRenderer } = require('electron');
import {AtType, Group, MessageElement, Peer, PostDataSendMsg, User} from "./common/types";
import {
AtType,
ChatType,
Group,
MessageElement,
OnebotGroupMemberRole,
Peer,
PostDataSendMsg, SendMsgResult,
User
} from "./common/types";
let self_qq: string = ""
let groups: Group[] = []
let friends: User[] = []
let msgHistory: MessageElement[] = []
let uid_maps: Record<string, User> = {} // 一串加密的字符串 -> qq号
function getStrangerByUin(uin: string) {
for (const key in uid_maps) {
if (uid_maps[key].uin === uin) {
return uid_maps[key];
}
}
}
async function getUserInfo(uid: string): Promise<User> {
let user = uid_maps[uid]
if (!user) {
@@ -19,8 +37,25 @@ async function getUserInfo(uid: string): Promise<User> {
return user
}
function getFriend(qq: string) {
return friends.find(friend => friend.uid == qq)
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) {
@@ -38,11 +73,11 @@ async function getGroups() {
group.members = [];
let existGroup = groups.find(g => g.uid == group.uid)
if (!existGroup) {
console.log("更新群列表", groups)
// console.log("更新群列表", groups)
groups.push(group)
}
}
window.llonebot.updateGroups(groups)
}
}
return groups
}
@@ -61,6 +96,11 @@ async function getGroupMembers(group_qq: string, forced: boolean = false) {
if (!group!.members!.find(m => m.uid == member.uid)) {
group!.members!.push(member)
}
uid_maps[member.uid] = {
uin: member.uin,
uid: member.uid,
nickName: member.nick
};
}
window.llonebot.updateGroups(groups)
console.log(`更新群${group.name}成员列表`, group)
@@ -81,8 +121,8 @@ async function getGroupMember(group_qq: string, member_uid: string) {
}
}
async function handleNewMessage(messages: MessageElement[]) {
console.log("llonebot 收到消息:", messages);
for (let message of messages) {
let onebot_message_data: any = {
self: {
@@ -90,25 +130,50 @@ async function handleNewMessage(messages: MessageElement[]) {
user_id: self_qq
},
self_id: self_qq,
time: 0,
time: parseInt(message.raw.msgTime || "0"),
type: "message",
post_type: "message",
message_type: message.peer.chatType,
detail_type: message.peer.chatType,
message_id: message.raw.msgId,
sub_type: "",
message: []
message: [],
raw_message: "",
font: 14
}
// let group: Group
if (message.peer.chatType == "group") {
if (message.raw.chatType == ChatType.group) {
let group_id = message.peer.uid
let group = (await getGroup(group_id))!
onebot_message_data.message_type = onebot_message_data.sub_type = "group"
onebot_message_data["group_id"] = message.peer.uid
let groupMember = await getGroupMember(group_id, message.sender.uid)
onebot_message_data["user_id"] = groupMember!.uin
console.log("收到群消息", onebot_message_data)
} else if (message.peer.chatType == "private") {
onebot_message_data["user_id"] = message.peer.uid
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.raw.chatType == ChatType.friend) {
onebot_message_data["user_id"] = message.raw.senderUin;
onebot_message_data.message_type = onebot_message_data.sub_type = "friend"
let friend = await getFriend(message.raw.senderUin);
onebot_message_data.sender = {
user_id: friend!.uin,
nickname: friend!.nickName
}
} else if (message.raw.chatType == ChatType.temp) {
let senderQQ = message.raw.senderUin;
let senderUid = message.sender.uid;
let sender = await getUserInfo(senderUid);
onebot_message_data["user_id"] = senderQQ;
onebot_message_data.message_type = "friend"
onebot_message_data.sub_type = "group";
onebot_message_data.sender = {
user_id: senderQQ,
nickname: sender.nickName
}
}
for (let element of message.raw.elements) {
let message_data: any = {
@@ -132,13 +197,21 @@ async function handleNewMessage(messages: MessageElement[]) {
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
let startS = "file://"
if (!element.picElement.sourcePath.startsWith("/")) {
startS += "/"
}
// todo: 转成base64
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)
}
if (msgHistory.length > 10000) {
msgHistory.splice(0, 100)
}
msgHistory.push(message)
console.log("发送上传消息给ipc main", onebot_message_data)
window.llonebot.postData(onebot_message_data);
@@ -146,6 +219,13 @@ async function handleNewMessage(messages: MessageElement[]) {
}
async function listenSendMessage(postData: PostDataSendMsg) {
console.log("收到发送消息请求", postData);
let sendMsgResult: SendMsgResult = {
retcode: 0,
status: 0,
data: {},
message: "发送成功"
}
if (postData.action == "send_private_msg" || postData.action == "send_group_msg") {
let peer: Peer | null = null;
if (!postData.params) {
@@ -156,28 +236,48 @@ async function listenSendMessage(postData: PostDataSendMsg) {
}
}
if (postData.action == "send_private_msg") {
let friend = getFriend(postData.params.user_id)
let friend = await getFriend(postData.params.user_id)
if (friend) {
console.log("好友消息", postData)
peer = {
chatType: "private",
chatType: ChatType.friend,
name: friend.nickName,
uid: friend.uin
uid: friend.uid
}
} else {
// 临时消息
console.log("发送临时消息", postData)
let receiver = getStrangerByUin(postData.params.user_id);
if (receiver) {
peer = {
chatType: ChatType.temp,
name: receiver.nickName,
uid: receiver.uid
}
} else {
sendMsgResult.status = -1;
sendMsgResult.retcode = -1;
sendMsgResult.message = `发送失败,未找到对象${postData.params.user_id},检查他是否为好友或是群友`;
}
}
} else if (postData.action == "send_group_msg") {
let group = await getGroup(postData.params.group_id)
if (group) {
peer = {
chatType: "group",
chatType: ChatType.group,
name: group.name,
uid: group.uid
}
} else {
sendMsgResult.status = -1;
sendMsgResult.retcode = -1;
sendMsgResult.message = `发送失败,未找到群${postData.params.group_id}`;
console.log("未找到群, 发送群消息失败", postData)
}
}
if (peer) {
let sendFiles: string[] = [];
for (let message of postData.params.message) {
if (message.type == "at") {
// @ts-ignore
@@ -189,14 +289,42 @@ async function listenSendMessage(postData: PostDataSendMsg) {
message.atNtUid = atMember.uid
message.atUid = atUid
message.content = `@${atMember.cardName || atMember.nick}`
}
else if (message.type == "text"){
} else if (message.type == "text") {
message.content = message.data?.text || message.content
} else if (message.type == "image" || message.type == "voice" || message.type == "record") {
// 收到的是uri格式的需要转成本地的, uri格式有三种http, file, base64
let url = message.data?.file || message.file
let uri = new URL(url);
let ext: string;
if (message.type == "image") {
ext = ".png"
}
else if (message.type == "image" || message.type == "voice"){
message.file = message.data?.file || message.file
if (message.type == "voice" || message.type == "record") {
message.type = "voice"
ext = ".amr"
}
else if (message.type == "reply"){
let localFilePath = `${Date.now()}${ext}`
if (uri.protocol == "file:") {
localFilePath = url.split("file://")[1]
} else {
const {errMsg, path} = await window.llonebot.downloadFile({
uri: url,
fileName: `${Date.now()}${ext}`
})
console.log("下载文件结果", errMsg, path)
if (errMsg) {
console.log("下载文件失败", errMsg);
sendMsgResult.status = -1;
sendMsgResult.retcode = -1;
sendMsgResult.message = `发送失败,下载文件失败,${errMsg}`;
break;
} else {
localFilePath = path;
}
}
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
@@ -204,8 +332,27 @@ async function listenSendMessage(postData: PostDataSendMsg) {
}
}
console.log("发送消息", postData)
window.LLAPI.sendMessage(peer, postData.params.message).then(res => console.log("消息发送成功:", res),
err => console.log("消息发送失败", postData, err))
if (sendMsgResult.status !== 0) {
window.llonebot.sendSendMsgResult(postData.ipc_uuid, sendMsgResult)
return;
}
window.LLAPI.sendMessage(peer, postData.params.message).then(res => {
console.log("消息发送成功:", peer, postData.params.message)
if (sendFiles.length) {
window.llonebot.deleteFile(sendFiles);
}
window.llonebot.sendSendMsgResult(postData.ipc_uuid, sendMsgResult)
},
err => {
sendMsgResult.status = -1;
sendMsgResult.retcode = -1;
sendMsgResult.message = `发送失败,${err}`;
window.llonebot.sendSendMsgResult(postData.ipc_uuid, sendMsgResult)
console.log("消息发送失败", postData, err)
})
} else {
console.log(sendMsgResult, postData);
window.llonebot.sendSendMsgResult(postData.ipc_uuid, sendMsgResult)
}
}
}
@@ -217,15 +364,6 @@ function recallMessage(msgId: string) {
let chatListEle: HTMLCollectionOf<Element>
function onLoad() {
window.llonebot.startExpress();
window.llonebot.listenSendMessage((postData: PostDataSendMsg) => {
listenSendMessage(postData).then()
});
window.llonebot.listenRecallMessage((arg: { message_id: string }) => {
recallMessage(arg.message_id)
})
async function getGroupsMembers(groupsArg: Group[]) {
// 批量获取群成员列表
let failedGroups: Group[] = []
@@ -240,9 +378,8 @@ function onLoad() {
setTimeout(() => {
getGroupsMembers(failedGroups).then()
}, 1000)
}
else{
console.log("全部群成员获取完毕", groups)
} else {
window.llonebot.log("全部群成员获取完毕")
}
}
@@ -257,137 +394,228 @@ function onLoad() {
func(messages).then(() => {
})
console.log("chatListEle", chatListEle)
// console.log("chatListEle", chatListEle)
}
async function initAccountInfo() {
let accountInfo = await window.LLAPI.getAccountInfo();
window.llonebot.log("getAccountInfo " + JSON.stringify(accountInfo));
if (!accountInfo.uid) {
return false;
}
let selfInfo = await window.LLAPI.getUserInfo(accountInfo.uid);
window.llonebot.setSelfInfo({
user_id: accountInfo.uin,
nickname: selfInfo.nickName
});
window.llonebot.log("selfInfo " + JSON.stringify(selfInfo));
return true;
}
function onLoad() {
window.llonebot.log("llonebot render onLoad");
window.llonebot.getRunningStatus().then(running => {
if (running) {
return;
}
initAccountInfo().then(
(initSuccess) => {
if (!initSuccess) {
return;
}
if (friends.length == 0) {
getFriends().then(() => {
});
}
if (groups.length == 0) {
getGroups().then(() => {
getGroupsMembers(groups).then(() => {
});
});
}
window.LLAPI.on("new-messages", onNewMessages);
window.LLAPI.on("new-send-messages", onNewMessages);
})
})
window.llonebot.log("llonebot render start");
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.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)
})
window.llonebot.log("llonebot loaded");
// 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, true).then(()=> {
// console.log("获取群成员列表成功", groups);
// alert("获取群成员列表成功")
// })
// getGroupMembers(peer.uid, false).then()
// }
// })
async function func() {
for (const group of groups) {
await getGroupMembers(group.uid, true)
// });
// });
//
// // 配置观察选项
// const config = {attributes: true, childList: true, subtree: true};
//
// // 传入目标节点和观察选项
// observer.observe(targetNode, config);
//
// } catch (e) {
// window.llonebot.log(e)
// }
// }
// }
//
// // getChatListEle();
}
}
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 plugin_path = (window as any).LiteLoader.plugins.LLOneBot.path;
const {port, host} = await window.llonebot.getConfig()
const html = `
<section>
<div>
<label>监听端口</label>
<input id="port" type="number" value="${port}"/>
</div>
<div>
<label>事件上报地址(http)</label>
<input id="host" type="text" value="${host}"/>
</div>
<button id="save">保存(重启QQ后生效)</button>
</section>
async function onSettingWindowCreated(view: Element) {
window.llonebot.log("setting window created");
const {port, hosts} = await window.llonebot.getConfig()
function creatHostEleStr(host: string) {
let eleStr = `
<setting-item data-direction="row" class="hostItem vertical-list-item">
<h2>事件上报地址(http)</h2>
<input class="host input-text" type="text" value="${host}"
style="width:60%;padding: 5px"
placeholder="如果localhost上报失败试试局域网ip"/>
</setting-item>
`
return eleStr
}
let hostsEleStr = ""
for (const host of hosts) {
hostsEleStr += creatHostEleStr(host);
}
let html = `
<div class="config_view">
<setting-section>
<setting-panel style="padding: 10px">
<setting-list class="wrap">
<setting-item class="vertical-list-item" data-direction="row">
<setting-text>监听端口</setting-text>
<input id="port" type="number" value="${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-section>
</div>
`
const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
function addHostEle(initValue: string = "") {
let addressDoc = parser.parseFromString(creatHostEleStr(initValue), "text/html");
let addressEle = addressDoc.querySelector("setting-item")
let hostItemsEle = document.getElementById("hostItems");
hostItemsEle.appendChild(addressEle);
}
doc.getElementById("addHost").addEventListener("click", () => addHostEle())
doc.getElementById("save")?.addEventListener("click",
() => {
const portEle: HTMLInputElement = document.getElementById("port") as HTMLInputElement
const hostEle: HTMLInputElement = document.getElementById("host") as HTMLInputElement
const hostEles: HTMLCollectionOf<HTMLInputElement> = document.getElementsByClassName("host") as HTMLCollectionOf<HTMLInputElement>;
// const port = doc.querySelector("input[type=number]")?.value
// const host = doc.querySelector("input[type=text]")?.value
// 获取端口和host
const port = portEle.value
const host = hostEle.value
if (port && host) {
let hosts: string[] = [];
for (const hostEle of hostEles) {
if (hostEle.value) {
hosts.push(hostEle.value);
}
}
window.llonebot.setConfig({
port: parseInt(port),
host: host
hosts: hosts
})
}
alert("保存成功");
})
doc.querySelectorAll("section").forEach((node) => view.appendChild(node));
doc.body.childNodes.forEach(node => {
view.appendChild(node);
});
}
setTimeout(onLoad, 2000)
export {
onLoad,
onConfigView
onSettingWindowCreated
}