Discord js giveaway command - javascript

I am currently trying to make a Discord.js command where the first person who reacts wins the prize. There are 2 issues that I am encountering right now. First, the bot is picking up the last prize that was entered through with the command rather than the current one. Secondly, the giveaway sent before a bot restart won't work after the bot restarts.
Here is the code:
const DropModel = require('../modules/DropModel');
const { MessageEmbed, ReactionCollector } = require("discord.js")
const { COLOR, MONGO } = require("../util/BotUtil");
module.exports = {
name: "drop",
description: "First to react wins the giveaway!",
async execute(message, args) {
let prizes = args.slice(0).join(' ').toString()
if (!prizes) return message.channel.send("You didn't provide a prize.");
const newDrop = new DropModel({
guildId: message.guild.id,
prize: prizes,
channelId: message.channel.id,
createdBy: message.author,
timeCreated: new Date(),
});
newDrop.save();
let Drops = await DropModel.findOne({ guildId: message.guild.id, channelId: message.channel.id });
if (!Drops) return;
const { prize, createdBy } = Drops;
const DropEmbed = new MessageEmbed()
.setTitle(`${prize}`)
.setDescription(`First to React with 🎁 wins the giveaway
Hosted by: ${createdBy}`)
.setColor(COLOR)
.setTimestamp();
const dropMsg = await message.channel.send(`🎁 **giveaway** 🎁`, DropEmbed);
await Drops.remove();
await dropMsg.react('🎁');
const filter = (reaction, user) => !user.bot;
const reaction = new ReactionCollector(dropMsg, filter, { max: 1 });
reaction.on('collect', async (reaction, user) => {
const { embeds } = dropMsg;
const embed = embeds[0];
embed.setTitle(`Someone called giveaway!`);
embed.setDescription(`Winner: ${user.toString()}
Please contact ${createdBy} to claim your giveaway!`);
await dropMsg.edit(embed);
dropMsg.channel.send(`${user.toString()} won **${prize}**!`);
});
}
}
Any help regarding the issues mentioned above would be appreciated! Thanks!

You can save the giveaway end timestamp in JSON file or whatever database and then delete it when it's finished.

Related

Discord.js Adding Emojis to a send message and grab the message id

Hey Stack Overflow Community,
I have another question in regard to discord.js.I want to send a message and add an emoji to it, from which I later want to get the list of users who have reacted. In order to do so I have 2 questions:
-How can I add an emoji? Do I need a separate event listener for a message or can I do it within my interactionCreate event? I have tried pannel.react("👍") which gives me the error: 'TypeError: pannel.react is not a function'. Does anyone know how to let this work?
-My other question is if there is a way to access the message id from the send message, in order to check who has participated later on in another command?
I have an index file with my command and event handlers. The script is from my "setup.js" command in the "commands" folder:
const { SlashCommandBuilder } = require("#discordjs/builders");
const Discord = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("setup")
.setDescription("Setup Tweet to be rewarded")
.addChannelOption(option =>
option
.setName('destination')
.setDescription('Select a channel for the reward pannel')
.setRequired(true)
)
.addStringOption(option =>
option
.setName("twitterlink")
.setDescription("Enter the Twitter Link")
.setRequired(false)
),
async execute(interaction) {
interaction.reply({
content: "Pannel send",
ephemeral: true
}).then( function () {
const channel = interaction.options.getChannel("destination");
const channelid = channel.id;
const twitterlink = interaction.options.getString("twitterlink");
const pannel = interaction.guild.channels.cache.get(channelid).send(twitterlink);
});
}
};
Thank you very much for your assistance in advance.
Cleaned it up a bit and this should work for you
const {
SlashCommandBuilder,
} = require("#discordjs/builders");
const Discord = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("setup")
.setDescription("Setup Tweet to be rewarded")
.addChannelOption(option =>
option
.setName('destination')
.setDescription('Select a channel for the reward pannel')
.setRequired(true),
)
.addStringOption(option =>
option
.setName("twitterlink")
.setDescription("Enter the Twitter Link")
.setRequired(false),
),
async execute(interaction) { // Fixed below here and simplified it
const channel = interaction.guild.channels.cache.get(interaction.options.getChannel("destination").id);
const twitterlink = interaction.options.getString("twitterlink");
channel.send(twitterlink).then(msg => {
msg.react('🍎'),
});
return interaction.reply({
content: "Pannel send",
ephemeral: true,
});
},
};
Okay with the help from #Gh0st I was able to find a solution:
The problem in order to send a message is that the .get() function need the channel id. I have accessd it to interaction.options.getChannel("destination").id);.
I couldnt add a reaction because my .send command was not await: const pannel = await channel.send(twitterlink).
The message id is easiy to find by using .id on the variable of the message:
const pannelid = pannel.id.
The resulting code can be found below:
const { SlashCommandBuilder } = require("#discordjs/builders");
const Discord = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("setup")
.setDescription("Setup Tweet to be rewarded")
.addChannelOption(option =>
option
.setName('destination')
.setDescription('Select a channel for the reward pannel')
.setRequired(true)
)
.addStringOption(option =>
option
.setName("twitterlink")
.setDescription("Enter the Twitter Link")
.setRequired(false)
),
async execute(interaction) { // Fixed below here and simplified it
const channel = interaction.guild.channels.cache.get(interaction.options.getChannel("destination").id);
const twitterlink = interaction.options.getString("twitterlink");
const pannel = await channel.send(twitterlink)
pannel.react('🍎');
const pannelid = pannel.id
return interaction.reply({
content: "Pannel send",
ephemeral: true,
});
},
};

Reacting to the emoji only once - Discord.js

I am developing this bot, and I want the user to be able to react only once in the emoji, and if he reacts other times the command does not work. Can someone help me?
let messagereturn = await message.channel.send(embed);
await messagereturn.react('🔁');
const reactions = ['🔁'];
const filter = (reaction, user) => reactions.includes(reaction.emoji.name) && user.id === User.id;
const collector = messagereturn.createReactionCollector(filter)
collector.on('collect', async emoji => {
switch(emoji._emoji.name) {
case('🔁'):
const embed1 = new Discord.MessageEmbed()
.setColor('#00ff00')
.setDescription(`${User} **deu um tapa em** ${message.author}`)
.setImage(rand)
await message.channel.send(embed1)
}
})
The createReactionCollector method has an optional options object, and it allows you to set the max reactions to collect, which in your case is 1.
example:
const collector = messagereturn.createReactionCollector(filter, { max: 1 })

I'm trying to create a channel named like user args. [DISCORD.JS V12]

It just gives me an error that the function message.guild.channels.create does not work because it's not a correct name.
My intention is to create a command where you will be asked how the channel you want to create be named. So it's ask you this. After this you send the wanted name for the channel. Now from this the bot should name the channel.
(sorry for bad english and low coding skills, im a beginner)
module.exports = {
name: "setreport",
description: "a command to setup to send reports or bugs into a specific channel.",
execute(message, args) {
const Discord = require('discord.js')
const cantCreate = new Discord.MessageEmbed()
.setColor('#f07a76')
.setDescription(`Can't create channel.`)
const hasPerm = message.member.hasPermission("ADMINISTRATOR");
const permFail = new Discord.MessageEmbed()
.setColor('#f07a76')
.setDescription(`${message.author}, you don't have the permission to execute this command. Ask an Admin.`)
if (!hasPerm) {
message.channel.send(permFail);
}
else if (hasPerm) {
const askName = new Discord.MessageEmbed()
.setColor(' #4f6abf')
.setDescription(`How should the channel be called?`)
message.channel.send(askName);
const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, { max: 1, time: 10000 });
console.log(collector)
var array = message.content.split(' ');
array.shift();
let channelName = array.join(' ');
collector.on('collect', message => {
const created = new Discord.MessageEmbed()
.setColor('#16b47e')
.setDescription(`Channel has been created.`)
message.guild.channels.create(channelName, {
type: "text",
permissionOverwrites: [
{
id: message.guild.roles.everyone,
allow: ['VIEW_CHANNEL','READ_MESSAGE_HISTORY'],
deny: ['SEND_MESSAGES']
}
],
})
.catch(message.channel.send(cantCreate))
})
}
else {
message.channel.send(created)
}
}
}
The message object currently refers to the original message posted by the user. You're not declaring it otherwise, especially seeing as you're not waiting for a message to be collected before defining a new definition / variable for your new channel's name.
NOTE: In the following code I will be using awaitMessages() (Message Collector but promise dependent), as I see it more fitting for this case (Seeing as you're more than likely not hoping for it to be asynchronous) and could clean up the code a little bit.
const filter = m => m.author.id === message.author.id
let name // This variable will later be used to define our channel's name using the user's input.
// Starting our collector below:
try {
const collected = await message.channel.awaitMessages(filter, {
max: 1,
time: 30000,
errors: ['time']
})
name = collected.first().content /* Getting the collected message and declaring it as the variable 'name' */
} catch (err) { console.error(err) }
await message.guild.channels.create(name, { ... })

Discord avatar display code is not running

I wanted to use the command "-ava #(user)" to display the avatar of the specified user. I created this code but I'm not sure why when I type the command in discord where the bot is, nothing is returned. This is the following code for my discord bot:
const BaseCommand = require('../../utils/structures/BaseCommand');
const Discord = require('discord.js');
module.exports = {
name: 'ava',
description: 'Provide user with certain avatar as requested.',
execute(message, args) {
if (args[0]) {
const user = message.mentions.users.first();
if (!user) return message.reply('Please mention a user to access their avatar');
const otherIconEmbed = new Discord.RichEmbed()
.setTitle(`${user.username}'s Avatar`)
.setImage(user.displayAvatarURL);
message.channel.send(otherIconEmbed).catch(err => console.log(err));
}
const myIconEmbed = new Discord.RichEmbed()
.setTitle(`${message.author.username}'s avatar!`)
.setImage(message.author.displayAvatarURL);
message.channel.send(myIconEmbed).catch(err => console.log(err));
}
}
Simply you have to put () after displayAvatarURL so it gives displayAvatarURL () and if you want to make it animated you must put displayAvatarURL ({dynamic: true}) 🙂

How to fix Discord API: Unknown Message error?

I'm trying to make a meme command but whenever I try to use it I get this error "DiscordAPIError: Unknown Message".
This was working earlier but when I came back to my PC it started glitching out.
Here's my code
const { RichEmbed } = require("discord.js");
const randomPuppy = require("random-puppy");
const usedCommandRecently = new Set();
module.exports = {
name: "meme",
aliases: ["memes", "reddit"],
category: "fun",
description: "Sends a random meme",
run: async (client, message, args) => {
if (message.deletable) message.delete();
var Channel = message.channel.name
//Check it's in the right channel
if(Channel != "memes") {
const channelembed = new RichEmbed()
.setColor("BLUE")
.setTitle(`Use me in #memes`)
.setDescription(`Sorry ${message.author.username} this command is only usable in #memes !`)
return message.channel.send(channelembed);
}
//Check cooldown
if(usedCommandRecently.has(message.author.id)){
const cooldownembed = new RichEmbed()
.setColor("GREEN")
.setTitle("Slow it down, pal")
.setDescription(`Sorry ${message.author.username} this command has a 30 second cooldown per member, sorry for any inconvenice this may cause`)
message.channel.send(cooldownembed)
} else{
//Post meme
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
const img = await randomPuppy(random);
const embed = new RichEmbed()
.setColor("RANDOM")
.setImage(img)
.setTitle(`From /r/${random}`)
.setURL(`https://reddit.com/r/${random}`);
message.channel.send(embed);
}
}
}
Im not sure, but maybe problem in your require block.
const { RichEmbed } = require("discord.js");
the right way its:
const Discord = require("discord.js");
let cooldownembed = new Discord.RichEmbed();
and why you use return here
return message.channel.send(channelembed);

Categories

Resources