我想为我的用 python 编写的不和谐机器人添加一个经济系统。我在 youtube 上关注了 this tutorial 并将其实现到我的代码中。这是它的样子:
from discord.ext import commands
import json
import os
class Eco(commands.Cog):
def __init__(self, client):
self.client = client
#function to get bank data
async def getbankdata(self):
with open("bank.json", "r") as f:
users = json.load(f)
return users
#function to open a new account for a user if they don't have one
async def open_account(self, user):
users = await self.client.getbankdata(self)
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["wallet"] = 0
users[str(user.id)]["bank"] = 0
with open("bank.json", "w") as f:
json.dump(users, f)
return True
#check balance command
@commands.command()
async def bal(self, ctx):
user = ctx.author
await self.open_account(user)
users = await self.getbankdata()
walletamt = users[str(user.id)]["wallet"]
bankamt = users[str(user.id)]["bank"]
await ctx.send(f'Wallet: {walletamt}, Bank: {bankamt}')
def setup(client):
client.add_cog(Eco(client))
在教程中,所有代码都写在 main.py 文件中,在这里我将所有代码写在一个 cog 文件中,所以我不得不稍微调整一下功能。每当我尝试运行 bal
命令时,我都会收到一条错误消息,指出 'Bot' object has no attribute 'getbankdata'
。我似乎无法找到错误的根源。有人能帮我吗?我也很感激我的代码中可能引发错误的任何其他更正。
答案 0 :(得分:3)
错误出在 open_account
方法中。不是self.client.getbankdata
,而是self.getbankdata
async def open_account(self, user):
users = self.getbankdata()
# ...