On Message

Preview

Similarly to how we created a hello command before, we can create commands without a prefix.

Basically, you can run code whenever anyone types any message. You can then check if the message they sent is the same as what you set it to be.

Coding

The template we will be following:

@client.event
async def on_message(message):
  if message == "anything":
    await message.channel.send(response)

Like when we created the on_ready event for our bot before, we can create another event. This event is called on_message. This event runs whenever anyone in your server types a message. Literally, any message.

In this case, we can use if statements to check if the message they sent is the same as our predefined requirement. For example, if I wanted to check if someone said hello I could replace the word anything in the template with hello. This means the following code would only run if the message is "hello"

Note the double equal signs (==). This is used to check if 2 things are equal to each other. One equal sign indicates you are assigning something to a variable. Make sure to use double equal signs in this case.

Now, your turn. Create a hello on_message event that replicates the behavior of our first hello command.

Only select the Final Code tab once you have completed your on message event. If you are stuck please see a mentor.

Last updated