【问题标题】:Cog file is incapable of locating .json file in the same directoryCog 文件无法在同一目录中找到 .json 文件
【发布时间】:2021-11-18 07:51:02
【问题描述】:

正如标题所示,我为我的 discord 机器人创建的 cog 文件无法读取/写入保存它的同一文件夹中的 .json 文件。我尝试手动指定文件路径,移动 .json将文件复制到主 bot 文件的根文件夹,将 .json 文件全部重命名无济于事。移动 .json 文件会阻止机器人抛出丢失文件错误,但它会使 cog 文件不再同时工作,这实际上是在没有解决方案的情况下产生两个问题。

cog文件如下

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))

主文件如下,如果有帮助的话

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')

在使用诸如“.”之类的前缀之前,该机器人运行良好。或 '$' 为例。 一旦使用前缀,就会抛出以下错误:

cent/Documents/Py 括号 bot/Main.py" 忽略异常 on_message Traceback(最近一次通话最后一次):文件 "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", 第 343 行,在 _run_event 等待coro(*args,**kwargs)文件“/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py”, 第 979 行,在 on_message 中 等待self.process_commands(消息)文件“/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py”, 第 975 行,在 process_commands 中 ctx = await self.get_context(message) 文件“/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py”, 第 886 行,在 get_context 前缀=等待self.get_prefix(消息)文件“/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py”, 第 831 行,在 get_prefix 中 ret = await discord.utils.maybe_coroutine(prefix, self, message) 文件 "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/utils.py", 第 341 行,在 Maybe_coroutine 中 value = f(*args, **kwargs) 文件“/Users/vincent/Documents/Py 括号 bot/cogs/Prefix_changer.py”,第 34 行,在 get_prefix with open('prefixes.json', 'r') as f: FileNotFoundError: [Errno 2] No such file or directory: 'prefixes.json'

如果不是很明显,.json 文件是 prefixes.json。

【问题讨论】:

  • 是prefix.json和你的代码在同一个文件夹吗?
  • @GhostOps 是的,它们都在我的 Cogs 文件夹中,该文件夹是机器人根目录的子文件夹。它是 Python bot[folder] -> Cogs[folder] (和 Main.py 在同一个文件夹中) -> prefixes.json 和 prefix_changer.py

标签: python json discord bots


【解决方案1】:

将文件路径设置为包含cogs/ 修复了它。我不知道 cog 不会在 .json 文件所在的同一目录中查找。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2012-01-05
    相关资源
    最近更新 更多