discord.py属性错误(object object没有属性' id')
因此,我正在遵循有关如何制作经济机器人的教程,现在每当我尝试提出命令时,它都会响应此错误!
File "main.py", line 164, in open_account
if str(user.id) in users:
AttributeError: 'dict' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/EconomyCurrencyBot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/EconomyCurrencyBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/EconomyCurrencyBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'dict' object has no attribute 'id'
这是main.py中的代码
import discord
from discord.ext import commands
import os
import keep_alive
import json
import random
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
bot = commands.Bot(command_prefix = "$")
@bot.command()
async def balance(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
wallet_amt = users[str(user.id)]["wallet"]
bank_amt = users[str(user.id)]["bank"]
em = discord.Embed(title = f"{ctx.author.name}'s balance", color = discord.Color.red())
em.add_field(name = "Wallet",value = wallet_amt)
em.add_field(name = "Bank",value = bank_amt)
await ctx.send(embed = em)
@bot.command()
async def beg(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
earnings = random.randrange(101)
await ctx.send(f"Someone gave you {earnings} coins!")
users[str(user.id)]["wallet"] += earnings
with open("MainBank.json","w") as f:
json.dump(users,f)
@bot.command()
async def deposit(ctx,amount = None):
await open_account(ctx.author)
if amount == None:
await ctx.send('Please enter the amount you want to deposit')
return
bal = await update_bank(ctx.author)
amount = int(amount)
if amount>bal[0]:
await ctx.send('You do not have enough money!')
return
if amount<bal[0]:
await ctx.send('Number must be in the positives!')
return
await update_bank(ctx.author,-1*amount)
await update_bank(ctx.author,amount,"bank")
await ctx.send('Deposit Succesful!')
@bot.command()
async def send(ctx,member:discord.member, amount = None):
await open_account(ctx.author)
await open_account(member)
if amount == None:
await ctx.send('Please enter the amount you want to send')
return
bal = await update_bank(ctx.author)
if amount == "all":
amount = bal[0]
amount = int(amount)
if amount>bal[1]:
await ctx.send('You do not have enough money!')
return
if amount<bal[0]:
await ctx.send('Number must be in the positives!')
return
await update_bank(ctx.author,-1*amount,"bank")
await update_bank(member,amount,"bank")
await ctx.send("Succesfully gave" + {amount} + "of coins!")
@bot.command()
async def rob(ctx,member:discord.member):
await open_account(ctx.author)
await open_account(member)
bal = await update_bank(member)
if bal[0]<100:
await ctx.send('He does not have enough money!')
return
earnings = random.randrange(100, bal[0])
await update_bank(ctx.author,earnings)
await update_bank(member,-1*earnings)
await ctx.send('Rob went succesful!')
@bot.command()
async def slots(ctx,amount = None):
await open_account(ctx.author)
if amount == None:
await ctx.send('Please enter the amount you want to deposit')
return
bal = await update_bank(ctx.author)
amount = int(amount)
if amount>bal[0]:
await ctx.send('You do not have enough money!')
return
if amount<bal[0]:
await ctx.send('Number must be in the positives!')
return
final = []
for i in range(3):
a = random.choice(["X","W","O","I","E"])
final.append(a)
await ctx.send(str(final))
if final[0] == final[1] or final[0] == final[2] or final[2] == final[1]:
await update_bank(ctx.author,3*amount)
await ctx.send("You Won!")
else:
await update_bank(ctx.author,-1*amount)
await ctx.send("You lost!")
@bot.command()
async def withdraw(ctx,amount = None):
await open_account(ctx.author)
if amount == None:
await ctx.send('Please enter the amount you want to withdraw')
return
bal = await update_bank(ctx.author)
amount = int(amount)
if amount>bal[1]:
await ctx.send('You do not have enough money!')
return
if amount<bal[0]:
await ctx.send('Number must be in the positives!')
return
await update_bank(ctx.author,amount)
await update_bank(ctx.author,-1*amount,"bank")
await ctx.send('Withdraw Succesful!')
async def open_account(user):
users = await get_bank_data()
with open("MainBank.json","r") as f:
user = json.load(f)
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("MainBank.json","w") as f:
json.dump(users,f)
return True
async def get_bank_data():
with open("MainBank.json","r") as f:
users = json.load(f)
return users
async def update_bank(user,change = 0,mode = "wallet"):
users = await get_bank_data()
users[str(user.id)][mode] += change
with open("MainBank.json","w") as f:
json.dump(users,f)
bal = [users[str(user.id)]["wallet"],users[str(user.id)]["bank"]]
return bal
keep_alive.keep_alive()
bot.run(os.getenv('Token'))
,这是我的JSON文件中的代码,
{"903639795824214014": {"wallet":0, "bank":0}}
我相信这将是一个非常简单的解决方案,我希望有人可以提供帮助。我观看的教程有3个部分,但我只观看了第一个2部分,因为第三部分只是添加了另一个命令。这是教程的第一和第二部分的两个链接:
- 观看?v = 7ap_8jy_ble
So I am following a tutorial on how to make an economy bot and now anytime I try to put in a command, it responds with this error!
File "main.py", line 164, in open_account
if str(user.id) in users:
AttributeError: 'dict' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/EconomyCurrencyBot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/EconomyCurrencyBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/EconomyCurrencyBot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'dict' object has no attribute 'id'
Here is the code in main.py
import discord
from discord.ext import commands
import os
import keep_alive
import json
import random
client = discord.Client()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
bot = commands.Bot(command_prefix = "quot;)
@bot.command()
async def balance(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
wallet_amt = users[str(user.id)]["wallet"]
bank_amt = users[str(user.id)]["bank"]
em = discord.Embed(title = f"{ctx.author.name}'s balance", color = discord.Color.red())
em.add_field(name = "Wallet",value = wallet_amt)
em.add_field(name = "Bank",value = bank_amt)
await ctx.send(embed = em)
@bot.command()
async def beg(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
earnings = random.randrange(101)
await ctx.send(f"Someone gave you {earnings} coins!")
users[str(user.id)]["wallet"] += earnings
with open("MainBank.json","w") as f:
json.dump(users,f)
@bot.command()
async def deposit(ctx,amount = None):
await open_account(ctx.author)
if amount == None:
await ctx.send('Please enter the amount you want to deposit')
return
bal = await update_bank(ctx.author)
amount = int(amount)
if amount>bal[0]:
await ctx.send('You do not have enough money!')
return
if amount<bal[0]:
await ctx.send('Number must be in the positives!')
return
await update_bank(ctx.author,-1*amount)
await update_bank(ctx.author,amount,"bank")
await ctx.send('Deposit Succesful!')
@bot.command()
async def send(ctx,member:discord.member, amount = None):
await open_account(ctx.author)
await open_account(member)
if amount == None:
await ctx.send('Please enter the amount you want to send')
return
bal = await update_bank(ctx.author)
if amount == "all":
amount = bal[0]
amount = int(amount)
if amount>bal[1]:
await ctx.send('You do not have enough money!')
return
if amount<bal[0]:
await ctx.send('Number must be in the positives!')
return
await update_bank(ctx.author,-1*amount,"bank")
await update_bank(member,amount,"bank")
await ctx.send("Succesfully gave" + {amount} + "of coins!")
@bot.command()
async def rob(ctx,member:discord.member):
await open_account(ctx.author)
await open_account(member)
bal = await update_bank(member)
if bal[0]<100:
await ctx.send('He does not have enough money!')
return
earnings = random.randrange(100, bal[0])
await update_bank(ctx.author,earnings)
await update_bank(member,-1*earnings)
await ctx.send('Rob went succesful!')
@bot.command()
async def slots(ctx,amount = None):
await open_account(ctx.author)
if amount == None:
await ctx.send('Please enter the amount you want to deposit')
return
bal = await update_bank(ctx.author)
amount = int(amount)
if amount>bal[0]:
await ctx.send('You do not have enough money!')
return
if amount<bal[0]:
await ctx.send('Number must be in the positives!')
return
final = []
for i in range(3):
a = random.choice(["X","W","O","I","E"])
final.append(a)
await ctx.send(str(final))
if final[0] == final[1] or final[0] == final[2] or final[2] == final[1]:
await update_bank(ctx.author,3*amount)
await ctx.send("You Won!")
else:
await update_bank(ctx.author,-1*amount)
await ctx.send("You lost!")
@bot.command()
async def withdraw(ctx,amount = None):
await open_account(ctx.author)
if amount == None:
await ctx.send('Please enter the amount you want to withdraw')
return
bal = await update_bank(ctx.author)
amount = int(amount)
if amount>bal[1]:
await ctx.send('You do not have enough money!')
return
if amount<bal[0]:
await ctx.send('Number must be in the positives!')
return
await update_bank(ctx.author,amount)
await update_bank(ctx.author,-1*amount,"bank")
await ctx.send('Withdraw Succesful!')
async def open_account(user):
users = await get_bank_data()
with open("MainBank.json","r") as f:
user = json.load(f)
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("MainBank.json","w") as f:
json.dump(users,f)
return True
async def get_bank_data():
with open("MainBank.json","r") as f:
users = json.load(f)
return users
async def update_bank(user,change = 0,mode = "wallet"):
users = await get_bank_data()
users[str(user.id)][mode] += change
with open("MainBank.json","w") as f:
json.dump(users,f)
bal = [users[str(user.id)]["wallet"],users[str(user.id)]["bank"]]
return bal
keep_alive.keep_alive()
bot.run(os.getenv('Token'))
and here is the code in my json file
{"903639795824214014": {"wallet":0, "bank":0}}
I am sure that this would be a very simple fix to this and I hope someone can help. The tutorial I watched has 3 parts but I only watched the first 2 since the 3rd part was just adding another command. Here are the 2 links to the 1st and 2nd part of the tutorial:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
json.load()
返回python
dict
。因此,加载用户时,它将不会返回discord.user
对象,它将返回字典。因此,您必须使用用户['id']
。编辑:而不是
用户['id']
(我的错误,对不起)useuser [str(whate_your_users_id_is)]
您的json键是用户ID,因此当您使用时JSON.LOAD(),它像JSON文件中的词典一样返回一个字典。
我建议使用repl。它的内置数据库,它的工作原理与词典完全一样,但即使在代码重播上也可以节省。
https://pypi.org/project/project/replit/
docs.replit.com/hosting/database-faq“ rel =“ nofollow noreferrer”> https://docs.replit.com/hosting/database-faq
https://replit.com/@util/replit/replit-database-proxy (fork this)
json.load()
returns a Pythondict
. So when loading the user, it will not return aDiscord.User
object, it will return a dictionary. Therefore, you must useuser['id']
.EDIT: Instead of
user['id']
(My mistake, sorry) useuser[str(whatever_your_users_id_is)]
Your JSON keys are the user ids, so when you use json.load(), it returns a dictionary like the one in your json file.
I would recommend using Repl.it's built in database, it works exactly like a dictionary but it saves even on code rerun.
https://pypi.org/project/replit/
https://docs.replit.com/hosting/database-faq
https://replit.com/@util/Replit-Database-proxy (fork this)