json文件错误:json.decoder.JSONONDecodeError.JSON.decoder.JSONONDecodeError。期待值:第1行第1列(char 0)

问题描述 投票:0回答:1

我正在使用 discord.py 来创建一个多用途的 discord 机器人,但我在制作自定义货币时遇到了一些麻烦。

我决定使用一个.json文件来存储服务器上每个人的名字和货币,但是当我运行这个文件时,我得到了这个错误。

from dotenv import load_dotenv
from discord.ext import commands
import random
from discord import Game
import discord
import json
load_dotenv()
TOKEN = 'TOKENHERE'
GUILD = os.getenv('DISCORD_GUILD')  # Same thing but gets the server name
bot = commands.Bot(command_prefix='r!')
on = "I'm up and running!"
print("Booting up...")
cmds = ["r!test - responds with: I hear you!"]
channel2 = bot.get_channel(CHANNELID)

@bot.event  # idk what this means but you have to do it
async def on_ready():  # when the bot is ready
    for guild in bot.guilds:
        if guild.name == GUILD:
            break
    print(
        f'{bot.user} has connected to Discord! They have connected to the following server: '  # client.user is just the bot name
        f'{guild.name}(id: {guild.id})')  # guild.name is just the server name
    channel2 = bot.get_channel(703869904264101969)
    global amounts
    try:
        with open('amounts.json') as f:
            amounts = json.load(f)
    except FileNotFoundError:
        print("Could not load amounts.json")
        amounts = {}
    await channel2.send(on)
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="r!help"))


@bot.command(name='test', help='Responds with: I can hear you! Used mainly for testing. ')
async def test(ctx):
    await ctx.send("I hear you!")

@bot.command(name='ping', help='Tells you the latency of the bot.')
async def ping(ctx):
    await ctx.send("Pong! " + str(int(bot.latency) * 1000) + "ms!")

@bot.command(name='say or simonsays', help='Responds with whatever you say after.', aliases = ['say', 'simonsays'])
async def say(ctx, *, contents: str):
   await ctx.send(contents)

@bot.command(name='diceroll', help='Rolls a dice!')
async def diceroll(ctx, number_of_dice: int, number_of_sides: int):
    dice = [
        str(random.choice(range(1, number_of_sides + 1)))
        for i in range(number_of_dice)
    ]
    await ctx.send(', '.join(dice))

@bot.event
async def on_member_join(member):
    await channel2.send(f'{member} has joined the server.')

@bot.event
async def on_member_remove(member):
    await channel2.send(f'{member} has left the server. F')

@bot.command(name='coolnotcool', help='Tells you whether you are cool or not.')
async def coolnotcool(ctx, *, member: str):
    coolornot = random.choice(range(1, 3))
    if coolornot == 1:
        await ctx.send(f'{member} is cool.')
    elif coolornot == 2:
        await ctx.send(f'{member} is not cool.')

@bot.command(name='8ball', help='Ask it a question and it will respond')
async def eightball(ctx, question):
    answers=['It is certain.', 'Without a doubt.', 'You may rely on it.', 'Yes, definitely.', 'It is decidedly so.', 'As I see it, yes.', 'Most likely.', 'Yes.', 'Outlook good.', 'Signs point to yes.', 'Reply hazy, try again.', 'Better not tell you now.', 'Ask again later.', 'Cannot predict now.', 'Concentrate, then ask again.', 'Dont count on it.', 'Outlook not so good.', 'My sources say no.', 'Very doubtful.', 'My reply is no.']
    response = random.choice(range(1, 21))
    await ctx.send(str(answers[response]))

@bot.command(name='coinflip', help='Responds with either heads or tails. Good for making a decision.')
async def coinflip(ctx):
    answer = random.choice(range(1, 3))
    if answer == 1:
        await ctx.send('Heads!')
    else:
        await ctx.send('Tails!')

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('Please pass in all required arguments.')
bot.run(TOKEN)

@bot.command(pass_context=True, name='bal', help='Shows you how many rb you have in the bank.')
async def bal(ctx):
    id = str(ctx.message.author.id)
    if id in amounts:
        await ctx.send("You have {} in the rb bank".format(amounts[id]))
    else:
        await ctx.send("You do not have an account yet. Type r!register to register!")

@bot.command(pass_context=True, name='register', help='Register to start using RuinBot currency!')
async def register(ctx):
    id = str(ctx.message.author.id)
    if id not in amounts:
        amounts[id] = 100
        await ctx.send("You are now registered! Remember, type r!save to save!")
        _save()
    else:
        await ctx.send("You already have an account.")

@bot.command(name='save', help='Your currency autosaves, but remember to always save just in case! This saves your currency.')
async def save(ctx):
    _save()
    await ctx.send("Data saved!")

@bot.command(pass_context=True, name='give', help='Give another member some rb!')
async def give(ctx, amount: int, other: discord.Member):
    primary_id = str(ctx.message.author.id)
    other_id = str(other.id)
    if primary_id not in amounts:
        await ctx.send("You do not have an account")
    elif other_id not in amounts:
        await ctx.send("The other party does not have an account")
    elif amounts[primary_id] < amount:
        await ctx.send("You cannot afford this transaction")
    else:
        amounts[primary_id] -= amount
        amounts[other_id] += amount
        await ctx.send("Transaction complete")
    _save()

def _save():
    with open('amounts.json', 'w+') as f:
        json.dump(amounts, f)

如果有人能帮我解决这个问题,那就太好了。.json文件是空的。

python json currency discord.py
1个回答
1
投票

空的json文件是你的错误。编辑json文件,使其包含以下内容。{}

© www.soinside.com 2019 - 2024. All rights reserved.