Reputation: 31
I know how to make it react to hi, hello etc. The problem is it will react even if "hi" is inside a word for example "chill" how would I stop it from reacting to "chill" like messages. I tried using spaces but they just end up breaking it even more
@bot.listen() #react to messages
async def on_message(message):
if message.guild is not None:
content = message.content
reaction = "👋"
if 'hi' in content.lower():
try:
await asyncio.sleep(1)
await message.add_reaction(f"<{reaction}>")
print(f'added reaction {reaction} {content}')
except Exception as e:
print(f'error adding reaction {reaction} {content}')
Upvotes: 0
Views: 108
Reputation: 2429
That happens because with if 'hi' in content.lower()
you are looking if the string hi
is found within the string message.content
. The best way to overcome this issue would be using regex (regular expressions).
You could create a function like the following, which will check if the string passed as parameter is found within another string. The difference with what you did is that this method includes the word within the \b
regex tags, which are for word boundaries, this allows us to search for whole words only.
import re
def findCoincidences(w):
return re.compile(r'\b({0})\b'.format(w)).search
You could simply add that to your code and use it like this:
# ...
if findCoincidences('hi')(content.lower()):
try:
await asyncio.sleep(1)
await message.add_reaction(f"<{reaction}>")
print(f'added reaction {reaction} {content}')
except Exception as e:
print(f'error adding reaction {reaction} {content}')
Basically this new findCoincidences()
function would return us a re.Match
object if he finds the word "hi" in the content of the message, so it would go into the try
statements.
Upvotes: 2