Discord Bot集成Cogs模块时触发FileNotFoundError: [WinError 3]路径不存在问题求助
FileNotFoundError: [WinError 3] When Loading Discord.py Cogs Let's break down and fix the issues you're facing with your Discord bot's Cogs setup step by step.
First: Resolve the Path Not Found Issue
The FileNotFoundError pops up because your script is searching for the cogs folder in the current working directory—which might not be the same folder where your main.py is stored. To fix this, we'll use absolute paths based on main.py's location, so the script always looks in the right place no matter how you run it.
Update your main.py code where you load cogs:
import discord import os from dotenv import load_dotenv from discord.ext import commands # Get the absolute path of the folder containing main.py BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # Build the full path to the cogs folder COGS_DIR = os.path.join(BASE_DIR, 'cogs') # Client initialization client = commands.Bot(command_prefix='-') client.remove_command("help") # Cog management commands @client.command() async def load(context, extension): client.load_extension(f'cogs.{extension}') @client.command() async def unload(context, extension): client.unload_extension(f'cogs.{extension}') # Load all valid cog files for filename in os.listdir(COGS_DIR): if filename.endswith('.py'): client.load_extension(f'cogs.{filename[:-3]}') # Run the bot with the correct .env path load_dotenv(os.path.join(BASE_DIR, '.env.txt')) client.run(os.getenv('BOT_TOKEN'))
This code uses os.path.abspath(__file__) to grab the full path of main.py, then constructs the path to your cogs folder from that. We also fixed the path to your .env.txt file to avoid similar issues later.
Second: Fix the Syntax Error in Your Cog File
Even if you fix the path, your cog will fail to load due to a syntax mistake. The setup function is missing a colon at the end of its definition, and it doesn't need a self parameter (it's a top-level function, not a class method).
Update your cog code to:
import discord from discord.ext import commands from datetime import datetime class GeneralCommands(commands.Cog): def __init__(self, client): self.client = client def setup(client): # Added colon and removed unnecessary 'self' parameter client.add_cog(GeneralCommands(client))
Quick Additional Checks
- Double-check that the
cogsfolder is exactly in the same directory asmain.py—no typos likeCogsinstead ofcogs(Windows is case-insensitive, but matching exactly avoids confusion). - Ensure there are no hidden files or subfolders in the
cogsdirectory that might interfere, and all your cog files end with.py.
内容的提问来源于stack exchange,提问作者binds

