Discord.py 如何让机器人不回复 PM

Discord.py How to make bot not respond to PM's

正如标题所问,有没有办法让机器人在 PM 中不工作,只在频道中使用时工作?

我现在所做的就是在我的@client.command 前面加上这个声明

@client.command(pass_context=True)
async def profile(ctx):
    if ctx.message.server == None:
        pass
    else:
        # Code

有没有更简单的方法来做到这一点?我读到我可以对其使用全局检查,但我不确定如何实现它。

编辑:我正在使用 Commands Extension

对此进行编码

我在 documentation 中没有看到任何关于全局禁用私人消息事件的内容。

你所做的正是我所做的。你说你不想每次都重复这一行,但是你只能有一个on_message(),这样那一行就只需要出现一次;每个需要遵守这些规则的命令都将位于 if 块中:

@client.event
async def on_message(message):
    if message.server is not None:
        if message.content.startswith('!dice'):
            ...

        if message.content.startswith('!roulette'):
            ...

编辑:看来您正在使用 commands 扩展,这几乎没有记录。

阅读 Command 的文档字符串时,我遇到了 this 部分:

no_pm : bool
    If ``True``\, then the command is not allowed to be executed in
    private messages. Defaults to ``False``. Note that if it is executed
    in private messages, then :func:`on_command_error` and local error handlers
    are called with the :exc:`NoPrivateMessage` error.

因此,如果您这样定义命令:

@client.command(pass_context=True, no_pm=True)
async def profile(ctx):
    ...

它将在 PM 中被禁用。

"no_pm = true" 现在好像不行了。 所以在@client.command()

下面添加“@commands.guild_only()”

示例:

@client.command()
@commands.guild_only()
async def commandname():

如果你想用 @bot.event 编码,你必须这样做:

@bot.event
async def on_message(message):
    if message.content.startswith('!dm')
        await message.author.send('Hi. This message is send in DM!')