javascript - 限制用户对消息的反应
问题描述
我正在为 JavaScript 中的 Discord 构建一个简单的投票机器人,现在我正在尝试实现每个用户对消息的最大反应数。
例如,假设我们对投票问题有以下选项:
问题?
选项 A
选项 B
选项 C
选项 D
选项 E
每个“选项”都是对机器人给出的消息的反应,我想确保用户不能对这些选项做出反应。 3
- 我的思路是做一个
messageReactionAdd
监听器,然后当用户对 做出反应时4th time
,删除最后一个反应,向他发送一条消息,例如“您已经投票3 times
,请删除反应以再次投票”。 - 尽管如此,我仍然试图在对象中导航以查找每个用户的总反应数,我可以找到 每个表情符号的总反应数,但这不是我需要的。
有人可以给我一些见解吗?
编辑
用于发送消息的代码:
Embed = new Discord.MessageEmbed()
.setColor(0x6666ff)
.setTitle(question)
.setDescription(optionsList);
message.channel.send(Embed).then(messageReaction => {
for (var i = 0; i < options.length; i++){
messageReaction.react(emojiAlphabet[i][0]);
}
message.delete().catch(console.error);
});
解决方案
尝试这个:
const {Collection} = require('discord.js')
// the messages that users can only react 3 times with
const polls = new Set()
// Collection<Message, Collection<User, number>>: stores how many times a user has reacted on a message
const reactionCount = new Collection()
// when you send a poll add the message the bot sent to the set:
polls.add(message)
client.on('messageReactionAdd', (reaction, user) => {
// edit: so that this does not run when the bot reacts
if (user.id === client.user.id) return
const {message} = reaction
// only do the following if the message is one of the polls
if (polls.has(message)) {
// if message hasn't been added to collection add it
if (!reactionCount.get(message)) reactionCount.set(message, new Collection())
// reaction counts for this message
const userCount = reactionCount.get(message)
// add 1 to the user's reaction count
userCount.set(user, (userCount.get(user) || 0) + 1)
if (userCount.get(user) > 3) {
reaction.users.remove(user)
// <@!id> mentions the user (using their nickname if they have one)
message.channel.send(`<@!${user.id}>, you've already voted 3 times, please remove a reaction to vote again.`)
}
}
})
client.on('messageReactionRemove', (reaction, user) => {
// edit: so that this does not run when the bot reacts
if (user.id === client.user.id) return
const {message} = reaction
const userCount = reactionCount.get(message)
// subtract 1 from user's reaction count
if (polls.has(message)) userCount.set(user, reactionCount.get(message).get(user) - 1)
})
推荐阅读
- r - 如何在 R 的数据框 (df) 内找到每个 data_point 的平均值?
- android - FileProvider 无法使用 无法找到包含的已配置根
- hadoop - 如何通过脚本并行运行选定的 Azkaban 作业?
- ios - 如何将多个故事板连接到单个 viewcontroler.swift 文件?
- php - 如何将特定字符串之后的所有字符串放入php中的数组中
- php - 条纹存款(预付)付款。需提前2个月向客户收费
- batch-file - 使用 NSIS 的 ExecDos 插件获取批处理脚本 exitCode
- mysql - mysql在where子句中重复子查询
- sql - 如何将 XML 值分解到 MSSQL 中的列中?
- cdi - CDI 1.1 Interceptor / InterceptorBinding 被调用两次