强制不协调以显示失败的交互消息

2024-04-19 21:12:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

但是,我正在运行一些稍长的任务,因此我调用了ctx.defer()方法,这给了我更多的时间来响应并显示“应用程序名称正在思考…”动画不协调的一面

如果我的任务引发一些内部异常,我想手动触发“此交互失败”消息。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")

Tags: 方法fromtestimport应用程序消息botdefer
1条回答
网友
1楼 · 发布于 2024-04-19 21:12:27

文档中指出,延迟消息将允许消息更新长达15分钟。没有任何方法可以让交互尽早失败,但是您可以尝试故意发送一个无效/中断的响应,看看这是否会使挂起的交互无效

然而,这远远不是好的实践,在discord-py-slash-command库的实现范围内是不可能的

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

预期错误

您可以简单地使用隐藏的用户消息进行响应

ctx.send('error description', hidden=True)
return

要使其工作,您必须首先将消息延迟到隐藏阶段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

请注意,只有在前一个延迟被称为ctx.defer(hidden=True)时,响应才会被隐藏。如果使用了ctx.defer(),执行不会失败,并且会向控制台打印一条警告

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

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

相关问题 更多 >