首页 > 解决方案 > 如果 commands.dm_only() 返回 false,则捕获错误

问题描述

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

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

这是我的代码:

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)

标签: pythonerror-handlingdiscorddiscord.pybots

解决方案


您可以为此创建一个错误处理程序。您可以使用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

推荐阅读