You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
tellme-bot/packages/server/plugins/xmpp.js

74 lines
1.6 KiB

3 years ago
/**
* plugin for handle xmpp in tellme-bot
*
* create event send-message
*
* @author Björn Hase
* @license hhttps://www.gnu.org/licenses/gpl-3.0.en.html GPL-3
* @link https://gitea.node001.net/HerrHase/tellme-bot.git
*
*/
import { client, xml } from '@xmpp/client'
export default function (fastify, options, done) {
/**
* handler for send-message event
*
* @param {object} data
*
*/
async function handleSendMessage(data) {
2 years ago
let send = false
3 years ago
// Sends a chat message to itself
const message = xml(
2 years ago
'message', {
3 years ago
type: 'chat',
to: options.to
},
xml('body', {}, data.message)
)
2 years ago
try {
await xmpp.send(message)
} catch (error) {
console.log(error)
}
3 years ago
}
const xmpp = client({
service: options.service,
domain: options.domain,
username: options.username,
password: options.password
})
// handle if client has errors
xmpp.on('error', (error) => {
console.error(error)
})
// handle if client goes online
2 years ago
xmpp.on('online', (address) => {
console.log('Xmpp: connected to ' + address)
3 years ago
// check for event and remove it
if (fastify.eventEmitter.listeners('send-message').length > 0) {
fastify.eventEmitter.off('send-message', handleSendMessage)
}
// add event if client going online
fastify.eventEmitter.on('send-message', handleSendMessage)
})
// connect
xmpp
.start()
.catch(console.log)
done()
2 years ago
}