I am making a blacklist command for my discord bot that interacts with JSON to read and write a JSON file to add or remove blacklisted users. I have a file named _json.py that houses the read and write functions, and it looks like this.
import json
from pathlib import Path
def get_path():
cwd = Path(__file__).parents[1]
cwd = str(cwd)
return cwd
def read_json(filename):
cwd = get_path()
with open(cwd+'/bot_config'+filename+'.json', 'r') as file:
data = json.load(file)
return data
def write_json(data, filename):
cwd = get_path()
with open(cwd+'/bot_config'+filename+'.json', 'w') as file:
json.dump(data, file, indent=4)
The file that houses my blacklist/unblacklist command, and all other moderation commands is called moderation.py. Here are the imports and the blacklist/unblacklist commands.
import discord
from discord.ext import commands
from datetime import datetime
import _json
class Moderation(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
@commands.has_permissions(ban_members=True)
async def blacklist(self, context, member : discord.Member):
if context.message.author.id == member.id:
myEmbed = discord.Embed(title="ERROR: Unable to Self Punish", timestamp=datetime.utcnow(), color=0xFF0000)
myEmbed.set_footer(icon_url=context.author.avatar_url, text=f"Invoked by {context.message.author}")
await context.message.channel.send(embed=myEmbed)
return
self.client.blacklisted_users.append(member.id)
data = _json.read_json("blacklist")
data["blacklistedUsers"].append(member.id)
_json.write_json(data, "blacklist")
await context.send(f"{member.mention} has been blacklisted.")
@commands.command()
@commands.has_permissions(ban_members=True)
async def unblacklist(self, context, member : discord.Member):
self.client.blacklisted_users.remove(member.id)
data = _json.read_json("blacklist")
data["blacklistedUsers"].remove(member.id)
_json.write_json(data, "blacklist")
await context.send(f"{member.mention} has been unblacklisted.")
def setup(client):
client.add_cog(Moderation(client))
When I try to use the blacklist command on a user in my test server, it raises this error in the terminal.
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module '_json' has no attribute 'read_json'