0

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'
binds
  • 125
  • 2
  • 10

1 Answers1

1

_json is the name of a built-in module so your interpreter will take that one instead of your own file. Give it another name like json_utils and import that instead. I know you added the underscore to not confuse it with the existing json module (without underscore), but the module with the underscore also exists.

stijndcl
  • 5,294
  • 1
  • 9
  • 23
  • when i rename the file and try to import it, i get an unresolved import error. – binds Aug 11 '21 at 15:41
  • 1
    I'm gonna have to see your directory structure & the new import to help you with that. – stijndcl Aug 11 '21 at 16:17
  • I renamed the file to `_blacklist` and changed the `import _json` to `import _blacklist`. The `_blacklist` is underlined and is an unresolved import. – binds Aug 11 '21 at 16:46
  • This is why I asked for your directory structure - are those two in the same directory, or is either of them in a subdirectory? What IDE are you using? – stijndcl Aug 11 '21 at 16:51
  • Both the `_blacklist.py` file and the `moderation.py` where I am trying to import blacklist file are in the same folder. I am using Visual Studio Code. My project is: **Main Folder**: bot | **Inside Bot**: *__pycache__*| *bot_config* - json files in here | *cogs* - houses my `listeners.py`, `general.py`, `_blacklist.py` and `moderation.py` | git.ignore & main.py (in bot folder) – binds Aug 11 '21 at 16:54
  • Try "from cogs import _blacklist", if that doesn't help take a look at all the possible solutions in this post: https://stackoverflow.com/questions/53939751/pylint-unresolved-import-error-in-visual-studio-code | reloading window, changing python path in settings, fixing workspace directory, ... – stijndcl Aug 11 '21 at 17:19
  • the first one works, but when i try to execute the `-blacklist [member]` command in my test server, it raises this error: `discord.ext.commands.errors.CommandInvokeError: Command raised an exception: FileNotFoundError: [Errno 2] No such file or directory: 'c:\\Users\\binds\\Desktop\\Programming Repositories\\ROGUE Repository\\bot/bot_configblacklist.json'` – binds Aug 11 '21 at 17:25
  • The error speaks for itself, the file doesn't exist. You forgot a slash in the filename to indicate the directory: it says ``bot_configblacklist.json``, looking at your code for the `read` and `write` functions it should be `/bot_config/ + filename` (mind the extra `/` after `bot_config`). I'm not sure forward slashes will work on Windows though, as it uses "\\" instead of "/". You may have to use "\\" or `os.path.join()` if "/" doesn't work. – stijndcl Aug 11 '21 at 17:31
  • fixed it. the help is appreciated! – binds Aug 11 '21 at 18:12
  • @binds If it fixed your problem then you should mark my answer as correct – stijndcl Aug 11 '21 at 18:16