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

Discord.py/Defectio库Cog加载动态提示与耗时统计实现方案咨询

Defectio/Discord.py Cog加载动画与耗时统计实现方案

核心思路

  • 统一封装Cog加载逻辑,无需修改单个Cog内部代码即可批量适配所有Cog
  • 打点动画使用异步后台任务运行,不阻塞Cog实际加载流程
  • 分别记录单个Cog加载耗时与全部Cog加载总耗时

完整实现代码

import asyncio
import sys
import time
import defectio
from defectio.ext import commands

# 初始化机器人
bot = commands.Bot(command_prefix="!", case_insensitive=True)

# 你要加载的所有Cog列表,按实际情况修改
COG_LIST = [
    "cogs.administration",
    "cogs.fun",
    "cogs.moderation"
]

async def loading_animation(cog_name: str, stop_event: asyncio.Event):
    """打点动画异步任务"""
    dot_count = 1
    while not stop_event.is_set():
        sys.stdout.write(f"\rLoading {cog_name} cog{'.' * dot_count}")
        sys.stdout.flush()
        dot_count = (dot_count % 3) + 1
        await asyncio.sleep(0.5)

async def load_single_cog(cog_path: str) -> float:
    """加载单个Cog,返回加载耗时"""
    # 提取Cog名称
    cog_name = cog_path.split(".")[-1].capitalize()
    # 创建停止动画的事件
    stop_anim = asyncio.Event()
    # 启动动画后台任务
    anim_task = asyncio.create_task(loading_animation(cog_name, stop_anim))
    
    # 记录加载开始时间
    start_time = time.perf_counter()
    try:
        await bot.load_extension(cog_path)
    except Exception as e:
        # 加载出错时停止动画并输出错误
        stop_anim.set()
        await anim_task
        sys.stdout.write(f"\r加载Cog {cog_name} 失败:{str(e)}\n")
        sys.stdout.flush()
        return 0
    # 计算耗时
    cost_time = time.perf_counter() - start_time
    
    # 停止动画
    stop_anim.set()
    await anim_task
    # 输出加载完成提示
    sys.stdout.write(f"\r{cog_name} cog loaded in {cost_time:.2f} seconds\n")
    sys.stdout.flush()
    return cost_time

async def load_all_cogs():
    """批量加载所有Cog并统计总耗时"""
    total_start = time.perf_counter()
    for cog in COG_LIST:
        await load_single_cog(cog)
    # 输出总耗时提示
    total_time = time.perf_counter() - total_start
    print(f"All cogs loaded in {total_time:.2f} seconds")

# 在机器人启动时加载所有Cog
@bot.event
async def on_ready():
    await load_all_cogs()
    print(f"机器人已登录:{bot.user}")

# 启动机器人
bot.run("你的机器人Token")

适配说明

  • 仅需要修改COG_LIST列表为实际的Cog路径即可生效,无需调整每个Cog内部的代码
  • 可以修改loading_animation函数里await asyncio.sleep(0.5)的数值,调整打点动画的播放速度
  • Cog加载失败会单独输出错误提示,不会中断其他Cog的加载流程
  • 如果你使用的是同步加载Cog的旧版本库,把await bot.load_extension(cog_path)改为bot.load_extension(cog_path)即可正常运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 00:45:06