From d49a32c841efa85c1cf1ee25da5affb533b47e79 Mon Sep 17 00:00:00 2001 From: idranme <96647698+idranme@users.noreply.github.com> Date: Tue, 27 Aug 2024 11:27:06 +0800 Subject: [PATCH] fix: send file element (#47) --- src/bot/message.ts | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/src/bot/message.ts b/src/bot/message.ts index 1120311..30906ab 100644 --- a/src/bot/message.ts +++ b/src/bot/message.ts @@ -1,6 +1,7 @@ -import { Context, h, MessageEncoder, pick, Universal } from 'koishi' +import { Context, Dict, h, MessageEncoder, pick, Universal } from 'koishi' import { BaseBot } from './base' import { CQCode } from './cqcode' +import { fileURLToPath } from 'node:url' export interface Author extends Universal.User { time?: string | number @@ -106,6 +107,35 @@ export class OneBotMessageEncoder extends MessageEn this.children = [] } + private async sendFile(attrs: Dict) { + const src: string = attrs.src || attrs.url + const name = attrs.title || (await this.bot.ctx.http.file(src)).filename + // 本地文件路径 + const file = src.startsWith('file:') ? fileURLToPath(src) : await this.bot.internal.downloadFile(src) + if (this.session.event.channel.type === Universal.Channel.Type.DIRECT) { + await this.bot.internal.uploadPrivateFile( + this.channelId.slice(PRIVATE_PFX.length), + file, + name, + ) + } else { + await this.bot.internal.uploadGroupFile( + this.channelId, + file, + name, + ) + } + const session = this.bot.session() + // 相关 API 没有返回 message_id + session.messageId = '' + session.userId = this.bot.selfId + session.channelId = this.session.channelId + session.guildId = this.session.guildId + session.isDirect = this.session.isDirect + session.app.emit(session, 'send', session) + this.results.push(session.event.message) + } + private text(text: string) { this.children.push({ type: 'text', data: { text } }) } @@ -145,7 +175,7 @@ export class OneBotMessageEncoder extends MessageEn await this.render(children) // https://github.com/koishijs/koishi-plugin-adapter-onebot/issues/23 if (attrs.href) this.text(`(${attrs.href})`) - } else if (['video', 'audio', 'image', 'img', 'file'].includes(type)) { + } else if (['video', 'audio', 'image', 'img'].includes(type)) { if (type === 'video' || type === 'audio') await this.flush() if (type === 'audio') type = 'record' if (type === 'img') type = 'image' @@ -163,6 +193,9 @@ export class OneBotMessageEncoder extends MessageEn const cap = /^data:([\w/.+-]+);base64,/.exec(attrs.file) if (cap) attrs.file = 'base64://' + attrs.file.slice(cap[0].length) this.children.push({ type, data: attrs }) + } else if (type === 'file') { + await this.flush() + await this.sendFile(attrs) } else if (type === 'onebot:music') { await this.flush() this.children.push({ type: 'music', data: attrs })