首页 > 解决方案 > on_message 函数重复,Discord.py 重写

问题描述

我正在制作一个机器人,当它检测到您正在使用禁用词时,它会删除您的消息。很简单,但是,当我这样做时。on_message 函数正在重复。我不知道为什么,但我希望你能回答我的问题

@client.event
async def on_message(msg):
    contents = msg.content.split(" ")
    for word in contents:
        if word.lower() in chat_filter: #ChatFilter is a list of words that cannot be used
            try:
                await msg.delete()
                await msg.channel.send("**YOU ARE NOT ALLOWED TO USE THIS WORD!!!**")
            except discord.errors.NotFound:
                return

标签: pythondiscorddiscord.py-rewrite

解决方案


您正在遍历消息中的每个单词,并为每个也在chat_filter. 相反,如果任何单词在禁止列表中,请发送一条消息:

@client.event
async def on_message(msg):
    contents = msg.content.split(" ")
    if any(word in chat_filter for word in contents):
        try:
            await msg.delete()
            await msg.channel.send("**YOU ARE NOT ALLOWED TO USE THIS WORD!!!**")
        except discord.errors.NotFound:
            return

推荐阅读