0

I am making a leveling system for my discord bot in discord.py (python 3.6.8) but I keep getting this error and I can't really understand what it means.

Here is my code:

import random, asyncio, os, discord, json, time
from discord.ext.commands import Bot

BOT_PREFIX = ("&")
client = Bot(command_prefix=BOT_PREFIX)
client.remove_command('help')

if not os.path.exists('users.json'):
    open('users.json', 'w').close()

@client.event
async def on_message(message):
    with open("users.json", "r") as f:
        users = json.load(f)

        if message.author.bot:
            return
        if message.channel.is_private:
            return
        else:
            await update_data(users, message.author, message.server)
            number = random.randint(5,10)
            await add_experience(users, message.author, number, message.server)
            await level_up(users, message.author, message.channel, message.server)

        with open("users.json", "w") as f:
            json.dump(users, f)
    await client.process_commands(message)

async def update_data(users, user, server):
    if not user.id + "-" + server.id in users:
        users[user.id + "-" + server.id] = {}
        users[user.id + "-" + server.id]["experience"] = 0
        users[user.id + "-" + server.id]["level"] = 0
        users[user.id + "-" + server.id]["last_message"] = 0

async def add_experience(users, user, exp, server):
    if time.time() - users[user.id + "-" + server.id]["last_message"] > 5:
        users[user.id + "-" + server.id]["experience"] += exp
        users[user.id + "-" + server.id]["last_message"] = time.time()
    else:
        return

async def level_up(users, user, channel, server):
    experience = users[user.id + "-" + server.id]["experience"]
    lvl_start = users[user.id + "-" + server.id]["level"]
    lvl_end = int(experience ** (1/4))

    if lvl_start < lvl_end:
        await client.send_message(channel, f"{user.mention}, has leveled up to level {lvl_end}!")
        users[user.id + "-" + server.id]["level"] = lvl_end


print('[BOT SUCCESSFULLY STARTED]\n\n')
client.run('YOUR_TOKEN_HERE')

Here is my error:

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\NeverEndingCycle\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 307, in _run_event
    yield from getattr(self, event)(*args, **kwargs)
  File "C:\Users\NeverEndingCycle\Desktop\Coding_Stuff\Py_Code\Bot_Testing\Logic_Tests\XP-Logic\main.py", line 14, in on_message
    users = json.load(f)
  File "C:\Users\NeverEndingCycle\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 299, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "C:\Users\NeverEndingCycle\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Users\NeverEndingCycle\AppData\Local\Programs\Python\Python36\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\NeverEndingCycle\AppData\Local\Programs\Python\Python36\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Edit: This has been resolved please check my answer down below if you are having the same issue.

5
  • 2
    "told to add more details" can you add part of the JSON payload? The error tells you exactly where the issue is. It says the first character in your payload is invalid. So do print(f) before users = json.load(f) and add that to your question or just add the contents of users.json. After that we can help. Commented Apr 19, 2019 at 19:20
  • When I print 'f' I get this: <_io.TextIOWrapper name='users.json' mode='r' encoding='cp1252'> The data wont append to users.json so there is no content for me to add. Commented Apr 19, 2019 at 20:45
  • You open the file to read from it then within the read context you open the file to write to it. You can't do both at the same time, and my bad do print(f.read()). Commented Apr 19, 2019 at 20:48
  • When I do that literally nothing prints. My json file is empty so there is nothing to print I believe. Commented Apr 19, 2019 at 20:50
  • Okay I figured it out. Check my answer. Commented Apr 19, 2019 at 21:19

2 Answers 2

3

That error is because what you are attempted to load is not a json and is not being processed properly.

You can know this because json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) the line 1 column 1 char 0 is indicating that the json is not being read at all. When the error refers back to the first positional character, it means that the format of that content is not correct for a json to be read.

Sign up to request clarification or add additional context in comments.

5 Comments

So what did I do wrong to make my data not correct for a json to be read? How can I fix the issue?
We would need to see the contents of that file. Are you sure that the file is an accurate JSON?
The file is completely empty, the entire reason I asked this question is because this error stops me from adding any data to the JSON file.
That’s your problem. The error is on json.load(f) on the with open read loop. That is failing because the file is empty and therefore cannot be read in as a json.
Okay I figured it out. Check my answer.
0

Okay I figured it out. I needed to un-indent this block one time:

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

This is why the data was not being saved. As for the error, I believe @GiraffeMan91 was right. Because the data was not being saved and the JSON was empty there was nothing to be decoded thus giving the JSONDecodeErorr.

Here is the working version of the code above:

import random, asyncio, os, discord, json, time
from discord.ext.commands import Bot

BOT_PREFIX = ("&")
client = Bot(command_prefix=BOT_PREFIX)
client.remove_command('help')

if not os.path.exists('users.json'):
    open('users.json', 'w').close()

@client.event
async def on_message(message):
    with open("users.json", "r") as f:
        users = json.load(f)

        if message.author.bot:
            return
        if message.channel.is_private:
            return
        else:
            await update_data(users, message.author, message.server)
            number = random.randint(5,10)
            await add_experience(users, message.author, number, message.server)
            await level_up(users, message.author, message.channel, message.server)

    with open("users.json", "w") as f:
        json.dump(users, f)
    await client.process_commands(message)

async def update_data(users, user, server):
    if not user.id + "-" + server.id in users:
        users[user.id + "-" + server.id] = {}
        users[user.id + "-" + server.id]["experience"] = 0
        users[user.id + "-" + server.id]["level"] = 0
        users[user.id + "-" + server.id]["last_message"] = 0

async def add_experience(users, user, exp, server):
    if time.time() - users[user.id + "-" + server.id]["last_message"] > 5:
        users[user.id + "-" + server.id]["experience"] += exp
        users[user.id + "-" + server.id]["last_message"] = time.time()
    else:
        return

async def level_up(users, user, channel, server):
    experience = users[user.id + "-" + server.id]["experience"]
    lvl_start = users[user.id + "-" + server.id]["level"]
    lvl_end = int(experience ** (1/4))

    if lvl_start < lvl_end:
        await client.send_message(channel, f"{user.mention}, has leveled up to level {lvl_end}!")
        users[user.id + "-" + server.id]["level"] = lvl_end


print('[BOT SUCCESSFULLY STARTED]\n\n')
client.run('YOUR_TOKEN_HERE')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.