ValueError: circular reference detected with replit database - python

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)

Related

AttributeError: module 'discord.ext.commands' has no attribute 'qualified_name' | Discord.py

I'm tryna make a help command. But when I run >help <cmd>
I get this error:
AttributeError: module 'discord.ext.commands' has no attribute 'qualified_name'
Here is the code:
class HelpCommand(commands.HelpCommand):
color = 0x171616
def footer(self):
return f"{self.clean_prefix}{self.invoked_with} <command> for more details"
def get_command_signature(self, command):
return f"```yaml\n{self.clean_prefix}{command.qualified_name} {command.signature}```"
async def send_cog_help(self, cog):
em = discord.Embed(
title=f"***{cog.qualified_name}** Commands", colour=self.color)
if cog.description:
em.description = cog.description
filtered = await self.filter_commands(cog.get_commmands(), sort=True)
for command in filtered:
em.add_field(name=command.qualified_name,
value=command.short_doc or "No Description Provided")
em.set_footer(text=self.footer())
await self.get_destination().send(embed=em)
async def send_command_help(self, command):
em = discord.Embed(title=command.qualified_name, color=self.color)
if command.help:
em.description = command.help
em.add_field(name="Syntax", value=self.get_command_signature(commands))
em.set_footer(text=self.footer())
await self.get_destination().send(embed=em)
async def send_bot_help(self, mapping):
em = discord.Embed(title="Loofah Help", color=self.color)
for cog, commands in mapping.items():
if not cog:
continue
filtered = await self.filter_commands(commands, sort=True)
if filtered:
value = "\t".join(f"`{i.name}`" for i in commands)
em.add_field(name=cog.qualified_name, value=value)
em.set_footer(text=self.footer())
await self.get_destination().send(embed=em)
Full traceback error:
Traceback (most recent call last):
File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\pc\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\help.py", line 882, in command_callback
return await self.send_command_help(cmd)
File "D:\Kunnu\Loofah Rewrite\cogs\help.py", line 34, in send_command_help
em.add_field(name="Syntax", value=self.get_command_signature(commands))
File "D:\Kunnu\Loofah Rewrite\cogs\help.py", line 13, in get_command_signature
return f"```yaml\n{self.clean_prefix}{command.qualified_name} {command.signature}```"
AttributeError: module 'discord.ext.commands' has no attribute 'qualified_name'
Any help is appreciated

AttributeError: 'NoneType' object has no attribute 'get_role' 'send' or 'members'

I'm getting the same error multiple times for a program and I can't find what the issue is; I keep getting the same error
_ClientEventTask exception was never retrieved
future: <ClientEventTask state=finished event=on_ready coro=<bound method Mod.on_ready of <lib.cogs.mod.Mod object at 0x000001B219E2BBE0>> exception=AttributeError("'NoneType' object has no attribute 'send'")>
Traceback (most recent call last):
File "C:\Users\jacob\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Projects\BobbyBot\lib\cogs\mod.py", line 278, in on_ready
self.mute_role = self.bot.guild.get_role(653941858128494600)
AttributeError: 'NoneType' object has no attribute 'get_role'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\jacob\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 348, in _run_event
await self.on_error(event_name, *args, **kwargs)
File "c:\Projects\BobbyBot\lib\bot\__init__.py", line 125, in on_error
await self.stdout.send("An error occured.")
AttributeError: 'NoneType' object has no attribute 'send'
_ClientEventTask exception was never retrieved
future: <ClientEventTask state=finished event=on_ready coro=<bound method Reactions.on_ready of <lib.cogs.reactions.Reactions object at 0x000001B219ECC7C0>> exception=AttributeError("'NoneType' object has no attribute 'send'")>
Traceback (most recent call last):
File "C:\Users\jacob\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Projects\BobbyBot\lib\cogs\reactions.py", line 27, in on_ready
"\u2764\ufe0f": self.bot.guild.get_role(653940117680947232), # Red
AttributeError: 'NoneType' object has no attribute 'get_role'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\jacob\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 348, in _run_event
await self.on_error(event_name, *args, **kwargs)
File "c:\Projects\BobbyBot\lib\bot\__init__.py", line 125, in on_error
await self.stdout.send("An error occured.")
AttributeError: 'NoneType' object has no attribute 'send'
Here is the main document of which everything is based:
from asyncio import sleep
from datetime import datetime
from glob import glob
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from discord import Embed, File, DMChannel, Intents
from discord.errors import HTTPException, Forbidden
from discord.ext.commands import Bot as BotBase
from discord.ext.commands import Context
from discord.ext.commands import (CommandNotFound, BadArgument, MissingRequiredArgument,
CommandOnCooldown)
from discord.ext.commands import when_mentioned_or, command, has_permissions
from ..db import db
OWNER_IDS = [213438742315139073]
COGS = [path.split("\\")[-1][:-3] for path in glob("./lib/cogs/*.py")]
IGNORE_EXCEPTIONS = (CommandNotFound, BadArgument)
def get_prefix(bot, message):
prefix = db.field(
"SELECT Prefix FROM guilds WHERE GuildID = ?", message.guild.id)
return when_mentioned_or(prefix)(bot, message)
class Ready(object):
def __init__(self):
for cog in COGS:
setattr(self, cog, False)
def ready_up(self, cog):
setattr(self, cog, True)
print(f" {cog} cog ready")
def all_ready(self):
return all([getattr(self, cog) for cog in COGS])
class Bot(BotBase):
def __init__(self):
self.ready = False
self.cogs_ready = Ready()
self.guild = None
self.scheduler = AsyncIOScheduler()
try:
with open("./data/banlist.txt", "r", encoding="utf-8") as f:
self.banlist = [int(line.strip()) for line in f.readlines()]
except FileNotFoundError:
self.banlist = []
db.autosave(self.scheduler)
super().__init__(
command_prefix=get_prefix,
owner_ids=OWNER_IDS,
intents=Intents.all()
)
def setup(self):
for cog in COGS:
self.load_extension(f"lib.cogs.{cog}")
print(f" {cog} cog loaded")
print("setup complete")
def update_db(self):
db.multiexec("INSERT OR IGNORE INTO guilds (GuildID) VALUES (?)",
((guild.id,) for guild in self.guilds))
db.multiexec("INSERT OR IGNORE INTO exp (UserID) VALUES (?)",
((member.id,) for member in self.guild.members if not member.bot))
to_remove = []
stored_members = db.column("SELECT UserID FROM exp")
for id_ in stored_members:
if not self.guild.get_member(id_):
to_remove.append(id_)
db.multiexec("DELETE FROM exp WHERE UserID = ?",
((id_,) for id_ in to_remove))
db.commit()
def run(self, version):
self.VERSION = version
print("running setup...")
self.setup()
with open("./lib/bot/token.0", "r", encoding="utf-8") as tf:
self.TOKEN = tf.read()
print("running bot...")
super().run(self.TOKEN, reconnect=True)
async def process_commands(self, message):
ctx = await self.get_context(message, cls=Context)
if ctx.command is not None and ctx.guild is not None:
if message.author.id in self.banlist:
await ctx.send("You are banned from using commands.")
elif not self.ready:
await ctx.send("I'm not ready to receive commands. Please wait a few seconds.")
else:
await self.invoke(ctx)
async def rules_reminder(self):
await self.stdout.send("Remember to adhere to the rules!")
async def on_connect(self):
print(" bot connected")
async def on_disconnect(self):
print("bot disconnected")
async def on_error(self, err, *args, **kwargs):
if err == "on_command_error":
await args[0].send("Something went wrong.")
await self.stdout.send("An error occured.")
raise
async def on_command_error(self, ctx, exc):
if any([isinstance(exc, error) for error in IGNORE_EXCEPTIONS]):
pass
elif isinstance(exc, MissingRequiredArgument):
await ctx.send("One or more required arguments are missing.")
elif isinstance(exc, CommandOnCooldown):
await ctx.send(f"That command is on {str(exc.cooldown.type).split('.')[-1]} cooldown. Try again in {exc.retry_after:,.2f} secs.")
elif hasattr(exc, "original"):
# if isinstance(exc.original, HTTPException):
# await ctx.send("Unable to send message.")
if isinstance(exc.original, Forbidden):
await ctx.send("I do not have permission to do that.")
else:
raise exc.original
else:
raise exc
async def on_ready(self):
if not self.ready:
self.stdout = self.get_channel(759434903145152533)
self.scheduler.add_job(self.rules_reminder, CronTrigger(
day_of_week=0, hour=12, minute=0, second=0))
self.scheduler.start()
self.update_db()
embed = Embed(title="Now Online",
description="Bobby Bot is now online.", timestamp=datetime.utcnow())
fields = [("Name", "Bobby Bot", True),
("Latency", str(round(bot.latency * 1000)) + "ms", True)]
for name, value, inline in fields:
embed.add_field(name=name, value=value, inline=inline)
embed.set_author(name="Bobby Bot", icon_url="https://cdn.discordapp.com/attachments/794376573213736991/887527732228018276/Bobbys.png")
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/794376573213736991/887527732228018276/Bobbys.png")
await self.stdout.send(embed=embed)
while not self.cogs_ready.all_ready():
await sleep(0.5)
await self.stdout.send("Now online!")
self.ready = True
print(" bot ready")
meta = self.get_cog("Meta")
await meta.set()
else:
print("bot reconnected")
async def on_message(self, message):
if not message.author.bot:
if isinstance(message.channel, DMChannel):
if len(message.content) < 50:
await message.channel.send("Your message should be at least 50 characters in length.")
else:
member = self.guild.get_member(message.author.id)
embed = Embed(title="Modmail",
colour=member.colour,
timestamp=datetime.utcnow())
embed.set_thumbnail(url=member.avatar_url)
fields = [("Member", member.display_name, False),
("Message", message.content, False)]
for name, value, inline in fields:
embed.add_field(name=name, value=value, inline=inline)
mod = self.get_cog("Mod")
await mod.log_channel.send(embed=embed)
await message.channel.send("Message relayed to moderators.")
else:
await self.process_commands(message)
bot = Bot()
No matter what I try it keeps coming up with the same error regardless of the fact that I know I followed the vid tutorial I was going through exactly. I can't find why it's not recognising self
self.guild is None
You defined self.guild as None and that's the reason why you get the NoneType error. The self.guild should be a guild object I think, but it isn't. None has no attributes like get_role() or something, because its empty and not a discord guild.
self.stdout doesn't exist
I read your code and can't find it anywhere. Because its not in your code, you can't use it as variable, you need to define it.

Pass dictionary to another class

I have a FastAPI app and am looking to pass a dictionary from the POST method to another module in a subdirectory.
My main.py looks like this
from fastapi import FastAPI
from pydantic import BaseModel
from app.api import mymodule
from app.api.mymodule import MyClass
app = FastAPI(debug = True, version="0.0.1")
class MyAPIModel(BaseModel):
"""
Required input from frontend for IP Allocation
"""
forename: str
surname: str
age: int
#app.get("/")
async def default():
return {"Default root page"}
#app.get("/home")
async def home():
return {"message": "Homepage for Application"}
#app.post("/ip")
async def ip(request: MyAPIModel):
superhero = request.dict()
superhero_request = MyClass.get_type(superhero)
Mymodule.py looks like
import api
class MyClass:
def __init__(self, superhero):
self.mysetup = api(url, token)
self.superhero_info = superhero
"""
Here is where I want to access the dictionary
and use it
"""
def get_type(self):
return self.superhero_info
My POST request is a json dict of the BaseModel
{
"forename": "peter",
"surname": "parker",
"age": 28
}
But doing so I get the following error
File "/usr/local/lib/python3.7/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/usr/local/lib/python3.7/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc from None
File "/usr/local/lib/python3.7/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/usr/local/lib/python3.7/site-packages/starlette/routing.py", line 550, in __call__
await route.handle(scope, receive, send)
File "/usr/local/lib/python3.7/site-packages/starlette/routing.py", line 227, in handle
await self.app(scope, receive, send)
File "/usr/local/lib/python3.7/site-packages/starlette/routing.py", line 41, in app
response = await func(request)
File "/usr/local/lib/python3.7/site-packages/fastapi/routing.py", line 148, in app
dependant=dependant, values=values, is_coroutine=is_coroutine
File "/usr/local/lib/python3.7/site-packages/fastapi/routing.py", line 101, in run_endpoint_function
return await dependant.call(**values)
File "./app/main.py", line 36, in ip
Allocate.get_type(iprequest)
File "./app/api/mymodule.py", line 21, in get_type
return self.superhero_info
AttributeError: 'dict' object has no attribute 'superhero'
Is there a way to pass the dictionary to the method class so I can perform other tasks on it before returning?
Was pointed in the right direction by the comments. Full working code is
#app.post("/ip")
async def ip(request: MyAPIModel):
mydata = request.dict()
test = MyClass()
results = test.get_type(mydata)
return results
Needed to return both in the subclass and the main.py

My code returns a JSONDecodeError but the only thing in the file is {}

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.

Discord.py missing required argument

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.

Categories