diff --git a/packages/koishi-utils/src/segment.ts b/packages/koishi-utils/src/segment.ts index 099cea1064..b3ddfd907f 100644 --- a/packages/koishi-utils/src/segment.ts +++ b/packages/koishi-utils/src/segment.ts @@ -1,3 +1,5 @@ +import { types } from 'util' + export interface segment { type: string data: segment.Data @@ -82,18 +84,29 @@ export namespace segment { }).join('') } - export type Factory = (value: primitive, data?: segment.Data) => string + export type Factory = (value: T, data?: segment.Data) => string - function createFactory(type: string, key: string): Factory { + function createFactory(type: string, key: string): Factory { return (value, data = {}) => segment(type, { ...data, [key]: value }) } + function createAssetFactory(type: string): Factory { + return (value, data = {}) => { + if (Buffer.isBuffer(value)) { + value = 'base64://' + value.toString('base64') + } else if (types.isArrayBuffer(value)) { + value = 'base64://' + Buffer.from(value).toString('base64') + } + return segment(type, { ...data, url: value }) + } + } + export const at = createFactory('at', 'id') export const sharp = createFactory('sharp', 'id') export const quote = createFactory('quote', 'id') - export const image = createFactory('image', 'url') - export const video = createFactory('video', 'url') - export const audio = createFactory('audio', 'url') + export const image = createAssetFactory('image') + export const video = createAssetFactory('video') + export const audio = createAssetFactory('audio') } export { segment as s } diff --git a/packages/plugin-puppeteer/src/index.ts b/packages/plugin-puppeteer/src/index.ts index f1491674e6..250e631a4a 100644 --- a/packages/plugin-puppeteer/src/index.ts +++ b/packages/plugin-puppeteer/src/index.ts @@ -159,7 +159,7 @@ export function apply(ctx: Context, config: Config = {}) { buffer = PNG.sync.write(png) }).catch(noop) } - return segment.image('base64://' + buffer.toString('base64')) + return segment.image(buffer) }, (error) => { logger.debug(error) return '截图失败。' diff --git a/packages/plugin-tools/src/weather.ts b/packages/plugin-tools/src/weather.ts index 5dd9d36117..07694b9a16 100644 --- a/packages/plugin-tools/src/weather.ts +++ b/packages/plugin-tools/src/weather.ts @@ -22,7 +22,7 @@ export function apply(ctx: Context) { params: { lon, lat, lang, unit }, responseType: 'arraybuffer', }) - return segment.image('base64://' + Buffer.from(data).toString('base64')) + return segment.image(data) } catch (error) { ctx.logger('tools').warn(error) }