AttributeError: 'LevelingSystem' object has no attribute 'author'

AttributeError: 'LevelingSystem' object has no attribute 'author'

我正在制作一个不和谐的机器人,我目前正在开发一个调平系统。但我不断得到一个 AttributeError: 'LevelingSystem' 对象没有属性 'author'

这是它的代码

import discord
from discord.ext import commands
from discord.utils import get
import json
import random
import time


class LevelingSystem(commands.Cog):
    """ Leveling system for discord """

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

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

        if message.author.bot:
            return
        else:
            with open("X:\Code\Projects\Python\AlphaWolf\cogs\levels.json", 'r') as f:
                levels = json.load(f)

            await update_data(levels, message.author.id)

        async def update_data(levels, user):
            for member in guild.members:
                if user not in levels:
                    levels[user] = {}
                    levels[user]["experience"] = 0
                    levels[user]["level"] = 1
                    print(" Registered {} to .json".format(user))
                    with open("X:\Code\Projects\Python\AlphaWolf\cogs\levels.json", 'w') as f:
                        json.dump(levels, f)

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

您正在使用 cogs,并且因为您的事件在 class 中,您需要将 self 关键字作为第一个参数包含在 class 方法中。

class LevelingSystem(commands.Cog):
    """ Leveling system for discord """

    def __init__(self, bot): # self is used here
        self.bot = bot

    @commands.Cog.listener()
    async def on_message(self, message, guild): # need it here as well
        # rest of the code

假设 self 关键字被调用 message 因为它始终是 class 方法中的第一个参数。
因此,当您说 message.author 时,程序实际上假设您的 class 中有一个名为 author 的属性 - 它会将 message.author 视为 self.author