第一次海报在这里。很抱歉,如果这是一个明显的解决方法,但对于Nodejs和一般编程人员来说,我还是一个新手。
我目前正在尝试创建一个Discord机器人,该机器人可让任何用户使用!vote命令启动“喜欢它或讨厌它”投票。一旦开始投票,机器人就会发出宣布投票的消息,然后用心脏和头骨表情符号对自己的消息做出反应,分别表示爱和恨选项。 这部分按预期工作。
经过一段设定的时间(很短的时间)后,机器人应计算表情符号反应并找出是否有更多的心,更多的头骨或两者相等。根据结果,它将发送另一条消息宣布投票结果。 这部分无法正常工作。
就目前情况而言,我可以通过在聊天室中发送新消息并使用适当的表情符号对该消息做出反应,来使漫游器响应我的!vote命令。机器人还将等待设定的时间,并宣布投票结果。但是,它总是宣布投票是中立的,无论我在计时器过期之前点击了哪个表情符号(当然,请确保我没有同时点击两者)。
我的用于明显比较选票数的代码无法正常运行。但是,在花了几个小时尝试了不同的修复程序之后,我无法找出解决方案,这使我发疯。有一部分不正确吗?如果是这样,我该如何解决?
非常感谢所有能够发出声音的人。潜伏了一段时间并在过去找到其他人的问题后,我想我终于会向Stack Overflow的好心人寻求帮助。你们摇滚!
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.on('message', function(message){
if(message.content.toLowerCase().startsWith('!vote'))
{
var heartCount = 0;
var skullCount = 0;
message.channel.send(
"The vote begins! Do we love it or hate it?")
.then(async function (message){
try {
await message.react("❤️")
await message.react("?")
}
catch (error) {
console.error('One of the emojis failed to react.');
}
})
const filter = (reaction, user) => {
return ["❤️","?"].includes(reaction.emoji.name) && user.id === message.author.id };
message.awaitReactions(filter, {time: 10000})
.then(collected => {
for (var i = 0; i < collected.length; i++){
if (collected[i].emoji.name === "❤️")
{heartCount++;}
else if (collected[i].emoji.name === "?")
{skullCount++;}
};
if (heartCount > skullCount){
message.channel.send("We love it!");
}
else if (heartCount < skullCount){
message.channel.send("We hate it.");
}
else {
message.channel.send("We're neutral about it.");
}
})
}
});
bot.login(process.env.BOT_TOKEN);
答案 0 :(得分:0)
第一个问题是user.id === message.author.id
,因此只有消息作者可以做出反应。 message.channel.send
返回新消息的承诺,因此您可以使用then =>
进行消息响应。最好使用操作collector on collect
获取计数,然后在收集器结束时发送一条消息。
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.on('message', function(message){
var heartCount = 0;
var skullCount = 0;
if(message.content.toLowerCase().startsWith('!vote')) {
message.channel.send('The vote begins! Do we love it or hate it?').then(msg => {
msg.react(`❤️`).then(() => msg.react('?'));
const filter = (reaction, user) => {
return [`❤️`, '?'].includes(reaction.emoji.name);
};
const collector = msg.createReactionCollector(filter, {time: 10000});
collector.on('collect', (reaction, reactionCollector) => {
if (reaction.emoji.name === `❤️`) {
heartCount+=1
} else if (reaction.emoji.name === `?`) {
skullCount+=1
}
});
collector.on('end', (reaction, reactionCollector) => {
if (heartCount > skullCount){
message.channel.send("We love it!");
}
else if (heartCount < skullCount){
message.channel.send("We hate it.");
}
else {
message.channel.send("We're neutral about it.");
}
});
})
}
})