Skip to content

Commit

Permalink
feat(utils): support segment.image(buffer)
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Mar 31, 2021
1 parent 217fbcd commit 02691b8
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 7 deletions.
23 changes: 18 additions & 5 deletions packages/koishi-utils/src/segment.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { types } from 'util'

export interface segment {
type: string
data: segment.Data
Expand Down Expand Up @@ -82,18 +84,29 @@ export namespace segment {
}).join('')
}

export type Factory = (value: primitive, data?: segment.Data) => string
export type Factory<T> = (value: T, data?: segment.Data) => string

function createFactory(type: string, key: string): Factory {
function createFactory(type: string, key: string): Factory<primitive> {
return (value, data = {}) => segment(type, { ...data, [key]: value })
}

function createAssetFactory(type: string): Factory<string | Buffer | ArrayBuffer> {
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 }
2 changes: 1 addition & 1 deletion packages/plugin-puppeteer/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 '截图失败。'
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-tools/src/weather.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down

0 comments on commit 02691b8

Please sign in to comment.