【问题标题】:I tried to make a balance command in discord.py but it didn't worked and gives unexpected errors我试图在 discord.py 中创建一个平衡命令,但它没有奏效并出现意外错误
【发布时间】:2021-06-07 08:11:51
【问题描述】:

我试图为我的机器人创建一个余额检查命令,但是当我尝试它时,它不起作用 bot 的其他命令有效,但 bal 命令不起作用。

所做的更改:定义用户并将 {} 添加到 json 文件。

这也是我得到的新错误:

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 21, in balance
    await open_account(ctx.author)
  File "main.py", line 36, in open_account
    users[str(user.id)]["wallet"]=0
KeyError: '774126913664188416'

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: KeyError: '774126913664188416' 

代码如下:

import discord
import discord.ext
import webserver
import json
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("elon musk is the richest person in world")

@client.command(name='bal')
async def balance(ctx):
  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)

  
async def open_account(user):
    users = await get_bank_data()
    
    if str(user.id) in users:
      return False
    else:
      users[str(user.id)]["wallet"]=0
      
    with open("mainbank.json","w") as f:
      users = json.dump(users,f)
      return True

async def get_bank_data():
  with open("mainbank.json","r") as f:
    users = json.load(f)
    
  return users

keep_alive()
client.run('token')

【问题讨论】:

    标签: python command discord.py balance


    【解决方案1】:

    您的代码在某一时刻包含错误。您忘记定义user。以下代码对于该命令是正确的:

    @client.command()
    async def balance(ctx):
        await open_account(ctx.author)
        user = ctx.author # Defined user
        users = await get_bank_data()
        wallet_amt = users[str(user.id)]["wallet"] # We need the user here
        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)
    

    您的async 事件本身并没有错,但我们不需要在那里定义user,它没有任何好处。所以正确的做法是:

    async def open_account(user):
        users = await get_bank_data()
    
        if str(user.id) in users:
            return False
        else:
            users[str(user.id)]["wallet"] = 0
    
        with open("mainbank.json", "w") as f:
            json.dump(users, f)
        return True
    

    请确保您的 JSON 文件如下所示:

    {}
    

    总结一下:

    • 我们根据需要定义了user
    • 删除了不必要/无用的定义

    【讨论】:

    • 好的,但我的机器人仍然没有显示消息....
    • 出现什么错误?也请不要删除您的 cmets...
    • 我删除了,因为我不小心发送了一半的评论,抱歉,哈哈
    • 现在我编辑了我的帖子我编辑了我所做的更改并编辑了错误
    • KeyError 表示用户在 JSON 中不存在。打开它看看。
    猜你喜欢
    • 2018-10-02
    • 2021-09-04
    • 2019-10-22
    • 2022-10-07
    • 2020-08-02
    • 2021-08-04
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多