强制不和谐显示失败的交互消息

Seo*_*eon 5 python discord discord.py discord.js

如果应用程序未能在 3 秒内响应交互,Discord 将自动超时并触发自定义“此交互失败”消息。

然而,我正在运行一些稍长的任务,所以我调用该ctx.defer()方法,这给了我更多的时间来响应并显示“<application_name>正在思考...”动画不和谐端。

如果我的任务引发一些内部异常,我想手动触发“此交互失败”消息。Discord API 是否公开了这样做的方法?

我试图触发的消息

一个虚拟示例,使用discord-py-slash-command

import discord
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
slash = SlashCommand(bot)

@slash.slash(name="test")
async def _test(ctx: SlashContext):
    await ctx.defer()
    try:
        assert 1==2
    except AssertionError:
        # Somehow trigger the error message

bot.run("discord_token")
Run Code Online (Sandbox Code Playgroud)

小智 2

文档指出,推迟消息将允许消息更新最多 15 分钟。没有有意使交互提前失败的方法,但是您可以尝试故意发送无效/损坏的响应,看看这是否会使待处理的交互无效。

然而,这远非良好实践,并且在discord-py-slash-command库的实施限制内是不可能的。

我建议手动调用错误响应,以向用户显示更好的错误响应。失败的交互可能有多种原因,从错误的代码到服务完全不可用,并且对用户没有真正的帮助。

预期错误

您可以简单地回复隐藏的用户消息。

ctx.send('error description', hidden=True)
return
Run Code Online (Sandbox Code Playgroud)

为此,您必须首先将消息推迟到隐藏阶段ctx.defer(hidden=True)。如果您希望服务器上的所有用户都能看到最终答案,则可以在顶部发送普通消息 ( ctx.channel.send),也可以使用“普通”延迟将错误消息显示为公共消息。

意外错误

为了捕获意外错误,我建议监听on_slash_command_error事件处理程序。

@client.event
async def on_slash_command_error(ctx, error):

    if isinstance(error, discord.ext.commands.errors.MissingPermissions):
        await ctx.send('You do not have permission to execute this command', hidden=True)

    else:
       await ctx.send('An unexpected error occured. Please contact the bot developer', hidden=True)
       raise error  # this will show some debug print in the console, when debugging
Run Code Online (Sandbox Code Playgroud)

请注意,仅当先前的延迟被称为 时,响应才会被隐藏ctx.defer(hidden=True)。如果ctx.defer()使用了,执行不会失败,并且警告将打印到您的控制台。

这样,调用方法可以通过选择相应的defer参数来决定意外错误是否对所有用户可见。

discord-py-slash-command文档中讨论延迟的部分: https://discord-py-slash-command.readthedocs.io/en/stable/quickstart.html