如何在discord.py/pycord中检测斜杠命令是否在线程中执行
检测Discord斜杠命令是否在线程中执行
完全可行,不需要额外实现is_thread()方法,直接通过判断交互/上下文对应的频道类型即可实现需求,具体代码示例如下:
基于Interaction对象的实现(discord.py 2.0+ 斜杠命令标准写法)
@bot.tree.command(name="check_thread") async def check_thread(interaction: discord.Interaction): # 判断当前命令所在频道是否为线程 if isinstance(interaction.channel, discord.Thread): await interaction.response.send_message("该命令在线程中执行") else: await interaction.response.send_message("该命令未在线程中执行")
基于Context对象的实现(兼容部分旧写法)
@bot.tree.command(name="check_thread_ctx") async def check_thread_ctx(ctx: commands.Context): if isinstance(ctx.channel, discord.Thread): await ctx.send("该命令在线程中执行") else: await ctx.send("该命令未在线程中执行")
原理说明
discord.py中所有线程频道(包括公共线程、私有线程等)都继承自discord.Thread类,普通文本频道、语音频道等则属于其他类型(如discord.TextChannel),通过isinstance()判断频道对象的类型,就能准确识别命令是否在线程中执行。
内容的提问来源于stack exchange,提问作者syrok
相关产品推荐
相关产品推荐

