Discord.j - Function strangely empty - node.js

this question is linked to another one. If you need to know why I'm asking this, check this question.
I'm developing a bot who should get a collection filled with members who have a specific role. But after testing and double checking role name and be sure I'm testing the bot in a server and not in DM the collection is always empty and unusable (the program couldn't run without it).
const eventMembers = message.guild.members.cache.filter(m =>
m.roles.cache.some(r => r.name === "event")
);
const connectedMembers = eventMembers.members.filter(m => {
return voiceChannel.members.has(m.id)
});
console.log(connectedMembers);
If anybody has a hint or a solution I take it

You forgot return :)
const eventMembers = message.guild.members.cache.filter(m => {
return m.roles.cache.some(r => r.name === "event")
});
or
const eventMembers = message.guild.members.cache.filter(m => m.roles.cache.some(r => r.name === "event"));
You can check for the role with this name exist:
let role = message.guild.roles.cache.find(role => role.name === 'event')
if (role) {
console.log('ok')
} else {
console.log('No role found with this nickname')
}
V2
const eventMembers = message.guild.members.cache.filter(m => {
return m.roles.cache.some(r => r.name === "event") && m.voice && m.voice.channelID === message.member.voice.channelID
});
or
const eventMembers = message.guild.members.cache.filter(m => m.roles.cache.some(r => r.name === "event") && m.voice && m.voice.channelID === message.member.voice.channelID)
V3 :D
bot.on('message', message => {
if(message.content === '!test') {
if(!message.member.voice.channel) return message.reply('You need joinVoiceChannel for use this command');
let targetRole = message.guild.roles.cache.find(role => role.name === 'event')
if (!targetRole) return message.reply('Can`t find a role');
let eventMembersNotInVoice = targetRole.members.filter(member => member.voice.channelID !== message.member.voice.channelID)
console.log(eventMembersNotInVoice.size)
}
});

Related

Reactionrole does not work with custom emoji but will work using default ones

Hi everyone I have been trying to make my reactionrole work for a bit now and have run into a problem. So far my bot doesnt seem to work using a custom emoji on my own discord server but seems to run fine with default ones I used a default and custom one to check. I don't get a log for 2 so it seems to go wrong there. I also tried changing reaction.emoji.name to id but with no result. Any help would be appreciated.
const yellowTeamRole = message.guild.roles.cache.find(role => role.name === "Iron");
const blueTeamRole = message.guild.roles.cache.find(role => role.name === "Gold");
const yellowTeamEmoji = '<:Iron:1006186923917852712>';
const blueTeamEmoji = '🔴';
let embed = new Discord.MessageEmbed()
.setColor('#e42643')
.setTitle('Choose a team to play on!')
.setDescription('Choosing a team will allow you to interact with your teammates!\n\n'
+ `${yellowTeamEmoji} for yellow team\n`
+ `${blueTeamEmoji} for blue team`);
let messageEmbed = await message.channel.send({embeds: [embed]});
messageEmbed.react(yellowTeamEmoji);
messageEmbed.react(blueTeamEmoji);
client.on('messageReactionAdd', async (reaction, user) => {
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.channel.id == channel) {
console.log('1');
if (reaction.emoji.name === yellowTeamEmoji) {
console.log('2');
await reaction.message.guild.members.cache.get(user.id).roles.add(yellowTeamRole);
}
if (reaction.emoji.name === blueTeamEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.add(blueTeamRole);
}
} else {
return;
}
});
You don't get a log because in your if statement you're comparing the whole emote to only its name.
You're basically doing this:
if("Iron" === "<:Iron:1006186923917852712>")
What you should do is get the emote in your client or guild and access the name property through .name
// the id of your emote
const foundEmote = client.emojis.cache.find(e => e.id === "1006186923917852712");
if(reaction.emoji.name === foundEmote.name) {
// your code
}

Discord.JS Reaction collector not working

const optionsEmbed = new Discord.MessageEmbed()
.setTitle("What would you like to setup?")
.setDescription(":one: Prefix\n:two: Mod Log Channel")
.setColor('RANDOM');
message.channel.send(optionsEmbed)
.then(async (msg) => {
await msg.react('1️⃣');
await msg.react('2️⃣');
const filter = (reaction, user) => {
return reaction.emoji.name === '1️⃣' || reaction.emoji.name === '2️⃣' && user.id === message.author.id;
};
const collector = message.createReactionCollector(filter, {
time: 30000
});
let collected = 0;
collector.on('collect', (reaction, user) => {
collected++;
if (reaction.emoji.name === "one") return managePrefix();
if (reaction.emoji.name === "two") return manageModLogChannel();
msg.delete();
collector.end();
});
collector.on('end', collected => {
if (collected === 0) return message.channel.send("You took too long to react, cancelled setup.");
});
});
async function managePrefix() {
const getCurrentPrefix = await message.getServerDatabase(message.guild.id, "prefix")
const currentPrefixEmbed = new Discord.MessageEmbed()
.setTitle("Info")
.setDescription("Current Prefix: " + getCurrentPrefix + "\n\nPlease reply with the new prefix or *cancel* to cancel.")
.setColor('RED');
message.channel.send(currentPrefixEmbed)
.then(async (msg) => {
const filter = (msgg, user) => {
return user.id == message.author.id;
}
const collector = message.channel.createMessageCollector(filter, {
time: 60000
});
let collected = 0;
collector.on('collect', async (m) => {
collected++;
msg.delete()
if (m.content.toLowerCase() === "cancel") {
m.delete();
return collector.end()
}
await message.setServerDatabase(message.guild.id, "prefix", m.content)
await m.reply("Set prefix to `" + m.content + "`");
collector.end()
});
collector.on('end', collected => {
if (collected === 0) return message.channel.send("You took too long to respond, cancelled setup.")
});
});
}
async function manageModLogChannel() {
const getCurrentPrefix = await message.getServerDatabase(message.guild.id, "modLogChannel")
const currentPrefixEmbed = new Discord.MessageEmbed()
.setTitle("Info")
.setDescription("Current ModLogChannel: <#" + getCurrentPrefix + ">\n\nPlease reply with the new channel or *cancel* to cancel.")
.setColor('RED');
message.channel.send(currentPrefixEmbed)
.then(async (msg) => {
const filter = (msgg, user) => {
return user.id == message.author.id;
}
const collector = message.channel.createMessageCollector(filter, {
time: 60000
});
let collected = 0;
collector.on('collect', async (m) => {
collected++;
msg.delete()
if (m.content.toLowerCase() === "cancel") {
m.delete();
return collector.end()
}
if (!m.mentions.channels.first()) {
m.delete()
message.channel.send("Not a valid channel, cancelled setup.");
return collector.end();
}
const channel = m.mentions.channels.first();
await message.setServerDatabase(message.guild.id, "modLogChannel", channel.id)
await m.reply("Set channel to `<#" + m.content + ">`");
collector.end()
});
collector.on('end', collected => {
if (collected === 0) return message.channel.send("You took too long to respond, cancelled setup.")
});
});
}
I am trying to make a config command, upon reacting to the first embed.. nothing happens.
If that first listener is not working, then I doubt the message collectors are working either.
The user should be able to react to a main embed which asks them if they want to change the prefix or mod log channel, from there it will then ask them what they want to change it to with the cancel option, it then saves it in the database using the custom functions (message.getServerDatabase and message.setServerDatabase())
Does anyone know what I'm doing wrong?
The reason it is not working as you want it to is that you are calling the .createReactionCollector() method on the wrong Message object. You should create the reaction collector on msg instead of message.
Like this:
const collector = msg.createReactionCollector(filter, {
time: 30000
});
Also collector.end() is not a function, you probably want to use collector.stop() instead.

How do i send a message based of a reaction

i have code that creates a reaction menu then outputs whichever option the user chose
client.on('message', async message => {
if (message.author.bot) return;
if (message.content === 'y.Einek')
{
const sentMessage = await message.channel.send(Einek);
const reactions = ['🇳', '🇭', '🇽'];
for (const reaction of reactions) await sentMessage.react(reaction);
const filter = (reaction, user) => reactions.includes(reaction) && user.id === message.author.id;
const collected = await sentMessage.awaitReactions(filter, { max: 1, timeout: 5000, errors: ['time'] }).catch(() => null);
if (!collected) return message.channel.send('You either took too long or something went wrong selecting your difficulty.');
const { name } = collected.first().emoji;
const response = name === '🇳' ? 'Normal' : (name === '🇭' ? 'Hard' : 'Extreme');
return message.channel.send(response);
}
});
and everything works fine except it doesn't output "response"
This code should work. Using the catch method for any error instead.
client.on('message', async message => {
if (message.author.bot) return;
if (message.content === 'y.Einek') {
const sentMessage = await message.channel.send(Einek);
const reactions = ['🇳', '🇭', '🇽'];
for (const reaction of reactions) await sentMessage.react(reaction);
const filter = (reaction, user) => reactions.includes(reaction) && user.id === message.author.id;
sentMessage.awaitReactions(filter, { max: 1, timeout: 5000, errors: ['time'] }).then(collected => {
const { name } = collected.first().emoji;
const response = name === '🇳' ? 'Normal' : (name === '🇭' ? 'Hard' : 'Extreme');
sentMessage.channel.send(response);
}).catch(() => message.channel.send('You either took too long or something went wrong selecting your difficulty.'));
}
});

Send is undefined

client.on('guildMemberAdd', member => {
member.roles.add(member.guild.roles.cache.find(i => i.name === 'User'))
const welcomeEmbed = new Discord.MessageEmbed()
welcomeEmbed.setColor('#5cf000')
welcomeEmbed.setTitle('**' + member.user.username + '** Has joined! **' )
member.guild.channels.cache.find(i => i.name === 'welcome').send(welcomeEmbed)
})
Send is undefined im not to sure what to do.
Your bug is in member.guild.channels.cache.find(i => i.name === 'welcome'), There are no channels named 'welcome'.
You may want to add a check:
const channel = member.guild.channels.cache.find(i => i.name === 'welcome');
if (channel) {
channel.send(welcomeEmbed);
}

How would I get my discord.js bot to add a role when someone reacts to a message?

Right now, I'm trying to make a reaction roles bot, but I keep on getting an error. Here is my code.
const Discord = require('discord.js');
const keepAlive = require('./server');
const client = new Discord.Client();
client.on('message', message => {
if (message.author !== null && message.author.bot) return;
if (message.toString().toLowerCase().includes('start reaction roles')) {
message.delete()
const embed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('React to get notified')
.setDescription(`Hello! Please react to this message to get a role. Here are the roles that you can get by reacting:\n> 🖐 | React with this emoji to get <#&727665971443269635> notifications.\n> ⚠️ | React with this emoji to get <#&727633811709362187>.\nYou can chose one of the emojis, or both of them.`)
message.channel.send(embed).then(sentMessage => {
sentMessage.react("🖐")
.then(() => sentMessage.react("⚠️"))
.catch(() => console.error('One of the emojis failed to react.'));
})
const collector = sentMessage.createReactionCollector();
collector.on('collect', (reaction, user) => {
if (reaction.emoji.name === '🖐'){
role = message.guild.roles.find(role => role.name === "ne1 here");
message.member.addRole(role);
}
else if (reaction.emoji.name === '⚠️'){
role = message.guild.roles.find(role => role.name === "HR notifications");
message.member.addRole(role);
}
})
}
});
keepAlive();
client.login(process.env.TOKEN);
The part where it says const collector = sentMessage.createReactionCollector(); is not working. If someone could please help me with this, that would be great.
I just figured out how to make it run. Here is the code if you want to use it (this is my entire code. Remove some parts if needed).
const Discord = require('discord.js');
const keepAlive = require('./server');
const client = new Discord.Client();
client.on('message', message => {
if (message.author !== null && message.author.bot) return;
if (message.toString().toLowerCase().includes('start reaction roles')) {
message.delete()
const embed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('React to get notified')
.setDescription(`Hello! Please react to this message to get a role. Here are the roles that you can get by reacting:\n> 🖐 | React with this emoji to get <#&727665971443269635> notifications.\n> ⚠️ | React with this emoji to get <#&727633811709362187>.\nYou can chose one of the emojis, or both of them.\n\n**NOTE:**\nCurrently, this command does not support removing your roles. If you want to remove your role, click on the emoji. Then, click on your profile, and click the X next to the role you want to remove. You can always get it back by reacting.`)
message.channel.send(embed).then(sentMessage => {
sentMessage.react("🖐").then(() => sentMessage.react("⚠️")).then(() => {
const filter = (reaction, user) => {
return true;
}
const collector = sentMessage.createReactionCollector(filter);
collector.on('collect', (reaction, user) => {
if (reaction.emoji.name === '🖐'){
role = message.guild.roles.cache.find(role => role.name === "ne1 here");
message.member.roles.add(role);
}
else if (reaction.emoji.name === '⚠️'){
role = message.guild.roles.cache.find(role => role.name === "HR notifications");
message.member.roles.add(role);
}
})
})
.catch(() => console.error('One of the emojis failed to react.'));
})
}
});
keepAlive();
client.login(process.env.TOKEN);
I hope this is useful.

Resources