Python discord.py我想让机器人对hi、hello等做出反应

Python discord.py我想让机器人对hi、hello等做出反应,python,python-3.x,discord,discord.py,discord.py-rewrite,Python,Python 3.x,Discord,Discord.py,Discord.py Rewrite,我知道如何让它对hi、hello等做出反应。问题是,即使“hi”在一个词中,它也会做出反应,例如“chill”,我如何阻止它对类似“chill”的消息做出反应。我试着使用空格,但他们最终把它破坏得更厉害 @bot.listen() #react to messages async def on_message(message): if message.guild is not None: content = message.content reaction = "Tha

我知道如何让它对hi、hello等做出反应。问题是,即使“hi”在一个词中,它也会做出反应,例如“chill”,我如何阻止它对类似“chill”的消息做出反应。我试着使用空格,但他们最终把它破坏得更厉害

@bot.listen() #react to messages
async def on_message(message):
if message.guild is not None:
    content = message.content
    reaction = "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
@bot.listen()#对消息做出反应
异步def on_消息(消息):
如果message.guild不是None:
content=message.content

reaction=“发生这种情况是因为使用
如果content.lower()中的'hi',
您正在查找字符串
hi
是否在字符串
消息.content
中找到。解决此问题的最佳方法是使用regex()

您可以创建如下函数,该函数将检查作为参数传递的字符串是否在另一个字符串中找到。与您所做的不同之处在于,此方法将单词包含在
\b
regex标记中,用于单词边界,这允许我们仅搜索整个单词

# ...
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}')
您可以简单地将其添加到代码中,并按如下方式使用:

#。。。
如果FindIncidences('hi')(content.lower()):
尝试:
等待asyncio.sleep(1)
等待消息。添加_反应(f“”)
打印(f'添加的反应{reaction}{content}')
例外情况除外,如e:
打印(f'添加反应{reaction}{content}'时出错)

基本上,如果在消息内容中找到单词“hi”,这个新的
findcocincidences()
函数将返回一个
re.Match
对象,因此它将进入
try
语句。

发生这种情况是因为
如果内容中有'hi'
您正在查找字符串
hi
是否在字符串
消息内容中找到。解决此问题的最佳方法是使用regex()

您可以创建如下函数,该函数将检查作为参数传递的字符串是否在另一个字符串中找到。与您所做的不同之处在于,此方法将单词包含在
\b
regex标记中,用于单词边界,这允许我们仅搜索整个单词

# ...
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}')
您可以简单地将其添加到代码中,并按如下方式使用:

#。。。
如果FindIncidences('hi')(content.lower()):
尝试:
等待asyncio.sleep(1)
等待消息。添加_反应(f“”)
打印(f'添加的反应{reaction}{content}')
例外情况除外,如e:
打印(f'添加反应{reaction}{content}'时出错)

基本上,这个新的
findConcidences()
函数将返回一个
re.Match
对象,如果他在消息内容中找到“hi”这个词,那么它将进入
try
语句。

非常感谢,这项工作非常感谢,这项工作非常有效