首页 > 解决方案 > Python Discord.py - 检测消息是否调用任何命令

问题描述

我想知道一条消息是否可以调用任何命令而不执行它。

我的意思是,我有一条消息,我想知道该消息是否触发了任何命令。文档中有什么我没有注意到的吗?之类的东西ctx.command,它告诉我消息可以执行什么命令,而不运行它。

如果机器人没有发送权限,这是为了对用户进行 perm 检查和 DM。谢谢!

标签: pythondiscord.pydiscord.py-rewrite

解决方案


更简单的方法是实际编写一个检查来查看调用者是否可以调用命令,如果不能调用,则引发特殊错误。然后您可以在 中处理该错误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!

推荐阅读