Discord.js autorole from username - discord.js

I want to make my bot autorole if username of anyone member contains a specific tag and the code i made isn't working, bot starts fine but didn't assign role if user have tag in username than also so i thought to use stackoverflow to get some help
Here is the code:
client.on("userUpdate", async (oldUser, newUser) => {
if (oldUser.username !== newUser.username) {
let tag = "⚡";
let server_id = "793143091350470708";
let role = "888436049620119562";
if (newUser.username.includes(tag) && !client.guilds.get(server_id).members.get(newUser.id).roles.has(role)) {
client.guilds.get(server_id).members.get(newUser.id).addRole(role)
} if (!newUser.username.includes(tag) && client.guilds.get(server_id).members.get(newUser.id).roles.has(role)) {
client.guilds.get(server_id).members.get(newUser.id).removeRole(role)
}
}
})

You would require to define USER_UPDATE, GUILD_MEMBER_UPDATE, and
PRESENCE_UPDATE intents if you are on discord.js version 13 and further enable the members and presence intent too, they can be located in the Discord Developer Portal further I would like to suggest using the Client#guildMemberUpdate listener instead since your code has nothing to do with presence you would not need the "extra" intents.
Additional Information
Directed by this comment It has come to my notice that you are using version 12 of discord.js so you would want to make adequate changes to your code for that ( your code as it currently is, is clearly written for discord.js v11) the following changes would be made in your code:
client.on("guildMemberUpdate", async (oldUser, newUser) => {
if (oldUser.username !== newUser.username) {
let tag = "⚡";
let server_id = "793143091350470708";
let role = "888436049620119562";
if (newUser.username.includes(tag) && !client.guilds.cache.get(server_id).members.cache.get(newUser.id).roles.has(role)) {
client.guilds.cache.get(server_id).members.cache.get(newUser.id).roles.add(role)
} if (!newUser.username.includes(tag) && client.guilds.cache.get(server_id).members.cache.get(newUser.id).roles.has(role)) {
client.guilds.cache.get(server_id).members.cache.get(newUser.id).roles.remove(role)
}
}
})

Related

Getting nicknames of users of my Discord bot

I can see the names, ids and user numbers of the servers where my bot is located, but how can I get the list of users (nicknames)?
You can make use of guild.members.fetch() in order to get all members and then use the nickname property to receive their nicknames. Finally I removed all bots with a simple filter.
const members = (await message.guild.members.fetch())
.filter((m) => !m.user.bot)
.map((m) => m.displayName);
console.log(members);
Working example as a command:
client.on("message", async (message) => {
if (message.author.bot) return;
if (message.content === "!list") {
const members = (await message.guild.members.fetch())
.filter((m) => !m.user.bot)
.map((m) => m.displayName);
console.log(members);
}
});
client.login("your-token");
Thanks to #MrMythical who suggested using displayName only. That property automatically returns the normal username when no nickname has been set for a user.
Users do not have nicknames, only guild members, if you are trying to fetch a list of server member nicknames.
You can use the code snippet from below:
const map = message.guild.members.cache.filter(c=> !c.member.user.bot).map(c=>c.displayName).join('\n');
console.log(map)
The
message.guild.members.cache.filter(c=> !c.member.user.bot)
Filters bots from the list, the
.map(c=>c.displayName).join('\n');
maps the data and only the user nicknames and joins them by paragraph breaks.
If there are any issues, please comment!

Discord.JS - How to get user ID from username?

can someone please help me to retrieve username from user ID and send a message to the chat with that ID?
if (message.content.startsWith(prefix)) {
const [CMD_NAME, ...args] = message.content
.trim()
.substring(prefix.length)
.split(/\s+/);
if (CMD_NAME === "getid") {
const getid1 = new MessageEmbed()
.setDescription("❗️ | Please tag the member to retrieve the ID!")
.setColor(10181046);
if (args.length === 0) return message.reply(getid1);
const username = client.guilds.cache.get('<GUILD ID>');
const userid = client.users.cache.find(username => username.tag === 'Someone#1234').id
message.channel.send(`${username} id is ${userid}`);
}
}
});
When I type the command "d!getid #Username", it shows me this error:
C:\Users\USER\Desktop\DiscordBotas\index.js:152 const userid = client.users.cache.find(username => username.tag === 'Someone#1234').id TypeError: Cannot read property 'id' of undefined at Client. (C:\Users\USER\Desktop\DiscordBotas\index.js:152:90)
You are creating a lambda of a variable that you just defined above the actual lambda, this could probably mess with your code.
The const username = client.guilds.cache.get('<GUILD ID>'); is wrong.
The fetching of the userId should probably work if you fix the line above it.
You are trying to get the user the wrong way. Firstly, why are you trying to match a user's tag with a guild? Maybe you think guild.cache has users? Well actually, this is client.guilds.cache, which only has guilds in it, and it returns a guild, not a user. Secondly, to get a user, you can try this method:
const user = client.users.cache.find(u => u.tag === 'SomeUser#0000')
console.log(user.id);
Below is code to get user by ID, but it probably won’t help with this, considering you would already have access to the ID
const user = client.users.cache.get("<UserID>");
console.log(user);
Also, you should add code to see if user isn’t found (client can’t find user with the condition). Here is some code to check that:
//... the find user code I put
if(!user) return message.reply('User could not be found');
message.channel.send(user.id);

Why does my discord bot not add roles properly?

I am trying to make a bot that would add a role that is in the server when a person types !join choiceOutOfVariousRoles. I am currently using discord version 12. My error message is:
fn = fn.bind(thisArg);
Although trying various techniques I could not get the code to work.
const Discord = require('discord.js');
const client= new Discord.Client();
const token = process.env.DISCORD_BOT_SECRET
client.on('ready', () => {
console.log("I'm in");
console.log(client.user.username);
});
client.on('message', msg => {
if (msg.content.toLowerCase().startsWith("!join"))
{
var args = msg.content.toLowerCase().split(" ")
console.log(args)
if (args[1] === 'sullen')
{
msg.channel.send('You have successfully joined Sullen!')
const sullenRole = msg.guild.roles.cache.find('name','Sullen')
msg.member.addRole(role.id)
}
}
});
client.login(token)
**EDIT: Fixed what everyone was saying and all I need to do now Is update the permissions, (my friend has to do that because its not my bot) and I should be all good. Thanks everyone! :D
discord.js introduces breaking changes very frequently, and v12 is no exception. You need to make sure you find up-to-date code otherwise it won't work. GuildMember#addRole was moved to GuildMemberRoleManager#add, which means you must use msg.member.roles.add(sullenRole).

How to Edit Embedded Message on Discord When Role Has Been Assigned or Removed

I am working on a Discord bot and I have an embed that shows the names of people who has that role, I want to make it edit that one message everytime the role is assigned or removed. Help would be very appreciated 🙂
You can use the Client#guildMemberUpdate. The event is fired whenever the GuildMember is updated. (This includes: role added, role removed, nickname changes etc.)
Here's a simple example:
client.on("guildMemberUpdate", (oldGuildMember, newGuildMember) => {
if (oldGuildMember.guild.id == "GuildID") { // Checking if the event was fired within the required Guild.
if (!oldGuildMember.roles.cache.equals(newGuildMember.roles.cache)) { // Checking if the roles were changed.
const Channel = client.channels.cache.get("ChannelIUD"); // Getting the channel your MessageEmbed is in.
const Role = oldGuildMember.guild.roles.cache.get("RoleID"); // Getting the Role by ID.
if (!Role || !Channel) return console.error("Invalid role or channel.");
Channel.messages.fetch("MessageID").then(message => { // Getting the MessageEmbed as a Message by ID
const Embed = new Discord.MessageEmbed(); // Updating the MessageEmbed.
Embed.addField(`Members of ${Role.name}`, Role.members.size > 0 ? `${Role.members.map(member => member.user.tag).join("; \n")};` : "This role has no members.");
Embed.setColor("RED");
message.edit(Embed).catch(error => console.error("Couldn't edit the message."));
}).catch(error => console.error("Couldn't fetch the message."));
};
};
});

Add a role to people that react with a certain emoji in a certain channel

I'm trying to make a discord.js bot for my server I made for people in my school. I'm trying to make a #classes channel and if you react to certain messages it gives you a role (which gives you access to the text channel for that class).
client.on('messageReactionAdd', (reaction, user) => {
console.log("client.on completed.")
if (message.channel.name === 'classes') {
console.log("if(message) completed.")
if (reaction.emoji.name === "reminder_ribbon") {
console.log("emoji test completed.")
const guildMember = reaction.message.guild.members.get(user.id);
const role = reaction.message.guild.roles.find(role => role.name === "FACS");
guildMember.addRole(role);
}
}
});
This is what I have tried so far, however, it does not give me/the other people reacted to it the role nor does it return an error message.
P.S. Also, how would I be able to make it so when they unreact it removes the role?
Edit: It seems it only gets reactions from cached messages/messages sent after bot startup. Also, message is not defined on the first if(message.channel.id) message.
Try to use the following code:
client.on('messageReactionAdd', (reaction, user) => {
if (reaction.message.channel.id === '552708152232116224') {
if (reaction.emoji.name === "reminder_ribbon") {
const guildMember = reaction.message.guild.members.get(user.id);
const role = reaction.message.guild.roles.get('552709290427940875');
guildMember.addRole(role);
}
}
});
First of all, reaction.users is an Object with all the users that reacted on the message, so you first have to define to which user you want to assign the role. I fixed this fetching the guildMember with user.id.
The second mistake was that you tried to assign a role ID to a guildMember although you first have to fetch the role and then assign the role Object to the guildMember.

Resources