Files
prosody-nodejs/examples/echo-bot.js
2025-12-27 03:39:14 +01:00

81 líneas
1.8 KiB
JavaScript

/**
* Simple example: Echo Bot
* A bot that echoes back any message sent to it
*/
const { Client } = require('@xmpp/client');
const { xml } = require('@xmpp/client');
// Bot configuration
const BOT_JID = 'echobot@localhost';
const BOT_PASSWORD = 'password';
const SERVER = 'localhost';
const PORT = 5222;
// Create XMPP client
const client = new Client({
service: `xmpp://${SERVER}:${PORT}`,
domain: 'localhost',
username: 'echobot',
password: BOT_PASSWORD
});
// Handle connection
client.on('online', async (address) => {
console.log(`Echo Bot online as ${address.toString()}`);
// Send initial presence
await client.send(xml('presence'));
console.log('Echo Bot ready to receive messages!');
});
// Handle incoming stanzas
client.on('stanza', async (stanza) => {
// Only process message stanzas
if (stanza.is('message')) {
const from = stanza.attrs.from;
const body = stanza.getChildText('body');
const type = stanza.attrs.type || 'chat';
// Ignore messages without body or from ourselves
if (!body || from === BOT_JID) return;
console.log(`Message from ${from}: ${body}`);
// Create echo response
const response = xml(
'message',
{ type, to: from },
xml('body', {}, `Echo: ${body}`)
);
// Send response
await client.send(response);
console.log(`Sent echo to ${from}`);
}
});
// Handle errors
client.on('error', (err) => {
console.error('Error:', err);
});
// Handle offline
client.on('offline', () => {
console.log('Echo Bot offline');
});
// Start the client
client.start().catch(console.error);
// Handle process termination
process.on('SIGINT', async () => {
console.log('\nShutting down Echo Bot...');
await client.stop();
process.exit(0);
});
console.log('Starting Echo Bot...');
console.log(`Connecting to ${SERVER}:${PORT} as ${BOT_JID}`);