Skip to content

Commit

Permalink
fix: send file element (#47)
Browse files Browse the repository at this point in the history
  • Loading branch information
idranme authored Aug 27, 2024
1 parent 8aa23a6 commit d49a32c
Showing 1 changed file with 35 additions and 2 deletions.
37 changes: 35 additions & 2 deletions src/bot/message.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -106,6 +107,35 @@ export class OneBotMessageEncoder<C extends Context = Context> 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 } })
}
Expand Down Expand Up @@ -145,7 +175,7 @@ export class OneBotMessageEncoder<C extends Context = Context> 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'
Expand All @@ -163,6 +193,9 @@ export class OneBotMessageEncoder<C extends Context = Context> 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 })
Expand Down

0 comments on commit d49a32c

Please sign in to comment.