Building out Bot Commands - making Discord bots with Discordpy 1.0.0 p.2




DiscordPy p.2 Continuing bot

Welcome to Part 2 of the DiscordPy bot creation for Sentdebot in my discord.gg/sentdex server. In this part, we're going to start building out our bot with actual logic that I want. Our code up to this point:

import discord

client = discord.Client()
token = open("token.txt","r").read()

@client.event  # event decorator/wrapper
async def on_ready():
    print(f"We have logged in as {client.user}")

@client.event
async def on_message(message):
    print(f"{message.channel}: {message.author}: {message.author.name}: {message.content}")

    if "hi there" in message.content.lower():
        await message.channel.send("HI!")



client.run(token)

Note that I've saved my token to token.txt, otherwise everything is the same as the previous tutorial.

So, to begin, sometimes it's cool to track a server's total users, and online numbers. Eventually, it'd be neat to just track these over time to graph trends like overall usergrowth, active users, messages per hour...etc, just to monitor the overall health of your server. To begin, we need to know how to reference our actual server. As of DiscordPy 1.0.0, your "server" is referred to as a guild instead. Prior versions were called server. So, first, I will reference the sentdex guild by its id:

sentdex_guild = client.get_guild(405403391410438165)

To figure out the id of a server, right click it, and choose "copy id"

With this, we can reference members of the guild, by doing something like:

member_reference = sentdex_guild.get_member_named("Sentdex#7777")

With that, we can do things like change roles, names...etc.

Instead though, let's just get some basic information from our guild. You can check all of the various attributes here: https://discordpy.readthedocs.io/en/rewrite/api.html#guild

One of the attributes is members. So we should be able to do a len() against the .members, but I also noticed tehre's also a member_count, so that's probably all we need.

@client.event
async def on_message(message):
    print(f"{message.channel}: {message.author}: {message.author.name}: {message.content}")
    sentdex_guild = client.get_guild(405403391410438165)

    if "sentdebot.member_count" == message.content.lower():
        await message.channel.send(f"```{sentdex_guild.member_count}```")

Now, if we do sentdebot.member_count in the discord, the bot replies with our number 8167 in my case.

I would like to eventually track more than this, however. Also, when I look at my server, it always says the users online is huge, but this doesn't account for idle/do not disturb...etc users. I'd like a more telling representation. Let's handle that next by iterating over our members. As we iterate over the members, we can check their status which will tell us if they're online, offline, idle, dnd...etc.

    elif "sentdebot.community_report()" == message.content.lower():
        online = 0
        idle = 0
        offline = 0

        for m in sentdex_guild.members:
            if str(m.status) == "online":
                online += 1
            if str(m.status) == "offline":
                offline += 1
            else:
                idle += 1

        await message.channel.send(f"```Online: {online}.\nIdle/busy/dnd: {idle}.\nOffline: {offline}```")

Cool! We're not actually saving this information or anything, but we can work on doing that later. For now, this will do.

I also added the ability to log the bot out in the video tutorial, here's the code for that:

    elif "sentdebot.logout()" == message.content.lower():
        await client.close()

In the next tutorial, we're going to cover an example of timing certain events to occur, rather than based purely on messages, for example.

The next tutorial:





  • Introduction and basic bot - making Discord bots with Discordpy 1.0.0 p.1
  • Building out Bot Commands - making Discord bots with Discordpy 1.0.0 p.2
  • Timing bot actions - making Discord bots with Discordpy 1.0.0 p.3
  • Embedding and Attaching w/ Image Example - making Discord bots with Discordpy 1.0.0 p.4