Set autorole on specific guilds only - discord.js

I'd like to auto set roles for new users when they join server X, problem is that this bot is on server Y as well, and server Y doesn't have the role.
client.on('guildMemberAdd', member => {
console.log('User ' + member.user.tag + ' has joined Steampunk.');
var role = member.guild.roles.find(x => x.name === "name");
member.addRole('247442955651121154');
})
I was hoping that I could do a simple check before applying the role, if user have joined server X, add the role, if else, do nothing. So far my attempts have failed.
Any input would be appreciated!

The original code is trying add a specific role you put in, and not the role you just looked up a line before that. There shouldn't be any issues with other servers the bot is in, because member.guild gives the guild of the member object, and since this member object is coming from a guildMemberAdd it means that member.guild will only return the guild that was just joined. The code in the edit has a lot of strange things going on, though.
The first issue I see is that in order to look through the channels in a guild, you have to use guild.channels.cache.find(), guild.channels.find() is old now and doesn't work in v12. Same goes for client.guild, guild.roles, etc. The part at the bottom of your edited code doesn't seem to make much sense at all. The code should get the roles of the newly joined guild (member.guild.roles.cache), look through them to find the role you want (you did this correctly with the .find()) and then apply the role to the member. Neither server nor role ever get used in your code, and guild.id is a property, not a method.
Let me know if you need help following these instructions, although it looks like you should be able to do it now. Always look at the discord.js docs first to check properties, methods, etc.

I ended up defining the guild in question by name, saved it as a const, and made a check for the specific guild.
If your bot is on several servers but you only want the greet/addRole on a specific one, all integrated into the message displayed on joining;
//Welcome message and autorole for specific server and channel.
client.on('guildMemberAdd', member => {
const = client.guilds.find(guild => guild.name === "Steampunk");
if (!guild) return;
const channel = member.guild.channels.find(ch => ch.name === "greetings");
if (!channel) return;
let botembed = new Discord.RichEmbed()
.setColor("#ff9900")
.setThumbnail(member.user.avatarURL)
.setDescription(`${member} Welcome to the Ark Steampunk Sponsored Mod Discord!\nPlease report all <#244843742568120321> and if u need any help view or ask your question in <#334492216292540417>. Have any ideas we got a section for that too <#244843792132341761>. Enjoy!:stuck_out_tongue: Appreciate all the support! <http://paypal.me/ispezz>`)
.setTimestamp()
.setFooter("Steampunk Bot", client.user.avatarURL);
channel.send(botembed);
console.log('User ' + member.user.tag + ' has joined ' + member.guild.name + '.');
var role = member.guild.roles.find(x => x.name === "name");
member.addRole('247442955651121154');
});

Related

Give Role when a member joins the voice channel. discord.js

Im trying to make discord.js code. When a member joins the voice channnel I want the bot to give them a role, when the member leaves, i want the role to be removed. thanks for your help.
const newChannelID = newState.channelID;
const oldChannelID = oldState.channelID;
if (oldChannelID === "835280102764838942"){
member.send('role given');
let role = message.guild.roles.cache.find(r => r.id === "835279162293747774");
member.roles.add(835279162293747774);
} else if(newChannelID === "835280102764838942"){
member.send('role removed');
member.roles.remove(835279162293747774);
}
})
There's a couple of things you need to clean up in your code. I'm going to assume you're using the voiceStateUpdate event to trigger your command.
Most importantly, (logic-wise) you actually need to flip-flop the way you add and remove roles. Currently, the general code states that if the user left the voice channel (thus oldChannelID = actual vc ID), then it would actually give the user a role. This seems to be the opposite of your intention, thus you'd simply swap out the code in each if/else if statement.
Second, the way you're assigning roles and adding them is incorrect. I'd recommend this resource for more info.
Third, you cannot access message if you were indeed using voiceStateUpdate as your event, since it only emits an oldState and a newState.
Lastly, you need to designate a text channel to send the message to. In my code, I manually grabbed the ID of the channel I wanted and plugged it into the code. You'll have to do the same by replacing the number strings I have with your own specific ones.
With that being said, here's the correct modified code:
client.on('voiceStateUpdate', (oldState, newState) => {
const txtChannel = client.channels.cache.get('803359668054786118'); //manually input your own channel
const newChannelID = newState.channelID;
const oldChannelID = oldState.channelID;
if (oldChannelID === "800743802074824747") { //manually put the voice channel ID
txtChannel.send('role removed');
let role = newState.guild.roles.cache.get("827306356842954762"); //added this
newState.member.roles.remove(role).catch(console.error);
} else if (newChannelID === "800743802074824747") {
txtChannel.send('role given');
let role = oldState.guild.roles.cache.get("827306356842954762"); //change this somewhat
oldState.member.roles.add(role).catch(console.error); //adding a catch method is always good practice
}
})

How do i make discord.js list all the members in a role?

if(message.content == `${config.prefix}mods`) {
const ListEmbed = new Discord.MessageEmbed()
.setTitle('Mods:')
.setDescription(message.guild.roles.cache.get('813803673703809034').members.map(m=>m.user.tag).join('\n'));
message.channel.send(ListEmbed);
}
Hey so iam making a command which displays all the members with that role but it only seems to be sending 1 of the mods
await message.guild.roles.fetch();
let role = message.guild.roles.cache.find(role => role.id == args[0]);
if (!role) return message.channel.send('Role does not exist'); //if role cannot be found by entered ID
let roleMembers = role.members.map(m => m.user.tag).join('\n');
const ListEmbed = new Discord.MessageEmbed()
.setTitle(`Users with \`${role.name}\``)
.setDescription(roleMembers);
message.channel.send(ListEmbed);
};
Make sure your command is async, otherwise it will not run the await message.guild.roles.fetch(); - this fetches all roles in the server to make sure the command works reliably.
In Discord.jsV12 the get method was redacted and find was implemented.
Aswell as this, I would highly recommend defining variables to use in embeds and for searching since it is much more easy to error trap.
If you have many members with the role, you will encounter the maximum character limit for an embeds description. Simply split the arguments between multiple embeds.

Set Role Color for Discord.js bot

I am trying to make my bot's role a pink color for the current server using the Client.on("ready") However whenever I run the bot with what I currently have the console returns:
(node:6504) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'cache' of undefined
Here is my code I am currently using. I know I need to for loop on every guild but I'm not sure how I would do that, I could use a for or just a .forEach however I can't find the correct way to do such.
const role = client.guild.roles.cache.get('Aiz Basic+');
role.edit({ name: 'Aiz Basic+', color: '#FFC0CB' });
In advance thank you to anybody who replies and helps with my message.
Client#Guild Isn‘t existing. Only Client#Guilds. You can fix this problem by looping through the cache of all your guilds with:
client.guilds.cache.forEach((g) => { })
And inside the loop you can use your code after fixing the .get function, because the get function needs a role id not a role name. You could find the role via the name by writing:
const role = <Guild>.roles.cache.find((r) => r.name === /* The role name */);
Make sure you replaced <Guild> with your guild variable.
Try this code if client.guild is not defined, it could also be because you are using bot instead of client
let role = message.guild.roles.cache.find(role => role.name === "Aiz Basic+");

Discord.js getting guildmember from username

I hope you can help I can't seem to find a solution for this speific use case.
When a user joins my server I want to show a welcome embed and update their nickname in the server.
I have the embed bit working fine but I cant seem to get the guildMember using the user supplied.
code: Discord.js v12.2
bot.on('guildMemberAdd', member=> {
const channel = member.guild.channels.cache.find(channel => channel.name === 'cloudservertesting');
if(!channel) return;
const embed = new Discord.MessageEmbed()
.setColor('#992D22')
.setTitle('New Member')
.setDescription(`**${member.user.username}** has joined Red Wine Gaming!, Welcome!`)
.setThumbnail(`${member.user.displayAvatarURL()}`)
.setTimestamp();
channel.send(embed);
//Change users Nickname Here
});
member.guild.members returns an object but it wont let me .filter
It would be ideal if I could get the guildmember from the mumer.user supplied on the user add so i can setNickname.
The GuildMember instance you're looking for is your parameter member. Check the documentation on the Client#guildMemberAdd event and you'll see the parameter is a GuildMember.
member.setNickname('foo')
.catch(console.error);
member.guild.members returns an object but it wont let me .filter
That would be because as of v12, it's a Manager, so you would have to utilize the cache property to use Collection#filter(). See GuildMemberManager specifically.

How to get GuildMember data from a User through a mention

I am making a "user info" command that returns the user's Discord username, their ID, their server join date and whether or not they are online. I am able to display all the information through user.id, user.username, and user.presence.status. But when I try to use user.joinedAt I get undefined in the display.
I know this is because the User class and the GuildMember class are not the same, and that the GuildMember class contains a User object.
But my problem is: how I could get the .joinedAt data from my user mention?
Here is my current code:
let user = message.mentions.users.first();
let embed = new Discord.RichEmbed()
.setColor('#4286f4')
.addField("Full Username:", `${user.username}#${user.discriminator}`)
.addField("User ID:", `${user.id}`)
.addField("Server Join Date:", `${user.joinedAt}`)
.addField("Online Status:", `${user.presence.status}`)
.setThumbnail(user.avatarURL);
message.channel.send(embed);
Here's the code for my user info command:
if (msg.split(" ")[0] === prefix + "userinfo") {
//ex `member #Rinkky
let args = msg.split(" ").slice(1) // gets rid of the command
let rMember = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0])) // Takes the user mentioned, or the ID of a user
let micon = rMember.displayAvatarURL // Gets their Avatar
if(!rMember)
return message.reply("Who that user? I dunno him.") // if there is no user mentioned, or provided, it will say this
let memberembed = new Discord.RichEmbed()
.setDescription("__**Member Information**__")
.setColor(0x15f153)
.setThumbnail(micon) // Their icon
.addField("Name", `${rMember.username}#${rMember.discriminator}`) // Their name, I use a different way, this should work
.addField("ID", rMember.id) // Their ID
.addField("Joined at", rMember.joinedAt) // When they joined
await message.channel.send(memberembed)
};
This will send an embed of their user info, this is my current code and
rMember.joinedAt
does work for me.
edit:
After looking at your question again, I found out I didn't need to post everything, you can't get the joined at because it's just the mention. Try this:
let user = message.guild.member(message.mentions.users.first())
Should work
You can technically find it by fetching getting the member from the guild and then using GuildMember.joinedAt: since the User class represents the user in every guild, you will always need the GuildMember to get info about a specific guild.
let user = message.mentions.users.first(),
member;
if (user) member = message.guild.member(user);
if (member) embed.addField("Server Join Date:", `${member.joinedAt}`);
With this said, I would not suggest you to do that, since it's not really efficient. Just take the mention from the members' collection and then take the user from that.
let member = message.mentions.members.first(),
user;
if (member) user = member.user;
The downside of this is that you can't use it if you want your command to be executable from the DMs too. In that case you should use the first method.
const member = message.channel.guild.members.cache.find(member => member.user == message.mentions.users.first())

Resources