93 lines
2.1 KiB
JavaScript
93 lines
2.1 KiB
JavaScript
/**
|
|
* Echo Bot Example
|
|
*
|
|
* A simple bot that echoes back messages that start with "!echo"
|
|
*
|
|
* Usage:
|
|
* node echo-bot.js <api-key> <server-url> <realm-id>
|
|
*
|
|
* Example:
|
|
* node echo-bot.js abc123 wss://example.com/chat/ws my-realm
|
|
*/
|
|
|
|
import ChatBot from '../index.js';
|
|
|
|
// Get arguments
|
|
const [,, apiKey, serverUrl, realmId] = process.argv;
|
|
|
|
if (!apiKey || !serverUrl || !realmId) {
|
|
console.log('Usage: node echo-bot.js <api-key> <server-url> <realm-id>');
|
|
console.log('Example: node echo-bot.js abc123 wss://example.com/chat/ws my-realm');
|
|
process.exit(1);
|
|
}
|
|
|
|
// Create the bot
|
|
const bot = new ChatBot('EchoBot');
|
|
|
|
// Set up message handler
|
|
bot.messageHandler = (message) => {
|
|
console.log(`[${message.username}]: ${message.content}`);
|
|
|
|
// Echo back messages that start with !echo
|
|
if (message.content.startsWith('!echo ')) {
|
|
const echoText = message.content.slice(6);
|
|
bot.print(echoText);
|
|
}
|
|
|
|
// Respond to !hello
|
|
if (message.content === '!hello') {
|
|
bot.print(`Hello, ${message.username}!`);
|
|
}
|
|
|
|
// Show help
|
|
if (message.content === '!help') {
|
|
bot.print('Commands: !echo <text>, !hello, !help');
|
|
}
|
|
};
|
|
|
|
// Set up event handlers
|
|
bot.onConnect = () => {
|
|
console.log('Bot connected!');
|
|
};
|
|
|
|
bot.onJoin = (room) => {
|
|
console.log(`Bot joined room: ${room}`);
|
|
bot.print('EchoBot is online! Type !help for commands.');
|
|
};
|
|
|
|
bot.onParticipantJoin = (participant) => {
|
|
console.log(`${participant.username} joined the chat`);
|
|
};
|
|
|
|
bot.onParticipantLeave = (participant) => {
|
|
console.log(`${participant.username} left the chat`);
|
|
};
|
|
|
|
bot.onError = (error) => {
|
|
console.error('Bot error:', error.message);
|
|
};
|
|
|
|
// Connect and join
|
|
async function main() {
|
|
try {
|
|
console.log(`Connecting to ${serverUrl}...`);
|
|
await bot.connect(apiKey, serverUrl);
|
|
|
|
console.log(`Joining room: ${realmId}...`);
|
|
await bot.joinRoom(realmId);
|
|
|
|
console.log('Bot is running. Press Ctrl+C to stop.');
|
|
} catch (error) {
|
|
console.error('Failed to start bot:', error.message);
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
// Handle shutdown
|
|
process.on('SIGINT', () => {
|
|
console.log('\nShutting down bot...');
|
|
bot.disconnect();
|
|
process.exit(0);
|
|
});
|
|
|
|
main();
|