Issue
I am writing a Discord bot. I want it to reply to the user only when they reply to my bot.
This is the relevant code:
if message.reference:
if "How are" in message.content.lower():
await asyncio.sleep(3)
await message.channel.send(random.choice(list4), reference=message)
The problem is that the message is sent even if a user replies to someone else, rather than to the bot. How can I make sure that a message is only sent when the user replies to the bot specifically?
Solution
You are currently just checking if the message has a reference, i.e., if it's a reply to another, not if it's replied to anyone specifically.
To check if a user has replied to one of your messages, use message_id
to get the message the user replied to. You can then check if the message was sent by your bot by getting the (referred) Message
and then checking its author
:
@bot.event
async def on_message(message: discord.Message):
referred_message = await message.channel.fetch_message(message.reference.message_id) #Get the message to which it's a reply
if referred_message.author == bot.user: #Check if the message it replies to was sent by your bot
if "how are" in message.content.lower(): #Changed "How are" to "how are" (small H)
await asyncio.sleep(3)
await message.channel.send(random.choice(list4), reference=message)
Also, if "How are" in message.content.lower():
will always return False
, as even (what you're expecting) "How are <something>" when .lower()
ed will not exactly match "How are <something>" ("H" != "h"
), so I've changed it to "how are" so it works properly.
Answered By - The Amateur Coder
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.