使用 cogs discord.py 说坏话时出错

时间:2021-05-17 21:22:49

标签: python discord discord.py

我收到错误,await channel.send(f"Hey Cole! I caught **{message.author}** saying **{msg_content}** in **{message.guild.name}** just now.") AttributeError: 'NoneType' object has no attribute 'name' 每当我输入一个错误的词时,我都会收到上述错误。虽然它仍然是我,但它说机器人说了坏话。我怎样才能解决这个问题?谢谢

我的代码是:

@commands.Cog.listener()
    async def on_message(self, message):

      msg_content = message.content.lower()
 
      curseWord = ['bad words here']
 
      if any(word in msg_content for word in curseWord):
        await message.delete()
        embed=discord.Embed(title="No No Word", description=f"{message.author.mention}, Hey! Those words arent allowed here!", color=0x00FFFF)
        author = message.author
        pfp = author.avatar_url
        embed.set_author(name=f"{author}", icon_url=pfp)
        await message.channel.send(embed=embed)

        user_id = 467715040087244800
        user = await self.bot.fetch_user(user_id)
        channel = await user.create_dm()
        await channel.send(f"Hey Cole! I caught **{message.author}** saying **{msg_content}** in **{message.guild.name}** just now.")

def setup(bot):
    bot.add_cog(AutoMod(bot))

2 个答案:

答案 0 :(得分:4)

您遇到了逻辑问题!

因为您的代码第一次就可以工作了,您就获得了 DM。您的机器人发送给您的 DM 的消息还会触发一个新的 on_message 事件。由于机器人在您的 DM 中重复了禁用词,您的机器人会被自己的垃圾邮件过滤器捕获,并想就此向您发送另一个 DM。顺便说一句,如果没有发生属性错误,这将导致无限循环。
这也解释了为什么会发生: 第二次您的 on_message 事件运行是由您自己的机器人在您的 DM 中触发的,因此 message.guild 将是 None。为了克服这个问题,您可以例如忽略 DM-Chat 中的消息。

@commands.Cog.listener()
    async def on_message(self, message):
      if message.channel.type == discord.ChannelType.private:
          return
      msg_content = message.content.lower()
      # finish rest of your code

答案 1 :(得分:3)

根据 itzFlubby 的回答,这是另一种解决方案,当您尝试获取 ID 时,它可能无法让您进入可能的速率限制。

看看下面的代码:

async def on_message(self, message):
    msg_content = message.content.lower()

    curseWord = ['YourWords']

    if any(word in msg_content for word in curseWord):
        if message.channel.type == discord.ChannelType.private:
            return # Ignore DMs
        await message.delete()
        embed = discord.Embed(title="No No Word",
                              description=f"{message.author.mention}, Hey! Those words arent allowed here!",
                              color=0x00FFFF)
        author = message.author
        pfp = author.avatar_url
        embed.set_author(name=f"{author}", icon_url=pfp)
        await message.channel.send(embed=embed)

        user = self.bot.get_user(YourID)
        await user.send(f"Hey Cole! I caught **{message.author}** saying **{msg_content}** in **{message.guild.name}** just now.") # Send it to you via DM

此处我们不获取 ID,而是将其发送到您定义的 user