0

I'm trying to create a simple discord bot that replies with mention to messages that contain certain words.

Also, I want the bot to respond only when it gets mentioned and without a prefix.

This was my try, but the bot didn't reply at all to the messages.

import discord
from discord.ext import commands

client = commands.Bot(command_prefix='')

@client.event
async def on_message(message):
    if client.user.mentioned_in(message){
      if message.content == "Hi"{
        await message.channel.send(f"Hello {message.author.mention}")
}
      if message.content == "How are you?"{
        await message.channel.send(f"I'm good {message.author.mention}")
}
}
client.run("TOKEN")

1 Answers1

2

message.content contains the entirety of the message text so when you do @mybot Hi, the message.content will be something like: <@MY_BOT_ID> hi. Your code is checking that the message.content is exactly equals to either Hi or How are you? and that is not going to be the case.

You could use Python's in operator to check for certain text:

@client.event
async def on_message(message):
    if client.user.mentioned_in(message):
        # making the text lowercase here to make it easier to compare
        message_content = message.content.lower()

        if "hi" in message_content:
            await message.channel.send(f"Hello {message.author.mention}")
        if "how are you?" in message_content:
            await message.channel.send(f"I'm good {message.author.mention}")


client.run("TOKEN")

Though, this isn't perfect. The bot will also respond to anything with the characters hi in. You could split the content of the messages by word and check that or you could use regular expressions. See this post for more info.

Additionally, your python code had some {} brackets - which is invalid syntax for if statements - I've corrected that in my example. Consider looking up python syntax.

ESloman
  • 1,961
  • 1
  • 10
  • 14
  • 1
    To add to this, you're missing the `message_content` intent so you can't read messages – stijndcl Dec 31 '22 at 13:00
  • Thanks, but it still doesn't work. I've added `import discord from discord.ext import commands client = commands.Bot(command_prefix='')` before your code, Do I miss something? – Jack Buttler Dec 31 '22 at 18:56
  • @JackButtler are you getting an error message at all? What message are you trying to get it to respond to when "it's not working"? Any information at all would be useful for trying to help you. – ESloman Jan 01 '23 at 11:12
  • There is no error message at all, I just start the bot -which has start with no errors at all-, but when I mentioned the bot and saying "@bot hi", the bot didn't reply at all. I really appreciate your help – Jack Buttler Jan 01 '23 at 23:23
  • Perhaps try adding a `print(message)` before the `if` statement to see if it's picking up messages at all? Did you add the message content intent like `stijndcl` suggested as well? – ESloman Jan 03 '23 at 08:11