Discord.py如何实现一个命令执行后自动触发另一个命令
Discord.py 命令触发另一命令实现方案
针对你需要执行,start命令固有逻辑后自动触发,hello命令的需求,有两种常用实现方式:
方案1:抽离公共逻辑(更推荐)
把命令的核心逻辑抽为独立函数,直接调用即可,无额外开销,也不会出现上下文传递异常问题,代码示例如下:
import discord from discord.ext import commands # 初始化Bot,命令前缀设置为, bot = commands.Bot(command_prefix=',', intents=discord.Intents.all()) # 抽离hello命令的核心逻辑为独立函数 async def hello_core(ctx: commands.Context): # 此处替换为你原hello命令的所有业务逻辑 await ctx.send(f"哈喽 {ctx.author.mention},这是hello命令的返回内容") # 注册hello命令 @bot.command(name='hello') async def hello(ctx: commands.Context): await hello_core(ctx) # 注册start命令 @bot.command(name='start') async def start(ctx: commands.Context): # 此处替换为你原start命令的固有预设逻辑 await ctx.send("start命令固有逻辑执行完毕,即将调用hello命令") # 执行完自身逻辑后直接调用hello的核心函数 await hello_core(ctx) bot.run("替换为你的Bot Token")
方案2:直接调用invoke方法触发命令
适合不想改动原有命令结构的快速实现场景,直接通过上下文的invoke方法触发目标命令即可,代码示例如下:
import discord from discord.ext import commands bot = commands.Bot(command_prefix=',', intents=discord.Intents.all()) @bot.command(name='hello') async def hello(ctx: commands.Context): await ctx.send(f"哈喽 {ctx.author.mention},这是hello命令的返回内容") @bot.command(name='start') async def start(ctx: commands.Context): # 先执行start的固有预设逻辑 await ctx.send("start命令固有逻辑执行完毕,即将调用hello命令") # 直接触发hello命令,传入当前上下文即可 await ctx.invoke(hello) bot.run("替换为你的Bot Token")
注意事项
- 如果目标命令需要传入参数,直接在invoke方法后追加参数即可,例如hello命令需要传入用户名参数,写法为
await ctx.invoke(hello, username="测试用户") - invoke方法默认不会触发命令的前置校验装饰器(如权限校验、冷却校验等),如果需要保留校验逻辑,建议使用方案1抽离公共逻辑的实现方式
- 必须开启对应Intents权限,否则Bot无法监听消息触发命令
内容的提问来源于stack exchange,提问作者YES
相关产品推荐
相关产品推荐

