Responding to Messages
In this lesson, you’ll learn how to make your bot respond to specific messages in a chat. You’ll add on to the previous functionality of your bot by handling the
Client can’t tell the difference between a bot user and a normal user account, your
on_message() handler should protect against a potentially recursive case where the bot sends a message that it might handle itself. You’ll learn how to compare the
message.author to the
client.user (your bot user), and ignore any of its own messages.
Before your bot begins to respond to specific messages within chat, you must modify your
on_message() event handler. The example you can currently see onscreen is a complete example. Before you see how it runs, however, we should delve into it and see what’s going on.
Client is unable to know the difference between a bot user and a regular user account, the
on_message() handler should be able to protect against a potentially recursive situation where the bot sends a message that it may, then, handle and respond to.
00:48 That’s what this line achieves. So, what does this mean? Well, let’s have a look at an example where this line would be critical. Let’s say you wanted your bot to respond to somebody saying “Happy Birthday” within your channel.
message that the bot is supposed to handle, i.e.
'happy birthday', is contained within the response of the bot. This means that if one person sends, “Happy Birthday”, then the bot will respond with “Happy Birthday”, which means the bot will then respond with “Happy Birthday”, meaning the bot will then, again, respond with “Happy Birthday”, meaning the bot will respond with “Happy Birthday”, meaning that the bot—see what’s happening?
There you go. The
RealPythonTutorialBot is just replying to itself constantly. It’s taking a breather every now and then, but otherwise, it’s just constantly going and it will continue to go until we stop the bot. Again, this is why checking the
author of the
message is so important.
The final section of the
on_message() event handler is this part:
if message.content == '99!':. This is what defines the message that your bot will respond to. In other words, it will check every message that is sent within chat to see if it is equal to
'99!'. If it’s not, it’ll just wait for the next one.
If it is, however, it will jump into the
if loop. Here it’ll choose a response randomly from the
brooklyn_99_quotes variable. Keep in mind, because it is
random.choice() you must, at the top of your file,
04:06 There you have it. You have a response from the bot and it’s not constantly going. Awesome job. Now that you’ve seen some ways to handle common Discord events, next up, you will learn how to deal with errors that event handlers may raise.
Become a Member to join the conversation.