我知道如何让它对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 = "👋"
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}')
这是因为使用
if 'hi' in content.lower()
时,您正在查找字符串hi
是否在字符串message.content
中找到。克服此问题的最佳方法是使用regex(regular expressions)您可以创建如下函数,该函数将检查作为参数传递的字符串是否在另一个字符串中找到。与您所做的不同之处在于,此方法包括
\b
regex标记中的单词,用于单词边界,这允许我们仅搜索整个单词您可以简单地将其添加到代码中,并按如下方式使用:
基本上,如果这个新的
findCoincidences()
函数在消息内容中找到单词“hi”,它将返回一个re.Match
对象,因此它将进入try
语句相关问题 更多 >
编程相关推荐