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

如何在Python机器人中创建子命令?

在Python机器人中创建子命令

我来给你展示如何在Python机器人里实现子命令功能,下面是完整的示例代码和简单解释:

首先,我们需要定义一个命令组作为主命令,使用@bot.group()装饰器:

@bot.group(pass_context=True)
async def First(ctx):
    # 如果用户只输入主命令,没有跟上子命令,就返回提示
    if ctx.invoked_subcommand is None:
        await bot.say('Invalid sub command passed...')

接下来,给这个命令组添加子命令,用@主命令名.command()装饰器来绑定:

@First.command(pass_context=True)
async def Second(ctx):
    # 回复用户并@对方
    msg = 'Finally got success {0.author.mention}'.format(ctx.message)
    await bot.say(msg)

简单说明下:

  • 当用户发送!First(假设你的机器人前缀是!),机器人会返回"Invalid sub command passed..."
  • 当用户发送!First Second,机器人就会执行子命令逻辑,回复你成功消息并@发送者

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:02:03