首先,如果你的机器人要在多个服务器上运行,它可能会被禁止 API,因为你会超过向消息添加反应的速率限制,如果我没记错的话,限制可能是 1 个反应每 0.25 秒一次。
无论如何,您所做的是正确的,但它只适用于一台服务器,因为 'emojisetting' 是机器人的全局变量。您可以创建一个对象数组来存储每个服务器的设置,例如:
emojisettings = [
{
guildID = 5365657435245;
enabled = true;
}
guildID = 3543265356345;
enabled = false;
}
]
在此示例中,我们为两个不同的服务器存储了两个设置,由它们的 ID 标识。此外,我们使用 true 和 false 代替 0/1,因为它更理想且易于处理。
那么我们需要让用户通过一个命令来处理这个设置,例如:
if (msg === prefix + 'START' || msg === prefix + 'STOP'){
//Define if enabling or not the bot
let enabling = true;
if(msg === prefix + 'STOP') enabling = false;
//Let's get the guild ID from the msg
let guildID = msg.guild.ID;
//Find the corresponding object in the array of the settings
let index = emojisettings.findIndex(element => element.guildID === guildID);
//If we found the guild setting
if(index >-1){
emojisettings[index].enabled = enabling;
}
//If not found that means the guild isn't stored in the array, so we need to create a new object for it
else{
emojisettings = emojisettings.push({guildID = msg.guild.ID, enabled = enabling});
}
//Reply to the message
if(enabling) message.channel.send("Snoopy is now reading the chat. :book:");
else message.channel.send("Snoopy is not reading the chat. :book:");
}
请记住,如果机器人停止,此设置将丢失,因此如果机器人停止运行,所有这些设置都将丢失,因此如果您想永久保留此设置,您将需要一个数据库,我建议您mongoDB,但还有很多其他的,如果你的机器人不在很多服务器上,你甚至可以使用一个简单的 json 文件,即使有时不是最佳且有风险。
之后我们可以简单地检查设置是否启用,如果启用则对消息做出反应:
bot.on('message', message => {
//Check if message was received in a server and not in DMs
if(message.channel.type !== 'text') return;
//Check if the setting is enabled for the server where you received the message
let enabled = emojisettings.find(element => element.guildID === message.guild.ID).enabled;
//If setting is enabled, react to the message
if (enabled) {
emojirandom = emojisnop[Math.floor(Math.random() * emojisnop.length)]
message.react(emojirandom)
}
}
});