discord.py [rewrite] 机器人没有正确发送消息

discord.py [rewrite] bot not sending message properly

最近,我的机器人在更改了与这段代码完全无关的内容后决定停止工作。 当我要求它向消息的作者 (message.author.send()) 发送消息时,它会发送通知但实际上没有消息出现。我得到了带有 1 ping 徽章的机器人图标,但是当我单击时,无法读取任何新消息。这是相关代码:

    async def on_message(self, Message):
        print('Scanning message')
        blacklisted_words = [
            # I won't show these here for obvious reasons
        ]
        
        
        offendingwords = []
        cursefound = False
        for cursecheck in blacklisted_words:
            if cursecheck in Message.content.lower():
                cursefound = True
                offendingwords.append(cursecheck)
        if cursefound == True:
            print('Found curse word, user notified\n')
            await Message.delete()
            
            words = []
            for word in offendingwords:
                words.append(word)
            
            await Message.author.send(f'Please watch your language in <#{Message.channel.id}>!\nOffending word(s) - `{str(words)}`')
            cursefound = False
        else:
            print('No curse words found\n')

请原谅我糟糕的格式,我对 Python 还是很陌生。

它还会抛出一个 AttributeError:

    await Message.author.send(f'Please watch your language in <#{Message.channel.id}>!\nOffending word(s) - `{str(words)}`')
AttributeError: 'ClientUser' object has no attribute 'send'

请尽量简化这一点,我太容易搞糊涂了。谢谢!

发生这种情况是因为机器人试图发送列表中禁止的相同词,因此消息被删除。

您可以执行以下操作,添加 if 语句以忽略 Bot。

@bot.event
async def on_message(Message):
    async def on_message(self, Message):

        #If the message author is not a BOT, Then run the following statement Else return
        if not Message.author.bot:
            print('Scanning message')
            blacklisted_words = [
                # I won't show these here for obvious reasons
            ]
            
            
            offendingwords = []
            cursefound = False
            for cursecheck in blacklisted_words:
                if cursecheck in Message.content.lower():
                    cursefound = True
                    offendingwords.append(cursecheck)
            if cursefound == True:
                print('Found curse word, user notified\n')
                await Message.delete()
                
                words = []
                for word in offendingwords:
                    words.append(word)
                
                await Message.author.send(f'Please watch your language in <#{Message.channel.id}>!\nOffending word(s) - `{str(words)}`')
                cursefound = False
            else:
                print('No curse words found\n')

如果您想向作者发送私信,message.author 没有 send() 函数。你可以创建一个函数来做这样的事情:

async def send_dm(ctx, member: discord.Member, *, message):
    channel = await member.create_dm()
    await channel.send(message)

并传递 member 作为邮件的作者。然后将消息作为您要发送的内容传递。这应该可以解决您得到的 AttributeError