首页 > 解决方案 > 我如何检查 ctx 是否是私人频道(dm 频道)

问题描述

本质上,我希望这个命令只能在 DMS 中运行,并且不能在我的机器人所在的服务器中激活,我知道有一个用于检查的装饰器,但我不确定如何准确地使用它,感谢任何帮助

class verify:
    def check():
        #something 

    @bot.command()
    @commands.check(check)
    async def verify(ctx):

标签: pythonpython-3.xdiscord.py

解决方案


编辑:

在我写完这篇文章几秒钟后,1.1.0 版发布了,其中包括一个内置的dm_only检查

原来的:

这与内置检查相反,内置guild_only检查定义为

def guild_only():
    """A :func:`.check` that indicates this command must only be used in a
    guild context only. Basically, no private messages are allowed when
    using the command.
    This check raises a special exception, :exc:`.NoPrivateMessage`
    that is inherited from :exc:`.CheckFailure`.
    """

    def predicate(ctx):
        if ctx.guild is None:
            raise NoPrivateMessage()
        return True

    return check(predicate)

所以dm_only支票看起来像

class NoGuildMessage(CheckFailure):
    pass

def dm_only():
    def predicate(ctx):
        if ctx.guild is not None:
            raise NoGuildMessage()
        return True

    return check(predicate)

推荐阅读