AttributeError: ‘ClientUser’ object has no attribute ‘guild_permissions’ on Discord.py

I am trying to make a “!invite” command to generate an invite link to the server and send it to the user’s DM. The command works, but I am getting the following error on console:

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:Users01EnvsPixlibsite-packagesdiscordclient.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:Users01PycharmProjectsTesting botcogsinvite.py", line 27, in on_message
    if ctx.author.guild_permissions.administrator:
AttributeError: 'ClientUser' object has no attribute 'guild_permissions'

Nevertheless, I get the link: My DM screenshot.

How can I fix this error?

Code:

from discord.ext import commands
from var.canais import inviteChannel


class Invite(commands.Cog):

    def __init__(self, client):
        self.client = client

    @commands.command(
        name='invite',
        pass_context=True
    )
    async def invite(self, ctx):
        invitelink = await ctx.channel.create_invite(
            max_uses=1,
            unique=True
        )
        if inviteChannel:
            await ctx.message.delete()
            await ctx.author.send(f'Invite link: {invitelink}')

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

        if inviteChannel:
            if ctx.author.guild_permissions.administrator:
                return
            else:
                if not ctx.content.startswith('!invite'):
                    await ctx.delete()


def setup(client):
    client.add_cog(Invite(client))

Answer

This error is occurring because the on_message event is also called when the bot sends a message, and in your case the bot is sending the message in a dm, therefore it should be a User object (Member objects are guild only), and user objects don’t have permissions since they are not inside a server. It’s a ClientUser object instead of User which is a special class like User that is unique to the bot. this is a separate class compared to User because this has some special methods that only the bot can use like one for editing the bot’s name and more to fix this just ignore if the message is sent from a bot so the code would be

@commands.Cog.listener()
async def on_message(self, ctx):
    if message.author.bot:
        return
    if inviteChannel:
        if ctx.author.guild_permissions.administrator:
            return
        if not ctx.content.startswith('!invite'):
            await ctx.delete()

Here I added if message.author.bot: return so that it stops the function execution if the author is a bot. and I also removed the unnecessary else statement