python - 如果 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)
解决方案
您可以为此创建一个错误处理程序。您可以使用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
推荐阅读
- selenium - Capybara:使用 find 查找第一级的元素
- eclipse - JPA JPQL 查询被转换为大写
- javascript - 将从表中获取的值传递到引导模式的问题
- pandas - 如何从数据框中绘制列
- angular - PWA 的线框和 UI 设计
- python-3.x - 使用pyodbc和python3查询具有特殊字符的字段时出现内存不足错误
- python - MQTTTextStreamSource 的 getBatch 返回的 DataFrame 没有 isStreaming=true
- ios - iOS Xcode 从 Maya 导入 COLLADA .dae 3D 模型,同时尊重枢轴点
- php - Laravel 中的传入数据处理
- html - 具有隐藏溢出的 flex 布局中的绝对定位按钮(带有 scolling)