Bot总是发送相同的响应|Discord.js



我正在尝试制作一个机器人程序,当有人使用命令!say时,它会随机响应,但我想在有人第一次使用此命令时发送一些信息(然后在第一次使用后发送随机消息(。

例如:

  1. (首次(!say,响应:info
  2. (第二次(!say,响应:随机响应
  3. (第n次(!say,响应:随机响应

我尝试使用new Map(),这样它就可以保留执行该命令一次的id,然后如果映射具有消息作者的id,则发送随机响应。

但问题是,机器人总是以";信息";并且从不具有随机响应。

这是我的代码

if (!mention) {
message.channel.send("You need to tag someone")
} else {
if (map.has(message.author.id)) {
if (mention.id == message.author.id) {
message.channel.send(random2)
//map.set(message.author.id)
} else if (message.mentions.users.first().bot) {
message.channel.send(random3)
//map.set(message.author.id)
} else {
message.channel.send(random)
//map.set(message.author.id)
}
} else {
message.channel.send("info")
map.set(message.author.id, Date.now())
console.log(map)
}

您需要在事件处理程序之外定义map变量,这样就不需要在每个传入消息上创建一个新变量。不过请注意,当你重新启动你的机器人时,它仍然会重置。

const map = new Map();
client.on('message', async (message) => {
if (message.author.bot) return;
if (map.has(message.author.id)) {
message.reply('you have already sent a message');
} else {
message.reply('you have not sent a message yet');
map.set(message.author.id, Date.now());
}
});

您还可以简化if-else语句:

const map = new Map();
client.on('message', async (message) => {
// ...
// ...
// ...
if (!mention) {
return message.channel.send('You need to tag someone');
}
if (!map.has(message.author.id)) {
map.set(message.author.id, Date.now());
return message.channel.send('info');
}
if (mention.id == message.author.id) {
return message.channel.send(random2);
}
if (message.mentions.users.first().bot) {
return message.channel.send(random3);
}
return message.channel.send(random);
});

"地图";没有定义,所以它对代码来说就像是一个无用的东西const map = new Map();等…

最新更新