Python discord bot 不接受错误

Posted

技术标签:

【中文标题】Python discord bot 不接受错误【英文标题】:Python discord bot does not accept errors 【发布时间】:2021-02-16 20:48:45 【问题描述】:

我已经编写了一个 python discord BOT 并且我已经有这个问题很长一段时间了。即使我在代码中提到了它,它也不排除错误。这是有问题的sn-p ==>

@client.command()
async def spoiler(ctx, *,text):
author = ctx.author
author = author.mention
try:
    await ctx.channel.purge(limit=1)
    await ctx.send("Spoiler from " + author + "\n" "||" + text + "||")
except discord.errors.Forbidden:
    await ctx.send("Grant me the permission to purge channels and try again.")
except asyncio.TimeoutError:
    await ctx.send(author + " Are you typing an essay or what?")
except discord.ext.commands.errors.MissingRequiredArgument:
    await ctx.send(author + " You need to type the text you want to disclose!")

它基本上是一个在不和谐中使用扰流器功能的命令。我希望 BOT 要求用户在命令“$spoiler”之后输入一个文本,以防他们还没有这样做。我尝试在我的服务器中只输入命令,但我收到了这个错误 - “discord.ext.commands.errors.MissingRequiredArgumen”。除了代码中的错误,我做了,但是python只是忽略它,就像它甚至没有指定一样。

这是我收到的错误 ==>

Ignoring exception in command spoiler:
Traceback (most recent call last):
File "C:\Softwares\Python\lib\site-packages\discord\ext\commands\bot.py", 
line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Softwares\Python\lib\site-packages\discord\ext\commands\core.py", 
line 851, in invoke
await self.prepare(ctx)
File "C:\Softwares\Python\lib\site-packages\discord\ext\commands\core.py", 
line 786, in prepare
await self._parse_arguments(ctx)
File "C:\Softwares\Python\lib\site-packages\discord\ext\commands\core.py", 
line 706, in _parse_arguments
kwargs[name] = await self.transform(ctx, param)
File "C:\Softwares\Python\lib\site-packages\discord\ext\commands\core.py", 
line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: text is a required 
argument that is missing.

有人知道解决这个问题的方法吗?

【问题讨论】:

【参考方案1】:

这可能不是您处理错误的方式,但它是万一所有其他方法都失败的方式之一。

@client.command()
async def spoiler(ctx, *,text):
    author = ctx.author
    author = author.mention
    try:
        await ctx.channel.purge(limit=1)
        await ctx.send("Spoiler from " + author + "\n" "||" + text + "||")
    except asyncio.TimeoutError:#using try and except for handling timeout error
        await ctx.send("Are you typing an essay or what?")      

@spoiler.error
async def spoiler_error(ctx, error):
    if isinstance(error, discord.errors.Forbidden):#permission error, may need to change
        await ctx.send("Grant me the permission to purge channels and try again.")
    if isinstance(error, discord.ext.commands.errors.MissingRequiredArgument):#if text is a missing required argument
        await ctx.send("You need to type the text you want to disclose!")

【讨论】:

以上是关于Python discord bot 不接受错误的主要内容,如果未能解决你的问题,请参考以下文章

即使没有错误,Discord Welcome Bot (Python) 也无法工作

Discord bot异步/等待错误处理

Discord Python代码中的命令未找到错误

出现烫发错误后,Discord bot 不会响应

Discord Python Bot:改变状态

Discord Python - 私人频道 (DM) 中的 bot.wait_for_message