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

Discord机器人应用命令同步失败及Cog加载问题求助

问题排查与修复步骤

1. 调整Cog加载与命令同步顺序

必须先加载Cog再同步命令,否则Cog中的应用命令不会被注册到bot.tree中。修改main.py的on_ready函数:

@bot.event
async def on_ready():
    print(f'已登录为 {bot.user}')
    # 先加载Cog
    await bot.load_extension('cogs.calculations')
    print("已加载calculations Cog")
    # 再同步命令
    await bot.tree.sync()  # 全局同步应用命令
    print("应用命令已全局同步。")

2. 确认文件结构正确性

确保项目结构符合要求:

你的项目文件夹/
├── main.py
├── .env
└── cogs/
    └── calculations.py

若cogs文件夹不存在,需手动创建并将calculations.py放入其中。

3. 修复Cog内函数调用问题

calculations.py中的format_number是全局函数,在Cog方法中直接调用会报错,需改为类静态方法:

class calculationsCog(commands.Cog, name="calculations"):
    """实用工具命令集合"""

    def __init__(self, bot):
        self.bot = bot

    # 新增静态方法format_number
    @staticmethod
    def format_number(number):
        locale.setlocale(locale.LC_ALL, '')
        formatted_number = locale.format_string('%d', number, grouping=True)
        if number >= 1000000000000:
            suffix = f" ({locale.format_string('%0.2fT', number / 1000000000000, grouping=True)} 金币)"
        elif number >= 1000000000:
            suffix = f" ({locale.format_string('%0.2fB', number / 1000000000, grouping=True)} 金币)"
        elif number >= 1000000:
            suffix = f" ({locale.format_string('%0.2fM', number / 1000000, grouping=True)} 金币)"
        else:
            suffix = ""
        return formatted_number + suffix

    # 修改castle_cost方法中的调用
    async def castle_cost(self, interaction: discord.Interaction, castle_level: int, castle_target_level: int):
        # ... 原有逻辑 ...
        formatted_cost = self.format_number(castle_gold_cost)
        # ... 原有逻辑 ...

    # 修改ta_cost方法中的调用
    async def ta_cost(self, interaction: discord.Interaction, ta_level: int, ta_target_level: int):
        # ... 原有逻辑 ...
        formatted_cost = self.format_number(ta_gold_cost)
        # ... 原有逻辑 ...

4. 优先用服务器级同步测试

Discord全局同步可能延迟1-2小时,先通过/sync命令测试服务器级同步:

  1. 启动bot后,在Discord发送/sync;
  2. 同步完成后,ratio、castle_cost、ta_cost会立即在当前服务器显示。

5. 检查权限与Intents

  • 在Discord开发者门户开启Message Content Intent;
  • 确保bot邀请链接包含applications.commands权限(链接需带scope=bot%20applications.commands)。

6. 添加Cog加载错误捕获

在main.py中加入错误捕获,方便排查问题:

@bot.event
async def on_ready():
    print(f'已登录为 {bot.user}')
    try:
        await bot.load_extension('cogs.calculations')
        print("已成功加载calculations Cog")
    except Exception as e:
        print(f"加载Cog失败: {e}")
    await bot.tree.sync()
    print("应用命令已全局同步。")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 08:15:34