How to add custom reactions that actually work? - javascript

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

Related

Discord.js v13 Reaction Roles

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

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 check if an user has any role discord.js

I'm making a user info command in my discord bot using discord.js v12. The only problem I have with it is, that if an user doesn't have any roles, the highest role shows as ##everyone, not #everyone. So I would like to avoid it, and make it so if the user doesn't have any roles, it will say 'This user has no roles in this server'. My code is here (only the bit that has anything to do with the roles):
const { DiscordAPIError } = require("discord.js");
const Discord = require("discord.js");
const moment = require("moment");
module.exports = {
name: "profile",
description: "The bot will return the info about the user",
execute(message, args){
let userinfoget = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.member
var highestRoleID = userinfoget.roles.highest.id;
var joined = moment(userinfoget.joinedAt).format('DD/MM/YY, HH:mm:ss')
console.log(`Highest role = ${highestRoleID}`);
console.log(`User = ${userinfoget}`);
console.log(userinfoget.roles)
if(!userinfoget.roles) console.log('no roles')
const embed = new Discord.MessageEmbed()
.setColor(userinfoget.displayHexColor)
.setAuthor(`${userinfoget.user.tag}`, userinfoget.user.displayAvatarURL())
.addFields(
{name: `User ping`,
value: `<#${userinfoget.id}>`}
)
.addFields(
{name: `User ID`,
value: `${userinfoget.id}`}
)
.addFields(
{name: 'Joined Server',
value: moment(userinfoget.joinedAt).format('LLLL') + ' ' + timeFromJoiningServerMessage} // or moment(userinfoget.joinedAt).format('DD/MM/YY, HH:mm:ss')
)
.addFields(
{name: 'Joined Discord',
value: moment(userinfoget.user.createdAt).format('LLLL')} // or moment(userinfoget.createdAt).format('DD/MM/YY, HH:mm:ss')
)
.addFields(
{name: 'Highest role',
value: `<#&${highestRoleID}>`}
)
.addFields(
{name: 'Online Status',
value: `${status}`}
)
.addFields(
{name: 'Is a bot?',
value: `${isBot}`}
)
.setFooter('Bot made by mkpanda')
message.channel.send(embed);
}
As you can see, I tried doing !userinfoget.roles, but when logging it, it shows all the information about the user, not just the roles. How could I detect whether an user has any role or not? Thanks in advance :)
GuildMember.roles.cache is a Collection (very similar to an Array).
Therefore, you can use Collection#filter and check if the Role's name equals #everyone. That'll remove the #everyone role from the Collection and you can check if the GuildMember has any roles.
.addFields({
name: 'Highest role',
value: message.member.roles.cache.size ? message.member.roles.highest : "This member has no roles."
})
Useful links I strongly recommend you to visit:
Collection#map
Collection#filter
Conditional (ternary) operator
You could use this ;
userinfoget.roles.cache.size === 1 ? 'No roles' : userinfoget.roles.cache.map(r => '<#&' + r.id + '>').join(', ')
Since if no user has no roles then they will only be "#everyone" so the role size would be one. You can use this information to see if the user has or not roles

How to make a rich embed use the display color of a user discord.js

I'm working on my user info command. It reacts to &userinfo {user ping/user ID}. If there are no args (no ID or ping), it shows the info about the executer of the command. I was wondering, how I could make the info embed have the same color as the display color of the user (so if my nick color is #0052ad, the embed color would also be #0052ad). The code I came up with so far is this:
const { DiscordAPIError } = require('discord.js');
const Discord = require('discord.js');
const moment = require('moment');
module.exports = {
name: 'profile',
description: 'The bot will return the info about the user',
execute(message, args) {
let userinfoget =
message.mentions.members.first() ||
message.guild.members.cache.get(args[0]) ||
message.guild.member(message.author);
var highestRoleID = userinfoget.roles.highest.id;
console.log(`Highest role = ${highestRoleID}`);
console.log(`User = ${userinfoget}`);
const embed = new Discord.MessageEmbed()
.setColor(message.guild.userinfoget.displayHexColor)
.setAuthor(`${userinfoget.user.tag}`, userinfoget.user.displayAvatarURL())
.addFields({ name: `User ping`, value: `<#${userinfoget.id}>` })
.addFields({ name: `User ID`, value: `${userinfoget.id}` })
.addFields(
{
name: 'Joined server',
value: moment(userinfoget.joinedAt).format('LLLL'),
} // or moment(userinfoget.joinedAt).format('DD/MM/YY, HH:mm:ss')
)
.addFields(
{
name: 'Joined Discord',
value: moment(userinfoget.user.createdAt).format('LLLL'),
} // or moment(userinfoget.createdAt).format('DD/MM/YY, HH:mm:ss')
)
.addFields({ name: 'Highest role', value: `<#&${highestRoleID}>` })
.addFields({
name: 'Online Status',
value: `${userinfoget.presence.status}`,
});
message.channel.send(embed);
},
};
but the bot crashes and the error is Cannot read property 'displayHexColor' of undefined. I also tried .setColor(message.guild.userinfoget.displayHexColor) as I saw on other posts, but that makes the embed the display color of the bot. What is the mistake I made? Thanks.
That means message.guild.userinfoget is undefined. You can remove message.guild from the beginning, as you already defined userinfoget as a GuildMember.
userinfoget.displayHexColor
Also, you can shorten message.guild.member(message.author) to simply message.member, which will return the author as a GuildMember

How to get the date an account was created at discord.js v12?

I'm making a user info command, and I've come to trying to show when the account was created. The bot responds to &profile {user ping/user ID}, if there are no arguments, it shows info about the executer of the command. My code looks like this:
const { DiscordAPIError } = require("discord.js");
const Discord = require('discord.js');
const moment = require('moment');
module.exports = {
name: 'profile',
description: "The bot will return the info about the user",
execute(message, args){
let userinfoget = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.member(message.author)
const embed = new Discord.MessageEmbed()
.setColor('#DAF7A6') // or .setColor('RANDOM')
.setAuthor(`${userinfoget.user.tag}`, userinfoget.user.displayAvatarURL())
.addFields(
{name: `User ping`,
value: `<#${userinfoget.id}>`}
)
.addFields(
{name: `User ID`,
value: `${userinfoget.id}`}
)
.addFields(
{name: 'Joined server',
value: moment(userinfoget.joinedAt).format('LLLL')}
)
.addFields(
{name: 'Joined Discord',
value: moment(userinfoget.createdAt).format('LLLL')}
.addFields(
{name: 'Online Status',
value: `${userinfoget.presence.status}`}
)
.setFooter('Bot made by mkpanda')
message.channel.send(embed);
}
}
The time when the user joined the server is displayed correctly, but the account creation is always the current time. Any way to fix it?
GuildMember has no property called createdAt, only joinedAt.
You can only get the createdAt property from the User object.
moment(userinfoget.user.createdAt)
this is late but just in case someone else sees this: the client id is based of their creation date so you can easily convert it to a unix timestamp

Categories

Resources