Я сделал код для приема команд !favNum
и !favColor
. Если аргументы не переданы, бот попытается получить сохраненное значение; если аргумент передан, бот сохранит это значение.
Обработчик событий сообщений прослушивает сообщения на всех серверах, как указано Jakye в комментариях :
Событие клиента, message
, прослушивает сообщения со всех серверов, на которых работает ваш бот. Вы можете использовать message.guild
, чтобы получить Guild
.
Предупреждение: следующий код потеряет все данные, если бот перезапустится.
// Set a prefix for commands
const prefix = '!';
// Create a collection for all data
const data = new Discord.Collection();
// Create individual collections for different pieces of data
data.set('favNum', new Discord.Collection());
data.set('favColor', new Discord.Collection());
client.on('message', message => {
// Exit if the message was sent by a bot or doesn't start with the command prefix
if (message.author.bot || !message.content.startsWith(prefix)) return;
// Split the message into a command and arguments
const args = message.content.slice(prefix.length).trim().split(/\s+/g);
const command = args.shift().toLowerCase();
// Execute a section of code depending on what the command was
switch (command) {
// Favourite number command
case 'favNum':
// If no arguments were passed, try to get the saved value
if (!args[0]) {
if (!data.get('favNum').has(message.author.id)) return message.reply(`you haven't set a favorite number.`);
const favNum = data.get('favNum').get(message.author.id);
message.reply(`your favorite number is ${favNum}.`);
}
// If arguments were passed, set the value
data.get('favNum').set(message.author.id, args[0]);
break;
// Favourite color command
case 'favColor':
// If no arguments were passed, try to get the saved value
if (!data.get('favColor').has(message.author.id)) return message.reply(`you haven't set a favorite color.`);
const favColor = data.get('favColor').get(message.author.id);
message.reply(`your favorite color is ${favColor}.`);
}
// If arguments were passed, set the value
data.get('favColor').set(message.author.id, args[0]);
break;
// Default reply if the command was not recognized
default:
message.reply(`could not recognize the command \`command\`.`);
});