Skip to content

Instantly share code, notes, and snippets.

@acollierr17
Last active May 9, 2021 22:16
Show Gist options
  • Save acollierr17/c9e7aaf9eba97d8659b59395b5f2046d to your computer and use it in GitHub Desktop.
Save acollierr17/c9e7aaf9eba97d8659b59395b5f2046d to your computer and use it in GitHub Desktop.
Select a random user from a collection of users who reacted to the first reaction of a message via a given message ID. Example code is used for giveaways.
// THIS IS FOR
const { Client } = require('discord.js');
const client = new Client();
const g_channel_id = ''; // This should be a String and the channel ID of the giveaways channel
const g_message_id = ''; // This should be a String and the message ID of the givaway message
const winner_amount = ''; // This shiuld be a Number and it represents how many winners you wish to choose
client.on('ready', () => {
console.log('Bot is ready!');
};
client.on('message', async message => {
if (message.author.bot) return;
if (message.content.startsWith('randomuser')) {
let c = message.guild.channels.find(c => c.name === 'giveaways');
let m = await c.fetchMessage(MESSAGE_ID);
let reactions = m.reactions;
let reaction = reactions.first(); // This reaction would normally be the reaction a user would use to enter the giveawahy
let users = reaction.users.map(u => u.toString());
return message.channel.send(`**${users.random()}** has won the giveaway!`); // this uses the Array.prototpe.random method below
const c = message.guild.channels.get(g_channel_id);
const m = await c.fetchMessage(g_message_id);
const reactions = m.reactions;
const reaction = reactions.first(); // This reaction would normally be the reaction a user would use to enter the giveaway
const users = reaction.users.map(u => u.toString());
if (winner_amount == 1) {
return c.send(`**${users.random()}** has won the giveaway!`); // this uses the Array.prototpe.random method below
} else {
let winners;
const selected = randomAmount(users, winner_amount); // this uses the Array.prototype.randomAmount method below
if (winner_amount === 2) winners = selected.join(' and ');
else winners = selected.join(', ');
return c.send(`**${winners}** have won the giveaway!`);
}
}
});
client.login(TOKEN);
Array.prototype.random = function () {
return this[Math.floor(Math.random() * this.length)];
};
Array.prototype.randomAmount = function (array, length) => {
let arr = [];
for (let i = 0; i < length; i++) {
arr.push(array.random());
}
return arr;
};
@acollierr17
Copy link
Author

its give error
:(
can you help

I don't maintain this piece of code anymore, sorry. Also, I'm not a wizard or a super computer, so giving me so little information doesn't help me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment