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

Discord PY如何拆分Slash命令与错误处理至不同文件?

可以实现命令与错误处理分离的写法

当然可以把Discord.py中的命令和对应的错误处理分别放在不同文件里,下面是具体的实现方案:

1. 命令文件(commands.py)

这里只存放命令的核心逻辑,不包含错误处理代码:

from discord.ext import commands

class MyCommands(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def echo(self, ctx, arg):
        await ctx.send(arg)

    # 示例:新增一个加法命令
    @commands.command()
    async def add(self, ctx, num1: int, num2: int):
        await ctx.send(f"计算结果:{num1 + num2}")

2. 错误处理文件(error_handlers.py)

导入命令类后,为每个命令单独绑定错误处理函数:

from discord.ext import commands
from commands import MyCommands

# echo命令的错误处理
@MyCommands.echo.error
async def echo_error(ctx, error):
    await ctx.send("命令执行出错")
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("提示:缺少必要的输入参数")
    else:
        raise error

# add命令的错误处理
@MyCommands.add.error
async def add_error(ctx, error):
    await ctx.send("加法命令执行失败")
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("请输入两个数字参数")
    elif isinstance(error, commands.BadArgument):
        await ctx.send("请输入有效的数字类型参数")
    else:
        raise error

3. 主启动文件(main.py)

需要同时导入命令类和错误处理模块,确保错误绑定生效:

import discord
from discord.ext import commands
from commands import MyCommands
import error_handlers  # 导入错误处理文件,触发绑定逻辑

# 配置Bot权限
intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

@bot.event
async def on_ready():
    await bot.add_cog(MyCommands(bot))
    print(f"Bot已登录:{bot.user}")

# 替换为你的Bot令牌
bot.run("YOUR_BOT_TOKEN")

关键注意点

  • 确保文件路径正确,导入命令类时如果不在同一目录,要调整导入语句(比如用from .commands import MyCommands)
  • 错误处理函数中保留raise error,可以让未覆盖的错误触发默认处理,方便调试
  • 斜杠命令(@app_commands.command())的分离逻辑完全一致,只需替换命令装饰器即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 17:55:02