python - Python Discord.py - 检测消息是否调用任何命令
问题描述
我想知道一条消息是否可以调用任何命令而不执行它。
我的意思是,我有一条消息,我想知道该消息是否触发了任何命令。文档中有什么我没有注意到的吗?之类的东西ctx.command
,它告诉我消息可以执行什么命令,而不运行它。
如果机器人没有发送权限,这是为了对用户进行 perm 检查和 DM。谢谢!
解决方案
更简单的方法是实际编写一个检查来查看调用者是否可以调用命令,如果不能调用,则引发特殊错误。然后您可以在 中处理该错误on_command_error
,包括向用户发送警告消息。就像是:
WHITELIST_IDS = [123, 456]
class NotInWhiteList(commands.CheckFailure):
pass
def in_whitelist(whitelist):
async def inner_check(ctx):
if ctx.author.id not in whitelist:
raise NotInWhiteList("You're not on the whitelist!")
return True
return commands.check(inner_check)
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, NotInWhiteList):
await ctx.author.send(error)
@bot.command()
@in_whitelist(WHITELIST_IDS)
async def test(ctx):
await ctx.send("You do have permission")
要真正回答您的问题,您可以直接使用Bot.get_context
. 然后你可以检查ctx.command
自己。(我目前使用的计算机尚未discord.py
安装,因此可能无法正常工作)
您可以使用 . 检查上下文是否调用命令ctx.valid
。如果True
,则表示它调用命令。否则它不会。
@bot.event
async def on_message(message):
ctx = await bot.get_context(message)
if ctx.valid:
if ctx.command in restricted_commands and message.author.id not in WHITELIST_IDS:
await message.author.send("You do not have permission")
else:
await bot.process_commands(message)
else:
pass # This doesn't invoke a command!
推荐阅读
- firebase - 删除firebase实时数据库中的消息反应原生
- c++ - 使用 C++ 中的指针在数组中的特定位置插入元素
- python - Python中线性回归的梯度下降实现有什么问题
- react-native - 子数据长度改变时组件状态抛出错误
- python - 怎么去掉透明背景?
- flutter - 支付插件(谷歌支付)+flutter_stripe 集成
- pdf - iText7页面大小不适用于段落
- google-apps-script - 超出 JDBC 配额限制
- batch-file - 在 Inno Setup 中创建 cmd 的快捷方式以执行批处理文件
- android - 如何确定 Flutter TextFormField 的高度?