python - json 文件错误:json.decoder.JSONDecodeError:预期值:第 1 行第 1 列(字符 0)
问题描述
我正在使用 discord.py 创建一个多用途的不和谐机器人,但我在制作自定义货币时遇到了一些麻烦。
我决定使用 .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 文件为空。
解决方案
空的 json 文件是您的错误。编辑 json 文件,使其包含以下内容:
{}
推荐阅读
- kubernetes - gitlabCI中Kubernetes节点无法获取资源
- django - 如何在 django 中分别缓存基于类的视图和对象
- javascript - 每个用户的自定义个人资料页面
- python - 如何将节点和边列表转换为邻接矩阵?
- linux - 为什么我的 CGI 脚本无法访问 ttyUSB0?
- python - 找不到cleverhans模块
- r - 如何解决将坐标图应用于几何多边形的问题?
- performance - IPC 性能:匿名管道与套接字
- cucumber - 在柏树中使用黄瓜时我可以使用固定装置吗
- redirect - 如何编写 iis 配置规则以停止 .asmx 的重定向