Skip to content

Commit

Permalink
feat(qqguild): events
Browse files Browse the repository at this point in the history
  • Loading branch information
XxLittleCxX committed Sep 16, 2023
1 parent 1c99286 commit ec8b207
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 53 deletions.
43 changes: 11 additions & 32 deletions adapters/qqguild/src/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import FormData from 'form-data'
import { decodeMessage } from './utils'

export class QQGuildMessageEncoder extends MessageEncoder<QQGuildBot> {
// private mode: 'figure' | 'default' = 'default'
private content: string = ''
private file: Buffer
private filename: string
fileUrl: string
reference: string
dms: QQGuild.DMS

Expand All @@ -27,7 +27,7 @@ export class QQGuildMessageEncoder extends MessageEncoder<QQGuildBot> {

// 先文后图
async flush() {
if (!this.content.trim().length && !this.file) {
if (!this.content.trim().length && !this.file && !this.fileUrl) {
return
}
let endpoint = `/channels/${this.session.channelId}/messages`
Expand All @@ -50,6 +50,9 @@ export class QQGuildMessageEncoder extends MessageEncoder<QQGuildBot> {
if (this.file) {
form.append('file_image', this.file, this.filename)
}
if (this.fileUrl) {
form.append('image', this.fileUrl)
}

const r = await this.bot.http.post(endpoint, form, {
headers: form.getHeaders(),
Expand All @@ -64,15 +67,18 @@ export class QQGuildMessageEncoder extends MessageEncoder<QQGuildBot> {
}

// https://bot.q.qq.com/wiki/develop/api/gateway/direct_message.html#%E6%B3%A8%E6%84%8F
// session.guildId = this.session.guildId
this.results.push(session)
session.app.emit(session, 'send', session)
this.content = ''
this.file = null
this.filename = null
this.fileUrl = null
}

async resolveFile(attrs: Dict) {
if (attrs.url.startsWith('http')) {
return this.fileUrl = attrs.url
}
const { data, filename } = await this.bot.ctx.http.file(attrs.url, attrs)
this.file = Buffer.from(data)
this.filename = filename
Expand Down Expand Up @@ -102,42 +108,15 @@ export class QQGuildMessageEncoder extends MessageEncoder<QQGuildBot> {
this.reference = attrs.id
await this.flush()
} else if (type === 'image' && attrs.url) {
await this.flush()
await this.resolveFile(attrs)
await this.flush()
}
// else if (type === 'figure') {
// await this.flush()
// this.mode = 'figure'
// await this.render(children)
// await this.flush()
// this.mode = 'default'
// }
else if (type === 'message') {
// if (this.mode === 'figure') {
// await this.render(children)
// this.content += '\n'
// } else {
} else if (type === 'message') {
await this.flush()
await this.render(children)
await this.flush()
// }
} else {
await this.render(children)
}
}

// async send(content: h.Fragment) {
// try {
// return await super.send(content)
// } catch (e) {
// // https://bot.q.qq.com/wiki/develop/api/openapi/error/error.html#错误码处理:~:text=304031
// if ([304031, 304032, 304033].includes(e.code)) {
// const { channel_id, guild_id } = await this.bot.internal.createDMS(this.session.channelId, this.session.guildId || this.options.session.guildId)
// this.session.channelId = channel_id
// this.session.guildId = guild_id
// return await super.send(content)
// }
// throw e
// }
// }
}
14 changes: 13 additions & 1 deletion adapters/qqguild/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export type DispatchPayload = {
} | {
op: Opcode.DISPATCH
s: number
t: 'RESUME'
t: 'RESUMED'
d: string
} | {
op: Opcode.DISPATCH
Expand All @@ -130,6 +130,11 @@ export type DispatchPayload = {
s: number
t: 'GUILD_MEMBER_ADD' | 'GUILD_MEMBER_UPDATE' | 'GUILD_MEMBER_DELETE'
d: MemberWithGuild
} | {
op: Opcode.DISPATCH
s: number
t: 'MESSAGE_DELETE' | 'PUBLIC_MESSAGE_DELETE' | 'DIRECT_MESSAGE_DELETE'
d: Message.DeletionPayload
}

export type Payload = DispatchPayload | {
Expand Down Expand Up @@ -169,6 +174,8 @@ export type Payload = DispatchPayload | {
sessionId: string
seq: number
}
} | {
op: Opcode.INVALID_SESSION
}

export interface Attachment {
Expand Down Expand Up @@ -313,6 +320,11 @@ export namespace Message {
embeds: Embed[]
mentionEveryone: boolean
}

export interface DeletionPayload {
message: Partial<Message>
op_user: Pick<User, 'id'>
}
}

export interface User {
Expand Down
14 changes: 14 additions & 0 deletions adapters/qqguild/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,20 @@ export async function adaptSession(bot: QQGuildBot, input: QQGuild.DispatchPaylo
}[input.t]
session.guildId = input.d.id
session.guildName = input.d.name
} else if (input.t === 'DIRECT_MESSAGE_DELETE' || input.t === 'MESSAGE_DELETE' || input.t === 'PUBLIC_MESSAGE_DELETE') {
if (bot.config.app.type === 'private' && input.t === 'PUBLIC_MESSAGE_DELETE') return
session.type = 'message-deleted'
session.userId = input.d.message.author.id
session.operatorId = input.d.op_user.id
session.messageId = input.d.message.id
session.isDirect = input.d.message.direct_message
if (session.isDirect) {
session.guildId = `${input.d.message.src_guild_id}_${input.d.message.guild_id}`
session.channelId = `${input.d.message.guild_id}_${input.d.message.channel_id}`
} else {
session.guildId = input.d.message.guild_id
session.channelId = input.d.message.channel_id
}
} else {
return
}
Expand Down
51 changes: 31 additions & 20 deletions adapters/qqguild/src/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,24 +27,42 @@ export class WsClient extends Adapter.WsClient<QQGuildBot> {
const parsed: Payload = JSON.parse(data.toString())
logger.debug(require('util').inspect(parsed, false, null, true))
if (parsed.op === Opcode.HELLO) {
bot.socket.send(JSON.stringify({
op: Opcode.IDENTIFY,
d: {
token: `Bot ${bot.config.app.id}.${bot.config.app.token}`,
intents: 0 | bot.config.intents,
},
}))
if (this._sessionId) {
bot.socket.send(JSON.stringify({
op: Opcode.RESUME,
d: {
token: `Bot ${bot.config.app.id}.${bot.config.app.token}`,
session_id: this._sessionId,
seq: this._s,
},
}))
} else {
bot.socket.send(JSON.stringify({
op: Opcode.IDENTIFY,
d: {
token: `Bot ${bot.config.app.id}.${bot.config.app.token}`,
intents: 0 | bot.config.intents,
},
}))
}
this._ping = setInterval(() => this.heartbeat(), parsed.d.heartbeat_interval)

// @TODO resume
} else if (parsed.op === Opcode.INVALID_SESSION) {
this._sessionId = ''
this._s = null
logger.warn('offline: invalid session')
bot.socket?.close()
} else if (parsed.op === Opcode.RECONNECT) {

logger.warn('offline: server request reconnect')
this.bot.socket?.close()
} else if (parsed.op === Opcode.DISPATCH) {
this._s = parsed.s
if (parsed.t === 'READY') {
this._sessionId = parsed.d.sessionId
return bot.online()
}
if (parsed.t === 'RESUMED') {
return bot.online()
}
const session = await adaptSession(bot, parsed)
if (session) bot.dispatch(session)
logger.debug(require('util').inspect(session, false, null, true))
Expand All @@ -54,18 +72,11 @@ export class WsClient extends Adapter.WsClient<QQGuildBot> {
bot.socket.addEventListener('close', (e) => {
clearInterval(this._ping)
})
// Object.assign(bot, await bot.getSelf())
// await bot.internal.startClient(bot.config.intents)
// bot.internal.on('ready', bot.online.bind(bot))
// bot.internal.on('message', msg => {
// const session = bot.adaptMessage(msg)
// if (session) bot.dispatch(session)
// })
}

async stop(bot: QQGuildBot) {
// bot.internal.stopClient()
// bot.offline()
async stop(bot: QQGuildBot): Promise<void> {
bot.offline()
bot.socket?.close()
}
}

Expand Down

0 comments on commit ec8b207

Please sign in to comment.