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

Discord Bot使用await bot.start()无法运行及Cogs加载问题求助

Discord.py v2.x Cogs加载无响应/无输出问题修复

核心问题分析

你的代码存在两个致命冲突点:

  1. 重复启动Bot:同时调用了asyncio.run(main())和bot.run('TOKEN')。bot.run()是同步阻塞方法,会直接接管事件循环,导致前面的asyncio.run(main())完全没机会执行,或者执行到一半被打断。
  2. 事件注册时机错误:on_ready事件写在asyncio.run(main())之后,此时Bot启动流程已经开始,事件监听无法被正确注册。

修复后的代码

bot.py

import asyncio
import os
import discord
from discord.ext import commands
from discord.ext import tasks
from discord.ext.commands import cooldown, BucketType

# 配置Bot权限
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='-', intents=intents)
bot.remove_command("help")

# 事件必须在Bot启动前注册,确保能被触发
@bot.event
async def on_ready():
    print(f'已登录为 {bot.user} (ID: {bot.user.id})')
    print('------')

async def main():
    async with bot:
        # 加载指定cog,路径格式为「包名.文件名」
        await bot.load_extension("cogs.cog_function")
        # 建议用环境变量存储Token,避免硬编码泄露
        await bot.start(os.getenv('DISCORD_BOT_TOKEN'))

if __name__ == "__main__":
    # Windows环境下强制使用Selector事件循环(解决兼容性问题)
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    asyncio.run(main())

关键注意事项

  • 移除重复启动代码:彻底删除bot.run('TOKEN'),只用asyncio.run(main())配合bot.start()的异步启动方式(discord.py v2.x推荐写法)。
  • 补充cogs包标识:在cogs文件夹下新建一个空的__init__.py文件,让Python识别这是一个合法的模块包,否则load_extension会找不到cog文件。
  • 验证Intents权限:在Discord开发者后台的Bot页面,确保开启了Message Content Intent权限,否则Bot无法读取消息内容。
  • Token安全:不要硬编码Token到代码里,用环境变量(比如os.getenv('DISCORD_BOT_TOKEN'))读取更安全。

额外排查步骤

如果修复后仍无响应,可以在main函数中添加调试日志:

async def main():
    print("开始初始化Bot...")
    async with bot:
        print("正在加载cog...")
        await bot.load_extension("cogs.cog_function")
        print("cog加载完成,启动Bot...")
        await bot.start(os.getenv('DISCORD_BOT_TOKEN'))

通过终端输出判断哪一步出现阻塞,进一步定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 15:05:31