【问题标题】:Function is not defined within a cog discord.py函数未在 cog discord.py 中定义
【发布时间】:2021-03-23 01:40:05
【问题描述】:

我正在尝试通过将代码放入 cogs 来清理我的代码。出于某种原因,每当我尝试调用函数时,都会出现此错误:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'get_bank_data' is not defined

甚至认为它是。这是我的代码(为了便于阅读,我删掉了其他命令)。

class RpgCog(commands.Cog):
  def __init__(self, client):
    self.client = client
  async def open_account(self, user):

     users = await get_bank_data()

     if str(user.id) in users:
        return False
     else:
        users[str(user.id)] = {}
        users[str(user.id)]["hp"] = 20
        users[str(user.id)]["bank"] = 100
        users[str(user.id)]["leather_armour"] = 0
        users[str(user.id)]['stone_sword'] = 0
        users[str(user.id)]['health_potion'] = 5
        users[str(user.id)]['maxhp'] = 20
        users[str(user.id)]['kingdom'] = 1
        users[str(user.id)]['max_damage'] = 5
        users[str(user.id)]['min_damage'] = 1
        users[str(user.id)]['xp'] = 0
        users[str(user.id)]['agility'] = 20
        users[str(user.id)]['hermes_boots'] = 0
        users[str(user.id)]['leather_armour_equipped'] = 0
        users[str(user.id)]['stone_sword_equipped'] = 0
        users[str(user.id)]['no_sword'] = 1
        users[str(user.id)]['no_armour'] = 1
        users[str(user.id)]['fishing_rod'] = 0
        users[str(user.id)]['fishing_luck'] = 0
        users[str(user.id)]['fishing_rod_equipped'] = 0
        users[str(user.id)]['no_rod'] = 1

         with open('mainbank.json', 'w') as f:
            json.dump(users, f)

        return True

    async def get_bank_data(self, client):
       with open('mainbank.json', 'r') as f:
        users = json.load(f)

   @commands.command(name='bal')
   async def print_bal(self, ctx):
     user = ctx.author
     await RpgCog.open_account(self, user)
     users = await RpgCog.get_bank_data(self)
      
     bank_amt = users[str(user.id)]['bank']

     await ctx.channel.send(bank_amt)


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

这是我用来在 main.py 中调用 cog 的代码

for filename in os.listdir('./cogs'):
  if filename.endswith('.py'):
    client.load_extension(f'cogs.{filename[:-3]}')

【问题讨论】:

  • 请修复缩进...甚至无法阅读代码,一团糟
  • 好的,现在就这样做
  • 另外我相信你得到了不正确缩进的错误原因
  • 缩进是固定的@ŁukaszKwieciński

标签: python discord.py


【解决方案1】:

在类中访问方法和属性需要使用self

所以使用await self.get_bank_data()

get_bank_data 函数中不需要 client 参数,删除它

【讨论】:

  • 我刚试了一下,还是出现同样的错误,不知道为什么。首先它说 open_account 上缺少参数“用户”所以我添加了它然后我得到了 get_bank_data 没有找到的错误
  • 等一下,open_account函数在里面调用get_bank_data我没有改成self.get_bank_data()
  • 很高兴它有效!如果您需要其他内容,请发表评论
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-10
  • 1970-01-01
  • 2019-11-11
  • 2020-02-12
  • 2021-06-29
  • 1970-01-01
  • 2020-07-04
相关资源
最近更新 更多