python - 将数据注册到 json 时出现问题仅注册数字而不是字符串
问题描述
所以你好,至于我的 JSON 文件名的一些信息pokemon.json
,它注册用户时没有错误,但我需要发送字符串,比如如果我输入 .pick charmander 它会将charmander 的统计信息发送到我的 JSON 文件中,但它只发送这个:
"{ "user id" : {pokemon : 0} }"
还有更多信息,这是我得到的错误,代码也在错误下方:
Ignoring exception in command pick:
Traceback (most recent call last):
File "/home/dcoder/.cache/pypoetry/virtualenvs/project-e8xowoWm-py3.8/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 102, in pick
users[str(user.id)]["pokemon"]("name : Charmander, attack : {attack} ,defense : {defense} ,speed : {speed} ,special attack : {specialatk} ,special defense : {specialdef} ,gender : {gender} ,iv : {iv}")
TypeError: 'int' object is not callable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/dcoder/.cache/pypoetry/virtualenvs/project-e8xowoWm-py3.8/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "/home/dcoder/.cache/pypoetry/virtualenvs/project-e8xowoWm-py3.8/lib/python3.8/site-packages/discord/ext/commands/core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/dcoder/.cache/pypoetry/virtualenvs/project-e8xowoWm-py3.8/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: TypeError: 'int' object is not callable
现在代码:
import discord
import discord.ext
import webserver
import json
import random
from webserver import keep_alive
from discord.ext import commands
client = commands.Bot(command_prefix = '.')
@client.event
async def on_ready():
print('{0.user}'.format(client) , 'is now online')
await client.change_presence(activity=discord.Game(name="with pokemons"))
@client.command(name='fact')
async def facts(ctx):
await ctx.send("sticky leaf is gae")
@client.command(name='bal')
async def balance(ctx):
user = ctx.author
await open_account(ctx.author)
users = await get_bank_data()
wallet_amt = users[str(user.id)]["wallet"]
em = discord.Embed(title = f"{ctx.author}'s balance",color = discord.Color.blue())
em.add_field(name = "Wallet balance", value = wallet_amt)
await ctx.send(embed = em)
@client.command(name='beg')
async def beg(ctx):
user = ctx.author
await open_account(ctx.author)
users = await get_bank_data()
earnings = random.randrange(200)
await ctx.send(f"someone gave you {earnings} coins")
users[str(user.id)]["wallet"] += earnings
with open("mainbank.json","w") as f:
users = json.dump(users,f)
@client.command(name='invite')
async def invite(ctx):
await ctx.send("https://discord.com/api/oauth2/authorize?client_id=REDACTED&permissions=8&scope=bot")
async def open_account(user):
users = await get_bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)]={}
users[str(user.id)]["wallet"]=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
@client.command(name="start")
async def start(ctx):
em = discord.Embed(title = "Start your journey by choosing a pokemon",color=discord.Color.green())
em.add_field(name = "Gen 1 starters" ,value = "Bulbasaur , Squirtle , Charmander")
em.add_field(name = "Gen 2 starters", value = "Chikorita , Totodile , Cyndaquil")
em.add_field(name = "Gen 3 starters", value = "Treeko , Mudkip , Torchic")
em.add_field(name = "Gen 4 starters", value = "Turtwig , Piplup , Chimchar")
em.add_field(name = "Gen 5 starters", value = "Snivy , Oshawott , Tepig")
em.add_field(name = "Gen 6 starters", value = "Chespin , Froakie , Fennekin")
em.add_field(name = "Gen 7 starters", value = "Rowlet , Popplio , Litten")
em.add_field(name = "Gen 8 starters", value = "Grookey , Sobble , Scorbunny")
await ctx.send(embed = em)
@client.command(name="pick")
async def pick(ctx,arg):
await open_account_poke(ctx.author)
users = await get_poke_data()
user = ctx.author
if arg == "Charmander" or "charmander":
with open("pokemon.json","r") as f:
json.load(f)
iv = random.randrange(40,100)
male_female = ["male","female"]
gender = random.choice(male_female)
attack = random.randrange(100,500)
speed = random.randrange(100,500)
defense = random.randrange(100,500)
specialdef = random.randrange(100,500)
specialatk = random.randrange(100,500)
level = 5
users[str(user.id)]["pokemon"]("name : Charmander, attack : {attack} ,defense : {defense} ,speed : {speed} ,special attack : {specialatk} ,special defense : {specialdef} ,gender : {gender} ,iv : {iv}")
with open("pokemon.json","w") as f:
json.dump(users , f)
await ctx.send("You have choosen charmander")
async def open_account_poke(user):
users = await get_poke_data()
if str(user.id) in users:
return False
else:
users[str(user.id)]={}
users[str(user.id)]["pokemon"]=0
with open("pokemon.json","w") as f:
json.dump(users,f)
return True
async def get_poke_data():
with open("pokemon.json","r") as f:
users = json.load(f)
return users
keep_alive()
client.run('ignore this ')
解决方案
这一行:
users[str(user.id)]["pokemon"]("name : Charmander, attack : {attack} ,defense : {defense} ,speed : {speed} ,special attack : {specialatk} ,special defense : {specialdef} ,gender : {gender} ,iv : {iv}")
是无效的语法。我假设您正在尝试创建一个字典,它应该如下所示:
users[str(user.id)]["pokemon"] = {"name": "Charmander", "attack": attack, "defense": defense, "speed": speed, "special attack": specialatk, "special defense": specialdef, "gender": gender, "iv": iv}
json.load
然后将其序列化为 JSON 格式并将其写入您的 json 文件。
更详细地说,你得到的原因TypeError: 'int' object is not callable
是因为它认为你正在尝试执行一个存储在的函数,users[str(user.id)]["pokemon"]
因为你将括号放在它旁边,并将字符串作为参数。
如果你想了解更多关于 python 字典的信息,你可以访问这个链接。您可以在此处阅读有关 python 如何处理 json 数据的更多信息。
推荐阅读
- tensorflow - 使用预训练模型进行评估会导致类型错误
- javascript - 在Javascript中添加指向itens的链接的问题
- python - 在 numba jited 函数中使用 ndarray 子类“__matmul__”方法
- unreal-engine4 - 切换到 VR 模式后,如何恢复需要我切换到 VR 才能工作的“旧版 UI/模式”?
- r - 是否可以使用 outer() 生成笛卡尔积?
- azure - 在哪里可以查看 Azure 资源管理器模板资源的所有可能属性?
- proxy - 如何为 grpcurl 请求添加代理?
- angular - 如何在 Jasmine 测试用例中将代码覆盖率提高到 80%
- python-3.x - 尝试移动精灵 pygame 时的克隆问题
- java - 应该在一个 SpringBoot 应用程序中使用单个 ThreadPoolTaskExecutor 还是多个 ThreadPoolTaskExecutor?