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

2024-09-29 01:38:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道如何让它对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}')

enter image description here


Tags: to消息messagehelloifbotcontentawait
1条回答
网友
1楼 · 发布于 2024-09-29 01:38:14

这是因为使用if 'hi' in content.lower()时,您正在查找字符串hi是否在字符串message.content中找到。克服此问题的最佳方法是使用regexregular expressions

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

import re

def findCoincidences(w):
    return re.compile(r'\b({0})\b'.format(w)).search

您可以简单地将其添加到代码中,并按如下方式使用:

# ...
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}')

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

相关问题 更多 >