Compare commits

...

36 Commits

Author SHA1 Message Date
linyuchen
7ba7af13a8 ver: 2.3.0 2024-02-03 19:27:31 +08:00
linyuchen
fae61fbbde fix: 夜间模式输入框颜色
feat: log开关
2024-02-03 19:25:38 +08:00
linyuchen
ebc3968c4e fix: 不支持的消息不再上报 2024-02-03 15:46:23 +08:00
linyuchen
b3981f22f2 fix: bigint解析失败导致500 2024-02-03 15:18:22 +08:00
linyuchen
1554f1b08e 新增json消息上报,新增debug模式,新增开关控制上报文件base64编码,新增语音消息上报,修复撤回消息id类型不正常。修复@全体成员上报 2024-02-03 15:08:24 +08:00
linyuchen
08eb49ba67 Merge remote-tracking branch 'origin/main' 2024-02-02 21:57:27 +08:00
linyuchen
0fd8da0696 fix: 偶尔出现不能上报 2024-02-02 21:56:17 +08:00
linyuchen
1c6ec56c81 Update README.md 2024-01-31 18:45:39 +08:00
linyuchen
0ecacde730 fix: private message_type 2024-01-31 16:58:13 +08:00
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
14 changed files with 915 additions and 321 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 }}

View File

@@ -1,30 +1,32 @@
# LLOneBot API # LLOneBot API
将NTQQLiteLoaderAPI封装成OneBot11/12标准的API, V12没有完整测试 将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/releases/) 3.安装本项目插件[OneBotApi](https://github.com/linyuchen/LiteLoaderQQNT-OneBotApi/releases/), 注意本插件2.0以下的版本不支持LiteLoader 1.0.0及以上版本
*关于插件的安装方法: 上述的两个插件都没有上架NTQQLiteLoader插件市场需要自己下载源码复制到插件目录* *关于插件的安装方法: 上述的两个插件都没有上架NTQQLiteLoader插件市场需要自己下载复制到插件目录*
*Windows插件目录:`%USERPROFILE%/Documents/LiteLoaderQQNT/plugins`* *插件目录:`LiteLoaderQQNT/plugins`*
*Mac插件目录:`~/Library/Containers/com.tencent.qq/Data/Documents/LiteLoaderQQNT/plugins`*
## 支持的API ## 支持的API
目前只支持http协议POST方法不支持websocket事件上报也是http协议 目前只支持http协议POST方法不支持websocket事件上报也是http协议
主要功能:
- [x] 发送好友消息
- [x] 发送群消息
- [x] 获取好友列表
- [x] 获取群列表 - [x] 获取群列表
- [x] 获取群成员列表 - [x] 获取群成员列表
- [x] 获取好友列表
- [x] 发送群消息
- [x] 发送好友消息
- [x] 撤回消息 - [x] 撤回消息
- [x] 上报好友消息 - [x] 上报好友消息
- [x] 上报群消息 - [x] 上报群消息
@@ -34,7 +36,9 @@
- [x] 图片 - [x] 图片
- [x] 引用消息 - [x] 引用消息
- [x] @群成员 - [x] @群成员
- [x] 发送语音(只测试了silk编码的amr) - [x] 语音
- [x] json消息(只上报)
- [ ] 红包
- [ ] 转发消息记录 - [ ] 转发消息记录
- [ ] xml - [ ] xml
@@ -56,3 +60,71 @@
![](doc/image/example.jpg) ![](doc/image/example.jpg)
*暂时不支持`"message": "hello"`这种message为字符串的形式* *暂时不支持`"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/>
这是你的群特别多导致的,因为启动后会批量获取群成员列表,获取完之后就正常了
</details>
<br/>
<details>
<summary>撤回消息无效</summary>
<br/>
如果接口调用的传的`message`是number类型会导致精度丢失使用string类型可解决详情见<a href="https://github.com/linyuchen/LiteLoaderQQNT-OneBotApi/issues/17">issue#17</a>
</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/>

View File

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

32
package-lock.json generated
View File

@@ -9,7 +9,9 @@
"version": "1.0.0", "version": "1.0.0",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"express": "^4.18.2" "express": "^4.18.2",
"json-bigint": "^1.0.0",
"uuid": "^9.0.1"
}, },
"devDependencies": { "devDependencies": {
"@babel/preset-env": "^7.23.2", "@babel/preset-env": "^7.23.2",
@@ -2750,6 +2752,14 @@
"@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0"
} }
}, },
"node_modules/bignumber.js": {
"version": "9.1.2",
"resolved": "https://mirrors.cloud.tencent.com/npm/bignumber.js/-/bignumber.js-9.1.2.tgz",
"integrity": "sha512-2/mKyZH9K85bzOEfhXDBFZTGd1CTs+5IHpeFQo9luiBG7hghdC851Pj2WAhb6E3R6b9tZj/XKhbg4fum+Kepug==",
"engines": {
"node": "*"
}
},
"node_modules/body-parser": { "node_modules/body-parser": {
"version": "1.20.1", "version": "1.20.1",
"resolved": "https://mirrors.cloud.tencent.com/npm/body-parser/-/body-parser-1.20.1.tgz", "resolved": "https://mirrors.cloud.tencent.com/npm/body-parser/-/body-parser-1.20.1.tgz",
@@ -4008,6 +4018,14 @@
"node": ">=4" "node": ">=4"
} }
}, },
"node_modules/json-bigint": {
"version": "1.0.0",
"resolved": "https://mirrors.cloud.tencent.com/npm/json-bigint/-/json-bigint-1.0.0.tgz",
"integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==",
"dependencies": {
"bignumber.js": "^9.0.0"
}
},
"node_modules/json-buffer": { "node_modules/json-buffer": {
"version": "3.0.1", "version": "3.0.1",
"resolved": "https://mirrors.cloud.tencent.com/npm/json-buffer/-/json-buffer-3.0.1.tgz", "resolved": "https://mirrors.cloud.tencent.com/npm/json-buffer/-/json-buffer-3.0.1.tgz",
@@ -5213,6 +5231,18 @@
"node": ">= 0.4.0" "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": { "node_modules/vary": {
"version": "1.1.2", "version": "1.1.2",
"resolved": "https://mirrors.cloud.tencent.com/npm/vary/-/vary-1.1.2.tgz", "resolved": "https://mirrors.cloud.tencent.com/npm/vary/-/vary-1.1.2.tgz",

View File

@@ -17,16 +17,18 @@
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"express": "^4.18.2" "express": "^4.18.2",
"json-bigint": "^1.0.0",
"uuid": "^9.0.1"
}, },
"devDependencies": { "devDependencies": {
"electron": "^27.0.2",
"@babel/preset-env": "^7.23.2", "@babel/preset-env": "^7.23.2",
"@types/express": "^4.17.20", "@types/express": "^4.17.20",
"babel-loader": "^9.1.3", "babel-loader": "^9.1.3",
"electron": "^27.0.2",
"ts-loader": "^9.5.0", "ts-loader": "^9.5.0",
"typescript": "^5.2.2",
"webpack": "^5.89.0", "webpack": "^5.89.0",
"webpack-cli": "^5.1.4", "webpack-cli": "^5.1.4"
"typescript": "^5.2.2"
} }
} }

View File

@@ -10,3 +10,5 @@ export const CHANNEL_POST_ONEBOT_DATA = "llonebot_post_onebot_data"
export const CHANNEL_SET_SELF_INFO= "llonebot_set_self_info" export const CHANNEL_SET_SELF_INFO= "llonebot_set_self_info"
export const CHANNEL_DOWNLOAD_FILE= "llonebot_download_file" export const CHANNEL_DOWNLOAD_FILE= "llonebot_download_file"
export const CHANNEL_DELETE_FILE= "llonebot_delete_file" export const CHANNEL_DELETE_FILE= "llonebot_delete_file"
export const CHANNEL_GET_RUNNING_STATUS= "llonebot_get_running_status"
export const CHANNEL_FILE2BASE64= "llonebot_file2base64"

View File

@@ -1,9 +1,16 @@
export enum AtType { export enum AtType {
notAt = 0, notAt = 0,
atAll = 1,
atUser = 2 atUser = 2
} }
export type GroupMemberInfo = { export enum ChatType {
friend = 1,
group = 2,
temp = 100
}
export interface GroupMemberInfo {
avatarPath: string; avatarPath: string;
cardName: string; cardName: string;
cardType: number; cardType: number;
@@ -24,12 +31,12 @@ export const OnebotGroupMemberRole = {
} }
export type SelfInfo = { export interface SelfInfo {
user_id: string; user_id: string;
nickname: string; nickname: string;
} }
export type User = { export interface User {
avatarUrl?: string; avatarUrl?: string;
bio?: string; // 签名 bio?: string; // 签名
nickName: string; nickName: string;
@@ -37,22 +44,52 @@ export type User = {
uin: string; // QQ号 uin: string; // QQ号
} }
export type Group = { export interface Group {
uid: string; // 群号 uid: string; // 群号
name: string; name: string;
members?: GroupMemberInfo[]; members?: GroupMemberInfo[];
} }
export type Peer = { export interface Peer {
chatType: "private" | "group" chatType: ChatType
name: string name: string
uid: string // qq号 uid: string // qq号
} }
export type MessageElement = { 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 interface MessageElement {
raw: { raw: {
msgId: string, msgId: string,
msgTime: string,
msgSeq: string, msgSeq: string,
senderUin: string; // 发送者QQ号
chatType: ChatType,
elements: { elements: {
replyElement: { replyElement: {
senderUid: string, // 原消息发送者QQ号 senderUid: string, // 原消息发送者QQ号
@@ -74,31 +111,10 @@ export type MessageElement = {
fileName: string fileName: string
fileUuid: string fileUuid: string
}, },
pttElement: { pttElement: PttElement,
canConvert2Text: boolean arkElement: ArkElement
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, peer: Peer,
sender: { sender: {
uid: string // 一串加密的字符串 uid: string // 一串加密的字符串
@@ -107,20 +123,29 @@ export type MessageElement = {
} }
} }
export enum MessageType {
text = "text",
image = "image",
voice = "record",
at = "at",
reply = "reply",
json = "json"
}
export type SendMessage = { export type SendMessage = {
type: "text", type: MessageType.text,
content: string, content: string,
data?: { data?: {
text: string, // 纯文本 text: string, // 纯文本
} }
} | { } | {
type: "image" | "voice", type: "image" | "voice" | "record",
file: string, // 本地路径 file: string, // 本地路径
data?: { data?: {
file: string // 本地路径 file: string // 本地路径
} }
} | { } | {
type: "at", type: MessageType.at,
atType?: AtType, atType?: AtType,
content?: string, content?: string,
atUid?: string, atUid?: string,
@@ -129,7 +154,7 @@ export type SendMessage = {
qq: string // at的qq号 qq: string // at的qq号
} }
} | { } | {
type: "reply", type: MessageType.reply,
msgId: string, msgId: string,
msgSeq: string, msgSeq: string,
senderUin: string, senderUin: string,
@@ -139,9 +164,9 @@ export type SendMessage = {
} }
export type PostDataAction = "send_private_msg" | "send_group_msg" | "get_group_list" 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" | "get_friend_list" | "delete_msg" | "get_login_info" | "get_group_member_list" | "get_group_member_info"
export type PostDataSendMsg = { export interface PostDataSendMsg {
action: PostDataAction action: PostDataAction
message_type?: "private" | "group" message_type?: "private" | "group"
params?: { params?: {
@@ -152,9 +177,20 @@ export type PostDataSendMsg = {
user_id: string, user_id: string,
group_id: string, group_id: string,
message: SendMessage[]; message: SendMessage[];
ipc_uuid?: string
} }
export type Config = { export interface Config {
port: number, port: number
hosts: string[], hosts: string[]
enableBase64?: boolean
debug?: boolean
log?: boolean
} }
export interface SendMsgResult {
status: number
retcode: number
data: any
message: string
}

10
src/global.d.ts vendored
View File

@@ -4,9 +4,9 @@ import {
GroupMemberInfo, GroupMemberInfo,
MessageElement, MessageElement,
Peer, Peer,
PostDataSendMsg, PostDataSendMsg, PttElement,
SelfInfo, SelfInfo,
SendMessage, SendMessage, SendMsgResult,
User User
} from "./common/types"; } from "./common/types";
@@ -27,6 +27,7 @@ declare var LLAPI: {
getGroupMemberList(group_id: string, num: number): Promise<{result: { infos: Map<string, GroupMemberInfo> }}> getGroupMemberList(group_id: string, num: number): Promise<{result: { infos: Map<string, GroupMemberInfo> }}>
getPeer(): Promise<Peer> getPeer(): Promise<Peer>
add_qmenu(func: (qContextMenu: Node)=>void): void add_qmenu(func: (qContextMenu: Node)=>void): void
Ptt2Text(msgId:string, peer: Peer, elements: MessageElement[]): Promise<any>
}; };
@@ -43,8 +44,11 @@ declare var llonebot: {
setConfig(config: Config):void; setConfig(config: Config):void;
getConfig():Promise<Config>; getConfig():Promise<Config>;
setSelfInfo(selfInfo: SelfInfo):void; setSelfInfo(selfInfo: SelfInfo):void;
downloadFile(arg: {uri: string, localFilePath: string}):Promise<string>; downloadFile(arg: {uri: string, fileName: string}):Promise<{errMsg: string, path: string}>;
deleteFile(path: string[]):Promise<void>; deleteFile(path: string[]):Promise<void>;
getRunningStatus(): Promise<boolean>;
sendSendMsgResult(sessionId: string, msgResult: SendMsgResult): void;
file2base64(path: string): Promise<{err: string, data: string}>;
}; };
declare global { declare global {

View File

@@ -1,7 +1,9 @@
import {log} from "./utils";
const express = require("express"); const express = require("express");
const bodyParser = require('body-parser'); const JSONbig = require('json-bigint');
import {sendIPCRecallQQMsg, sendIPCSendQQMsg} from "./IPCSend"; import {sendIPCRecallQQMsg, sendIPCSendQQMsg} from "./IPCSend";
import {OnebotGroupMemberRole, PostDataAction, PostDataSendMsg, SendMessage} from "../common/types"; import {OnebotGroupMemberRole, PostDataAction, PostDataSendMsg, SendMessage, SendMsgResult} from "../common/types";
import {friends, groups, selfInfo} from "./data"; import {friends, groups, selfInfo} from "./data";
// @SiberianHusky 2021-08-15 // @SiberianHusky 2021-08-15
@@ -17,15 +19,13 @@ function checkSendMessage(sendMsgList: SendMessage[]) {
let data = msg["data"]; let data = msg["data"];
if (type === "text" && !data["text"]) { if (type === "text" && !data["text"]) {
return 400; return 400;
} else if (["image", "voice"].includes(type)) { } else if (["image", "voice", "record"].includes(type)) {
if (!data["file"]) { if (!data["file"]) {
return 400; return 400;
} } else {
else{
if (checkUri(data["file"])) { if (checkUri(data["file"])) {
return 200; return 200;
} } else {
else{
return 400; return 400;
} }
} }
@@ -35,19 +35,20 @@ function checkSendMessage(sendMsgList: SendMessage[]) {
} else if (type === "reply" && !data["id"]) { } else if (type === "reply" && !data["id"]) {
return 400; return 400;
} }
} } else {
else{
return 400 return 400
} }
} }
return 200; return 200;
} }
// ==end== // ==end==
function handlePost(jsonData: any) { function handlePost(jsonData: any, handleSendResult: (data: SendMsgResult) => void) {
log("API receive post:" + JSON.stringify(jsonData))
if (!jsonData.params) { if (!jsonData.params) {
jsonData.params = jsonData jsonData.params = JSON.parse(JSON.stringify(jsonData));
delete jsonData.params.params;
} }
let resData = { let resData = {
status: 0, status: 0,
@@ -55,6 +56,7 @@ function handlePost(jsonData: any) {
data: {}, data: {},
message: '' message: ''
} }
if (jsonData.action == "get_login_info") { if (jsonData.action == "get_login_info") {
resData["data"] = selfInfo resData["data"] = selfInfo
} else if (jsonData.action == "send_private_msg" || jsonData.action == "send_group_msg") { } else if (jsonData.action == "send_private_msg" || jsonData.action == "send_group_msg") {
@@ -68,7 +70,8 @@ function handlePost(jsonData: any) {
if (resData.status == 200) { if (resData.status == 200) {
resData.message = "发送成功"; resData.message = "发送成功";
resData.data = jsonData.message; resData.data = jsonData.message;
sendIPCSendQQMsg(jsonData); sendIPCSendQQMsg(jsonData, handleSendResult);
return;
} else { } else {
resData.message = "发送失败, 请检查消息格式"; resData.message = "发送失败, 请检查消息格式";
resData.data = jsonData.message; resData.data = jsonData.message;
@@ -133,7 +136,7 @@ function handlePost(jsonData: any) {
} }
}) })
} else if (jsonData.action == "delete_msg") { } else if (jsonData.action == "delete_msg") {
sendIPCRecallQQMsg(jsonData.message_id) sendIPCRecallQQMsg(String(jsonData.message_id))
} }
return resData return resData
} }
@@ -143,15 +146,32 @@ export function startExpress(port: number) {
const app = express(); const app = express();
// 中间件用于解析POST请求的请求体 // 中间件用于解析POST请求的请求体
app.use(express.urlencoded({extended: true, limit: "500mb"})); app.use(express.urlencoded({extended: true, limit: "500mb"}));
app.use(bodyParser({limit: '500mb'})) app.use(express.json({
app.use(express.json()); limit: '500mb',
verify: (req: any, res: any, buf: any, encoding: any) => {
req.rawBody = buf;
}
}));
app.use((req: any, res: any, next: any) => {
try {
req.body = JSONbig.parse(req.rawBody.toString());
next();
} catch (error) {
// next(error);
next();
}
});
function parseToOnebot12(action: PostDataAction) { function parseToOnebot12(action: PostDataAction) {
app.post('/' + action, (req: any, res: any) => { app.post('/' + action, (req: any, res: any) => {
let jsonData: PostDataSendMsg = req.body; let jsonData: PostDataSendMsg = req.body;
jsonData.action = action jsonData.action = action
let resData = handlePost(jsonData) let resData = handlePost(jsonData, (data: SendMsgResult) => {
res.send(resData) res.send(data)
})
if (resData) {
res.send(resData)
}
}); });
} }
@@ -170,8 +190,12 @@ export function startExpress(port: number) {
// 处理POST请求的路由 // 处理POST请求的路由
app.post('/', (req: any, res: any) => { app.post('/', (req: any, res: any) => {
let jsonData: PostDataSendMsg = req.body; let jsonData: PostDataSendMsg = req.body;
let resData = handlePost(jsonData) let resData = handlePost(jsonData, (data: SendMsgResult) => {
res.send(resData) res.send(data)
})
if (resData) {
res.send(resData)
}
}); });
app.post('/send_msg', (req: any, res: any) => { app.post('/send_msg', (req: any, res: any) => {
let jsonData: PostDataSendMsg = req.body; let jsonData: PostDataSendMsg = req.body;
@@ -186,11 +210,15 @@ export function startExpress(port: number) {
jsonData.action = "send_private_msg" jsonData.action = "send_private_msg"
} }
} }
let resData = handlePost(jsonData) let resData = handlePost(jsonData, (data: SendMsgResult) => {
res.send(resData) res.send(data)
})
if (resData) {
res.send(resData)
}
}) })
app.listen(port, "0.0.0.0", () => { 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 {ipcMain, webContents} from 'electron'; import {ipcMain, webContents} from 'electron';
import {PostDataSendMsg} from "../common/types"; import {PostDataSendMsg, SendMsgResult} from "../common/types";
import {CHANNEL_RECALL_MSG, CHANNEL_SEND_MSG} from "../common/IPCChannel"; 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) { function sendIPCMsg(channel: string, data: any) {
let contents = webContents.getAllWebContents(); let contents = webContents.getAllWebContents();
@@ -8,15 +10,26 @@ function sendIPCMsg(channel: string, data: any) {
try { try {
content.send(channel, data) content.send(channel, data)
} catch (e) { } 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); sendIPCMsg(CHANNEL_SEND_MSG, postData);
} }
export function sendIPCRecallQQMsg(message_id: string) { export function sendIPCRecallQQMsg(message_id: string) {
sendIPCMsg(CHANNEL_RECALL_MSG, {message_id}); sendIPCMsg(CHANNEL_RECALL_MSG, {message_id: message_id});
} }

View File

@@ -2,6 +2,7 @@
import * as path from "path"; import * as path from "path";
import {ipcMain} from 'electron'; import {ipcMain} from 'electron';
import * as util from 'util';
import {Config, Group, SelfInfo, User} from "../common/types"; import {Config, Group, SelfInfo, User} from "../common/types";
import { import {
@@ -13,48 +14,90 @@ import {
CHANNEL_SET_CONFIG, CHANNEL_SET_CONFIG,
CHANNEL_START_HTTP_SERVER, CHANNEL_START_HTTP_SERVER,
CHANNEL_UPDATE_FRIENDS, CHANNEL_UPDATE_FRIENDS,
CHANNEL_UPDATE_GROUPS, CHANNEL_DELETE_FILE CHANNEL_UPDATE_GROUPS, CHANNEL_DELETE_FILE, CHANNEL_GET_RUNNING_STATUS, CHANNEL_FILE2BASE64
} from "../common/IPCChannel"; } from "../common/IPCChannel";
import {ConfigUtil} from "./config"; import {ConfigUtil} from "./config";
import {startExpress} from "./HttpServer"; import {startExpress} from "./HttpServer";
import {log} from "./utils"; import {checkFileReceived, CONFIG_DIR, getConfigUtil, isGIF, log} from "./utils";
import {friends, groups, selfInfo} from "./data"; import {friends, groups, selfInfo} from "./data";
import {} from "../global";
const fs = require('fs'); const fs = require('fs');
let running = false;
// 加载插件时触发 // 加载插件时触发
function onLoad(plugin: any) { function onLoad() {
log("main onLoaded");
function getConfigUtil() { // const config_dir = browserWindow.LiteLoader.plugins["LLOneBot"].path.data;
const configFilePath = path.join(plugin.path.data, `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) => { ipcMain.handle(CHANNEL_GET_CONFIG, (event: any, arg: any) => {
return getConfigUtil().getConfig() return getConfigUtil().getConfig()
}) })
ipcMain.handle(CHANNEL_DOWNLOAD_FILE, async (event: any, arg: {uri: string, localFilePath: string}) => { 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); let url = new URL(arg.uri);
if (url.protocol == "base64:"){ if (url.protocol == "base64:") {
// base64转成文件 // base64转成文件
let base64Data = arg.uri.split("base64://")[1] let base64Data = arg.uri.split("base64://")[1]
const buffer = Buffer.from(base64Data, 'base64'); try {
const buffer = Buffer.from(base64Data, 'base64');
fs.writeFileSync(arg.localFilePath, buffer); fs.writeFileSync(filePath, buffer);
} } catch (e: any) {
else if (url.protocol == "http:" || url.protocol == "https:") { return {
success: false,
errMsg: `base64文件下载失败,` + e.toString(),
path: ""
}
}
} else if (url.protocol == "http:" || url.protocol == "https:") {
// 下载文件 // 下载文件
let res = await fetch(url) let res = await fetch(url)
if (!res.ok) {
return {
success: false,
errMsg: `${url}下载失败,` + res.statusText,
path: ""
}
}
let blob = await res.blob(); let blob = await res.blob();
let buffer = await blob.arrayBuffer(); let buffer = await blob.arrayBuffer();
fs.writeFileSync(arg.localFilePath, Buffer.from(buffer)); try {
fs.writeFileSync(filePath, Buffer.from(buffer));
} catch (e: any) {
return {
success: false,
errMsg: `${url}下载失败,` + e.toString(),
path: ""
}
}
} }
// todo: 需要识别gif格式 else{
return arg.localFilePath; 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) => { ipcMain.on(CHANNEL_SET_CONFIG, (event: any, arg: Config) => {
getConfigUtil().setConfig(arg) getConfigUtil().setConfig(arg)
@@ -95,7 +138,7 @@ function onLoad(plugin: any) {
}) })
ipcMain.on(CHANNEL_POST_ONEBOT_DATA, (event: any, arg: any) => { ipcMain.on(CHANNEL_POST_ONEBOT_DATA, (event: any, arg: any) => {
for(const host of getConfigUtil().getConfig().hosts) { for (const host of getConfigUtil().getConfig().hosts) {
try { try {
fetch(host, { fetch(host, {
method: "POST", method: "POST",
@@ -105,9 +148,9 @@ function onLoad(plugin: any) {
}, },
body: JSON.stringify(arg) body: JSON.stringify(arg)
}).then((res: any) => { }).then((res: any) => {
log("新消息事件上传"); log(`新消息事件上传成功: ${host} ` + JSON.stringify(arg));
}, (err: any) => { }, (err: any) => {
log("新消息事件上传失败:" + err + JSON.stringify(arg)); log(`新消息事件上传失败: ${host} ` + err + JSON.stringify(arg));
}); });
} catch (e: any) { } catch (e: any) {
log(e.toString()) log(e.toString())
@@ -122,6 +165,7 @@ function onLoad(plugin: any) {
ipcMain.handle(CHANNEL_SET_SELF_INFO, (event: any, arg: SelfInfo) => { ipcMain.handle(CHANNEL_SET_SELF_INFO, (event: any, arg: SelfInfo) => {
selfInfo.user_id = arg.user_id; selfInfo.user_id = arg.user_id;
selfInfo.nickname = arg.nickname; selfInfo.nickname = arg.nickname;
running = true;
}) })
ipcMain.on(CHANNEL_DELETE_FILE, (event: any, arg: string[]) => { ipcMain.on(CHANNEL_DELETE_FILE, (event: any, arg: string[]) => {
@@ -129,16 +173,51 @@ function onLoad(plugin: any) {
fs.unlinkSync(path); fs.unlinkSync(path);
} }
}) })
ipcMain.handle(CHANNEL_GET_RUNNING_STATUS, (event: any, arg: any) => {
return running;
})
ipcMain.handle(CHANNEL_FILE2BASE64, async (event: any, path: string): Promise<{err: string, data: 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;
})
} }
// 创建窗口时触发 // 创建窗口时触发
function onBrowserWindowCreated(window: any, plugin: any) { function onBrowserWindowCreated(window: any) {
} }
try {
onLoad();
} catch (e: any) {
console.log(e.toString())
}
// 这两个函数都是可选的 // 这两个函数都是可选的
export { export {
onLoad, onBrowserWindowCreated onBrowserWindowCreated
} }

View File

@@ -1,8 +1,57 @@
import * as path from "path";
import {json} from "express";
import {selfInfo} from "./data";
import {ConfigUtil} from "./config";
const fs = require('fs'); 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.user_id}.json`)
return new ConfigUtil(configFilePath)
}
export function log(msg: any) { export function log(msg: any) {
if (!getConfigUtil().getConfig().log){
return
}
let currentDateTime = new Date().toLocaleString(); 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'
}
// 定义一个异步函数来检查文件是否存在
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();
});
}

View File

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

View File

@@ -2,14 +2,33 @@
// import express from "express"; // import express from "express";
// const { ipcRenderer } = require('electron'); // const { ipcRenderer } = require('electron');
import {AtType, Group, MessageElement, OnebotGroupMemberRole, Peer, PostDataSendMsg, User} from "./common/types"; import {
import * as stream from "stream"; AtType,
ChatType,
Group,
MessageElement, MessageType,
OnebotGroupMemberRole,
Peer,
PostDataSendMsg,
SendMsgResult,
User
} from "./common/types";
import {checkFileReceived} from "./main/utils";
let self_qq: string = "" let self_qq: string = ""
let groups: Group[] = [] let groups: Group[] = []
let friends: User[] = [] let friends: User[] = []
let msgHistory: MessageElement[] = [] let msgHistory: MessageElement[] = []
let uid_maps: Record<string, User> = {} // 一串加密的字符串 -> qq号 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> { async function getUserInfo(uid: string): Promise<User> {
let user = uid_maps[uid] let user = uid_maps[uid]
if (!user) { if (!user) {
@@ -79,6 +98,11 @@ async function getGroupMembers(group_qq: string, forced: boolean = false) {
if (!group!.members!.find(m => m.uid == member.uid)) { if (!group!.members!.find(m => m.uid == member.uid)) {
group!.members!.push(member) group!.members!.push(member)
} }
uid_maps[member.uid] = {
uin: member.uin,
uid: member.uid,
nickName: member.nick
};
} }
window.llonebot.updateGroups(groups) window.llonebot.updateGroups(groups)
console.log(`更新群${group.name}成员列表`, group) console.log(`更新群${group.name}成员列表`, group)
@@ -99,8 +123,9 @@ async function getGroupMember(group_qq: string, member_uid: string) {
} }
} }
async function handleNewMessage(messages: MessageElement[]) { async function handleNewMessage(messages: MessageElement[]) {
console.log("llonebot 收到消息:", messages);
const {debug, enableBase64} = await window.llonebot.getConfig();
for (let message of messages) { for (let message of messages) {
let onebot_message_data: any = { let onebot_message_data: any = {
self: { self: {
@@ -108,18 +133,24 @@ async function handleNewMessage(messages: MessageElement[]) {
user_id: self_qq user_id: self_qq
}, },
self_id: self_qq, self_id: self_qq,
time: 0, time: parseInt(message.raw.msgTime || "0"),
type: "message", type: "message",
post_type: "message", post_type: "message",
message_type: message.peer.chatType, message_type: message.peer.chatType,
detail_type: message.peer.chatType, detail_type: message.peer.chatType,
message_id: message.raw.msgId, message_id: message.raw.msgId,
sub_type: "", sub_type: "",
message: [] message: [],
raw_message: "",
font: 14
} }
if (message.peer.chatType == "group") { if (debug) {
onebot_message_data.raw = JSON.parse(JSON.stringify(message))
}
if (message.raw.chatType == ChatType.group) {
let group_id = message.peer.uid let group_id = message.peer.uid
let group = (await getGroup(group_id))! let group = (await getGroup(group_id))!
onebot_message_data.detail_type = onebot_message_data.message_type = onebot_message_data.sub_type = "group"
onebot_message_data["group_id"] = message.peer.uid onebot_message_data["group_id"] = message.peer.uid
let groupMember = await getGroupMember(group_id, message.sender.uid) let groupMember = await getGroupMember(group_id, message.sender.uid)
onebot_message_data["user_id"] = groupMember!.uin onebot_message_data["user_id"] = groupMember!.uin
@@ -129,24 +160,38 @@ async function handleNewMessage(messages: MessageElement[]) {
card: groupMember!.cardName, card: groupMember!.cardName,
role: OnebotGroupMemberRole[groupMember!.role] role: OnebotGroupMemberRole[groupMember!.role]
} }
console.log("收到群消息", onebot_message_data) // console.log("收到群消息", onebot_message_data)
} else if (message.peer.chatType == "private") { } else if (message.raw.chatType == ChatType.friend) {
onebot_message_data["user_id"] = message.peer.uid onebot_message_data["user_id"] = message.raw.senderUin;
let friend = await getFriend(message.sender.uid) onebot_message_data.detail_type = onebot_message_data.message_type = "private"
onebot_message_data.sub_type = "friend"
let friend = await getFriend(message.raw.senderUin);
onebot_message_data.sender = { onebot_message_data.sender = {
user_id: friend!.uin, user_id: friend!.uin,
nickname: friend!.nickName 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.detail_type = onebot_message_data.message_type = "private"
onebot_message_data.sub_type = "group";
onebot_message_data.sender = {
user_id: senderQQ,
nickname: sender.nickName
}
} }
for (let element of message.raw.elements) { for (let element of message.raw.elements) {
let message_data: any = { let message_data: any = {
data: {}, data: {},
type: "unknown" type: "unknown"
} }
if (element.textElement?.atType == AtType.atUser) { if (element.textElement && element.textElement?.atType !== AtType.notAt) {
message_data["type"] = "at" message_data["type"] = "at"
if (element.textElement.atUid != "0") { if (element.textElement.atType == AtType.atAll) {
message_data["data"]["mention"] = element.textElement.atUid message_data["data"]["mention"] = "all"
message_data["data"]["qq"] = "all"
} else { } else {
let uid = element.textElement.atNtUid let uid = element.textElement.atNtUid
let atMember = await getGroupMember(message.peer.uid, uid) let atMember = await getGroupMember(message.peer.uid, uid)
@@ -160,16 +205,43 @@ async function handleNewMessage(messages: MessageElement[]) {
message_data["type"] = "image" message_data["type"] = "image"
message_data["data"]["file_id"] = element.picElement.fileUuid message_data["data"]["file_id"] = element.picElement.fileUuid
message_data["data"]["path"] = element.picElement.sourcePath message_data["data"]["path"] = element.picElement.sourcePath
let startS = "file://" message_data["data"]["file"] = element.picElement.sourcePath
if (!element.picElement.sourcePath.startsWith("/")) {
startS += "/"
}
message_data["data"]["file"] = startS + element.picElement.sourcePath
} else if (element.replyElement) { } else if (element.replyElement) {
message_data["type"] = "reply" message_data["type"] = "reply"
message_data["data"]["id"] = msgHistory.find(msg => msg.raw.msgSeq == element.replyElement.replayMsgSeq)?.raw.msgId message_data["data"]["id"] = msgHistory.find(msg => msg.raw.msgSeq == element.replyElement.replayMsgSeq)?.raw.msgId
} else if (element.pttElement) {
message_data["type"] = MessageType.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"] = MessageType.json;
message_data["data"]["data"] = element.arkElement.bytesData;
} }
onebot_message_data.message.push(message_data) if (message_data.data.file) {
let filePath: string = message_data.data.file;
message_data.data.file = "file://" + filePath
if (enableBase64) {
// filePath = filePath.replace("\\Ori\\", "\\Thumb\\")
let {err, data} = await window.llonebot.file2base64(filePath);
if (err) {
console.log("文件转base64失败", err)
} else {
message_data.data.file = "base64://" + data
}
}
}
if (message_data.type !== "unknown"){
onebot_message_data.message.push(message_data);
}
}
if (msgHistory.length > 10000) {
msgHistory.splice(0, 100)
} }
msgHistory.push(message) msgHistory.push(message)
console.log("发送上传消息给ipc main", onebot_message_data) console.log("发送上传消息给ipc main", onebot_message_data)
@@ -178,6 +250,13 @@ async function handleNewMessage(messages: MessageElement[]) {
} }
async function listenSendMessage(postData: PostDataSendMsg) { 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") { if (postData.action == "send_private_msg" || postData.action == "send_group_msg") {
let peer: Peer | null = null; let peer: Peer | null = null;
if (!postData.params) { if (!postData.params) {
@@ -190,22 +269,41 @@ async function listenSendMessage(postData: PostDataSendMsg) {
if (postData.action == "send_private_msg") { if (postData.action == "send_private_msg") {
let friend = await getFriend(postData.params.user_id) let friend = await getFriend(postData.params.user_id)
if (friend) { if (friend) {
console.log("好友消息", postData)
peer = { peer = {
chatType: "private", chatType: ChatType.friend,
name: friend.nickName, name: friend.nickName,
uid: friend.uid 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") { } else if (postData.action == "send_group_msg") {
let group = await getGroup(postData.params.group_id) let group = await getGroup(postData.params.group_id)
if (group) { if (group) {
peer = { peer = {
chatType: "group", chatType: ChatType.group,
name: group.name, name: group.name,
uid: group.uid uid: group.uid
} }
} else { } else {
sendMsgResult.status = -1;
sendMsgResult.retcode = -1;
sendMsgResult.message = `发送失败,未找到群${postData.params.group_id}`;
console.log("未找到群, 发送群消息失败", postData) console.log("未找到群, 发送群消息失败", postData)
} }
} }
@@ -217,30 +315,50 @@ async function listenSendMessage(postData: PostDataSendMsg) {
message.type = "text" message.type = "text"
message.atType = AtType.atUser message.atType = AtType.atUser
let atUid = message.data?.qq || message.atUid let atUid = message.data?.qq || message.atUid
let group = await getGroup(postData.params.group_id) if (atUid == "all") {
let atMember = group.members.find(member => member.uin == atUid) message.atType = AtType.atAll
message.atNtUid = atMember.uid atUid = "0";
message.atUid = atUid message.content = `@全体成员`
message.content = `@${atMember.cardName || atMember.nick}` }
else {
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") { } else if (message.type == "text") {
message.content = message.data?.text || message.content message.content = message.data?.text || message.content
} else if (message.type == "image" || message.type == "voice") { } else if (message.type == "image" || message.type == "voice" || message.type == "record") {
// todo: 收到的应该是uri格式的需要转成本地的, uri格式有三种http, file, base64 // 收到的是uri格式的需要转成本地的, uri格式有三种http, file, base64
let url = message.data?.file || message.file let url = message.data?.file || message.file
let uri = new URL(url); let uri = new URL(url);
let ext: string; let ext: string;
if (message.type == "image") { if (message.type == "image") {
// todo: 需要识别gif格式
ext = ".png" ext = ".png"
} }
if (message.type == "voice") { if (message.type == "voice" || message.type == "record") {
message.type = "voice"
ext = ".amr" ext = ".amr"
} }
let localFilePath = `${Date.now()}${ext}` let localFilePath = `${Date.now()}${ext}`
if (uri.protocol == "file:") { if (uri.protocol == "file:") {
localFilePath = url.split("file://")[1] localFilePath = url.split("file://")[1]
} else { } else {
await window.llonebot.downloadFile({uri: url, localFilePath: localFilePath}) 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 message.file = localFilePath
sendFiles.push(localFilePath); sendFiles.push(localFilePath);
@@ -252,11 +370,27 @@ async function listenSendMessage(postData: PostDataSendMsg) {
} }
} }
console.log("发送消息", postData) console.log("发送消息", postData)
if (sendMsgResult.status !== 0) {
window.llonebot.sendSendMsgResult(postData.ipc_uuid, sendMsgResult)
return;
}
window.LLAPI.sendMessage(peer, postData.params.message).then(res => { window.LLAPI.sendMessage(peer, postData.params.message).then(res => {
console.log("消息发送成功:", peer, postData.params.message) console.log("消息发送成功:", peer, postData.params.message)
window.llonebot.deleteFile(sendFiles); if (sendFiles.length) {
window.llonebot.deleteFile(sendFiles);
}
window.llonebot.sendSendMsgResult(postData.ipc_uuid, sendMsgResult)
}, },
err => console.log("消息发送失败", postData, err)) 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)
} }
} }
} }
@@ -268,182 +402,251 @@ function recallMessage(msgId: string) {
let chatListEle: HTMLCollectionOf<Element> let chatListEle: HTMLCollectionOf<Element>
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 {
window.llonebot.log("全部群成员获取完毕")
}
}
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)
}
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() { function onLoad() {
window.llonebot.log("llonebot render onLoad");
window.llonebot.listenSendMessage((postData: PostDataSendMsg) => { window.llonebot.getRunningStatus().then(running => {
listenSendMessage(postData).then().catch(err => console.log("listenSendMessage err", err)) if (running) {
}) return;
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) { initAccountInfo().then(
console.log("获取群成员列表失败,重试", failedGroups.map(group => group.name)) (initSuccess) => {
setTimeout(() => { if (!initSuccess) {
getGroupsMembers(failedGroups).then() return;
}, 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)
} }
} if (friends.length == 0) {
getFriends().then(() => {
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()
}
})
}); });
}); }
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.llonebot.listenSendMessage((postData: PostDataSendMsg) => {
const config = {attributes: true, childList: true, subtree: true}; listenSendMessage(postData).then().catch(err => console.log("listenSendMessage err", err))
})
// 传入目标节点和观察选项 window.llonebot.listenRecallMessage((arg: { message_id: string }) => {
observer.observe(targetNode, config); // console.log("listenRecallMessage", arg)
recallMessage(arg.message_id)
} catch (e) { })
window.llonebot.log(e) 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, false).then()
// }
// })
// });
// });
//
// // 配置观察选项
// const config = {attributes: true, childList: true, subtree: true};
//
// // 传入目标节点和观察选项
// observer.observe(targetNode, config);
//
// } catch (e) {
// window.llonebot.log(e)
// }
// }
// }
//
// // getChatListEle();
} }
} );
} });
// getChatListEle();
} }
// 打开设置界面时触发 // 打开设置界面时触发
async function onConfigView(view: any) { async function onSettingWindowCreated(view: Element) {
const {port, hosts} = await window.llonebot.getConfig() window.llonebot.log("setting window created");
let config = await window.llonebot.getConfig()
function creatHostEleStr(host: string) { function creatHostEleStr(host: string) {
let eleStr = ` let eleStr = `
<div class="hostItem vertical-list-item"> <setting-item data-direction="row" class="hostItem vertical-list-item">
<h2>事件上报地址(http)</h2> <h2>事件上报地址(http)</h2>
<input class="host" type="text" value="${host}" <input class="host input-text" type="text" value="${host}"
style="width:60%;padding: 5px" style="width:60%;padding: 5px"
placeholder="不支持localhost,如果是本机请填写局域网ip"/> placeholder="如果localhost上报失败试试局域网ip"/>
</div> </setting-item>
` `
return eleStr return eleStr
} }
let hostsEleStr = "" let hostsEleStr = ""
for (const host of hosts) { for (const host of config.hosts) {
hostsEleStr += creatHostEleStr(host); hostsEleStr += creatHostEleStr(host);
} }
const html = ` let html = `
<section class="wrap"> <div class="config_view llonebot">
<div class="vertical-list-item"> <setting-section>
<h2>监听端口</h2> <setting-panel>
<input id="port" type="number" value="${port}"/> <setting-list class="wrap">
</div> <setting-item class="vertical-list-item" data-direction="row">
<div> <setting-text>监听端口</setting-text>
<button id="addHost" class="q-button">添加上报地址</button> <input id="port" type="number" value="${config.port}"/>
</div> </setting-item>
<div id="hostItems"> <div>
${hostsEleStr} <button id="addHost" class="q-button">添加上报地址</button>
</div> </div>
<button id="save" class="q-button">保存(监听端口重启QQ后生效)</button> <div id="hostItems">
</section> ${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">日志目录:${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(); const parser = new DOMParser();
@@ -452,7 +655,7 @@ async function onConfigView(view: any) {
function addHostEle(initValue: string = "") { function addHostEle(initValue: string = "") {
let addressDoc = parser.parseFromString(creatHostEleStr(initValue), "text/html"); let addressDoc = parser.parseFromString(creatHostEleStr(initValue), "text/html");
let addressEle = addressDoc.querySelector("div") let addressEle = addressDoc.querySelector("setting-item")
let hostItemsEle = document.getElementById("hostItems"); let hostItemsEle = document.getElementById("hostItems");
hostItemsEle.appendChild(addressEle); hostItemsEle.appendChild(addressEle);
} }
@@ -460,6 +663,24 @@ async function onConfigView(view: any) {
doc.getElementById("addHost").addEventListener("click", () => addHostEle()) 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("log", "log");
doc.getElementById("save")?.addEventListener("click", doc.getElementById("save")?.addEventListener("click",
() => { () => {
const portEle: HTMLInputElement = document.getElementById("port") as HTMLInputElement const portEle: HTMLInputElement = document.getElementById("port") as HTMLInputElement
@@ -474,18 +695,22 @@ async function onConfigView(view: any) {
hosts.push(hostEle.value); hosts.push(hostEle.value);
} }
} }
window.llonebot.setConfig({ config.port = parseInt(port);
port: parseInt(port), config.hosts = hosts;
hosts: hosts window.llonebot.setConfig(config);
})
alert("保存成功"); alert("保存成功");
}) })
doc.querySelectorAll("section").forEach((node) => view.appendChild(node));
doc.body.childNodes.forEach(node => {
view.appendChild(node);
});
} }
setTimeout(onLoad, 5000)
export { export {
onLoad, onSettingWindowCreated
onConfigView
} }