Merge branch 'dev'

# Conflicts:
#	src/renderer.ts
This commit is contained in:
linyuchen
2024-01-31 11:33:41 +08:00
12 changed files with 420 additions and 157 deletions

View File

@@ -7,7 +7,7 @@
## 安装方法 ## 安装方法
1.安装[NTQQLiteLoader](https://liteloaderqqnt.github.io/guide/install.html) 1.安装[LiteLoaderQQNT](https://liteloaderqqnt.github.io/guide/install.html)
2.安装修改后的[LiteLoaderQQNT-Plugin-LLAPI](https://github.com/linyuchen/LiteLoaderQQNT-Plugin-LLAPI/releases),原版的功能有缺陷 2.安装修改后的[LiteLoaderQQNT-Plugin-LLAPI](https://github.com/linyuchen/LiteLoaderQQNT-Plugin-LLAPI/releases),原版的功能有缺陷
@@ -21,13 +21,16 @@
目前只支持http协议POST方法不支持websocket事件上报也是http协议 目前只支持http协议POST方法不支持websocket事件上报也是http协议
主要功能:
- [x] 发送好友消息
- [x] 发送临时消息
- [x] 发送群消息
- [x] 获取好友列表
- [x] 获取群列表 - [x] 获取群列表
- [x] 获取群成员列表 - [x] 获取群成员列表
- [x] 获取好友列表
- [x] 发送群消息
- [x] 发送好友消息
- [x] 撤回消息 - [x] 撤回消息
- [x] 上报好友消息 - [x] 上报好友消息
- [x] 上报临时消息
- [x] 上报群消息 - [x] 上报群消息
消息格式支持: 消息格式支持:
@@ -58,5 +61,70 @@
*暂时不支持`"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/>
小概率事件有可能是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文档 ## onebot11文档
<https://11.onebot.dev/> <https://11.onebot.dev/>

View File

@@ -4,20 +4,20 @@
"name": "LLOneBot", "name": "LLOneBot",
"slug": "LLOneBot", "slug": "LLOneBot",
"description": "LiteLoaderQQNT的OneBotApi", "description": "LiteLoaderQQNT的OneBotApi",
"version": "2.0.4", "version": "2.1.0",
"thumbnail": "./icon.png", "thumbnail": "./icon.png",
"authors": [{ "authors": [{
"name": "linyuchen", "name": "linyuchen",
"link": "https://github.com/linyuchen" "link": "https://github.com/linyuchen"
}], }],
"repository": { "repository": {
"repo": "linyuchen/LiteLoaderQQNT-OneBotApi", "repo": "linyuchen/LiteLoaderQQNT-OneBotApi",
"branch": "main", "branch": "main",
"release": { "release": {
"tag": "latest", "tag": "latest",
"name": "LLOneBot.zip" "name": "LLOneBot.zip"
} }
}, },
"platform": [ "platform": [
"win32", "win32",
"linux", "linux",

15
package-lock.json generated
View File

@@ -9,7 +9,8 @@
"version": "1.0.0", "version": "1.0.0",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"express": "^4.18.2" "express": "^4.18.2",
"uuid": "^9.0.1"
}, },
"devDependencies": { "devDependencies": {
"@babel/preset-env": "^7.23.2", "@babel/preset-env": "^7.23.2",
@@ -5213,6 +5214,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,17 @@
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"express": "^4.18.2" "express": "^4.18.2",
"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

@@ -3,6 +3,12 @@ export enum AtType {
atUser = 2 atUser = 2
} }
export enum ChatType {
friend = 1,
group = 2,
temp = 100
}
export type GroupMemberInfo = { export type GroupMemberInfo = {
avatarPath: string; avatarPath: string;
cardName: string; cardName: string;
@@ -44,7 +50,7 @@ export type Group = {
} }
export type Peer = { export type Peer = {
chatType: "private" | "group" | "friend" chatType: ChatType
name: string name: string
uid: string // qq号 uid: string // qq号
} }
@@ -52,8 +58,10 @@ export type Peer = {
export type MessageElement = { export type MessageElement = {
raw: { raw: {
msgId: string, msgId: string,
msgTime: string,
msgSeq: string, msgSeq: string,
senderUin: string; // 发送者QQ号 senderUin: string; // 发送者QQ号
chatType: ChatType,
elements: { elements: {
replyElement: { replyElement: {
senderUid: string, // 原消息发送者QQ号 senderUid: string, // 原消息发送者QQ号
@@ -139,7 +147,7 @@ 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 type PostDataSendMsg = {
action: PostDataAction action: PostDataAction
@@ -152,9 +160,17 @@ 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 type Config = {
port: number, port: number,
hosts: string[], hosts: string[],
} }
export type SendMsgResult = {
status: number,
retcode: number,
data: any,
message: string,
}

5
src/global.d.ts vendored
View File

@@ -6,7 +6,7 @@ import {
Peer, Peer,
PostDataSendMsg, PostDataSendMsg,
SelfInfo, SelfInfo,
SendMessage, SendMessage, SendMsgResult,
User User
} from "./common/types"; } from "./common/types";
@@ -43,9 +43,10 @@ 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>; getRunningStatus(): Promise<boolean>;
sendSendMsgResult(sessionId: string, msgResult: SendMsgResult): void;
}; };
declare global { declare global {

View File

@@ -2,7 +2,7 @@ import {log} from "./utils";
const express = require("express"); const express = require("express");
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
@@ -18,7 +18,7 @@ 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;
} }
@@ -45,7 +45,7 @@ function checkSendMessage(sendMsgList: SendMessage[]) {
} }
// ==end== // ==end==
function handlePost(jsonData: any) { function handlePost(jsonData: any, handleSendResult: (data: SendMsgResult)=>void) {
log("API receive post:" + JSON.stringify(jsonData)) log("API receive post:" + JSON.stringify(jsonData))
if (!jsonData.params) { if (!jsonData.params) {
jsonData.params = JSON.parse(JSON.stringify(jsonData)); jsonData.params = JSON.parse(JSON.stringify(jsonData));
@@ -57,6 +57,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") {
@@ -70,7 +71,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;
@@ -151,8 +153,10 @@ export function startExpress(port: number) {
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(data)})
res.send(resData) if (resData){
res.send(resData)
}
}); });
} }
@@ -171,8 +175,10 @@ 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(data)})
res.send(resData) 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;
@@ -187,11 +193,13 @@ 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(data)})
res.send(resData) 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();
@@ -14,7 +16,17 @@ function sendIPCMsg(channel: string, data: any) {
} }
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);
} }

View File

@@ -17,7 +17,7 @@ import {
} from "../common/IPCChannel"; } from "../common/IPCChannel";
import {ConfigUtil} from "./config"; import {ConfigUtil} from "./config";
import {startExpress} from "./HttpServer"; import {startExpress} from "./HttpServer";
import {isGIF, log} from "./utils"; import {CONFIG_DIR, isGIF, log} from "./utils";
import {friends, groups, selfInfo} from "./data"; import {friends, groups, selfInfo} from "./data";
import {} from "../global"; import {} from "../global";
@@ -29,40 +29,78 @@ let running = false;
// 加载插件时触发 // 加载插件时触发
function onLoad() { function onLoad() {
log("main onLoaded"); log("main onLoaded");
// const config_dir = browserWindow.LiteLoader.plugins["LLOneBot"].path.data; // const config_dir = browserWindow.LiteLoader.plugins["LLOneBot"].path.data;
const config_dir = global.LiteLoader.plugins["LLOneBot"].path.data;
function getConfigUtil() { function getConfigUtil() {
const configFilePath = path.join(config_dir, `config_${selfInfo.user_id}.json`) const configFilePath = path.join(CONFIG_DIR, `config_${selfInfo.user_id}.json`)
return new ConfigUtil(configFilePath) return new ConfigUtil(configFilePath)
} }
if (!fs.existsSync(config_dir)) { if (!fs.existsSync(CONFIG_DIR)) {
fs.mkdirSync(config_dir, {recursive: true}); 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: ""
}
}
} }
if (isGIF(arg.localFilePath)) { else{
fs.renameSync(arg.localFilePath, arg.localFilePath + ".gif"); return {
arg.localFilePath += ".gif"; success: false,
errMsg: `不支持的file协议,` + url.protocol,
path: ""
}
} }
return arg.localFilePath; 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)
@@ -103,7 +141,7 @@ function onLoad() {
}) })
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",
@@ -113,9 +151,9 @@ function onLoad() {
}, },
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())

View File

@@ -1,8 +1,19 @@
import * as path from "path";
import {json} from "express";
import {selfInfo} from "./data";
const fs = require('fs'); const fs = require('fs');
export const CONFIG_DIR = global.LiteLoader.plugins["LLOneBot"].path.data;
export function log(msg: any) { export function log(msg: any) {
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) => {
}) })
} }
@@ -13,4 +24,5 @@ export function isGIF(path: string) {
fs.readSync(fd, buffer, 0, 4, 0); fs.readSync(fd, buffer, 0, 4, 0);
fs.closeSync(fd); fs.closeSync(fd);
return buffer.toString() === 'GIF8' return buffer.toString() === 'GIF8'
} }

View File

@@ -1,6 +1,6 @@
// 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_GET_CONFIG,
@@ -33,6 +33,9 @@ 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.send(CHANNEL_LOG, "发送消息API已注册");
ipcRenderer.on(CHANNEL_SEND_MSG, (event: any, args: PostDataSendMsg) => { ipcRenderer.on(CHANNEL_SEND_MSG, (event: any, args: PostDataSendMsg) => {

View File

@@ -2,15 +2,31 @@
// 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,
import {raw} from "express"; ChatType,
Group,
MessageElement,
OnebotGroupMemberRole,
Peer,
PostDataSendMsg, SendMsgResult,
User
} from "./common/types";
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) {
@@ -80,6 +96,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)
@@ -100,9 +121,8 @@ async function getGroupMember(group_qq: string, member_uid: string) {
} }
} }
async function handleNewMessage(messages: MessageElement[]) { async function handleNewMessage(messages: MessageElement[]) {
// console.log("llonebot 收到消息:", messages); console.log("llonebot 收到消息:", messages);
for (let message of messages) { for (let message of messages) {
let onebot_message_data: any = { let onebot_message_data: any = {
self: { self: {
@@ -110,7 +130,7 @@ 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,
@@ -121,9 +141,10 @@ async function handleNewMessage(messages: MessageElement[]) {
raw_message: "", raw_message: "",
font: 14 font: 14
} }
if (message.peer.chatType == "group") { 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.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
@@ -134,13 +155,25 @@ async function handleNewMessage(messages: MessageElement[]) {
role: OnebotGroupMemberRole[groupMember!.role] role: OnebotGroupMemberRole[groupMember!.role]
} }
// console.log("收到群消息", onebot_message_data) // console.log("收到群消息", onebot_message_data)
} else if (message.peer.chatType == "private" || message.peer.chatType == "friend") { } else if (message.raw.chatType == ChatType.friend) {
onebot_message_data["user_id"] = message.raw.senderUin; onebot_message_data["user_id"] = message.raw.senderUin;
let friend = await getFriend(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 = { 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.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) { for (let element of message.raw.elements) {
let message_data: any = { let message_data: any = {
@@ -168,6 +201,7 @@ async function handleNewMessage(messages: MessageElement[]) {
if (!element.picElement.sourcePath.startsWith("/")) { if (!element.picElement.sourcePath.startsWith("/")) {
startS += "/" startS += "/"
} }
// todo: 转成base64
message_data["data"]["file"] = startS + element.picElement.sourcePath message_data["data"]["file"] = startS + element.picElement.sourcePath
} else if (element.replyElement) { } else if (element.replyElement) {
message_data["type"] = "reply" message_data["type"] = "reply"
@@ -175,6 +209,9 @@ async function handleNewMessage(messages: MessageElement[]) {
} }
onebot_message_data.message.push(message_data) 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)
window.llonebot.postData(onebot_message_data); window.llonebot.postData(onebot_message_data);
@@ -183,6 +220,12 @@ async function handleNewMessage(messages: MessageElement[]) {
async function listenSendMessage(postData: PostDataSendMsg) { async function listenSendMessage(postData: PostDataSendMsg) {
console.log("收到发送消息请求", postData); 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) {
@@ -195,22 +238,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)
} }
} }
@@ -245,10 +307,23 @@ async function listenSendMessage(postData: PostDataSendMsg) {
if (uri.protocol == "file:") { if (uri.protocol == "file:") {
localFilePath = url.split("file://")[1] localFilePath = url.split("file://")[1]
} else { } else {
localFilePath = await window.llonebot.downloadFile({uri: url, localFilePath: localFilePath}) const {errMsg, path} = await window.llonebot.downloadFile({
sendFiles.push(localFilePath); 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);
} else if (message.type == "reply") { } else if (message.type == "reply") {
let msgId = message.data?.id || message.msgId let msgId = message.data?.id || message.msgId
let replyMessage = msgHistory.find(msg => msg.raw.msgId == msgId) let replyMessage = msgHistory.find(msg => msg.raw.msgId == msgId)
@@ -257,13 +332,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)
if (sendFiles.length) { if (sendFiles.length) {
window.llonebot.deleteFile(sendFiles); 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)
} }
} }
} }
@@ -308,7 +397,7 @@ function onNewMessages(messages: MessageElement[]) {
// console.log("chatListEle", chatListEle) // console.log("chatListEle", chatListEle)
} }
async function initAccountInfo(){ async function initAccountInfo() {
let accountInfo = await window.LLAPI.getAccountInfo(); let accountInfo = await window.LLAPI.getAccountInfo();
window.llonebot.log("getAccountInfo " + JSON.stringify(accountInfo)); window.llonebot.log("getAccountInfo " + JSON.stringify(accountInfo));
if (!accountInfo.uid) { if (!accountInfo.uid) {
@@ -325,21 +414,23 @@ async function initAccountInfo(){
function onLoad() { function onLoad() {
window.llonebot.log("llonebot render onLoad"); window.llonebot.log("llonebot render onLoad");
window.llonebot.getRunningStatus().then(running=>{ window.llonebot.getRunningStatus().then(running => {
if (running) { if (running) {
return; return;
} }
initAccountInfo().then( initAccountInfo().then(
(initSuccess)=>{ (initSuccess) => {
if (!initSuccess) { if (!initSuccess) {
return; return;
} }
if (friends.length == 0) { if (friends.length == 0) {
getFriends().then(()=>{}); getFriends().then(() => {
});
} }
if (groups.length == 0) { if (groups.length == 0) {
getGroups().then(()=>{ getGroups().then(() => {
getGroupsMembers(groups).then(()=>{}); getGroupsMembers(groups).then(() => {
});
}); });
} }
window.LLAPI.on("new-messages", onNewMessages); window.LLAPI.on("new-messages", onNewMessages);
@@ -354,93 +445,93 @@ function onLoad() {
recallMessage(arg.message_id) recallMessage(arg.message_id)
}) })
window.llonebot.log("llonebot loaded"); window.llonebot.log("llonebot loaded");
// window.LLAPI.add_qmenu((qContextMenu: Node) => { // window.LLAPI.add_qmenu((qContextMenu: Node) => {
// let btn = document.createElement("a") // let btn = document.createElement("a")
// btn.className = "q-context-menu-item q-context-menu-item--normal vue-component" // btn.className = "q-context-menu-item q-context-menu-item--normal vue-component"
// btn.setAttribute("aria-disabled", "false") // btn.setAttribute("aria-disabled", "false")
// btn.setAttribute("role", "menuitem") // btn.setAttribute("role", "menuitem")
// btn.setAttribute("tabindex", "-1") // btn.setAttribute("tabindex", "-1")
// btn.onclick = () => { // btn.onclick = () => {
// // window.LLAPI.getPeer().then(peer => { // // window.LLAPI.getPeer().then(peer => {
// // // console.log("current peer", peer) // // // console.log("current peer", peer)
// // if (peer && peer.chatType == "group") { // // if (peer && peer.chatType == "group") {
// // getGroupMembers(peer.uid, true).then(()=> { // // getGroupMembers(peer.uid, true).then(()=> {
// // console.log("获取群成员列表成功", groups); // // console.log("获取群成员列表成功", groups);
// // alert("获取群成员列表成功") // // alert("获取群成员列表成功")
// // }) // // })
// // } // // }
// // }) // // })
// async function func() { // async function func() {
// for (const group of groups) { // for (const group of groups) {
// await getGroupMembers(group.uid, true) // await getGroupMembers(group.uid, true)
// } // }
// } // }
// //
// func().then(() => { // func().then(() => {
// console.log("获取群成员列表结果", groups); // console.log("获取群成员列表结果", groups);
// // 找到members数量为空的群 // // 找到members数量为空的群
// groups.map(group => { // groups.map(group => {
// if (group.members.length == 0) { // if (group.members.length == 0) {
// console.log(`${group.name}群成员为空`) // console.log(`${group.name}群成员为空`)
// } // }
// }) // })
// window.llonebot.updateGroups(groups) // window.llonebot.updateGroups(groups)
// }) // })
// } // }
// btn.innerText = "获取群成员列表" // btn.innerText = "获取群成员列表"
// console.log(qContextMenu) // console.log(qContextMenu)
// // qContextMenu.appendChild(btn) // // qContextMenu.appendChild(btn)
// }) // })
// //
// window.LLAPI.on("context-msg-menu", (event, target, msgIds) => { // window.LLAPI.on("context-msg-menu", (event, target, msgIds) => {
// console.log("msg menu", event, target, msgIds); // console.log("msg menu", event, target, msgIds);
// }) // })
// //
// // console.log("getAccountInfo", LLAPI.getAccountInfo()); // // console.log("getAccountInfo", LLAPI.getAccountInfo());
// function getChatListEle() { // function getChatListEle() {
// chatListEle = document.getElementsByClassName("viewport-list__inner") // chatListEle = document.getElementsByClassName("viewport-list__inner")
// console.log("chatListEle", chatListEle) // console.log("chatListEle", chatListEle)
// if (chatListEle.length == 0) { // if (chatListEle.length == 0) {
// setTimeout(getChatListEle, 500) // setTimeout(getChatListEle, 500)
// } else { // } else {
// try { // try {
// // 选择要观察的目标节点 // // 选择要观察的目标节点
// const targetNode = chatListEle[0]; // const targetNode = chatListEle[0];
// //
// // 创建一个观察器实例并传入回调函数 // // 创建一个观察器实例并传入回调函数
// const observer = new MutationObserver(function (mutations) { // const observer = new MutationObserver(function (mutations) {
// mutations.forEach(function (mutation) { // mutations.forEach(function (mutation) {
// // console.log("chat list changed", mutation.type); // 输出 mutation 的类型 // // console.log("chat list changed", mutation.type); // 输出 mutation 的类型
// // 获得当前聊天窗口 // // 获得当前聊天窗口
// window.LLAPI.getPeer().then(peer => { // window.LLAPI.getPeer().then(peer => {
// // console.log("current peer", peer) // // console.log("current peer", peer)
// if (peer && peer.chatType == "group") { // if (peer && peer.chatType == "group") {
// getGroupMembers(peer.uid, false).then() // getGroupMembers(peer.uid, false).then()
// } // }
// }) // })
// }); // });
// }); // });
// //
// // 配置观察选项 // // 配置观察选项
// const config = {attributes: true, childList: true, subtree: true}; // const config = {attributes: true, childList: true, subtree: true};
// //
// // 传入目标节点和观察选项 // // 传入目标节点和观察选项
// observer.observe(targetNode, config); // observer.observe(targetNode, config);
// //
// } catch (e) { // } catch (e) {
// window.llonebot.log(e) // window.llonebot.log(e)
// } // }
// } // }
// } // }
// //
// // getChatListEle(); // // getChatListEle();
} }
); );
}); });
} }
// 打开设置界面时触发 // 打开设置界面时触发
async function onSettingWindowCreated (view: Element) { async function onSettingWindowCreated(view: Element) {
window.llonebot.log("setting window created"); window.llonebot.log("setting window created");
const {port, hosts} = await window.llonebot.getConfig() const {port, hosts} = await window.llonebot.getConfig()