Discord.js AutoRole Reaction do nothing - node.js

my little problem is the next one :
When i react a message, my bot do nothing :D and it's not the objectives.
My events :
module.exports = async(client, messageReaction, user) => {
const message = messageReaction.message;
const member = message.guild.members.cache.get(user.id);
const emoji = messageReaction.emoji.name;
const channel = message.guild.channels.cache.find(c => c.id === '739163072064651296');
const lol = message.guild.roles.cache.get("763104201588473896"); //id role lol
const wz = message.guild.roles.cache.get("763104236119785584"); //id role wz
if (["lol", "wz"].includes(emoji) && message.channel.id === channel.id) {// lol = emoji name and wz too
switch (emoji) {
case "lol":
member.roles.add(lol);
message.channel.send('test')
break;
case "wz":
member.roles.add(wz);
message.channel.send('test')
break;
};
};
};
My events handler :
fs.readdir("./Events/",(error , f) => {
if(error) console.log(error);
console.log(`${f.length} events chargรฉs`);
f.forEach((f) => {
const events = require(`./Events/${f}`);
const event = f.split(".")[0];
client.on(event, events.bind(null, client));
});
});
If someone can help it's perfect ! Thank you !

I tried to understand what you wanted to make but couln't understand you at all, your trying to make a autoRole sytem that listen's to reactions? AutoRole is supposed to be in a guildMemberAdd event, so if a member join's, you add a role automatically, but from the code you provided, it looks like it listen's to reactions on some message? If your trying to make a Reaction Role system, then follow this. Other than that, i can't help you.
If your trying to make a autoRole system follow this
From what i know, when you add a role to someone, you will have to do the following
member.roles.add("roleid")
But what your doing is basically this:
member.roles.add(message.guild.roles.cache.get("763104201588473896")) //as lol is defined like that
So, to fix it, instead of getting the role object, then trying to add the role to the user, do this, and be sure to make the file name "guildMemberAdd.js":
module.exports = async(client, member) => {
const lol = "763104201588473896" //id role lol
const wz = "763104236119785584"; //id role wz
member.roles.add(lol);
member.roles.add(wz);
};

Related

How can I import a module.export to my main code since it doesnt act like a function and it doesnt return any variables?

I have started a little side-project which is about developing a discord bot that will be able to remove a given role from a given user in a server. I have designed a module (remove_role.js) to function like this but since this is my first project I can't find a way to import it to the main code (index.js). Below is the code of the module.
module.exports = {
commands: ['removerole', 'delrole', 'deleterole'],
minArgs: 2,
expectedArgs: "<Target user's #> <The role name>",
permissions: 'ADMINISTRATOR',
callback: (message, arguments) => {
const targetUser = message.mentions.users.first()
if (!targetUser) {
message.reply('Please specify someone to remove a role from.')
return
}
arguments.shift()
const roleName = arguments.join(' ')
const { guild } = message
const role = guild.roles.cache.find((role) => {
return role.name === roleName
})
if (!role) {
message.reply('There is no role with the name "${roleName}"')
return
}
const member = guild.members.cache.get(targetUser.id)
if (member.roles.cache.get(role.id)) {
member.roles.remove(role)
message.reply('That user no longer has the ${roleName} role')
}
else {
message.reply('That user does not have the ${roleName} role')
}
},
}
I suppose you have read a little bit about how require() work.
The exported value can really be anything, it does not need to be a function. When you do a require() on the file, the file gets executed and you get a reference to whatever was exported from that file.
In your example, you would at the top of your index.js do
const remove_role = require("./remove_role.js")
// You now have the object exported in remove_role.js.
console.log(remove_role.permissions) // prints ADMINISTRATOR

.push is not a function. (DISCORD.JS)

Trying to make a cooldown on message events when giving a user xp. Running into an issue where cooldowns.push() is not a fucntion I have done googling and what I have found is that I need to have an array but to my understanding a Discord.Collection is the same thing.
I need this to check the collection to see if the users ID is in there, but if it is not add it for 3 seconds then remove it.
const config = require(`../settings/config.js`)
const prefix = config.prefix
const { createConnection } = require(`mysql`)
const mysql = require("../settings/mysql.js")
const Discord = require(`discord.js`)
let cooldowns = new Discord.Collection()
module.exports = async (client, message, member) => {
if (!cooldowns.has(message.author.id)) {
cooldowns.push(message.author.id)
}
setTimeout(() => cooldowns.delete(message.author.id), 3000)
Thanks in advance!!
From https://discordjs.guide/additional-info/collections.html#array-like-methods:
Discord.js comes with this utility class known as Collection. It extends JavaScript's native Map class, so it has all the features of Map and more!
So no, it's not an array, it's a Map. In your case I think you'd want to use:
cooldowns.set(message.author.id, 1)

How can I resolve this problem (node.js, discord.js)

if (!args[1]) return message.channel.send('You need to specify a person!')
if (!args[2]) return message.channel.send('Please specify a time for how long the ban council will last.')
var tim = args[2]
const sweden = message.mentions.users.first()
message.react('๐Ÿ‘').then(() => message.react('๐Ÿ‘Ž'))
const mappo = ['๐Ÿ‘', '๐Ÿ‘Ž']
if (!args[1]) return message.channel.send('Please specify a person!')
if(message.guild){ //this will check if the command is being called from a server
const embad = new Discord.MessageEmbed()
.setTitle('Ban Council')
.addField('The Convicted:', `${sweden.tag}`)
.addField('Rules:', 'Vote on whether the convicted is guilty or not with the prompted reactions. The ban will end automatically in 5 seconds.')
message.channel.send(embad)
setTimeout(function(){
if(sweden){
const lyft = message.guild.member(sweden)
if(lyft){
if(message.reactions.cache.map(r => `${'๐Ÿ‘'} ${r.users.cache.size}`)[0] > message.reactions.cache.map(r => `${'๐Ÿ‘'} ${r.users.cache.size}`)[1]){
lyft.ban({ ression: 'Majority has exiled you from server. '}).then(() => {
message.reply(`The user ${december.tag} was banned as a result of a majority vote.`)
})
} else {
message.channel.send('The ban was cancelled.')
}
}else{
message.reply('The user is not in this server.')
}
}else{
message.reply('You need to specify a person!')
}
}, tim)
} else {
message.channel.send('Banning does not work here!')
}
It sends the "Ban cancelled" before it actually has the chance to take input. I've tried collectors, and it doesn't work because of the max: part, how can I resolve this problem? (Also it returns no errors)
This is in a case. (appending onto what feedback I got)
Firstly you should beautify your code before you post on stackoverflow, you could have removed the break keyword and just explain it was inside of a switch case
The reason it does not work is because you are checking the message's reaction, and not the embed that you send, so to fix this you need to assign a variable to message.channel.send(embad), but this is a promise so you need to await it, which requires an async function
lastly awaitReactions and createReactionCollector are probably better options,
So here's the new code:
(async () => {
if (!args[1]) return message.channel.send('You need to specify a person!');
if (!args[2]) return message.channel.send('Please specify a time for how long the ban council will last.')
if (!message.guild) return message.channel.send('Banning does not work here');
var tim = args[2]
const sweden = message.mentions.member.first()
const mappo = ['๐Ÿ‘', '๐Ÿ‘Ž']
message.react('๐Ÿ‘').then(() => message.react('๐Ÿ‘Ž'))
const embad = new Discord.MessageEmbed()
.setTitle('Ban Council')
.addField('The Convicted:', `${sweden.tag}`)
.addField('Rules:', 'Vote on whether the convicted is guilty or not with the prompted reactions. The ban will end automatically in 5 seconds.')
const embedMessage = await message.channel.send(embad);
setTimeout(function () {
if (!sweden) return message.reply('You need to mention a person');
const filter = (reaction) => mappo.includes(reaction.emoji.name);
embad.awaitReactions(filter, { time: 5000 })
.then(collection => {
//not the most optimal way to do it
const emoji1 = collection.find(e => e.emoji.name === '๐Ÿ‘');
const emoji2 = collection.find(e => e.emoji.name === '๐Ÿ‘Ž');
//both default to 0
const upvotes = emoji1 && emoji1.users.size || 0;
const downvotes = emoji2 && emoji2.users.size || 0;
if (upvotes > downvotes) {
lyft.ban({ reason: 'Majority has exiled you from server. ' })
.then(() => message.reply(`The user ${december.tag} was banned as a result of a majority vote.`));
} else {
message.channel.send('The ban was cancelled.');
}
})
.catch(console.error);
}, tim);
})();
It's been around 8 months since I made this post, and I found the answer, and an even more effective way to do it. I won't post the entire code, as it's pretty long and not very neat. However, this is a much more effective way of counting reactions.
My Original Code was:
const upvotes = message.reactions.cache.map(r => ${'๐Ÿ‘'} ${r.users.cache.size})[0]
const downvotes = message.reactions.cache.map(r => ${'๐Ÿ‘Ž'} ${r.users.cache.size})[1]
It doesn't work very well either.
const [upvoteReaction, downvoteReaction] = message.reactions.cache.first(2);
const upvotes = upvoteReaction.users.cache.size;
const downvotes = downvoteReaction.users.cache.size;
It takes the number of reactions from the first two reactions on the message. Seeing as how the only reactions are thumbs up and thumbs down, it will get the numbers from both of them. From there, you can just compare the two.

Muted role only working in channels everyone can see | Bot discord.js

Okay so I have a bot and the muted role works for channels everyone can see, but when a staff member gets muted they cant chat in the general chats but can chat in staff chats, the staff chats are onlyvisible by staff+ here is the code in case something needs be be changed
const { red_dark } = require("../../colors.json");
const ms = require("ms");
module.exports = {
name: "mute",
description: "Mutes a member in the discord!",
usage: "!mute <user> <reason>",
category: "moderation",
accessableby: "Members",
aliases: ["m", "nospeak"],
run: async (bot, message, args) => {
// check if the command caller has permission to use the command
if(!message.member.hasPermission("MANAGE_ROLES", "ADMINISTRATOR") || !message.guild.owner) return message.channel.send(":x: **You do not have the permission to use this command!**");
if(!message.guild.me.hasPermission(["MANAGE_ROLES", "ADMINISTRATOR"])) return message.channel.send(":x: **I do not have the permission to add roles!**")
//define the reason and mutee
let tomute = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]));
if(!tomute) return message.reply("Couldn't find user.");
let muterole = message.guild.roles.find(`name`, "Muted");
//start of create role
if(!muterole){
try{
muterole = await message.guild.createRole({
name: "Muted",
color: "#ff0000",
permissions:[]
})
message.guild.channels.forEach(async (channel, id) => {
await channel.overwritePermissions(muterole, {
SEND_MESSAGES: false,
ADD_REACTIONS: false,
CONNECT: false
});
});
}catch(e){
console.log(e.stack);
}
}
//end of create role
let mutetime = args[1];
if(!mutetime) return message.reply(":X: You didn't specify a time!");
await(tomute.addRole(muterole.id));
message.reply(`<#${tomute.id}> has been muted for ${ms(ms(mutetime))}`);
tomute.send(`Hello, you have been muted in ${message.guild.name} for: **${mutetime}**`).catch(err => console.log(err))
setTimeout(function(){
tomute.removeRole(muterole.id);
message.channel.send(`<#${tomute.id}> is no longer muted! Welcome Back!!`);
}, ms(mutetime));
}
}```
Firstly, due to new NodeJS update this line is incorrect:
let muterole = message.guild.roles.find(`name`, "Muted");
Should be changed to something like this:
let muterole = message.guild.roles.find(r => r.name === "Muted");
Other than that, it must be some channel permissions. I recently found out if a user (without the specificed mod/ administrative permissions) has "Send Messages" to Allow on one of their roles, they bypass the mute. To change this, their role with this allowed, you must set it to null (the gray option in the middle) in order to deny them from talking via the mute role. Example:
If I try to mute anyone with "Beta Testers" role, they can still talk in this certain channel, even if muted people are denied it.
I hope this makes somewhat sense, and I hope I cleared out some confusion, and this helped!
Have a nice day

showing user with multiple roles discord.js

with this command set to only one role. I want to set more than one role. how can I do it ?
let rolid = "663047983675342849";
let tokuchi = client.guilds
.get(sunucuid)
.roles.get(rolid)
.members.filter(o => !o.voiceChannel).map(member => member.user);
.setDescription(tokuchi.join("\n"))```
You can get all members with multiple role somethink like this, but other code shown leaves questions
let sGuild = client.guilds.get(sunucuid)
let membersWithRoles = sunucuid.members.filter(member => {
return member.roles.some(r=>['ROLEID','ROLEID'].includes(r.id))
})
console.log(membersWithRoles)
v2 version
At the fist you dont need get guild in all comands, use message.guild for this.
This code will return array of users usernames with any of your roles and if they dont have voiceconnection now.
exports.run = async (client, message, args) => {
if(message.channel.type === 'dm') return
if (!message.member.hasPermission("ADMINISTRATOR"))
return message.channel.send(" Missing Permission");
let tokuchi = message.guild.members.filter(member => {
return member.roles.some(r=>['ROLEID','ROLEID'].includes(r.id)) && !member.voiceChannel
}).map(member => (member.user.username))
const basarili = new Discord.RichEmbed()
.setColor('RANDOM')
.setAuthor(`Seste Olmayan Yetkililer`, client.user.avatarURL)
.setDescription(tokuchi.join("\n"))
.setFooter("Created by Tokuchi")
.setTimestamp()
.addField(`ฤฐลŸlemi GerรงekleลŸtiren KiลŸi:`, `${message.author.username}#${message.author.discriminator}`)
return message.channel.send(basarili)
};
its return a users.username because you cant .join('\n) users, its a collection, not array.

Resources