Skip to content

Instantly share code, notes, and snippets.

@dragon-fish
Last active December 10, 2021 14:11
Show Gist options
  • Save dragon-fish/1a03d0d40dec2cb39ba9c6bd21b2487c to your computer and use it in GitHub Desktop.
Save dragon-fish/1a03d0d40dec2cb39ba9c6bd21b2487c to your computer and use it in GitHub Desktop.
Koishi plugin QQ Channel Patch
/**
* @name koishi-plugin-qq-channel-patch
* @author Dragon-Fish <dragon-fish@qq.com>
*
* @desc Temporary patch for QQ channel for koishi.js
*/
// Packages
const { CQBot } = require('koishi-adapter-onebot')
const { segment } = require('koishi-core')
/**
* @param {import('koishi-core').Context} ctx
*/
function apply(ctx) {
// Adjust guild cahnnelId
ctx.on('message', (session) => {
if (session.subtype === 'guild') {
session.channelId = `guild:${session.guildId || ''}-${session.channelId}`
}
})
// Hack Adapter Onebot
CQBot.prototype.sendMessage = function (channelId, content) {
content = renderText(content)
if (channelId.startsWith('private:')) {
return this.sendPrivateMessage(channelId.slice(8), content)
} else if (channelId.startsWith('guild:')) {
return this.sendGuildMessage(channelId.slice(6), content)
} else {
return this.sendGroupMessage(channelId, content)
}
}
CQBot.prototype.sendGuildMessage = async function (channel, content) {
if (!content) return
const [guildId, channelId] = channel.split('-')
const session = this.createSession({
content,
subtype: 'guild',
guildId,
channelId,
})
if (this.app.bail(session, 'before-send', session)) return
session.messageId = (
await this.get('send_guild_channel_msg', {
guild_id: guildId,
channel_id: channelId,
message: content,
})
).messageId
this.app.emit(session, 'send', session)
return session.messageId
}
}
function renderText(source) {
return segment.parse(source).reduce((prev, { type, data }) => {
if (type === 'at') {
if (data.type === 'all') return prev + '[CQ:at,qq=all]'
return prev + `[CQ:at,qq=${data.id}]`
} else if (['video', 'audio', 'image'].includes(type)) {
if (type === 'audio') type = 'record'
if (!data.file) data.file = data.url
} else if (type === 'quote') {
type = 'reply'
}
return prev + segment(type, data)
}, '')
}
module.exports = {
name: 'qq-channel-patch',
apply,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment