Brandon Weeks
Brandon Weeks

Reputation: 59

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

Upvotes: 2

Views: 11675

Answers (1)

WQYeo
WQYeo

Reputation: 4046

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)

Upvotes: 4

Related Questions