I keep on getting an error:
Traceback (most recent call last):
File "main.py", line 34, in <module>
database = json.loads(f.read())
File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Heres the code I believe is failing:
with open('db.json') as f:
database = json.loads(f.read())
I can't seem to find out whats going on, as in a website where i searched up how to get all of the text from a file, and I got the code above.
Heres the full code:
import discord
import json
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
cmd = message.content.split(' ')
if message.author == client.user:
return
if cmd[0] == "!login":
lusername = cmd[1]
lpassword = cmd[2]
laccountInfo = getValue('$' % lusername)
laccountInfoArray = laccountInfo.split(' ')
if laccountInfoArray[0] == lpassword:
await message.reply("Successfully logged in!")
await message.delete()
if cmd[0] == "!register":
rusername = cmd[1]
rpassword = cmd[2]
rindex = "$" % rusername
if doesKeyExist(rindex):
message.reply("An account like that already exists!")
else:
setValue(rindex, rpassword)
await message.delete()
with open('db.json') as f:
database = json.loads(f.read())
def saveDatabase():
json.dump(database, open('db.json', 'w'))
def setValue(key, value):
database[key] = value;
saveDatabase()
def getValue(key):
return database[key]
def doesKeyExist(key):
if key not in database:
return False
if key in database:
return True
client.run('')
EDIT: I'm such an idiot that I left the db.json file empty.
The db.json file looks like this now:
{
"$admin": "root"
}
Is your Json file being opened properly? I see the first error occurs on line 34 which is where the file is to be opened. I also noticed that the path (a string) does not provide any additional path information. try specifying that in similar format to below?
with open('c:\\folder1\\folder2\\db.json') as f:
database = json.loads(f.read())
Related
I'm trying to run this code that will send the links which will be opened from a json file, so i don't have to manually put in.
#commands.command()
async def socials(self, ctx):
with open('twit.json', 'insta.json', 'yt.json', "r") as f:
data = json.loads(f.read())
guildID = str(ctx.guild.id)
insta = data[guildID]
twit = data[guildID]
yt = data[guildID]
embed = discord.Embed(title = ctx.guild_name +' Socials', color = discord.Colour.blue())
embed.add_field(name = 'Youtube', value = f'Subscribe to Our Youtube! \n{yt} ', inline = False)
embed.add_field(name = 'Instagram', value = f'Follow Our Instagram! \n{insta}', inline = False)
embed.add_field(name = 'Twitter', value = f'Follow Our Twitter! \n{twit}', inline = False)
embed.set_thumbnail(url=ctx.guild.icon_url)
embed.set_footer(icon_url=ctx.guild.icon_url)
await ctx.send(embed=embed)
This is my error message. Sorry if the problem is simple, I'm new to python.
File "/home/pi/.local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/pi/Desktop/DIscord Team Bot Tem/cogs/socials.py", line 195, in socials
with open('twit.json', 'insta.json', 'yt.json', "r") as f:
TypeError: an integer is required (got type str)
And this is the full error message
Ignoring exception in command socials:
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/pi/Desktop/DIscord Team Bot Tem/cogs/socials.py", line 195, in socials
with open('twit.json', 'insta.json', 'yt.json', "r") as f:
TypeError: an integer is required (got type str)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/discord/ext/commands/bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "/home/pi/.local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/pi/.local/lib/python3.7/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: an integer is required (got type str)
You can't open more than one file in a single open context manager, there are mainly two solutions:
Chain a couple of context managers
with open("twit.json", "r") as f1, \
open("insta.json", "r") as f2, \
open("yt.json", "r") as f3:
# do something with f1, f2 and f3
Use contextlib.ExitStack
from contextlib import ExitStack
files = ["twit.json", "insta.json", "yt.json"]
with ExitStack() as stack:
opened_files = [stack.enter_context(open(fp)) for fp in files]
... # process `opened_files`
# the files will be closed as soon as the context manager ends
The open() function only opens one file; to open multiple files, you have to call it multiple times, either writing it out several times or in a loop.
For example, with a loop:
guildID = str(ctx.guild.id)
data = {}
for social in ('twit', 'insta', 'yt'):
with open('%s.json' % social, 'r') as f:
data[social] = json.load(f)[guildID]
Or, one after the other:
guildID = str(ctx.guild.id)
with open('twit.json', 'r') as f:
twit = json.load(f)[guildID]
with open('insta.json', 'r') as f:
insta = json.load(f)[guildID]
with open('yt.json', 'r') as f:
yt = json.load(f)[guildID]
A loop is more suitable if the files have parallel structure and you'll be doing the same thing with all of them; separate code is more suitable if the files have different structure and you need to do different things with each of them.
So I'm developing discord bot with discord.py for my server. I'm using replit's database system. When I try to add instance of my class Player to key of that database it says:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 36, in jointothefun
db[f"{context.message.author.id}"] = p
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/replit/database/database.py", line 486, in __setitem__
self.set(key, value)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/replit/database/database.py", line 495, in set
self.set_raw(key, _dumps(value))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/replit/database/database.py", line 56, in dumps
return json.dumps(val, separators=(",", ":"), cls=DBJSONEncoder)
File "/usr/lib/python3.8/json/__init__.py", line 234, in dumps
return cls(
File "/usr/lib/python3.8/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
ValueError: Circular reference detected
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: Circular reference detected
I have no idea why it's not working at all. Some one could help?
Oh and source code (yes i know i'm making spaghetti code)
Main file for bot
from discord.ext import commands
from replit import db
from alive import startup
from playerclass import Player
print(db.keys())
class PlayerClient(discord.Client):
async def on_member_join(self,member):
print(f"{member} joined")
async def on_ready(self):
print("Bot ready to work!")
def __init__(self):
self.intents = discord.Intents(messages = True, guilds = True, reactions = True, members = True, presences = True)
self.bot = commands.Bot(command_prefix = '~rpg ', intents = intents)
intents = discord.Intents(messages = True, guilds = True, reactions = True, members = True, presences = True)
client = bot = commands.Bot(command_prefix = '~rpg ', intents = intents)
#client.command(name='join')
async def jointothefun(context):
keys = db.keys()
rpgc = client.get_channel(811518285634863124)
if context.message.channel == rpgc:
if not f"{context.message.author.id}" in keys:
await context.message.channel.send("Hi "+str(context.message.author.mention))
#not working code
db[f"{context.message.author.id}"] = Player(100,0,0,0,0,1)
else:
await context.message.channel.send("Bruh you've joined already")
else:
await context.message.channel.send('Yo wrong channel!')
#client.command(name='stats')
async def stats(context):
rpgc = client.get_channel(811518285634863124)
if context.message.channel==rpgc:
keys = db.keys()
if str(context.message.author.id) in keys:
embed=db[str(context.message.author.id)].displayEquipment
await context.send(embed=embed)
else:
await context.message.channel.send("Join first to access stats!")
else:
await context.message.channel.send(f"XD {context.message.author.mention} to nie ten kanał! Pisz na #rpg")
#client.command()
async def ping(ctx):
await ctx.send("Pong!")
startup()
#yes i know that will not work but it's private i guess it's obvious
client.run("my bot token")
Player class
from item_class import Weapon
import discord
class Player:
def __init__(self,h,m,de,c,t,dm):
self.hp=h
self.mana=m
self.defense=de
self.coins=c
self.truecoins=t
self.weapon=Weapon("Stick",10,1,1,100,1,0)
self.dmg=dm+self.weapon.dmg
self.itlist=[]
def addItemToEq(self,it):
self.itlist.append(it)
def displayEquipment(self,client,context):
embed = discord.Embed(
title="Inventory",colour=discord.Colour.Green)
for i in self.itlist:
if type(i)==Weapon:
embed.add_field(i.self.name,"Weapon",False)
else:
embed.add_field(i.self.name,"Item",False)
return embed
Item class
import random
class Item:
def __init__(self,name):
self.name = name
def use(self):
print("its normal item bruh")
class Food(Item):
def __init__(self,name,nutrition):
self.name=name
self.hpboost=nutrition
class Weapon(Item):
def __init__(self,name,durablity,dmgboost,critchcmin,critchcmax,crit,boost):
self.name=name
self.durablity=durablity
self.dmg=dmgboost
self.critmin=critchcmin
self.critmax=critchcmax
self.critdmg=crit
self.fnc=boost
def attack(self):
print(self.dmg)
print(str(self.calcCrit()))
self.durablity-=1
def calcCrit(self):
if random.randint(self.critmin,self.critmax)<=self.critmax/2:
return True
else:
return False
def useBoost(self):
self.boost()
I would be so grateful if someone would help me :)
as answered here, the values of replit's database must be JSON-serializable. This means, you'd have to pass (most likely) a dict instead of a class object, but then you won't be able to use the object's functions.
Anything in Replit's database has to be JSON serializable. (Str, int, float, list, etc)
You could save the important properties as a json to the database. (e.g "name": "stick", "durablity": 10, "dmg": 1)
Please read to the bottom before answering.
My code loads the JSON from a file called reference.json. Then it adds different object to file, then dumps it back to the file. But when it does that return this error:
Ignoring exception in command import:
Traceback (most recent call last):
File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "C:\code\nexus-developments\workflow-discord-bot\cogs\import_test_suite.py", line 120, in attach_command
self.dump_json(json_content, new_file, new_channel, message=message)
File "C:\code\nexus-developments\workflow-discord-bot\cogs\import_test_suite.py", line 61, in dump_json
reference_content = json.load(reference_file)
File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\json\__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\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)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Joshua\Anaconda3\envs\workflow-discord-bot-env\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)
JSON file:
{}
Coding Snippet:
def dump_json(self, json_content, new_file, channel, message=None):
if new_file:
reference_file = open("json/reference.json", "w+")
reference_content = json.load(reference_file)
reference_content[str(channel.name)] = {}
reference_content[str(channel.name)]["guild_id"] = int(channel.guild.id)
reference_content[str(channel.name)]["channel_id"] = int(channel.id)
reference_content[str(channel.name)]["message_id"] = int(message.id)
json.dump(reference_content, reference_file, indent=4)
file = open(f"json/{channel.name}.json", "w")
json.dump(json_content, file, indent=4)
Full Code:
from discord.ext import commands
from os import path
import utils
import discord
import json
class ImportTestSuite(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def get_json_content(self, ctx):
attachments = ctx.message.attachments
if len(attachments) == 0:
embed = discord.Embed(description="You need to provide 1 JSON attachment",
timestamp=ctx.message.created_at,
colour=discord.colour.Colour.red())
embed = utils.add_promotion_footer(embed)
await ctx.send(embed=embed)
return None
attachment = attachments[0]
if attachment.filename.split(".")[1] != "json":
embed = discord.Embed(description="You must attach a `.json` file",
timestamp=ctx.message.created_at,
colour=discord.colour.Colour.red())
embed = utils.add_promotion_footer(embed)
await ctx.send(embed=embed)
return None
attachment_content = await attachment.read()
try:
json_content = json.loads(attachment_content)
except json.JSONDecodeError:
embed = discord.Embed(description="You must attach valid JSON.\nUse "
"https://jsonformatter.curiousconcept.com/ or an alternative to"
" validate JSON",
timestamp=ctx.message.created_at,
colour=discord.colour.Colour.red())
embed = utils.add_promotion_footer(embed)
await ctx.send(embed=embed)
return None
return json_content
def dump_json(self, json_content, new_file, channel, message=None):
if new_file:
print(message)
print(channel.id)
reference_file = open("json/reference.json", "w+")
reference_content = json.load(reference_file)
reference_content[str(channel.name)] = {}
reference_content[str(channel.name)]["guild_id"] = int(channel.guild.id)
reference_content[str(channel.name)]["channel_id"] = int(channel.id)
reference_content[str(channel.name)]["message_id"] = int(message.id)
json.dump(reference_content, reference_file, indent=4)
file = open(f"json/{channel.name}.json", "w")
json.dump(json_content, file, indent=4)
async def setup_new_channel(self, ctx, channel):
new_channel = await channel.category.create_text_channel(channel.name,
overwrites=channel.overwrites,
position=channel.position,
topic=channel.topic,
nsfw=channel.is_nsfw())
await channel.delete()
embed = discord.Embed(description="React with ✅ to start the test",
timestamp=ctx.message.created_at,
colour=discord.colour.Colour.green())
embed = utils.add_promotion_footer(embed)
message = await new_channel.send(embed=embed)
await message.add_reaction("✅")
return message, new_channel
def check_if_new_file(self, channel):
new_file = False
if not path.exists(f"json/{channel.name}.json"):
new_file = True
return new_file
#commands.command(name="import")
async def attach_command(self, ctx, channel: discord.TextChannel = None):
if channel is None:
channel = ctx.message.channel
json_content = await self.get_json_content(ctx)
if json_content is None:
return
new_file = self.check_if_new_file(channel)
if new_file:
message, new_channel = await self.setup_new_channel(ctx, channel)
self.dump_json(json_content, new_file, new_channel, message=message)
else:
await ctx.message.delete()
self.dump_json(json_content, new_file, channel)
def setup(bot):
bot.add_cog(ImportTestSuite(bot))
I have tried different modes and checked if the data is correct, all that is good.
Thanks in advance
The cause is given in this other SO post: Confused by python file mode "w+".
but not closing as duplicate because is may not be evident at first sight.
The error stack trace gives the line in your code that raises the error:
File "C:\code\nexus-developments\workflow-discord-bot\cogs\import_test_suite.py", line 61, in dump_json
reference_content = json.load(reference_file)
Just before, we can find:
reference_file = open("json/reference.json", "w+")
As explained in the referenced post, w+ mode truncates the file to 0 length, and json does not read your initialized data but an empty file and finds nothing since char 0, hence the error message.
I have absolutely no idea whatsoever what this error means. I Googled it to no end and have spent five days just on this error. Please help. It's for a Discord bot that keeps an XP system in Python, and stores the info for players in a .json file.
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Michael\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "JahBot.py", line 208, in on_message
users = json.load(f)
File "C:\Users\Michael\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\Michael\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\Users\Michael\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\Michael\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)
I will put my currency code here:
#client.event
async def on_member_join(member):
with open('users.json', 'r+') as f:
users = json.load(f)
await update_data(users, member)
with open('users.json', 'w') as f:
users = json.dump(users, f)
#client.event
async def on_message(message):
with open('users.json', 'r+') as f:
users = json.load(f)
await update_data(users, message.author)
await add_experience(users, message.author, 5)
await level_up(users, message.author, message.channel)
with open('users.json', 'w') as f:
users = json.dump(users, f)
async def update_data(users, user):
if not user.id in users:
users[user.id] = {}
users[user.id]['experience'] = 0
user[user.id]['level'] = 1
async def add_experience(users, user, exp):
users[user.id]['experience'] += exp
async def level_up(users, user, channel):
experience = users[user.id]['experience']
lvl_start = users[user.id]['level']
lvl_end = int(experience ** (1/4))
if lvl_start < lvl_end:
await client.send_message(channel, '{} has leveled up to level {}'.format(user.mention, lvl_end))
users[user.id]['level'] = lvl_end
in the json file you need to put
{
}
when i found it out myself i felt so dumb
I have a rewrite version discord.py.If message have content, error does not happened.I need that error does not happened if message have not content.
My code:
#client.command(pass_context = True)
def async search(ctx,message):
...
some code
...
if members_count < voice_channel.user_limit:
message.content += ' '
print(message.content)
invite = await channel.create_invite(max_age=0)
avatar = user.avatar_url
if message == '':
message_for_emb = '\u200b'
elif message != '':
message_for_emb = ':white_small_square: {}'.format(message)
if user.default_avatar_url == avatar:
avatar = 'https://i.imgur.com/XjeDXnB.png'
embed = discord.Embed(description=members, colour=discord.Embed.Empty)
embed.set_author(name='В поисках +{} в {} {}'.format((voice_channel.user_limit - members_count),
voice_channel.category.name,voice_channel.name), icon_url=avatar)
embed.add_field(name=message_for_emb,
value='Зайти: {} :white_check_mark:'.format(invite.url), inline=False)
await channel.send(embed=embed)
Full traceback:
Ignoring exception in command search:
Traceback (most recent call last):
File "C:\Users\Даниил\PycharmProjects\discordbot\venv\lib\site-packages\discord\ext\commands\bot.py", line 886, in invoke
yield from ctx.command.invoke(ctx)
File "C:\Users\Даниил\PycharmProjects\discordbot\venv\lib\site-packages\discord\ext\commands\core.py", line 491, in invoke
yield from self.prepare(ctx)
File "C:\Users\Даниил\PycharmProjects\discordbot\venv\lib\site-packages\discord\ext\commands\core.py", line 455, in prepare
yield from self._parse_arguments(ctx)
File "C:\Users\Даниил\PycharmProjects\discordbot\venv\lib\site-packages\discord\ext\commands\core.py", line 369, in _parse_arguments
transformed = yield from self.transform(ctx, param)
File "C:\Users\Даниил\PycharmProjects\discordbot\venv\lib\site-packages\discord\ext\commands\core.py", line 249, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: message is a required argument that is missing.
The way commands parse arguments means that defining
async def search(ctx, message):
means that search requires a word message as part of the command invocation. If you instead want to capture the remainder of the message, you can use the keyword-only argument syntax:
async def search(ctx, *, message)
This feature is documented here.