Vincent
Vincent

Reputation: 33

Cog file is incapable of locating .json file in the same directory

As the title suggests, the cog file I created for my discord bot is incapable of reading/writing to a .json file within the same folder it's saved in. I've tried manually specifying the file path, moving the .json file to the root folder of the main bot file, renaming the .json file all to no avail. Moving the .json file stops the bot from throwing a missing file error, but it makes the cog file no longer work at the same time, which is effectively creating two problems without a solution.

cog file is as follows

import discord
import logging
import json
import os
from discord.ext import commands


class Prefixes(commands.Cog):
    def __init__(self, client):
        self.client = client

#Sets default prefix for server on first join    
    @commands.Cog.listener()
    async def on_guild_join(guild):
        with open('prefixes.json', 'r') as f:
            prefixes = json.load(f)
        prefixes[str(guild.id)] = '.'
        with open ('prefixes.json', 'w') as f:
            json.dump(prefixes, f, indent = 4)

#Command for assigning a new prefix
@commands.command()
@commands.has_role("admin" == True)
async def change_prefix(ctx, prefix):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)
    prefixes[str(ctx.guild.id)] = prefix
    with open ('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent = 4)
    await ctx.send(f'Prefix changed to: {prefix}')

#Placeholder Prefix Command
def get_prefix(client, message):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)
    return prefixes[str(message.guild.id)]
client = commands.Bot(command_prefix = get_prefix)

#Removes the stored prefix when bot is kicked
async def on_guild_remove(guild):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)
    prefixes.pop(str(guild.id))
    with open ('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent= 4)


#Connects Cog to bot
def setup(client):
    client.add_cog(Prefixes(client))

And the main file is as follows, if that helps

from cogs.Prefix_changer import Prefixes, get_prefix
import discord
import logging
import os
import discord.ext.commands.errors
from discord.ext import commands


client = commands.Bot(command_prefix = get_prefix)

#Error messages
@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('Please specify a valid command extension.')
    elif isinstance(error, commands.CommandNotFound):
        await ctx.send('Command is not valid.')
    elif isinstance(error, commands.ExtensionNotLoaded):
        await ctx.send('Extension was not loaded.')
    elif isinstance(error, commands.ExtensionNotFound):
        await ctx.send('Extension could not be found.')
    elif isinstance(error, commands.ExtensionAlreadyLoaded):
        await ctx.send('Extension has already been loaded.')

#Loading Cogs
@client.command()
async def load(ctx, extension):
    client.load_extension(f'cogs.[extension]')
#unloading Cogs
@client.command()
async def unload(ctx, extension):
    client.unload_extension(f'cogs.[extension]')
#Searches the primary directory for Cogs folder
for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        client.load_extension(f'cogs.{filename[:-3]}')


client.run('token removed')

The bot runs fine until a prefix is used such as '.' or '$' as an example. As soon as a prefix is used, it throws the following errors:

cent/Documents/Py bracket bot/Main.py" Ignoring exception in on_message Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 979, in on_message await self.process_commands(message) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 975, in process_commands ctx = await self.get_context(message) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 886, in get_context prefix = await self.get_prefix(message) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 831, in get_prefix ret = await discord.utils.maybe_coroutine(prefix, self, message) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/utils.py", line 341, in maybe_coroutine value = f(*args, **kwargs) File "/Users/vincent/Documents/Py bracket bot/cogs/Prefix_changer.py", line 34, in get_prefix with open('prefixes.json', 'r') as f: FileNotFoundError: [Errno 2] No such file or directory: 'prefixes.json'

In case it wasn't obvious, the .json file is prefixes.json.

Upvotes: 1

Views: 190

Answers (1)

Vincent
Vincent

Reputation: 33

Setting the filepath to include cogs/ fixed it. I was not aware that the cog would not look in the same directory it was in for the .json file.

Upvotes: 0

Related Questions