Discord.py how to get the last message and reply to it without any prefix/command

Viewed 365

I want to make a bot for discord that will reply to each message using cleverbot. I would like that messages can be without any prefix or command. I will use cleverbot api or selenium for get the cleverbot answer. What is the easiest way to get the last message written in the chat and reply to it?

Something like this:

User: What is your favorite color? Bot: Green.

2 Answers

You should use the on_message event to listen for a message. Then you can check the content, get your response, and then use channel.send (passing reference=message) to reply.

Below is an example where every time a user says "hi" the bot responds with "hello":

@bot.event  # or, if in a cog, @commands.Cog.listener()
async def on_message(message):
    if message.author.bot:
        return  # ignore bots
    if message.content == "hi":
        await message.channel.send("hello", reference=message)

on_message event is working when a message sent to a channel that your bot can see.

In cog:

@commands.Cog.listener()
async def on_message(self, message):
  if not message.author.bot: #checking user is not a bot
    if message.content.lower() == "what is your favorite color":
      await message.reply("Green. What is your's?")

Not in cog:

@bot.event
async def on_message(message):
  if not message.author.bot:
    if message.content.lower() == "what is your favorite color":
      await message.reply("Green. What is your's?")
     
    #we are handling messages so your bot's commands will not work
    #but there is a solution for this
    else:
      ctx = bot.get_context(message) #getting commands.Context object
      await bot.invoke(ctx) #running command if exist
Related