Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python json文件错误:json.decoder.jsondeCoderror:预期值:第1行第1列(字符0)_Python_Json_Currency_Discord.py - Fatal编程技术网

Python json文件错误:json.decoder.jsondeCoderror:预期值:第1行第1列(字符0)

Python json文件错误:json.decoder.jsondeCoderror:预期值:第1行第1列(字符0),python,json,currency,discord.py,Python,Json,Currency,Discord.py,我正在使用discord.py创建一个多用途的discord bot,但在创建自定义货币时遇到了一些问题 我决定使用一个.json文件来存储服务器上每个人的姓名和货币,但当我运行此命令时,会出现以下错误: from dotenv import load_dotenv from discord.ext import commands import random from discord import Game import discord import json load_dotenv() TOK

我正在使用discord.py创建一个多用途的discord bot,但在创建自定义货币时遇到了一些问题

我决定使用一个.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)
从dotenv导入加载\u dotenv
从discord.ext导入命令
随机输入
从不和谐进口游戏
进口不和
导入json
加载_dotenv()
令牌='TOKENHERE'
GUILD=os.getenv('DISCORD_GUILD')#相同,但获取服务器名称
bot=commands.bot(命令前缀为'r!')
on=“我开始跑步了!”
打印(“启动…”)
cmds=[“r!test-响应:我听到了!”]
channel2=bot.get\u通道(CHANNELID)
@bot.event#知道这意味着什么,但你必须这么做
_ready()上的异步定义:#当bot就绪时
对于bot.guilds中的帮会:
如果guild.name==帮会:
打破
印刷品(
f'{bot.user}已连接到Discord!他们已连接到以下服务器:'#client.user只是bot名称
f'{guild.name}(id:{guild.id})#guild.name只是服务器名
通道2=机器人获取通道(703869904264101969)
全球金额
尝试:
将open('amounts.json')作为f:
amounts=json.load(f)
除FileNotFoundError外:
打印(“无法加载amounts.json”)
金额={}
等待频道2.发送(on)
等待bot.change_状态(activity=discord.activity(type=discord.ActivityType.waiting,name=“r!help”))
@命令(name='test',help='响应:我能听到你的声音!主要用于测试。'))
异步def测试(ctx):
等待ctx。发送(“我听到了!”)
@命令(name='ping',help='告诉您bot的延迟。'))
异步定义ping(ctx):
等待ctx.send(“Pong!”+str(int(bot.latency)*1000)+“ms!”)
@命令(name='say或simonsays',help='以您在后面所说的任何内容作为响应',别名=['say','simonsays'])
异步定义(ctx,*,内容:str):
等待ctx发送(内容)
@bot.command(name='dicerll',help='Rolls a dice!')
异步def骰子滚动(ctx,骰子数:int,边数:int):
骰子=[
str(随机选择(范围(1,边数+1)))
对于范围内的i(骰子数量)
]
等待ctx.发送(','.加入(骰子))
@机器人事件
成员加入时的异步定义(成员):
等待channel2.send(f'{member}已加入服务器。“)
@机器人事件
成员上的异步定义删除(成员):
等待channel2.send(f'{member}已离开服务器。f')
@命令(name='coolnotcool',help='告诉您是否酷。')
异步def coolnotcool(ctx,*,成员:str):
coolornot=随机选择(范围(1,3))
如果coolornot==1:
等待ctx.send(f'{member}很酷')
elif coolornot==2:
等待ctx.send(f'{member}不酷')
@bot.command(name='8ball',help='问它一个问题,它会回答')
异步def eightball(ctx,问题):
答复=[“这是肯定的”,“毫无疑问”,“你可以信赖它”,“是的,肯定的”,“这是肯定的”,“在我看来,是的”,“最有可能”,“是的”,“前景良好”,“迹象表明是的”,“回答模糊,再试一次”,“最好不要现在告诉你”,“以后再问”,“现在无法预测”,“集中精力,然后再问”,“不要指望它”,“前景展望”“不太好。”,“我的消息来源说没有。”,“非常可疑。”,“我的回答是没有。”]
响应=随机选择(范围(1,21))
等待ctx.send(str(应答[应答])
@bot.command(name='coinflip',help='正面或反面响应。有助于做出决策。'))
异步def coinflip(ctx):
答案=随机选择(范围(1,3))
如果答案=1:
等待ctx发送('Heads!')
其他:
等待ctx.send('Tails!')
@机器人事件
命令上的异步定义错误(ctx,错误):
如果isinstance(错误,commands.MissingRequiredArgument):
等待ctx.send('请传入所有必需的参数')
bot.run(令牌)
@命令(pass_context=True,name='bal',help='显示银行中有多少rb'
异步def bal(ctx):
id=str(ctx.message.author.id)
如果id的金额为:
wait ctx.send(“您在rb银行有{}”。格式(金额[id]))
其他:
等待ctx.send(“您还没有帐户。键入r!注册以注册!”)
@命令(pass_context=True,name='register',help='register以开始使用rainbot货币!')
异步def寄存器(ctx):
id=str(ctx.message.author.id)
如果id不在金额中:
金额[id]=100
等待ctx.send(“您现在已注册!请记住,键入r!save to save!”)
_保存()
其他:
等待ctx.send(“您已经有一个帐户了。”)
@命令(name='save',help='Your currency autosave,但请记住始终保存,以防万一!这样可以保存您的货币。'))
异步def保存(ctx):
_保存()
等待ctx.send(“数据已保存!”)
@命令(pass_context=True,name='give',help='give'给另一个成员一些rb!')
异步def give(ctx,amount:int,other:discord.Member):
primary_id=str(ctx.message.author.id)
other_id=str(other.id)
如果主id不在金额中:
等待ctx.send(“您没有帐户”)
elif其他不在金额中的id:
等待ctx.send(“另一方没有账户”)
elif金额[主id]<金额:
等待ctx.send(“您负担不起这笔交易”)
其他:
金额[主id]-=金额
金额[其他id]+=金额
等待ctx发送(“交易完成”)
_保存()
def_save():
将open('amounts.json','w+')作为f:
json.dump(金额,f)

如果有人能帮上忙,那就太好了。json文件是空的。

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