I’m in the process of developing a Discord bot while learning JavaScript, and I have some queries regarding its functionality:
Given that JavaScript doesn’t support multithreading, how can the bot manage multiple events from different servers? Specifically, how does it handle variables? For example, if the same event occurs in multiple servers, will the values interfere with each other?
Here’s an example of my code for context:
const { Client } = require('discord.js');
const bot = new Client();
const apiKey = 'your-token';
bot.on('ready', () => {
console.log('Bot is operational!');
});
bot.on('message', msg => {
if (msg.content.startsWith('nyan!')) {
let command = msg.content.slice(5); // Store command in a variable
if (command.includes('(')) {
switch (command.split('(')[0].trim()) {
case 'createChannel':
console.log(bot.guilds);
bot.guilds.cache.forEach(guild => {
console.log(guild);
guild.channels.create('new-general', { type: 'text' });
});
break;
}
} else {
switch (command) {
case 'ping':
msg.channel.send(`Ping: ${bot.ws.ping}`);
break;
case 'shutdown':
msg.channel.send("I'll return").then(() => {
bot.destroy();
process.exit();
});
break;
}
}
}
});
bot.login(apiKey);