Responding to Events
In this lesson, you’ll modify your code to listen for and then respond to events. An event is something that happens on Discord that you can use to trigger a reaction in your code.
Continuing to build on the previous code you’ve been working with, the
on_ready() event handler handles the event that the
Client has made a connection to Discord and prepared its response data. So, when Discord fires an event,
discord.py will route the event data to the corresponding event handler on your connected
Now, you will implement that behavior in your client using event handlers and verify its behavior in Discord. Just like before, you will handle the
on_ready() event by printing the bot user’s name in a formatted string, this line here. What is new, however, is the implementation of the
on_member_join() event handler.
the execution of the surrounding coroutine until the execution of each coroutine has finished. Now it’s time to test the behavior of your bot. Firstly, run the new version of
bot.py and wait for the
on_ready() event to fire, logging your message to
stdout. So let’s do that now. You can see it’s running.
Firstly, you’ll see that Discord introduced you to the guild by default with an automated message. If I click here, you can see
RealPythonTutorialBot has come up! It says, “Hi ST3V3N5, welcome to my Discord server!” That’s the default automated message that you set up earlier.
More importantly though, you would have noticed the badge on the left side of the screen, which informs you that you have a new unread message. When you selected it, you would have seen this message come up, because this is the DM channel with the
RealPythonTutorialBot that was set up. Once you selected it, you would have seen the new private message from your bot user, which is what you can see here. That is perfect.
02:54 That’s exactly what you want to see. Your bot user is now interacting with other users with pretty minimal code. In the next video, you will learn how to respond to specific messages within the chat.
Become a Member to join the conversation.