【问题标题】:catch error if commands.dm_only() returns false如果 commands.dm_only() 返回 false,则捕获错误
【发布时间】:2021-12-08 11:17:48
【问题描述】:

我想向我的 discord 机器人添加一个命令,该命令仅可用于私人聊天 (DM)。

为此,我使用discord.ext.commands.dm_only。它按预期工作,但如果我的dm_only-check 返回错误,我想执行特定事件,但我不知道该怎么做。 目前机器人只是在我的控制台中抛出一个错误,但如果聊天是公开的,我想打印/发送一条消息给用户(在同一个公共聊天中)。

这是我的代码:

import discord
from discord.ext import commands

client = commands.Bot(command_prefix = '/')

@commands.command()
@commands.dm_only()
async def command(ctx):
    # do something

client.add_command(command)

client.run(bot_token)

【问题讨论】:

    标签: python error-handling discord discord.py bots


    【解决方案1】:

    您可以为此创建一个错误处理程序。您可以使用on_command_error 侦听器或创建自定义错误处理程序。

    看看下面的代码:

    @client.command()
    @commands.dm_only()
    async def command(ctx):
        await ctx.send("TEST") # Test message
    
    @command.error # Error handler for the "command" command
    async def command_error(ctx, error):
        if isinstance(error, commands.PrivateMessageOnly): # Only usable in DM's
            await ctx.send("You can only use this in DM's!") # Send custom error message
    

    【讨论】:

    • 非常感谢,其他遇到类似问题的人,请参阅here on_command_error 听众
    猜你喜欢
    • 2013-10-15
    • 1970-01-01
    • 2014-12-07
    • 2015-11-11
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    • 2021-10-03
    相关资源
    最近更新 更多