Reacting to the emoji only once - Discord.js - javascript

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 })

Related

Quick.db .add function not working correctly

Im making an addmoney cmd for my discord bot but when the money, it gets added weirdly.
Eg. normally it would be 200 if i add 100 and there was already 100 but im my occasion its 100100.
Anyways code:
const { QuickDB } = require('quick.db');
const db = new QuickDB();
const discord = require("discord.js")
module.exports.run = async (bot, message, args) => {
if (!message.member.permissions.has("ADMINISTRATOR")) return message.reply("You do not have the permissions to use this commandπŸ˜”.")
if (!args[0]) return message.reply("Please specify a user❗")
let user = message.channel.members.first() || message.guild.members.cache.get(args[0]) || messsage.guild.members.cache.find(r => r.user.username.toLowerCase() === args[0].toLocaleLowerCase()) || message.guild.member.cache.find(r => r.displayName.toLowerCase() === args[0].toLocaleLowerCase())
if (!user) return message.reply("Enter a valid userβ›”.")
if (!args[1]) return message.reply("Please specify the amount of moneyπŸ’°.")
var embed = new discord.MessageEmbed()
.setColor("#C06C84")
.setAuthor(message.author.tag, message.author.displayAvatarURL({dynamic: true}))
.setDescription(`Cannot give that much moneyβ›”.
Please specify a number under 10000πŸ’Έ.`)
.setTimestamp()
if (isNaN(args[1]) ) return message.reply("Your amount is not a number❗.")
if (args[0] > 10000) return message.reply({embeds: [embed]})
await db.add(`money_${user.id}`, args[1])
let bal = await db.get(`money_${user.id}`)
let moneyEmbed = new discord.MessageEmbed()
.setColor("#C06C84")
.setDescription(`Gave $${args[1]} \n\nNew Balance: ${bal}`)
message.reply({embeds: [moneyEmbed]})
}
module.exports.help = {
name: "addmoney",
category: "economy",
description: 'Adds money!',
}
One way you could get this kind of behaviour is if args[1] was a string. In that case, instead of adding the value, it would just concatenate it with the current value of money_${user.id}. So, to fix it all you have to do is, instead of passing it directly, use parseInt() and then pass it. Then, your fixed part might look like this =>
await db.add(`money_${user.id}`, parseInt(args[1]))

Discord.js role not getting added with no errors

I'm trying to add a role to a user, but I’m getting no errors. I’m using a slash command.
let role = interaction.member.guild.roles.cache.find(r => r.name == "Amazing")
interaction.member.roles.add(role)
// interaction is from the interactionCreate event
In discord.js v13 interaction.member does not have a function to add roles.
I'd fetch the guildMember object then add the roles.
Example:
let guild = await client.guilds.fetch(interaction.guild_id)
let member = guild.members.cache.get(interaction.member.user.id);
let role = guild.roles.cache.find(r => r.name == "Amazing");
if (!role)
return console.log("the role doesn't exist");
member.roles.add(role);
Full example:
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("interactionCreate", async (interaction) => {
...
let guild = await client.guilds.fetch(interaction.guild_id)
let member = guild.members.cache.get(interaction.member.user.id);
let role = guild.roles.cache.find(r => r.name == "Amazing");
if (!role)
return console.log("the role doesn't exist");
member.roles.add(role);
});
client.login('Your-token');

Discord js giveaway command

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.

discord.js - give role by reacting - return value problem

So I wanted a command intomy bot, which iis able to give server roles if you react on the message. By google/youtube I done this. My problem is, that if I react on the message my algorith won't step into my switch also if I react to the costum emoji it won't even detect it that I reacted for it. Probably somewhere the return value is different but I was unable to find it yet. Sy could check on it?
const { MessageEmbed } = require('discord.js');
const { config: { prefix } } = require('../app');
exports.run = async (client, message, args) => {
await message.delete().catch(O_o=>{});
const a = message.guild.roles.cache.get('697214498565652540'); //CSGO
const b = message.guild.roles.cache.get('697124716636405800'); //R6
const c = message.guild.roles.cache.get('697385382265749585'); //PUBG
const d = message.guild.roles.cache.get('697214438402687009'); //TFT
const filter = (reaction, user) => ['πŸ‡¦' , 'πŸ‡§' , 'πŸ‡¨' , '<:tft:697426435161194586>' ].includes(reaction.emoji.name) && user.id === message.author.id;
const embed = new MessageEmbed()
.setTitle('Available Roles')
.setDescription(`
πŸ‡¦ ${a.toString()}
πŸ‡§ ${b.toString()}
πŸ‡¨ ${c.toString()}
<:tft:697426435161194586> ${d.toString()}
`)
.setColor(0xdd9323)
.setFooter(`ID: ${message.author.id}`);
message.channel.send(embed).then(async msg => {
await msg.react('πŸ‡¦');
await msg.react('πŸ‡§');
await msg.react('πŸ‡¨');
await msg.react('697426435161194586');
msg.awaitReactions(filter, {
max: 1,
time: 15000,
errors: ['time']
}).then(collected => {
const reaction = collected.cache.first();
switch (reaction.emoji.name) {
case 'πŸ‡¦':
message.member.addRole(a).catch(err => {
console.log(err);
return message.channel.send(`Error adding you to this role **${err.message}.**`);
});
message.channel.send(`You have been added to the **${a.name}** role!`).then(m => m.delete(30000));
msg.delete();
break;
case 'πŸ‡§':
message.member.addRole(b).catch(err => {
console.log(err);
return message.channel.send(`Error adding you to this role **${err.message}.**`);
});
message.channel.send(`You have been added to the **${b.name}** role!`).then(m => m.delete(30000));
msg.delete();
break;
case 'πŸ‡¨':
message.member.addRole(c).catch(err => {
console.log(err);
return message.channel.send(`Error adding you to this role **${err.message}.**`);
});
message.channel.send(`You have been added to the **${c.name}** role!`).then(m => m.delete(30000));
msg.delete();
break;
case '<:tft:697426435161194586>':
message.member.addRole(d).catch(err => {
console.log(err);
return message.channel.send(`Error adding you to this role **${err.message}.**`);
});
message.channel.send(`You have been added to the **${d.name}** role!`).then(m => m.delete(30000));
msg.delete();
break;
}
}).catch(collected => {
return message.channel.send(`I couldn't add you to this role!`);
});
});
};
exports.help = {
name: 'roles'
};
As of discord.js v12, the new way to add a role is message.member.roles.add(role), not message.member.addRole. Refer to the documentation for more information.
You need to use roles.add() instead of addRole()
Mate, You cannot use the id of emoji in codes(except when you are sending a message). so, the custom emoji has to be replaced by a real emoji that shows a box in your editor and works perfectly in discord. If you can find it, then this might be complete as discord API cannot find the emoji <:tft:697426435161194586>. you can get an emoji by using it in discord and opening discord in a browser and through inspect element, get the emoji.
Else, you will have to use different emoji.

Discord.js random role reactions

I'm trying to make a command that sends an embed and reacts with an emoji and when a member clicks the emoji it gives them a random role. any idea on how I would go about doing this?
const {Client, MessageEmbed} = require('discord.js')
const client = new Client()
client.on('messageCreate', async ({author, channel, guild, member}) => {
// don't do anything if it's a bot
if (author.bot) return
// don't do it if it's a DM
if (!guild) return
// replace these with whatever you want
const embed = new MessageEmbed({title: 'some embed'})
const emoji = 'πŸ˜€'
const roles = guild.roles.cache.filter(role =>
// you can't add the #everyone role
role.name !== '#everyone' &&
// or managed roles
!role.managed &&
// or roles that the bot isn't above
guild.me.roles.highest.comparePositionTo(role) > 0
)
try {
if (!roles.size) return await channel.send('There are no roles that I can add!')
const message = await message.channel.send({embeds: [embed]})
await message.react(emoji)
await message.awaitReactions({
// only for await for the πŸ˜€ emoji from the message author
filter: (reaction, user) => reaction.emoji.name === emoji && user.id === author.id,
// stop after 1 reaction
max: 1
})
await member.roles.add(roles.random())
} catch (error) {
// log all errors
console.error(error)
}
})
client.login('your token')
Note: Your bot must have the MANAGE_ROLES permission to be able to add a role to a guild member.

Categories

Resources