Remove every user from a discord role - discord

is there a way to delete all users from certain groups in a limit-saving way?
The way to delete every user one by one from a group seems very time consuming to me.
There are both possibilities, via a bot (Discord.js) that is already on the server or the Discord API.

I'd say your best bet is to just delete the role. The Role.delete method returns the Role after it has been deleted. You can just pass that exact return value back into guild.roles.create to clone the options from the previous role, in case you need to keep the properties of the Role but do not want the members anymore.
Ex:
declare const client: Client<true>
const guild = await client.guilds.fetch(`some-guild-id`)
const role = await guild.roles.fetch(`deleting-role-id`)
if (role) {
const deleted = await role.delete()
const recreated = await guild.roles.create(deleted)
}
This would be a pretty clean solution.

Related

Discord.js V13 dont know how to check if a user ID is in the current guild

I have been trying to check if a certain user ID exists in the current guild,
I have been looking at countless stack overflow questions and documentations hoping i could find the answer but nothing I try actually works.
i use Discord.js V13 with the latest node.js version
const server = client.guilds.fetch( message.guild.id );
if ( !server.member(args[0]) ) return commandFailed('a user with this ID does not exist');
// args[0] contains the userID
could someone please help me with this.
First: fetch returns a promise, you must handle that promise. However, you don't need to fetch the server since the server is already accessible through message.guild.
Second: Guild#member() is deprecated, try fetching the member directly and checking if a member returned.
I'll be using Async/Await for this example, make sure you're inside an Async function.
// const server = await client.guilds.fetch(message.guild.id); is not needed
const server = message.guild;
const member = await server.members.fetch(args[0]);
if (!member) return commandFailed('a user with this ID does not exist');
Take a look at this thread, which explains exactly what you want:
let guild = client.guilds.get('guild ID here'),
USER_ID = '123123123';
if (guild.member(USER_ID)) {
// there is a GuildMember with that ID
}

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 can i add role when member has 10 invites?

im making discord bot with discord.js v12 and im trying to give role when member has 10 invites
i found invitation code from here and modified it:
if(message.channel.type != "dm" && message.channel.id === '768475421953915093') {
message.delete();
var user = message.author;
message.guild.fetchInvites()
.then
(invites =>
{
const userInvites = invites.array().filter(o => o.inviter.id === user.id);
var userInviteCount = 0;
for(var i=0; i < userInvites.length; i++)
{
var invite = userInvites[i];
userInviteCount += invite['uses'];
}
if(userInviteCount >= 10){
const guildMember = message.member;
guildMember.addRole('767542365812886656');
message.author.send(`you have access now`)
}else {
message.author.send(`sry u have ${userInviteCount} invitations. u need at least five`)
}
}
)
}
yes, it works but you can trick the system easily. If you keep rejoining from the server, the invite counter increases. How can i stop that?
To do this, you will need an external database since Discord API doesn't provide any information about who used that invite and how many times.
ALERT: It's a simple feature but can be very hard for people that don't have any coding experience, so if it's your first project, don't give up and keep trying! :D
You can use MongoDB Atlas, which is very simples and free.
And the logic will be very simple:
1 - Create a collection to store the invites data, you can do something like in this example
2 - Create a collection (you can give any name, but in this example, I will refer to this collection as new_members) to store the new members data, it should have the fields serverId (to store the guild ID), userId (to store the user ID) and inviteCode (to store the invite code or url)
3 - When a user joins the discord server, it will trigger the "guildMemberAdd" event, and you will get the invite that was used (with the example that I give in the first step), and create a new doc in the new_members collection.
4 - After creating this new data, you will search for all the docs from the same invite, and filter them by userId (there are many ways to do this, this is one of them).
5 - With this array of docs, you can use his length to determine how many people were invited, and give the role.
VERY SIMPLE EXAMPLE, THAT SHOULDN'T BE USED:
DiscordClient.on("guildMemberAdd", async (member) => {
/**
* https://github.com/AnIdiotsGuide/discordjs-bot-guide/blob/master/coding-guides/tracking-used-invites.md
* Here you will get the invite that was used, and store in the "inviteCode" variable
*/
const inviteCode = await getInviteUsed()
await NewMemberRepository.insert({
serverId: member.guild.id,
userId: member.id,
inviteCode: inviteCode
});
const joinedMembersFromTheInvite = await NewMemberRepository.find({
inviteCode: inviteCode
});
/**
* https://stackoverflow.com/questions/43374112/filter-unique-values-from-an-array-of-objects
* Here you will filter the results by userId
*/
const invitesWithUniqueUsers = filterJoinedMembersByUserId(joinedMembers)
if (invitesWithUniqueUsers >= REQUIRED_INVITES_QTD) {
/**
* Gives the role to the creator of the invite
*/
}
});
Hope it helps, good luck! :D
OBS:
Yes, Discord API provides how many times an invite was used, but not how many a specific person used this invite.
In the examples, I used something like TypeORM, but if you are using JavaScript instead TypeScript, you can use Mongoose

Add / Remove user from role by ID [DISCORD.JS]

Hey today I'd like give and remove roles from a user by their ID
First try:
const user = '5454654687868768'
const role = '451079228381724672'
user.roles.remove(role)
Second Try:
const user = '5454654687868768'
const role = '451079228381724672'
user.removeRole(role)
Neither one of these methods seems to work, however.
const user = '5454654687868768'
const role = '451079228381724672'
These are just numbers which happen to be the id of your user and role object. They are nothing on their own and you can't call any Discordjs methods on them. To get the user and role object you will first have to get them using their respective ID.
Let's assume you want to add a role when someone joins the server, you can do the same thing in any type of event but we will use guildMemberAdd event for example:
bot.on('guildMemberAdd', async member => {
const memberID = '5454654687868768'; // you want to add/remove roles. Only members have roles not users. So, that's why I named the variable memberID for keeping it clear.
const roleID = '451079228381724672';
const guild = bot.guilds.cache.get('guild-ID'); // copy the id of the server your bot is in and paste it in place of guild-ID.
const role = guild.roles.cache.get(roleID); // here we are getting the role object using the id of that role.
const member = await guild.members.fetch(memberID); // here we are getting the member object using the id of that member. This is the member we will add the role to.
member.roles.add(role); // here we just added the role to the member we got.
}
See these methods are only working because they are real discordjs objects and not some numbers like you were trying to do. Also the async/await thing is there because we need to wait for the bot to get the member object from the API before we can add role to it.
Your first try was actually not that far off. The only problem is that roles.remove() is a guildMember function.
So first we need to define the member.
const member = message.guild.members.cache.get("member ID here");
Now we can remove or add a role. Source
member.roles.remove("role ID here");

Why doesn't Collection#find work for offline members who have no roles? (discord.js)

My Goal
My goal is to figure out why Collection#find returns undefined when I try to find a user in my server, but they're offline and have no roles.
Expectation
Usually the console logs an array of all the properties of the user
Actual Result
The console logs Collection#find, as undefined if the user in my server is offline and has no roles
What I've Tried
I've tried using Collection#get, but it turns out that it returns the same response. I've tried searching this up on Google, but no one has asked this question before.
Reproduction Steps
const Discord = require('discord.js');
const client = new Discord.Client();
const {prefix, token} = require('./config.json');
client.once('ready', () => {
console.log('Client is online');
const user = client.users.cache.find(user => user.tag === 'Someone#1234');
console.log(user);
};
client.login(token);
Make sure that whoever is helping you, whether it's an alt account or your friend, that they have no roles, and they're completely offline in your server
Output:
Client is online undefined
I had the same problem. I don't know why this happens, but I used this line to fix that:
((await m.guild.members.fetch()).filter(mb => mb.id === "The ID")).first()`
Basically, this collect all the members, then filters them with the property you want, and the first() at the end is to make it a single object instead of a collection.
Instead of the user.tag property, try using the user.username and the user.discriminator properties. This worked for me
const user = client.users.cache.find(user => user.username === 'Someone' && user.discriminator === '1234');
Also check spelling, capitalization, ect.
A simple solution to my problem is just create an async function and use await guild.members.fetch() to cache the users and then use Collection#find to get the user.

Resources