Skip to content

Commit

Permalink
feat(discord): optimize image segment sending, fix #280 (#282)
Browse files Browse the repository at this point in the history
  • Loading branch information
dragon-fish committed Jun 23, 2021
1 parent c342ce0 commit 12207bd
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 5 deletions.
57 changes: 53 additions & 4 deletions packages/adapter-discord/src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { segment } from 'koishi-utils'
import FormData from 'form-data'
import FileType from 'file-type'

export type HandleExternalAssets = 'auto' | 'download' | 'direct'

export class SenderError extends Error {
constructor(url: string, data: any, selfId: string) {
super(`Error when trying to request ${url}, data: ${JSON.stringify(data)}`)
Expand Down Expand Up @@ -126,16 +128,63 @@ export class DiscordBot extends Bot<'discord'> {
})
sentMessageId = r.id
} else {
try {
const { axiosConfig, discord = {} } = this.app.options
const sendMode =
data.mode as HandleExternalAssets || // define in segment
discord.handleExternalAssets || // define in app options
'auto' // default

// Utils
async function sendDownload() {
const a = await axios.get(data.url, {
...axiosConfig,
...discord.axiosConfig,
responseType: 'arraybuffer',
headers: {
accept: 'image/*',
},
})
const r = await this.sendEmbedMessage(requestUrl, a.data, {
const r = await that.sendEmbedMessage(requestUrl, a.data, {
...addition,
})
sentMessageId = r.id
} catch (e) {
throw new SenderError(data.url, data, this.selfId)
}
async function sendDirect() {
const r = await that.request('POST', requestUrl, {
content: data.url,
...addition,
})
sentMessageId = r.id
}

if (sendMode === 'direct') {
// send url directly
await sendDirect()
} else if (sendMode === 'download') {
// download send
await sendDownload()
} else {
// auto mode
await axios
.head(data.url, {
...axiosConfig,
...discord.axiosConfig,
headers: {
accept: 'image/*',
},
})
.then(async ({ headers }) => {
if (headers['content-type'].includes('image')) {
await sendDirect()
} else {
await sendDownload()
}
}, async () => {
await sendDownload()
})
.catch(() => {
throw new SenderError(data.url, data, this.selfId)
})
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion packages/adapter-discord/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { Adapter } from 'koishi-core'
import { AxiosRequestConfig } from 'axios'
import { DiscordBot } from './bot'
import { DiscordBot, HandleExternalAssets } from './bot'
import WsClient from './ws'
import * as DC from './types'
export * from './bot'

interface DiscordOptions extends Adapter.WsClientOptions {
endpoint?: string
axiosConfig?: AxiosRequestConfig
handleExternalAssets?: HandleExternalAssets
}

declare module 'koishi-core' {
Expand Down

0 comments on commit 12207bd

Please sign in to comment.