Whenever a message containing the word "poll" is posted in your server, treat the message like a poll. Whatever reaction is the first one to exceed the threshold defined on line 3 of the snippet wins the poll.
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});
let pollThreshold = 1; // Number of reactions required to win a poll.
let reactedMessage = await lib.discord.channels['@0.1.1'].messages.retrieve({
message_id: `${context.params.event.message_id}`,
channel_id: `${context.params.event.channel_id}`
});
let pollClosed = reactedMessage.reactions.find((reaction) => {
return reaction.me && reaction.emoji.name === 'π';
});
if (reactedMessage.content.toLowerCase().includes('poll') && !pollClosed) {
let mostCommonReaction = reactedMessage.reactions.reduce((currentLeader, reaction) => {
if (reaction.count > currentLeader.count) {
return reaction;
} else {
return currentLeader;
}
}, {count: 0});
if (mostCommonReaction.count >= pollThreshold) {
await lib.discord.channels['@0.1.1'].messages.reactions.create({
emoji: `π`,
message_id: `${context.params.event.message_id}`,
channel_id: `${context.params.event.channel_id}`
});
let victoryString = `The winner of the poll, with **${mostCommonReaction.count}** votes, is `;
if (mostCommonReaction.emoji.id) {
victoryString = victoryString + `<:${mostCommonReaction.emoji.name}:${mostCommonReaction.emoji.id}>`;
} else {
victoryString = victoryString + mostCommonReaction.emoji.name;
}
await lib.discord.channels['@0.1.1'].messages.create({
channel_id: `${context.params.event.channel_id}`,
content: victoryString,
message_reference: {
'message_id': `${context.params.event.message_id}`
}
});
}
}