You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Discord Bot重构后on_ready未触发及命令失效问题

Troubleshooting Discord Bot on_ready & Command Issues After Refactoring

Got it, let's walk through why your refactored Discord bot isn't firing the on_ready event or responding to the !event command. I've run into similar snags when splitting code into modules, so here are the most likely fixes to check:


1. Fix Your Module Import & Event/Command Registration

When you split code into eve.py and event.py, you need to make sure your bot instance is properly linked to the events/commands in the second module. Here's how to fix this:

Cogs are designed for modularizing bot code, so this will avoid most import headaches.

  • In event.py, wrap your events and commands in a Cog class:
    from discord.ext import commands
    
    class EventCog(commands.Cog):
        def __init__(self, bot):
            self.bot = bot
    
        @commands.Cog.listener()
        async def on_ready(self):
            print(f"Logged in as {self.bot.user} | Event cog loaded")
    
        @commands.command()
        async def event(self, ctx):
            await ctx.send("!event command triggered successfully!")
    
    def setup(bot):
        bot.add_cog(EventCog(bot))
    
  • In eve.py, load the cog and ensure your bot has the right intents:
    import discord
    from discord.ext import commands
    
    # Enable required intents (critical for modern Discord bots)
    intents = discord.Intents.default()
    intents.message_content = True  # Required to read message commands like !event
    
    bot = commands.Bot(command_prefix="!", intents=intents)
    
    # Load the event cog
    bot.load_extension("event")  # If running from src folder, use "src.event" if needed
    
    # Optional: Main bot on_ready for confirmation
    @bot.event
    async def on_ready():
        print(f"Main bot instance ready!")
    
    bot.run("YOUR_BOT_TOKEN_HERE")
    

Option B: Direct Import (For Simple Setups)

If you don't want to use Cogs, ensure the event.py uses the same bot instance from eve.py:

  • In eve.py:
    import discord
    from discord.ext import commands
    
    intents = discord.Intents.default()
    intents.message_content = True
    bot = commands.Bot(command_prefix="!", intents=intents)
    
    # Import event module AFTER defining the bot instance
    import event
    
    bot.run("YOUR_BOT_TOKEN_HERE")
    
  • In event.py:
    from eve import bot  # Import the same bot instance
    
    @bot.event
    async def on_ready():
        print("Bot is ready!")
    
    @bot.command()
    async def event(ctx):
        await ctx.send("!event works!")
    

Note: Avoid circular imports (don't import eve from event if event imports from eve) — this will break your code silently.


2. Verify Intents Are Enabled (Critical!)

Discord now requires explicit intents for bots to access most data. If you skip this, your bot won't receive messages or fire events:

  1. Go to the Discord Developer Portal → Your Bot → "Privileged Gateway Intents"
  2. Enable "Message Content Intent" (required for reading command messages) and any other intents you need
  3. Make sure your eve.py initializes the bot with these intents (as shown in the code examples above)

3. Check Your Working Directory & Import Paths

When you moved files to the src folder, your import paths might be broken depending on where you run the script:

  • If your project structure looks like this:
    your-project/
        src/
            eve.py
            event.py
    
  • Run the bot from the your-project directory with: python src/eve.py
  • Or, add the src folder to your Python path in eve.py to avoid import errors:
    import sys
    from pathlib import Path
    sys.path.append(str(Path(__file__).parent))  # Adds src folder to path
    

4. Catch Silent Import Errors

Sometimes imports fail silently, leaving your bot without events/commands. Add debug code to eve.py to check:

import traceback
try:
    import event
    print("✅ Successfully imported event module")
except Exception as e:
    print(f"❌ Error importing event module: {e}")
    traceback.print_exc()

This will show you if there's a syntax error, missing dependency, or path issue in event.py.


5. Double-Check Bot Permissions & Token

  • Ensure your bot token in eve.py is correct (copy-paste it again from the Developer Portal to be safe)
  • Confirm your bot has been invited to your server with the right permissions: Use an invite link that includes scope=bot+applications.commands and permissions like "Send Messages", "Read Message History", and "Read Messages/View Channels"

内容的提问来源于stack exchange,提问作者Caladyn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:26:14