How to get role members count in discord.js - discord.js

I want to get member count who have specific role. role.member is collection. how can i get member count?
ps i'll use role id.

You can use role.members.size:
client.on('message', (message) => {
let guild = await message.guild.fetchMembers();
let roleID = '3933783737379';
let memberCount = guild.roles.get(roleID).members.size;
message.channel.send(memberCount + " members have this role!");
});
Note this only counts cached members so maybe you will have to use guild.fetchMembers() before.

Related

How do I get a list of all members in a discord server, preferably those who aren't bot

I'm attempting checks if a username is in a valid username in the server. The check is done by the following code
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!logan',
intents=intents,
helpCommand=helpCommand)
Users = [# Need help getting users]
async def Fight(ctx, User):
if ctx.author.name != User:
if User in Users:
open_file = open(str(ctx.author.name), "w")
open_file.write(User + "\n300\nTurn")
open_file.close()
open_file = open(User, "w")
open_file.write(str(ctx.author.name) + "\n300\nNot")
open_file.close()
await ctx.author.send("You are now fighting " + User)
#await ctx.User.send("You are now fighting " + ctx.author.name)
else:
await ctx.send("User is not in this server")
else:
await ctx.send("You Cannot Fight Yourself")
I've tried googling, but I haven't found a valid answer
There are other ways to get your guild name, but here's a possible method to get it and get the member list from it.
In member (and user so), there is the ".bot" that is a boolean, 0 if not a bot.
listMembers = []
#bot.command(name="init")
async def FuncInit (ctx) :
global listMembers
guilde = ctx.message.guild
for member in guilde.members :
if not member.bot :
listMembers.append(member.name)

How to remove a role in discord.py without discord.ext

I want to remove a role from a user without using discord.ext ( because of certain resons I can't ) but I don't know how to do it ( so without commands ( by commands I mean #bot.commands....), and without ctx )
If you want this is the code where I want to put the thing that will remove the role :
if message.content.startswith('$rmv_role'):
member4 = message.content
member5 = member4.split()
member6 = member5[1]
server_id = message.guild.id
guild = client.get_guild(server_id)
role_id = 999988854696194048
role = discord.utils.get(guild.roles, id=role_id)
await message.delete()
user_id = ''.join(c for c in member6 if c.isdigit())
user = get(bot.get_all_members(), id=user_id)
*the code that remove roles*
return
discord.Member has a method called remove_roles().
So, the code is following:
await user.remove_roles(role)

Unable to Assign Role with member.roles.add (id)

I'm trying to make an assignrole command which takes userID and roleID as arguments.
content = message.content.slice(message.content.indexOf(' ')+1)
args = content.split(', ');
const userID = args[0]
const roleID = args[1]
const desiredUser = message.guild.members.cache.get(userID)
const desiredRole = message.guild.roles.cache.get(roleID)
if (desiredUser != undefined){
if (desiredRole != undefined){
usern = desiredUser.user.username
desiredUser.roles.add(roleID).catch(console.error);
message.channel.send(usern + " has been assigned the "+ desiredRole.name +" role")
console.log("added role")
} else {
message.channel.send("role with ID " + roleID + " does not exist")
}
} else {
message.channel.send("user with ID " + userID + " does not exist")
}
The function succeeds at "getting" the correct user and role, and successfully sends the "USER has been assigned the ROLENAME role" message. However, the role itself isn't actually added to the user!
My console throws a DiscordAPIError: Missing Permissions error, but I don't know how to interpret it. The error does not quit the bot, however.
How do I add the role to the user?
It is likely that you are missing the MANAGE_ROLES permission as it is, like the name would suggest, required to manage rules.
https://discord.com/developers/docs/topics/permissions
Here are other possibilities that may be causing the error:
I found these here
It is trying to execute an action on a guild member with a role higher than or equal to your bots highest role.
It is trying to modify or assign a role that is higher than or equal to its highest role.
It is trying to execute a forbidden action on the server owner.

How to make by bot to leave a server with a guild id

I want my bot to leave a discord server by using ;leave <GuildID>.
The code below does not work:
if (message.guild.id.size < 1)
return message.reply("You must supply a Guild ID");
if (!message.author.id == 740603220279164939)
return;
message.guild.leave()
.then(g => console.log(`I left ${g}`))
.catch(console.error);
You're most likely not supposed to be looking at message.guild.id, since that returns the ID of the guild you're sending the message in. If you want to get the guild ID from ;leave (guild id), you'll have to cut out the second part using something like .split().
// When split, the result is [";leave", "guild-id"]. You can access the
// guild ID with [1] (the second item in the array).
var targetGuild = message.content.split(" ")[1];
!message.author.id will convert the author ID (in this case, your bot ID) into a boolean, which results to false (since the ID is set and is not a falsy value). I'm assuming that you mean to have this run only if it the author is not the bot itself, and in that case, you're most likely aiming for this:
// You're supposed to use strings for snowflakes. Don't use numbers.
if (message.author.id == "740603220279164939") return;
And now, you just have to use the guild ID that you got from the message content and use that to leave the guild. To do that, just grab the Guild from your bot cache, and then call .leave(). All in all, your code should now look like this:
// Get the guild ID
var targetGuild = message.content.split(" ")[1];
if (!targetGuild) // targetGuild is undefined if an ID was not supplied
return message.reply("You must supply a Guild ID");
if (message.author.id == "740603220279164939") // Don't listen to self.
return;
client.guilds.cache.get(targetGuild) // Grab the guild
.leave() // Leave
.then(g => console.log(`I left ${g}`)) // Give confirmation after leaving
.catch(console.error);

How to get a number of online members?

I have a command that counts members and bots and outputs them separately. I would then like to output the number of online users. Is this possible?
This command gets member and bot count
if message.content.startswith('<count'):
membersInServer = message.guild.members
channel = message.channel
# Filter to the list, returns a list of bot-members
botsInServer = list(filter(filterOnlyBots, membersInServer))
botsInServerCount = len(botsInServer)
# (Total Member count - bot count) = Total user count
usersInServerCount = message.guild.member_count - botsInServerCount
msg = discord.Embed(title="Amount of Human Members in this Discord:", description=usersInServerCount, color=0x00FD00)
msg.add_field(name="Amount of Bot Users in this Discord:",value=botsInServerCount, inline=False)
await channel.send(embed=msg)
def filterOnlyBots(member):
return member.bot
I've tried client.member.status and that just returns Online
Each Member has a status property, which you can use it to check if the status is offline or not.
You can then filter your membersInServer by offline status.
onlineMembersInServer = list(filter(filterOnlyOnlineMembers, membersInServer))
onlineMembersCount = len(onlineMembersInServer)
# Somewhere...
def filterOnlyOnlineMembers(member):
return member.status != 'offline'
Note that it count online users and bots If you want to filter to only online users, you can change the filter to this:
# Set the filter to be a non-offline member, and the member not being a bot.
def filterOnlyOnlineMembers(member):
return member.status != 'offline' and not member.bot
Note that this might have performance issues if the server is large.
Edit
As #Patrick Haugh mentioned, you can make this into a 1-liner
sum(member.status!=discord.Status.offline and not member.bot for member in message.guild.members)

Resources