Connecting a Bot
In this lesson, you’ll use
Bot, which is a subclass of
Client that adds a little bit of extra functionality that is useful when you’re creating bot users. For example, a
Bot can handle events and commands, invoke validation checks, and more. Before you can get into the features specific to
Bot, you’ll convert
bot.py to use a
Bot instead of a
You’ll also work with a new component, the
Command. In general terms, a command is an order that a user gives to a bot so that it will do something. As you work with them, you’ll see how commands are different from events.
This is part 11, and here you will look at the subclass of
Bot. Firstly, what is
Bot in this case? Well, previously you have learnt that a bot is an automated user that can react and respond like a human user. In this particular case, though, a
Bot is a subclass of
Client that adds a little bit of extra functionality that is useful when creating a bot user. For example, a
Bot can handle events and commands, invoke validation checks, and more.
As you can see,
Bot can handle events much the same way that
Client does. However, note two differences between
Bot it is imported from the
discord.ext.commands module, and two, the
Commands are different from events because they are arbitrarily defined, directly called by the user, and flexible, in terms of their interface. In technical terms, a
Command is an object that wraps a function that is invoked by a text command in Discord.
Now, let’s take a look at an old event to better understand what this looks like. If you look at one of the bot implementations from earlier in the course, you can see where you created an
on_message() event handler, which receives the
message string and compares it with a predefined-option, specifically
'99!'. If you were to use a
Command, you can convert this example to be more specific.
There are several important characteristics to understand about using
Command. The first thing is that instead of using
bot.event, like before, you use
bot.command(), passing the invocation command
name as its
argument. Secondly, the function will now only be called when
!99 is mentioned in chat, which is the opposite to what it was earlier. This is different than the
on_message() event, which was executed anytime a user sent a message, regardless of the content of that message.
Now when the user invokes the
!help command, your bot will present a description of your command. Keep in mind that this functionality exists only in the
Bot subclass, not the
Command has another useful functionality: the ability to use a
Converter to change the types of its arguments.
Become a Member to join the conversation.