feat: face msg

feat: recall notice
This commit is contained in:
linyuchen 2024-02-17 20:06:17 +08:00
parent ba387b40ca
commit 1a1d673c8c
11 changed files with 173 additions and 103 deletions

View File

@ -1,22 +1,16 @@
// 运行在 Electron 主进程 下的插件入口 // 运行在 Electron 主进程 下的插件入口
import * as path from "path";
import { BrowserWindow, ipcMain } from 'electron'; import { BrowserWindow, ipcMain } from 'electron';
import * as util from 'util';
import { Config } from "../common/types"; import { Config } from "../common/types";
import { import { CHANNEL_GET_CONFIG, CHANNEL_LOG, CHANNEL_SET_CONFIG, } from "../common/channels";
CHANNEL_GET_CONFIG,
CHANNEL_LOG,
CHANNEL_SET_CONFIG,
} from "../common/channels";
import { postMsg, setToken, startHTTPServer, startWSServer } from "../onebot11/server"; import { postMsg, setToken, startHTTPServer, startWSServer } from "../onebot11/server";
import { CONFIG_DIR, getConfigUtil, log } from "../common/utils"; import { CONFIG_DIR, getConfigUtil, log } from "../common/utils";
import { addHistoryMsg, msgHistory, selfInfo } from "../common/data"; import { addHistoryMsg, getGroupMember, msgHistory, selfInfo, uidMaps } from "../common/data";
import { hookNTQQApiReceive, ReceiveCmd, registerReceiveHook } from "../ntqqapi/hook"; import { hookNTQQApiReceive, ReceiveCmd, registerReceiveHook } from "../ntqqapi/hook";
import { OB11Constructor } from "../onebot11/constructor"; import { OB11Constructor } from "../onebot11/constructor";
import { NTQQApi } from "../ntqqapi/ntcall"; import { NTQQApi } from "../ntqqapi/ntcall";
import { Group, RawMessage, SelfInfo } from "../ntqqapi/types"; import { ChatType, RawMessage } from "../ntqqapi/types";
const fs = require('fs'); const fs = require('fs');
@ -39,13 +33,13 @@ function onLoad() {
ipcMain.on(CHANNEL_SET_CONFIG, (event: any, arg: Config) => { ipcMain.on(CHANNEL_SET_CONFIG, (event: any, arg: Config) => {
let oldConfig = getConfigUtil().getConfig(); let oldConfig = getConfigUtil().getConfig();
getConfigUtil().setConfig(arg) getConfigUtil().setConfig(arg)
if (arg.port != oldConfig.port){ if (arg.port != oldConfig.port) {
startHTTPServer(arg.port) startHTTPServer(arg.port)
} }
if (arg.wsPort != oldConfig.wsPort){ if (arg.wsPort != oldConfig.wsPort) {
startWSServer(arg.wsPort) startWSServer(arg.wsPort)
} }
if (arg.token != oldConfig.token){ if (arg.token != oldConfig.token) {
setToken(arg.token); setToken(arg.token);
} }
}) })
@ -58,6 +52,7 @@ function onLoad() {
function postRawMsg(msgList: RawMessage[]) { function postRawMsg(msgList: RawMessage[]) {
const {debug, reportSelfMessage} = getConfigUtil().getConfig(); const {debug, reportSelfMessage} = getConfigUtil().getConfig();
for (let message of msgList) { for (let message of msgList) {
log("收到新消息", message)
message.msgShortId = msgHistory[message.msgId]?.msgShortId message.msgShortId = msgHistory[message.msgId]?.msgShortId
if (!message.msgShortId) { if (!message.msgShortId) {
addHistoryMsg(message) addHistoryMsg(message)
@ -76,7 +71,7 @@ function onLoad() {
} }
function start() { async function start() {
registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.NEW_MSG, (payload) => { registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.NEW_MSG, (payload) => {
try { try {
// log("received msg length", payload.msgList.length); // log("received msg length", payload.msgList.length);
@ -85,7 +80,38 @@ function onLoad() {
log("report message error: ", e.toString()) log("report message error: ", e.toString())
} }
}) })
registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.UPDATE_MSG, async (payload) => {
for (const message of payload.msgList) {
// log("message update", message, message.sendStatus)
if (message.sendStatus === 2) {
// 撤回消息上报
const oriMessage = msgHistory[message.msgId]
if (!oriMessage) {
continue
}
if (message.chatType == ChatType.friend) {
const friendRecallEvent = OB11Constructor.friendRecallEvent(message.senderUin, oriMessage.msgShortId)
postMsg(friendRecallEvent)
} else if (message.chatType == ChatType.group) {
let operatorId = message.senderUin
for (const element of message.elements) {
const operatorUid = element.grayTipElement?.revokeElement.operatorUid
const operator = await getGroupMember(message.peerUin, null, operatorUid)
operatorId = operator.uin
}
const groupRecallEvent = OB11Constructor.groupRecallEvent(
message.peerUin,
message.senderUin,
operatorId,
oriMessage.msgShortId
)
postMsg(groupRecallEvent)
}
continue
}
addHistoryMsg(message)
}
})
registerReceiveHook<{ msgRecord: RawMessage }>(ReceiveCmd.SELF_SEND_MSG, (payload) => { registerReceiveHook<{ msgRecord: RawMessage }>(ReceiveCmd.SELF_SEND_MSG, (payload) => {
const {reportSelfMessage} = getConfigUtil().getConfig() const {reportSelfMessage} = getConfigUtil().getConfig()
if (!reportSelfMessage) { if (!reportSelfMessage) {
@ -128,9 +154,8 @@ function onLoad() {
log("get self nickname failed", e.toString()) log("get self nickname failed", e.toString())
return setTimeout(init, 1000) return setTimeout(init, 1000)
} }
start(); start().then();
} } else {
else{
setTimeout(init, 1000) setTimeout(init, 1000)
} }
} }

View File

@ -1,5 +1,13 @@
import {ElementType, SendPicElement, SendPttElement, SendReplyElement, SendTextElement, AtType} from "./types"; import {
import {NTQQApi} from "./ntcall"; ElementType,
SendPicElement,
SendPttElement,
SendReplyElement,
SendTextElement,
AtType,
SendFaceElement
} from "./types";
import { NTQQApi } from "./ntcall";
export class SendMsgElementConstructor { export class SendMsgElementConstructor {
@ -44,7 +52,7 @@ export class SendMsgElementConstructor {
} }
} }
static async pic(picPath: string): Promise<SendPicElement>{ static async pic(picPath: string): Promise<SendPicElement> {
const {md5, fileName, path, fileSize} = await NTQQApi.uploadFile(picPath); const {md5, fileName, path, fileSize} = await NTQQApi.uploadFile(picPath);
const imageSize = await NTQQApi.getImageSize(picPath); const imageSize = await NTQQApi.getImageSize(picPath);
const picElement = { const picElement = {
@ -70,7 +78,7 @@ export class SendMsgElementConstructor {
}; };
} }
static async ptt(pttPath: string):Promise<SendPttElement> { static async ptt(pttPath: string): Promise<SendPttElement> {
const {md5, fileName, path, fileSize} = await NTQQApi.uploadFile(pttPath); const {md5, fileName, path, fileSize} = await NTQQApi.uploadFile(pttPath);
return { return {
elementType: ElementType.PTT, elementType: ElementType.PTT,
@ -94,4 +102,15 @@ export class SendMsgElementConstructor {
} }
}; };
} }
static face(faceId: number): SendFaceElement {
return {
elementType: ElementType.FACE,
elementId: "",
faceElement: {
faceIndex: faceId,
faceType: 1
}
}
}
} }

View File

@ -34,14 +34,14 @@ interface NTQQApiReturnData<PayloadType = unknown> extends Array<any> {
let receiveHooks: Array<{ let receiveHooks: Array<{
method: ReceiveCmd, method: ReceiveCmd,
hookFunc: (payload: any) => void, hookFunc: ((payload: any) => void | Promise<void>)
id: string id: string
}> = [] }> = []
export function hookNTQQApiReceive(window: BrowserWindow) { export function hookNTQQApiReceive(window: BrowserWindow) {
const originalSend = window.webContents.send; const originalSend = window.webContents.send;
const patchSend = (channel: string, ...args: NTQQApiReturnData) => { const patchSend = (channel: string, ...args: NTQQApiReturnData) => {
log(`received ntqq api message: ${channel}`, JSON.stringify(args)) // log(`received ntqq api message: ${channel}`, JSON.stringify(args))
if (args?.[1] instanceof Array) { if (args?.[1] instanceof Array) {
for (let receiveData of args?.[1]) { for (let receiveData of args?.[1]) {
const ntQQApiMethodName = receiveData.cmdName; const ntQQApiMethodName = receiveData.cmdName;
@ -50,7 +50,10 @@ export function hookNTQQApiReceive(window: BrowserWindow) {
if (hook.method === ntQQApiMethodName) { if (hook.method === ntQQApiMethodName) {
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
try { try {
hook.hookFunc(receiveData.payload); let _ = hook.hookFunc(receiveData.payload)
if (hook.hookFunc.constructor.name === "AsyncFunction"){
(_ as Promise<void>).then()
}
} catch (e) { } catch (e) {
log("hook error", e, receiveData.payload) log("hook error", e, receiveData.payload)
} }
@ -129,11 +132,7 @@ registerReceiveHook<{
// log("user info", payload); // log("user info", payload);
// }) // })
registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.UPDATE_MSG, (payload) => {
for (const message of payload.msgList) {
addHistoryMsg(message)
}
})
registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.NEW_MSG, (payload) => { registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.NEW_MSG, (payload) => {
for (const message of payload.msgList) { for (const message of payload.msgList) {

View File

@ -7,13 +7,14 @@ export interface User {
remark?: string remark?: string
} }
export interface SelfInfo extends User{ export interface SelfInfo extends User {
} }
export interface Friend extends User{} export interface Friend extends User {
}
export interface Group{ export interface Group {
groupCode: string, groupCode: string,
maxMember: number, maxMember: number,
memberCount: number, memberCount: number,
@ -62,6 +63,7 @@ export enum ElementType {
TEXT = 1, TEXT = 1,
PIC = 2, PIC = 2,
PTT = 4, PTT = 4,
FACE = 6,
REPLY = 7, REPLY = 7,
} }
@ -76,6 +78,7 @@ export interface SendTextElement {
atNtUid: string, atNtUid: string,
} }
} }
export interface SendPttElement { export interface SendPttElement {
elementType: ElementType.PTT, elementType: ElementType.PTT,
elementId: "", elementId: "",
@ -127,7 +130,13 @@ export interface SendReplyElement {
} }
} }
export type SendMessageElement = SendTextElement | SendPttElement | SendPicElement | SendReplyElement export interface SendFaceElement {
elementType: ElementType.FACE,
elementId: "",
faceElement: FaceElement
}
export type SendMessageElement = SendTextElement | SendPttElement | SendPicElement | SendReplyElement | SendFaceElement
export enum AtType { export enum AtType {
notAt = 0, notAt = 0,
@ -140,6 +149,7 @@ export enum ChatType {
group = 2, group = 2,
temp = 100 temp = 100
} }
export interface PttElement { export interface PttElement {
canConvert2Text: boolean; canConvert2Text: boolean;
duration: number; // 秒数 duration: number; // 秒数
@ -180,6 +190,22 @@ export interface PicElement {
fileUuid: string; fileUuid: string;
} }
export interface GrayTipElement {
revokeElement: {
operatorRole: string;
operatorUid: string;
operatorNick: string;
operatorRemark: string;
operatorMemRemark?: string;
wording: string; // 自定义的撤回提示语
}
}
export interface FaceElement {
faceIndex: number,
faceType: 1
}
export interface RawMessage { export interface RawMessage {
msgId: string; msgId: string;
msgShortId?: number; // 自己维护的消息id msgShortId?: number; // 自己维护的消息id
@ -191,6 +217,7 @@ export interface RawMessage {
sendNickName: string; sendNickName: string;
sendMemberName?: string; // 发送者群名片 sendMemberName?: string; // 发送者群名片
chatType: ChatType; chatType: ChatType;
sendStatus?: number; // 消息状态2是已撤回
elements: { elements: {
elementId: string, elementId: string,
replyElement: { replyElement: {
@ -208,17 +235,7 @@ export interface RawMessage {
picElement: PicElement; picElement: PicElement;
pttElement: PttElement; pttElement: PttElement;
arkElement: ArkElement; arkElement: ArkElement;
grayTipElement: GrayTipElement;
faceElement: FaceElement;
}[]; }[];
} }
export interface MessageElement {
raw: RawMessage;
peer: any;
sender: {
uid: string; // 一串加密的字符串
memberName: string;
nickname: string;
};
}

View File

@ -17,6 +17,9 @@ class GetMsg extends BaseAction<PayloadType, OB11Message> {
protected async _handle(payload: PayloadType){ protected async _handle(payload: PayloadType){
// log("history msg ids", Object.keys(msgHistory)); // log("history msg ids", Object.keys(msgHistory));
if (!payload.message_id){
throw("参数message_id不能为空")
}
const msg = getHistoryMsgByShortId(payload.message_id) const msg = getHistoryMsgByShortId(payload.message_id)
if (msg) { if (msg) {
const msgData = await OB11Constructor.message(msg); const msgData = await OB11Constructor.message(msg);

View File

@ -1,19 +1,10 @@
import { AtType, ChatType, Group } from "../../ntqqapi/types"; import { AtType, ChatType, Group, SendMessageElement } from "../../ntqqapi/types";
import { import { addHistoryMsg, friends, getGroup, getHistoryMsgByShortId, getStrangerByUin, } from "../../common/data";
addHistoryMsg,
friends,
getGroup,
getHistoryMsgByShortId,
getStrangerByUin,
} from "../../common/data";
import { OB11MessageData, OB11MessageDataType, OB11PostSendMsg } from '../types'; import { OB11MessageData, OB11MessageDataType, OB11PostSendMsg } from '../types';
import { NTQQApi } from "../../ntqqapi/ntcall"; import { NTQQApi, Peer } from "../../ntqqapi/ntcall";
import { Peer } from "../../ntqqapi/ntcall";
import { SendMessageElement } from "../../ntqqapi/types";
import { SendMsgElementConstructor } from "../../ntqqapi/constructor"; import { SendMsgElementConstructor } from "../../ntqqapi/constructor";
import { uri2local } from "../utils"; import { uri2local } from "../utils";
import { v4 as uuid4 } from 'uuid'; import { v4 as uuid4 } from 'uuid';
import { log } from "../../common/utils";
import BaseAction from "./BaseAction"; import BaseAction from "./BaseAction";
import { ActionName } from "./types"; import { ActionName } from "./types";
import * as fs from "fs"; import * as fs from "fs";
@ -25,7 +16,7 @@ export interface ReturnDataType {
class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> { class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
actionName = ActionName.SendMsg actionName = ActionName.SendMsg
protected async _handle(payload: OB11PostSendMsg){ protected async _handle(payload: OB11PostSendMsg) {
const peer: Peer = { const peer: Peer = {
chatType: ChatType.friend, chatType: ChatType.friend,
peerUid: "" peerUid: ""
@ -40,18 +31,16 @@ class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
peer.chatType = ChatType.group peer.chatType = ChatType.group
// peer.name = group.name // peer.name = group.name
peer.peerUid = group.groupCode peer.peerUid = group.groupCode
} } else if (payload?.user_id) {
else if (payload?.user_id) {
const friend = friends.find(f => f.uin == payload.user_id.toString()) const friend = friends.find(f => f.uin == payload.user_id.toString())
if (friend) { if (friend) {
// peer.name = friend.nickName // peer.name = friend.nickName
peer.peerUid = friend.uid peer.peerUid = friend.uid
} } else {
else {
peer.chatType = ChatType.temp peer.chatType = ChatType.temp
const tempUser = getStrangerByUin(payload.user_id.toString()) const tempUser = getStrangerByUin(payload.user_id.toString())
if (!tempUser) { if (!tempUser) {
throw(`找不到私聊对象${payload.user_id}`) throw (`找不到私聊对象${payload.user_id}`)
} }
// peer.name = tempUser.nickName // peer.name = tempUser.nickName
peer.peerUid = tempUser.uid peer.peerUid = tempUser.uid
@ -64,8 +53,7 @@ class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
text: payload.message text: payload.message
} }
}] as OB11MessageData[] }] as OB11MessageData[]
} } else if (!Array.isArray(payload.message)) {
else if (!Array.isArray(payload.message)) {
payload.message = [payload.message] payload.message = [payload.message]
} }
const sendElements: SendMessageElement[] = [] const sendElements: SendMessageElement[] = []
@ -76,22 +64,23 @@ class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
if (text) { if (text) {
sendElements.push(SendMsgElementConstructor.text(sendMsg.data!.text)) sendElements.push(SendMsgElementConstructor.text(sendMsg.data!.text))
} }
} break; }
break;
case OB11MessageDataType.at: { case OB11MessageDataType.at: {
let atQQ = sendMsg.data?.qq; let atQQ = sendMsg.data?.qq;
if (atQQ) { if (atQQ) {
atQQ = atQQ.toString() atQQ = atQQ.toString()
if (atQQ === "all") { if (atQQ === "all") {
sendElements.push(SendMsgElementConstructor.at(atQQ, atQQ, AtType.atAll, "全体成员")) sendElements.push(SendMsgElementConstructor.at(atQQ, atQQ, AtType.atAll, "全体成员"))
} } else {
else {
const atMember = group?.members.find(m => m.uin == atQQ) const atMember = group?.members.find(m => m.uin == atQQ)
if (atMember) { if (atMember) {
sendElements.push(SendMsgElementConstructor.at(atQQ, atMember.uid, AtType.atUser, atMember.cardName || atMember.nick)) sendElements.push(SendMsgElementConstructor.at(atQQ, atMember.uid, AtType.atUser, atMember.cardName || atMember.nick))
} }
} }
} }
} break; }
break;
case OB11MessageDataType.reply: { case OB11MessageDataType.reply: {
let replyMsgId = sendMsg.data.id; let replyMsgId = sendMsg.data.id;
if (replyMsgId) { if (replyMsgId) {
@ -101,20 +90,27 @@ class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
sendElements.push(SendMsgElementConstructor.reply(replyMsg.msgSeq, replyMsg.msgId, replyMsg.senderUin, replyMsg.senderUin)) sendElements.push(SendMsgElementConstructor.reply(replyMsg.msgSeq, replyMsg.msgId, replyMsg.senderUin, replyMsg.senderUin))
} }
} }
} break; }
break;
case OB11MessageDataType.face: {
const faceId = sendMsg.data?.id
if (faceId) {
sendElements.push(SendMsgElementConstructor.face(parseInt(faceId)))
}
}
break;
case OB11MessageDataType.image: case OB11MessageDataType.image:
case OB11MessageDataType.voice: { case OB11MessageDataType.voice: {
const file = sendMsg.data?.file const file = sendMsg.data?.file
if (file) { if (file) {
const {path, isLocal} = (await uri2local(uuid4(), file)) const {path, isLocal} = (await uri2local(uuid4(), file))
if (path) { if (path) {
if (!isLocal){ // 只删除http和base64转过来的文件 if (!isLocal) { // 只删除http和base64转过来的文件
deleteAfterSentFiles.push(path) deleteAfterSentFiles.push(path)
} }
if (sendMsg.type === OB11MessageDataType.image){ if (sendMsg.type === OB11MessageDataType.image) {
sendElements.push(await SendMsgElementConstructor.pic(path)) sendElements.push(await SendMsgElementConstructor.pic(path))
} } else {
else {
sendElements.push(await SendMsgElementConstructor.ptt(path)) sendElements.push(await SendMsgElementConstructor.ptt(path))
} }
} }
@ -126,10 +122,11 @@ class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
try { try {
const returnMsg = await NTQQApi.sendMsg(peer, sendElements) const returnMsg = await NTQQApi.sendMsg(peer, sendElements)
addHistoryMsg(returnMsg) addHistoryMsg(returnMsg)
deleteAfterSentFiles.map(f=>fs.unlink(f, ()=>{})) deleteAfterSentFiles.map(f => fs.unlink(f, () => {
return { message_id: returnMsg.msgShortId } }))
return {message_id: returnMsg.msgShortId}
} catch (e) { } catch (e) {
throw(e.toString()) throw (e.toString())
} }
} }
} }

View File

@ -113,6 +113,9 @@ export class OB11Constructor extends OB11EventConstructor{
} else if (element.arkElement) { } else if (element.arkElement) {
message_data["type"] = OB11MessageDataType.json; message_data["type"] = OB11MessageDataType.json;
message_data["data"]["data"] = element.arkElement.bytesData; message_data["data"]["data"] = element.arkElement.bytesData;
} else if (element.faceElement){
message_data["type"] = OB11MessageDataType.face;
message_data["data"]["id"] = element.faceElement.faceIndex.toString();
} }
if (message_data.data.http_file) { if (message_data.data.http_file) {
message_data.data.file = message_data.data.http_file message_data.data.file = message_data.data.http_file

View File

@ -3,7 +3,7 @@ import {
OB11EventPostType, OB11FriendRecallNoticeEvent, OB11EventPostType, OB11FriendRecallNoticeEvent,
OB11GroupRecallNoticeEvent, OB11GroupRecallNoticeEvent,
OB11HeartEvent, OB11HeartEvent,
OB11LifeCycleEvent, OB11MetaEvent, OB11NoticeBase OB11LifeCycleEvent, OB11MetaEvent, OB11NoticeEvent
} from "./types"; } from "./types";
import { heartInterval, selfInfo } from "../../common/data"; import { heartInterval, selfInfo } from "../../common/data";
@ -16,7 +16,7 @@ function eventBase(post_type: OB11EventPostType): OB11EventBase {
} }
export class OB11EventConstructor { export class OB11EventConstructor {
static lifeCycle(): OB11LifeCycleEvent { static lifeCycleEvent(): OB11LifeCycleEvent {
return { return {
...eventBase(OB11EventPostType.META) as OB11MetaEvent, ...eventBase(OB11EventPostType.META) as OB11MetaEvent,
meta_event_type: "lifecycle", meta_event_type: "lifecycle",
@ -24,7 +24,7 @@ export class OB11EventConstructor {
} }
} }
static heart(): OB11HeartEvent { static heartEvent(): OB11HeartEvent {
return { return {
...eventBase(OB11EventPostType.META) as OB11MetaEvent, ...eventBase(OB11EventPostType.META) as OB11MetaEvent,
meta_event_type: "heartbeat", meta_event_type: "heartbeat",
@ -36,9 +36,9 @@ export class OB11EventConstructor {
} }
} }
static groupRecall(group_id: string, user_id: string, operator_id: string, message_id: number): OB11GroupRecallNoticeEvent { static groupRecallEvent(group_id: string, user_id: string, operator_id: string, message_id: number): OB11GroupRecallNoticeEvent {
return { return {
...eventBase(OB11EventPostType.NOTICE) as OB11NoticeBase, ...eventBase(OB11EventPostType.NOTICE) as OB11NoticeEvent,
notice_type: "group_recall", notice_type: "group_recall",
group_id: parseInt(group_id), group_id: parseInt(group_id),
user_id: parseInt(user_id), user_id: parseInt(user_id),
@ -47,9 +47,9 @@ export class OB11EventConstructor {
} }
} }
static friendRecall(user_id: string, operator_id: string, message_id: number): OB11FriendRecallNoticeEvent { static friendRecallEvent(user_id: string, message_id: number): OB11FriendRecallNoticeEvent {
return { return {
...eventBase(OB11EventPostType.NOTICE) as OB11NoticeBase, ...eventBase(OB11EventPostType.NOTICE) as OB11NoticeEvent,
notice_type: "friend_recall", notice_type: "friend_recall",
user_id: parseInt(user_id), user_id: parseInt(user_id),
message_id message_id

View File

@ -16,12 +16,12 @@ export interface OB11MetaEvent extends OB11EventBase{
meta_event_type: "lifecycle" | "heartbeat" meta_event_type: "lifecycle" | "heartbeat"
} }
export interface OB11NoticeBase extends OB11EventBase{ export interface OB11NoticeEvent extends OB11EventBase{
post_type: OB11EventPostType.NOTICE post_type: OB11EventPostType.NOTICE
notice_type: "group_admin" | "group_decrease" | "group_increase" | "group_ban" | "friend_add" | "group_recall" | "friend_recall" notice_type: "group_admin" | "group_decrease" | "group_increase" | "group_ban" | "friend_add" | "group_recall" | "friend_recall"
} }
interface OB11GroupNoticeBase extends OB11NoticeBase{ interface OB11GroupNoticeBase extends OB11NoticeEvent{
group_id: number group_id: number
user_id: number user_id: number
} }
@ -49,7 +49,7 @@ export interface OB11GroupRecallNoticeEvent extends OB11GroupNoticeBase{
message_id: number message_id: number
} }
export interface OB11FriendRecallNoticeEvent extends OB11NoticeBase{ export interface OB11FriendRecallNoticeEvent extends OB11NoticeEvent{
notice_type: "friend_recall" notice_type: "friend_recall"
user_id: number user_id: number
message_id: number message_id: number

View File

@ -12,7 +12,7 @@ import { OB11Response } from "./actions/utils";
import { ActionName } from "./actions/types"; import { ActionName } from "./actions/types";
import BaseAction from "./actions/BaseAction"; import BaseAction from "./actions/BaseAction";
import { OB11Constructor } from "./constructor"; import { OB11Constructor } from "./constructor";
import { OB11LifeCycleEvent, OB11MetaEvent } from "./events/types"; import { OB11EventBase, OB11LifeCycleEvent, OB11MetaEvent, OB11NoticeEvent } from "./events/types";
let wsServer: websocket.Server = null; let wsServer: websocket.Server = null;
let accessToken = "" let accessToken = ""
@ -60,8 +60,6 @@ const expressAuthorize = (req: Request, res: Response, next: () => void) => {
return res.status(403).send(JSON.stringify({message: 'token verify failed!'})); return res.status(403).send(JSON.stringify({message: 'token verify failed!'}));
} }
} }
next(); next();
}; };
@ -87,7 +85,7 @@ let wsEventClients: websocket.WebSocket[] = [];
type RouterHandler = (payload: any) => Promise<OB11Return<any>> type RouterHandler = (payload: any) => Promise<OB11Return<any>>
let routers: Record<string, RouterHandler> = {}; let routers: Record<string, RouterHandler> = {};
function wsReply(wsClient: websocket.WebSocket, data: OB11Return<any> | OB11Message | OB11MetaEvent) { function wsReply(wsClient: websocket.WebSocket, data: OB11Return<any> | PostMsgType) {
try { try {
wsClient.send(JSON.stringify(data)) wsClient.send(JSON.stringify(data))
log("ws 消息上报", data) log("ws 消息上报", data)
@ -163,14 +161,14 @@ export function startWSServer(port: number) {
log("event上报ws客户端已连接") log("event上报ws客户端已连接")
wsEventClients.push(ws) wsEventClients.push(ws)
try { try {
wsReply(ws, OB11Constructor.lifeCycle()) wsReply(ws, OB11Constructor.lifeCycleEvent())
}catch (e){ }catch (e){
log("发送生命周期失败", e) log("发送生命周期失败", e)
} }
// 心跳 // 心跳
let wsHeart = setInterval(()=>{ let wsHeart = setInterval(()=>{
if (wsEventClients.find(c => c == ws)){ if (wsEventClients.find(c => c == ws)){
wsReply(ws, OB11Constructor.heart()) wsReply(ws, OB11Constructor.heartEvent())
} }
}, heartInterval) }, heartInterval)
ws.on("close", () => { ws.on("close", () => {
@ -182,11 +180,13 @@ export function startWSServer(port: number) {
}) })
} }
type PostMsgType = OB11Message | OB11MetaEvent | OB11NoticeEvent
export function postMsg(msg: OB11Message) { export function postMsg(msg: PostMsgType) {
const {reportSelfMessage} = getConfigUtil().getConfig() const {reportSelfMessage} = getConfigUtil().getConfig()
// 判断msg是否是event
if (!reportSelfMessage) { if (!reportSelfMessage) {
if (msg.user_id.toString() == selfInfo.uin) { if ((msg as OB11Message).user_id.toString() == selfInfo.uin) {
return return
} }
} }
@ -231,10 +231,10 @@ function registerRouter(action: string, handle: (payload: any) => Promise<any>)
} }
expressAPP.post(url, expressAuthorize, (req: Request, res: Response) => { expressAPP.post(url, expressAuthorize, (req: Request, res: Response) => {
_handle(res, req.body).then() _handle(res, req.body || {}).then()
}); });
expressAPP.get(url, expressAuthorize, (req: Request, res: Response) => { expressAPP.get(url, expressAuthorize, (req: Request, res: Response) => {
_handle(res, req.query as any).then() _handle(res, req.query as any || {}).then()
}); });
routers[action] = handle routers[action] = handle
} }

View File

@ -1,18 +1,18 @@
import { AtType, RawMessage } from "../ntqqapi/types"; import { AtType, RawMessage } from "../ntqqapi/types";
export interface OB11User{ export interface OB11User {
user_id: number; user_id: number;
nickname: string; nickname: string;
remark?: string remark?: string
} }
export enum OB11UserSex{ export enum OB11UserSex {
male = "male", male = "male",
female = "female", female = "female",
unknown = "unknown" unknown = "unknown"
} }
export enum OB11GroupMemberRole{ export enum OB11GroupMemberRole {
owner = "owner", owner = "owner",
admin = "admin", admin = "admin",
member = "member", member = "member",
@ -32,7 +32,7 @@ export interface OB11GroupMember {
title?: string title?: string
} }
export interface OB11Group{ export interface OB11Group {
group_id: number group_id: number
group_name: string group_name: string
member_count?: number member_count?: number
@ -92,7 +92,8 @@ export interface OB11Return<DataType> {
echo?: string echo?: string
} }
export interface OB11SendMsgReturn extends OB11Return<{message_id: string}>{} export interface OB11SendMsgReturn extends OB11Return<{ message_id: string }> {
}
export enum OB11MessageDataType { export enum OB11MessageDataType {
text = "text", text = "text",
@ -100,7 +101,8 @@ export enum OB11MessageDataType {
voice = "record", voice = "record",
at = "at", at = "at",
reply = "reply", reply = "reply",
json = "json" json = "json",
face = "face"
} }
export type OB11MessageData = { export type OB11MessageData = {
@ -132,6 +134,11 @@ export type OB11MessageData = {
data: { data: {
id: string, id: string,
} }
} | {
type: OB11MessageDataType.face,
data: {
id: string
}
} }
export interface OB11PostSendMsg { export interface OB11PostSendMsg {