Discord.js v13 Reaction Roles - javascript

I already have this code to post an embed and to add a reaction, I'm just wondering how I would go about adding a role to a user when they add the reaction?
if (message.content.startsWith(`${prefix}rr`)) {
let embed = new MessageEmbed()
.setColor("#ffffff")
.setTitle("📌 Our Servers Rules 📌")
.setDescription("To keep our server safe we need a few basic rules for everyone to follow!")
.setFooter("Please press ✅ to verify and unlock the rest of the server!")
.addFields(
{
name: "1.",
value: "Stay friendly and don't be toxic to other users, we strive to keep a safe and helpful environment for all!",
},
{
name: "2.",
value: "Keep it PG-13, don't use racist, homophobic or generally offensive language/overly explicit language!",
},
{
name: "3.",
value: "If you want to advertise another server/website etc please contact me first!",
},
{ name: "4.", value: "Don't cause drama, keep it civil!" },
{
name: "5.",
value: "If you have any questions please contact me #StanLachie#4834",
}
);
message.channel.send({ embeds: [embed] }).then((sentMessage) => {
sentMessage.react("✅");
});
}

You may want to check this Discord.js Guide page. But in summary...
const filter = (reaction, user) => {
return reaction.emoji.name === '✅' && user.id === message.author.id;
};
const collector = message.createReactionCollector({ filter });
collector.on('collect', (reaction, user) => {
const role = await message.guild.roles.fetch("role id");
message.guild.members.fetch(user.id).then(member => {
member.roles.add(role);
});
});

Related

cannot read property of 'channels' of undefined discord.js

const reason = args.slice(0).join(" ");
if (!reason) return message.channel.send('Reason for ticket?');
const user = message.guild.member(message.author);
const ticket = db.fetch(`Ticket_user_${user.id}`)
if(ticket) message.channel.send("You already made a ticket senpai! Close your old ticket.");
const channel = message.guild.channels.cache.find
(channel => channel.name === 'ticket')
if (!channel)
guild.channels.create('ticket', {
type: 'text',
permissionOverwrites: [
{
id: message.guild.id,
deny: ['VIEW_CHANNEL'],
},
{
id: message.author.id,
allow: ['VIEW_CHANNEL'],
},
],
})
.then(console.log)
.catch(err => {
message.channel.send("An error occurred while running the command. Please report this error to the support server:"+ err)
return;
})
db.add(`Ticket_user_${user.id}`)
const time = "3"
setTimeout(() => {
const embed = new Discord.MessageEmbed()
.setTitle(`Ticket#0001`)
.setDescription(`Reason: ${reason}`)
.addField("Welcome to my ticket senpai!! We are waiting for staff")
.setColor("PURPLE")
message.channel.send(embed)
}, ms(time))
}
}
I'm making a ticket system for my bot and ik you people smart because top.gg won't help
Thank you for the help this will help my bot and my code and make me smart plus I'm removing the dot becccause of downvote ig
Here in this code
if (!channel){
guild.channels.create('ticket', { //...... rest of the code
You didn't define guild. Try replacing guild with message.guild
Like this:
if (!channel){
message.guild.channels.create('ticket', { //.... rest of the code
Also, please remove the unnecessary part (dots) from the question

How to add custom reactions that actually work?

So, I have been working on this function which gives users roles according to what emoji they chose. If they chose one emoji, they'd get the role that the emoji indicates and so on. I have made the bot react to it's own message, I've set up all of the embeds and I've also set up all of the constants but it just does not seem to work!
Here's my code:
client.on('message', async Agreemessage => {
const BoomerEmoji = Agreemessage.guild.emojis.cache.find(emoji => emoji.name === "boomer")
const RatEmoji = Agreemessage.guild.emojis.cache.find(emoji => emoji.name === "robincutmoment")
const BoomerRole = Agreemessage.guild.roles.cache.find(role => role.name === "Les boomers normaux")
const RatRole = Agreemessage.guild.roles.cache.find(role => role.name === "The normal Rat Haven dwellers")
const ApprovalEmbed = new Discord.MessageEmbed()
.setColor('RED')
.setTitle('Hi there new user!')
.setDescription('Please use either one of the comamnds in order to get a role.')
.addFields(
{ name: '\u200B', value: '\u200B'},
{ name: 'Essential server roles', value: 'The command "^giveBoomerRole" gives you the "Les boomers normaux" role, and the command "^giveRatRole" gives you the "The normal Rat Haven dwellers" role.'},
{ name: '\u200B', value: '\u200B'},
{ name: 'Please read this.', value: 'Using the command "^giveBoomerRole" will give you access to only the Boomer Haven compartment, and the comamand "^giveRatRole" will give you access to the Rat Haven compartment. '},
{ name: '\u200B', value: '\u200B'},
{name: 'Read this as well.', value: 'To get access to both of these compartments, please consider using the command "^AccessToBoth" to receive the "Access to both compartments" role.'},
{ name: '\u200b', value: '\u200b'},
{ name: "Have some patience. A moderator will be with you in a bit!", value: "After you have used the command '-agree', please use either one of the commands, depending on which compartment you want to enter. A moderator will approve you shortly."}
)
.setTimestamp()
.setFooter('Time to pick a role!');
const AgreeErrorEmbed = new Discord.MessageEmbed()
.setColor('RED')
.setTitle(`Hello there ${Agreemessage.author.username}!`)
.setThumbnail('https://i.ytimg.com/vi/hAsZCTL__lo/maxresdefault.jpg')
.setDescription("It seems that you have already been verified!")
const BoomerRoleEmbed = new Discord.MessageEmbed()
.setColor("RED")
.setTitle(`Hi ${Agreemessage.author.username}`)
.setDescription("It seems that you already have the Boomer Haven role!")
.setThumbnail("https://wompampsupport.azureedge.net/fetchimage?siteId=7575&v=2&jpgQuality=100&width=700&url=https%3A%2F%2Fi.kym-cdn.com%2Fentries%2Ficons%2Ffacebook%2F000%2F032%2F558%2Ftemp6.jpg")
const BoomerEmbed = new Discord.MessageEmbed()
.setColor('GREEN')
.setTitle('Congratulations!')
.setDescription("You're all set!")
.setThumbnail('https://i.redd.it/db494tdiwv121.jpg')
.addFields(
{name: '\u200b', value: '\u200B'},
{name: 'Disclaimer:', value: "You now have access to the Boomer Haven compartment of the server. Please wait for a moderator to approve you, and you can then enjoy in the Boomer Rat Haven!"},
)
.setTimestamp()
.setFooter('Enjoy pls 😃')
const RatEmbed = new Discord.MessageEmbed()
.setColor('GREEN')
.setTitle('Congratulations!')
.setDescription("You're all set!")
.setThumbnail('https://i.redd.it/db494tdiwv121.jpg')
.addFields(
{name: '\u200b', value: '\u200B'},
{name: 'Disclaimer:', value: "You now have access to the Rat Haven compartment of the server. Please wait for a moderator to approve you, and you can then enjoy in the Boomer Rat Haven!"},
)
.setTimestamp()
.setFooter('Enjoy pls 😃')
if (Agreemessage.content === "-agree") {
const AgreeMessage = await Agreemessage.channel.send(ApprovalEmbed)
if (Agreemessage.member.roles.cache.some(role => role.name === "Awaiting Verification")) {
} else return Agreemessage.channel.send(AgreeErrorEmbed)
AgreeMessage.react(BoomerEmoji) | AgreeMessage.react(RatEmoji)
const filter = (reaction, user) => {
return [(BoomerEmoji), (RatEmoji)].includes(reaction.emoji.name) && user.id === Agreemessage.author.id;
};
AgreeMessage.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === (BoomerEmoji)) {
if (Agreemessage.member.roles.cache.some(role => role.name === "Les boomers normaux")) return Agreemessage.channel.send(BoomerRoleEmbed).then(console.log(`${Agreemessage.author.username} tried to get the Boomer role, but it turns out that he/she already has it!`))
else (AgreeMessage.member.roles.add(BoomerRole)).then(Agreemessage.channel.send(BoomerEmbed))
console.log(`${Agreemessage.author.username} has been given the Boomer role by me.`)
} else if (reaction.emoji.name === (RatEmoji)) {
if (Agreemessage.member.roles.cache.some(role => role.name === "The normal Rat Haven dwellers")) return Agreemessage.channel.send(RatRoleEmbed).then(console.log(`${Agreemessage.author.username} tried to get the Rat role but it turns out that already have it!`))
else (AgreeMessage.member.roles.add(RatRole)).then(Agreemessage.channel.send(RatEmbed))
console.log(`${Agreemessage.author.username} has been given the Rat role by me.`)
}
});
console.log(`${Agreemessage.author.username} is currently seeking approval.`)
}
});
You're comparing a full GuildEmoji object to an emoji name. You should be using the name property.
const filter = (reaction, user) =>
[BoomerEmoji.name, RatEmoji.name].includes(reaction.emoji.name) && user.id === Agreemessage.author.id;
// ...
if (reaction.emoji.name === BoomerEmoji.name) {...)
else if (reaction.emoji.name === RatEmoji.name) {...}

Some problems with the !kick command code

I'm having some problem with my Discord.js kick command.
My code:
const Discord = require('discord.js');
const { prefix, token } = require('../config.json');
module.exports = {
name: 'kick',
description: 'kick users',
execute(message, args) {
if (!message.member.hasPermission('KICK_MEMBERS')) {
return message.channel.send({
embed: {
color: 16777201,
description: `:x: | ${message.author}, You are not allowed to use this command.`,
footer: {
text: ` | Required permission: KICK_MEMBERS`,
},
},
});
}
if (!message.guild.me.permissions.has('KICK_MEMBERS')) {
return message.channel.send({
embed: {
color: 16777201,
description: `:x: | ${message.author}, I am not allowed to use this command.`,
footer: {
text: ` | Required permission: KICK_MEMBERS`,
},
},
});
}
if (!args[0]) {
return message.channel.send({
embed: {
color: 16777201,
description: `:x: | ${message.author}, You need to mention a user first.`,
footer: {
text: ` | Example: !kick #Bot`,
},
},
});
}
const member =
message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (member.user.id === message.author.id) {
return message.channel.send({
embed: {
color: 16777201,
description: `:x: | ${message.author}, You cannot expel yourself.`,
footer: {
text: ` | Example: !kick #Bot`,
},
},
});
}
try {
member.kick();
message.channel.send(`${member} has been kicked!`);
} catch (e) {
return message.channel.send(`User isn't in this server!`);
}
},
};
Ignore the code not being complete, I'm still thinking about the design of the embeds!
I'm trying to do 3 things:
I would like if someone tried to use the command by mentioning the bot, they would say something like "you are not allowed to do this"
The other thing I want is that it is not possible for a user to kick someone above him
I want the member to be kicked you have to react with yes or no
I'm going to try to solve your problems one by one:
First of all, I would like if someone tried to use the command by mentioning the bot, they would say something like "you are not allowed to do this"
You can execute an if statement to detect if the member mentioned shares the same ID as your bot using the client.user property (the user your client is logged in as)
if (member.id === client.user.id)
return message.channel.send('You cannot ban me');
The other thing I want is that it is not possible for a user to kick someone above him
You can solve this by comparing the roles.highest.position property of both members. This property will return a number. the higher the number, the higher the role in priority.
if (message.member.roles.highest.position <= member.roles.highest.position)
return message.channel.send(
'Cannot kick that member because they have roles that are higher or equal to you.'
);
And lastly, I want the member to be kicked you have to react with yes or no
For this you'll need to use a reaction collector. This is how you can do it using Message.awaitReactions. This method will wait for someone to react to a message, then log the emoji reacted.
// first send the confirmation message, then react to it with yes/no emojis
message.channel
.send(`Are you sure you want to kick ${member.username}?`)
.then((msg) => {
msg.react('👍');
msg.react('👎');
// filter function
const filter = (reaction, user) =>
['👍', '👎'].includes(reaction.emoji.name) && user.id === message.author.id; // make sure it's the correct reaction, and make sure it's the message author who's reacting to it
message
.awaitReactions(filter, { time: 30000 }) // make a 30 second time limit before cancelling
.then((collected) => {
// do whatever you'd like with the reactions now
if (message.reaction.name === '👍') {
// kick the user
} else {
// don't kick the user
}
})
.catch(console.log(`${message.author.username} didn't react in time`));
});

How do you add a role based on a message reaction?

Is there anything remotely wrong with this code?
no errors pop up and there isn't a reaction once the bot sends the messages.
any help would be appreciated, thank you in advance!
const a = msg.guild.roles.get('666712822985654322'); //Verified User
// the role constants are in the same chronological order as below.
const filter = (reaction,user) => ['668236468384169986'].includes(reaction.emoji.name);
const embed = new Discord.RichEmbed()
.setColor(0x00FF00)
.setTitle('Rules')
.setDescription(`
In order to gain access to the rest of the server you must read and abide by these rules:
By reacting with :white_check_mark: you agree to these rules
Roles:
:white_check_mark: ${a.toString()}`)
.setThumbnail(msg.author.avatarURL)
.addField('Rule #1:You do not talk about fight club', 'Second Rule: You do not TALK about fight club')
.setFooter("Use \'!command list\' to get aquainted with Peb 3000");
msg.channel.send(embed).then(async message => {
await message.react('668236468384169986'); //white check mark
message.awaitReaction(filter, {})
.then(collected =>{
const reaction = collected.first();
switch(reaction.emoji.name) {
case('\:white_check_mark:'):
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(3000));
break;
}
}).catch(collected => {
return msg.collected.send(`I couldn't add you to this role!`)
})
});
I'd recommend reading both An Idiot's Guide - Using Emojis as well as Discord.js Guide - Reactions, as your current approach for Unicode emojis won't work.
In your case, :white_check_mark: should be ✅ or an equivalent.
The collected options will triggeret when collector end collect, you no provide any options to stop collector, so its will never happen.
The 1 way to give member role on react follow this code. But when bot restart, you need again use this command and create collector.
const roleToAdd = msg.guild.roles.get('666712822985654322'); //Verified Role
if(!roleToAdd) return
let embed = new Discord.RichEmbed()
.setColor(0x00FF00)
.setTitle('Rules')
.setDescription(`
In order to gain access to the rest of the server you must read and abide by these rules:
By reacting with :white_check_mark: you agree to these rules
Roles:
:white_check_mark: ${a.toString()}`)
.setThumbnail(msg.author.avatarURL)
.addField('Rule #1:You do not talk about fight club', 'Second Rule: You do not TALK about fight club')
.setFooter("Use \'!command list\' to get aquainted with Peb 3000");
msg.channel.send(embed).then(message => {
const filter = (reaction, user) => reaction.emoji.name === '✅' && user.id === msg.author.id && reaction.message.id = message.id
const collector = message.createReactionCollector(filter, {});
collector.on('collect', r => {
if(r.emoji.name === '✅') {
let member = message.guild.members.get(reaction.users.last().id)
member.addRole(roleToAdd)
.then( member => {
message.channel.send(`You have been added to the **${roleToAdd.name}** role!`).then(m => m.delete(3000));
})
.catch(console.error)
}
})
collector.on('end', collected => console.log(`Collected ${collected.size} items`));
})
The way number 2 its listen reactionadd event. After restart its will work.
bot.on('messageReactionAdd', (reaction, user) => {
if(reaction.message.id === 'YOUR MESSAGE ID' && reaction.emoji.name === 'youreactionname') {
let meber = reaction.message.guild.members.get(user.id)
member.addRole('yourRole')
}
.catch(console.error)
});

Discord.js auto-ban user if they use a certain command

I'm attempting to make a simple $ping command but if a user uses said command, they'll automatically be banned from the server (a small little funny)
Here's the code for the functioning $ping but I don't know how to have the ${user} that uses it auto-banned from the bot. (Will have sufficient perms obviously)
I'll be removing the whole embed: section down basically, as I don't need any text or actual command running. Just the auto-ban, only thing ran will be a description: ${user} was banned
exports.exec = async (Cuckbot, message) => {
try {
let responseMessage = await message.channel.send({
embed: {
color: Cuckbot.colors.BLUE,
description: 'PINGing...'
}
});
await responseMessage.edit({
embed: {
color: Cuckbot.colors.BLUE,
title: `${Cuckbot.user.username} PING Statistics`,
fields: [
{
name: 'Response Time',
value: `${responseMessage.createdTimestamp - message.createdTimestamp}ms`,
inline: true
},
{
name: 'WebSocket PING',
value: `${Cuckbot.ping}ms`,
inline: true
}
]
}
});
}
catch (e) {
Cuckbot.log.error(e);
}
};
member.ban() is a function you can use to ban a member.
Example from Documentation:
// Ban a guild member
member.ban("Banned because used ping")
.then(() => console.log(`Banned ${member.displayName}`))
.catch(console.error);

Categories

Resources