Skip to content

Commit

Permalink
✨ feat:Complete basic type messages
Browse files Browse the repository at this point in the history
  • Loading branch information
sj817 committed Apr 7, 2024
1 parent 0018564 commit 4a80e67
Show file tree
Hide file tree
Showing 11 changed files with 798 additions and 332 deletions.
2 changes: 1 addition & 1 deletion lib/adapter/kritor/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export default class extends EventEmitter {
data = await this.SendApi(data.cmd, data.buf)
let res = this.decode(cmd, type, data.buf)
/** 统一使用str */
res.accountUin = String(res.account_uin)
res.account_uin = String(res.account_uin)
return res
}

Expand Down
174 changes: 117 additions & 57 deletions lib/adapter/kritor/converter.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
import {
KarinAtElement, KarinFaceElement,
// eslint-disable-next-line no-unused-vars
KarinElement, KarinMessage, KarinFileElement,
KarinAtElement,
KarinFaceElement,
KarinGroupRecallNotice,
KarinImageElement,
KarinMessage,
KarinTextElement
} from "../../bot/model.js";
import {kritor} from "./protos/compiled.js";
import {logger} from "#Karin";
import {raw} from "express";
} from '../../bot/model.js'
import { kritor } from './protos/compiled.js'
import { logger, Bot } from '#Karin'
// import { raw } from 'express'

/**
* 抽象转换器
*/
export class Converter {
async convert (raw) {}
async convert (raw) { }
}

/**
Expand All @@ -25,83 +27,141 @@ export class MessageConverter extends Converter {
* @param {kritor.common.PushMessageBody} message
* @return {Promise<KarinMessage>}
*/
async convert(message) {
await super.convert(message);
let toLog = ''
let msg = new KarinMessage({
message: null,
sender: {
id: message.sender.uin,
nickname: message.sender.nick
},
group: message.contact.scene === kritor.common.Scene.GROUP ?{
id: message.contact.peer,
name: '' // todo fetch from cache
} : null,
isPrivate: message.contact.scene === kritor.common.Scene.FRIEND,
isGroup: message.contact.scene === kritor.common.Scene.GROUP,
isGuild: message.contact.scene === kritor.common.Scene.GUILD,
// todo
isMaster: false,
logText: '',
logFnc: '',
at: '',
atBot: false,
img: [],
file: {},
reply_id: ''
})
convert (message) {
let { self_id, time, message_id, message_seq, contact, sender } = message
/** scene映射表 */
const sceneMap = {
[kritor.common.Scene.GROUP]: 'group',
[kritor.common.Scene.FRIEND]: 'friend',
[kritor.common.Scene.GUILD]: 'guild',
[kritor.common.Scene.NEARBY]: 'nearby',
[kritor.common.Scene.STRANGER]: 'stranger',
[kritor.common.Scene.STRANGER_FROM_GROUP]: 'stranger_from_group'
}
/*
0=群聊 1=私聊 2=频道 5=附近的人 6=陌生人 10=群临时会话
0=group 1=friend 2=guild 5=nearby 6=stranger 10=stranger_from_group
*/
const scene = sceneMap[contact.scene]
const elements = []

/**
*
* @type {Array<KarinElement>}
*/
let messages = []
for (let element of message.elements) {
switch (element.type) {
for (let i of message.elements) {
switch (i.type) {
case kritor.common.Element.ElementType.TEXT: {
toLog += element.text.text
messages.push(new KarinTextElement(element.text.text))
elements.push(new KarinTextElement(i.text.text))
break
}
case kritor.common.Element.ElementType.IMAGE: {
toLog += `<image:${element.image.file_url}>`
messages.push(new KarinImageElement(element.image.file_url))
elements.push(new KarinImageElement(i.image.file_url))
break
}
case kritor.common.Element.ElementType.AT: {
toLog += `<at:${element.at.uin}>`
messages.push(new KarinAtElement(element.at.uin, element.at.uid))
elements.push(new KarinAtElement(i.at.uid, i.at.uin))
break
}
case kritor.common.Element.ElementType.FACE: {
toLog += `<face:${element.face.id}, is_big: ${element.face.is_big}>`
messages.push(new KarinFaceElement(element.face.id, element.face.is_big))
elements.push(new KarinFaceElement(i.face.id, i.face.is_big))
break
}
// todo 其他类型
default: {
logger.info(element)
logger.info(i)
}
}
}

const e = {
event: 'message', // 事件类型
self_id,
time, // 消息时间戳
message_id, // 消息id
message_seq, // 消息序列号
sender,
contact: {
scene, // 场景
peer: contact.peer, // 群聊则为群号 私聊则为uid 频道消息则为频道号
sub_peer: contact.sub_peer // 群临时聊天则为群号 频道消息则为子频道号 其它情况可不提供
},
elements
}

/**
* 快速回复
* @param {Array<KarinElement>} elements
* @returns {<Promise{message_id}>}
*/
e.reply = (elements) => {
const contact = e.contact
const _elements = this.elements(elements)
return Bot.adapter[e.self_id].SendMessage(contact, _elements)
}

return e
}

elements (elements) {
const _elements = []
const ElementType = kritor.common.Element.ElementType
for (let i of elements) {
switch (i.type) {
case 'text': {
const { TEXT: type } = ElementType
const { text } = i
_elements.push({ type, text: { text } })
break
}
case 'image': {
const { IMAGE: type } = ElementType
const { file } = i
_elements.push({ type, image: { file } })
break
}
case 'at': {
const { AT: type } = ElementType
const { uid, uin = '' } = i
_elements.push({ type, at: { uid, uin } })
break
}
case 'face': {
const { FACE: type } = ElementType
const { id, is_big = false } = i
_elements.push({ type, face: { id, is_big } })
break
}
case 'reply': {
const { REPLY: type } = ElementType
const { id } = i
_elements.push({ type, reply: { id } })
break

}
case 'VOICE': {
const { VOICE: type } = ElementType
const { file } = i
_elements.push({ type, voice: { file } })
break
}
}
}
msg.raw_message = toLog
msg.message = messages
return msg
return _elements
}
}

/**
* Kritor 通知事件转换器
*/
export class NoticeConverter extends Converter {

/**
*
* @param {kritor.event.NoticeEvent} raw
* @return {Promise<KarinNotice>}
*/
async convert(raw) {
await super.convert(raw);
async convert (raw) {
await super.convert(raw)
switch (raw.type) {
case kritor.event.NoticeEvent.NoticeType.GROUP_POKE: {
// todo
Expand All @@ -113,6 +173,7 @@ export class NoticeConverter extends Converter {
notice.logText = `[群撤回:${raw.group_recall.group_id}] operator: ${raw.group_recall.operator_uin}, target: ${raw.group_recall.target_uin}, message_id: ${raw.group_recall.message_id}`
return notice
}
break
}
case kritor.event.NoticeEvent.NoticeType.GROUP_MEMBER_BANNED: {
// todo
Expand Down Expand Up @@ -146,21 +207,20 @@ export class NoticeConverter extends Converter {
* Kritor 请求事件转换器
*/
export class RequestConverter extends Converter {

/**
*
* @param {kritor.event.RequestsEvent} raw
* @return {Promise<void>}
*/
async convert(raw) {
await super.convert(raw);
async convert (raw) {
await super.convert(raw)
}
}

const Converters ={
const Converters = {
messageConverter: new MessageConverter(),
noticeConverter: new NoticeConverter(),
requestConverter: new RequestConverter()
};
}

export default Converters
export default Converters
22 changes: 12 additions & 10 deletions lib/adapter/kritor/index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import Api from './api.js'
import {Bot, logger} from '#Karin'
import { Bot, logger } from '#Karin'
import * as grpc from '@grpc/grpc-js'
import * as protoLoader from '@grpc/proto-loader'
import {kritor} from "./protos/compiled.js";
import Converters from "./converter.js";
import { kritor } from './protos/compiled.js'
import Converters from './converter.js'

export default class Kritor {
/**
Expand All @@ -28,6 +28,7 @@ export default class Kritor {

/** 初始化 gRPC 服务器 */
init () {
let bot_uin = ''
const authenticationProtoGrpcType = this.getProtoGrpcType('auth/authentication.proto')
const coreProtoGrpcType = this.getProtoGrpcType('core/core.proto')
const customizationGrpcType = this.getProtoGrpcType('customization/customization.proto')
Expand All @@ -51,19 +52,18 @@ export default class Kritor {
RegisterPassiveListener: (call) => {
/** 监听上报事件 */
call.on('data', data => {
if (!bot_uin) return logger.debug('未初始化selfId,暂不处理事件:', data)
logger.debug('上报事件:', data)
// 事件分发according to data.type
switch (data.type) {
case kritor.event.EventType.EVENT_TYPE_MESSAGE: {
Converters.messageConverter.convert(data.message).then(message => {
logger.info(`${message.isGroup ? 'Group[' + message.group.id + ']' : 'Private'}[${message.sender.nickname}(${message.sender.id})]: ${message.raw_message}`)
// 拿不到selfId?暂时默认只有一个好了
message.self_id = Object.keys(Bot.adapter)[0]
Bot.emit('message', message)
})
data.message.self_id = bot_uin
const message = Converters.messageConverter.convert(data.message)
Bot.emit('message', message)
break
}
case kritor.event.EventType.EVENT_TYPE_NOTICE: {
data.notice.self_id = bot_uin
Converters.noticeConverter.convert(data.notice).then(notice => {
if (notice) {
logger.info(notice.logText)
Expand All @@ -73,6 +73,7 @@ export default class Kritor {
break
}
case kritor.event.EventType.EVENT_TYPE_REQUEST: {
data.request.self_id = bot_uin
Converters.requestConverter.convert(data.request).then(request => {
Bot.emit('request', request)
})
Expand All @@ -91,6 +92,7 @@ export default class Kritor {
.then(res => {
const { account_uid: uid, account_uin: uin, account_name: name } = res
bot.account = { uid, uin, name }
bot_uin = uin
/** 注册bot */
Bot.emit('bot', bot)
})
Expand Down Expand Up @@ -123,4 +125,4 @@ export default class Kritor {
/** 监听程序退出事件 关闭服务器 */
process.on('exit', () => server.forceShutdown())
}
}
}
Loading

0 comments on commit 4a80e67

Please sign in to comment.