Discord 经济机器人不发送消息

Discord Economy Bot Not Sending Messages

嘿,我一直在努力让这个不和谐的经济机器人工作,但不幸的是。当我启动机器人时,在我 运行 钱包命令之前我没有收到任何错误。我在下面包含了代码和我收到的错误。任何帮助将非常感激。我相信它与 json 和无法写入有关。

代码:

import discord
from discord.ext import commands
import json
import os
import random

os.chdir("C:\Users\Nick\Desktop\Discord Bots\EconomyManager")

client = commands.Bot(command_prefix = '!',intents=discord.Intents.all())


@client.event
async def on_ready():
    print("Ready!")

#user commands
@client.command(aliases=['w'])
async def wallet(ctx):
    await open_account(ctx.author)
    
    users = await get_bank_data()

    rs3_amt = users[str(user.id)]["RS3"]
    old_amt = users[str(user.id)]["07"]

    em = discord.Embed(title = f"{ctx.author.name}'s Balance",color = discord.Color.red())
    em.add_field(name = "RS3",value = rs3_amt)
    em.add_field(name = "07",value = old_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)]["RS3"] = 0
        users[str(user.id)]["07"] = 0

    with open("mainwallet.json","w") as f:
        json.dump(users,f)
    return True


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

    return users

async def update_bank(user,change,mode = "wallet"):
    users = await get_bank_data()

    users[str(user.id)][mode] += change

    with open("mainwallet.json","w") as f:
        json.dump(users,f)
    bal = [users[str(user.id)]["RS3"],users[str(user.id)]["07"]]
    return bal

client.run("")

The error:

Ignoring exception in command wallet:
Traceback (most recent call last):
  File "C:\Users\Nick\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 181, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\Nick\Desktop\Discord Bots\EconomyManager\main.py", line 19, in wallet
    await open_account(ctx.author)
  File "C:\Users\Nick\Desktop\Discord Bots\EconomyManager\main.py", line 38, in open_account
    users[str(user.id)]["RS3"] = 0
KeyError: '196468210344787968'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Nick\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 360, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Nick\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 927, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Nick\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: '196468210344787968'

如果用户不存在,那么您必须使用键 "RS3""07"

创建字典
users[str(user.id)] = {"RS3": 0, "07": 0}

而不是赋值

users[str(user.id)]["RS3"] = 0
users[str(user.id)]["07"] = 0

编辑:

下一个问题是您在 wallet()

中忘记了 user = ctx.author
@client.command(aliases=['w'])
async def wallet(ctx):

    user = ctx.author   # <---
        
    await open_account(user)
    
    users = await get_bank_data()

    rs3_amt = users[str(user.id)]["RS3"]
    old_amt = users[str(user.id)]["07"]

    # ... rest ...

如果你没有文件.json那么你应该在读取文件

时使用try/except
async def get_bank_data():
    try:
        with open("mainwallet.json","r") as f:
            users = json.load(f)
    except FileNotFoundError as ex:
        print('FileNotFoundError:', ex)
        users = {}
   
    return users