Discord.js random role reactions - javascript

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.

Related

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

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

Need Assistance With My unmute command for discord.js

Basically This command is giving one major issue and that the fact that when the user is muted he won't be unmuted because of the command not responding back to the mute command
const Discord = require('discord.js');
const fs = module.require('fs');
module.exports.run = async (client, message, args) => {
if (!message.member.hasPermission('MANAGE_MESSAGES')) return;
let unMute = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!unMute) {
let exampleEmbed = new Discord.MessageEmbed()
.setDescription("__UNMUTE INFO__")
.setColor(client.colors.success)
.setThumbnail(client.user.displayAvatarURL())
.addField(`Unmute Command`, `Unmutes a mentioned user.`)
.addField(`Unmute Command`, `Unmutes User By Id.`)
.addField("Example", `${client.config.prefix}Unmutes #user`)
.addField("Example", `${client.config.prefix}Unmutes #id`)
message.channel.send(exampleEmbed);
return;
}
let role = message.guild.roles.cache.find(r => r.name === 'Muted');
message.channel.send(`Please Check roles to be sure user was unmuted`);
if (!role || !unMute.roles.cache.has(role.id)) return message.channel.send(`That user is not muted.`);
if (!role || !unMute.roles.cache.has(User.id)) return message.channel.send(`----`);
let guild = message.guild.id;
let member = client.mutes[unMute.id];
if (member) {
if (member === message.guild.id) {
delete client.mutes[unMute.id];
fs.writeFile("./mutes.json", JSON.stringify(client.mutes), err => {
if (err) throw err;
})
await unMute.roles.remove(role.id);
message.channel.send(`:white_check_mark: ${unMute} Has been unmuted.`);
}
return;
}
await unMute.roles.remove(role.id);
message.channel.send(`:white_check_mark: ${unMute} Has been unmuted.`);
message.delete();
}
module.exports.config = {
name: 'unmute',
description: 'Unmute a user.',
access: 'Manage Messages Permission',
usage: 'unmute #vision'
}
I'm Also getting an error message when manually unmuting the user
(node:6604) UnhandledPromiseRejectionWarning: ReferenceError: User is not defined
Any Form of help would be greatly appreciated and thank you for your time.
On the line if (!role || !unMute.roles.cache.has(User.id)) return message.channel.send('----'), you reference the variable User, but you haven't definied it anywhere, and even if it was defined, you need a role not a member or user. I'm pretty sure it should instead be Role.id. Also, not 100% sure on this, but I tnink it should just be Role not Role.id.

Is there a way to get channels by name? (Discord.js v12)

I was creating a lock command where the channel name/id would be passed as the 1st argument. The command use case would be something like this: .lock #[channel-name]/[channel_id]. This works with a channel id, however, it returns undefined when I attempt to use a channel name instead (e.g .lock #test). Would there be a way to achieve this?
const channel =
bot.channels.cache.find(
(channel) => channel.name == `#${args.slice(0).join('-')}`
) || bot.channels.cache.get(args[0]);
if (!channel) {
console.log(channel);
return message.reply('Please provide a channel name/id!');
}
if (!args[1]) {
return message.reply('Please set the lock type!');
}
if (!channel.permissionsFor(message.guild.roles.everyone).has('VIEW_CHANNEL')) {
const errorEmbed = new Discord.MessageEmbed()
.setDescription(
`āŒ \`VIEW_CHANNEL\` for \`${channel.name}\` is already disabled.`
)
.setColor('RED');
return message.channel.send(errorEmbed);
}
channel
.updateOverwrite(channel.guild.roles.everyone, { VIEW_CHANNEL: false })
.then(() => {
const msgEmbed = new Discord.MessageEmbed()
.setDescription(`āœ… The channel\`${channel.name}\` has been locked.`)
.setColor('GREEN');
message.channel.send(msgEmbed);
})
.catch((error) => {
console.log(error);
const errorEmbed = new Discord.MessageEmbed()
.setDescription(`āŒ Unable to lock \`${channel.name}\`.`)
.setColor('RED');
message.channel.send(errorEmbed);
});
discord.js parses channel mentions (#channel-name) as <#channelID>, not #channel-name.
You can use:
bot.channels.cache.get(args[0].match(/<#(\d+)>/)[1])
to get a channel from a mention.

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.

Categories

Resources