【问题标题】:Python Discord.py - Detect if a message invokes any commandsPython Discord.py - 检测消息是否调用任何命令
【发布时间】:2018-09-29 06:50:36
【问题描述】:

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

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

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

【问题讨论】:

    标签: python discord.py discord.py-rewrite


    【解决方案1】:

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

    【讨论】:

    • 正常工作,只是一个简短的说明:要检查消息是否调用命令,请使用 ctx.valid 。如果 valid 为 True,则表示该消息确实调用了命令,否则不调用。
    • @Aimarekin 是的。如果上下文无效,那么ctx.command 将是None,所以我们正在检查它。
    猜你喜欢
    • 2021-09-26
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 2020-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多