chipmunkbot3/plugins/matrix.js

92 lines
2.6 KiB
JavaScript

const matrix = require('matrix-js-sdk')
const htmlStringify = require('../util/chat/html_stringifier')
const CommandSource = require('../util/command/command_source')
function inject (bot, options) {
if (!options.matrix?.enabled) return
bot.matrix = {
client: options.matrix.client ?? matrix.createClient(options.matrix),
roomId: options.matrix.roomId,
commandPrefix: options.matrix.commandPrefix
}
bot.on('chat', async message => {
sendMessage(message)
})
bot.matrix.client.on('Room.timeline', (event, room, toStartOfTimeline) => {
if (event.getRoomId() !== bot.matrix.roomId || event.getType() !== 'm.room.message' || event.sender.userId === bot.matrix.client.getUserId()) return
const content = event.getContent()
let message = content.body
if (content.url) {
message = {
text: '[Attachment]',
color: bot.colors.primary,
clickEvent: {
action: 'open_url',
value: bot.matrix.client.mxcUrlToHttp(content.url)
}
}
} else if (message.startsWith(bot.matrix.commandPrefix)) {
const source = new CommandSource({ bot, permissionLevel: 1, sendFeedback })
bot.commands.execute(message.substring(bot.matrix.commandPrefix.length), source)
return
}
const senderText = {
text: String(event.sender.rawDisplayName || event.sender.name || event.sender.userId),
hoverEvent: {
action: 'show_text',
contents: ['User ID: ', String(event.sender.userId), '\nClick to copy the user id']
},
clickEvent: {
action: 'copy_to_clipboard',
value: String(event.sender.userId)
}
}
bot.fancyMsg('ChipmunkBot Matrix', senderText, message)
})
let dequeuingMessages = false
let queue = []
async function sendMessage (message) {
const html = htmlStringify(message, { lang: bot.registry.language })
queue.push(html)
if (dequeuingMessages) return
dequeuingMessages = true
while (queue.length !== 0) {
const html = queue.join('<br>')
queue = []
await _sendMessage(html)
}
dequeuingMessages = false
}
async function _sendMessage (html) {
const content = {
msgtype: 'm.text',
format: 'org.matrix.custom.html',
body: html,
formatted_body: html,
'm.mentions': {}
}
try {
await bot.matrix.client.sendEvent(bot.matrix.roomId, 'm.room.message', content, '')
} catch (error) {
console.error('Unable to send Matrix message:', error)
}
}
function sendFeedback (text, sendFeedback) {
sendMessage(text)
}
}
module.exports = inject