如何在Discord.py的app_commands中替代ctx参数?
在Discord.py的app_commands中替代ctx的功能
app_commands体系下不需要手动转换出ctx对象,discord.Interaction实例本身就提供了你需要的绝大多数常用属性,直接调用即可。
常用属性对应关系
原来基于commands.Command的ctx属性,可以直接用Interaction对象的对应属性替代:
ctx.author→interaction.user:获取发送命令的用户ctx.guild→interaction.guild:获取命令所在的服务器ctx.channel→interaction.channel:获取命令所在的频道ctx.message→interaction.message:仅当命令通过消息上下文触发时可用,对应触发命令的原消息
示例代码:获取用户信息
直接用interaction.user获取用户:
@app_commands.command(name='command', description='desc command') async def command_(self, interaction: discord.Interaction): # 获取发送命令的用户名称 await interaction.response.send_message(interaction.user.name)
特殊情况:手动获取ctx对象
如果确实需要一个兼容commands.Context的对象,可以通过以下方式获取,但这种场景很少,因为app_commands本身推荐直接使用Interaction操作:
@app_commands.command(name='command', description='desc command') async def command_(self, interaction: discord.Interaction): # 从interaction生成ctx对象 ctx = await interaction.client.get_context(interaction) await interaction.response.send_message(ctx.author.name) # 注意:如果要用ctx.send发送消息,必须先完成interaction的回应(比如上面的send_message) # 或者提前调用interaction.response.defer(),否则会报错 # await ctx.send("通过ctx发送的消息")
内容的提问来源于stack exchange,提问作者Bohdan
相关产品推荐
相关产品推荐

