在保留命令的同时监听 Discord.py 中的消息

Listening for messages in Discord.py while retaining commands

我的目标是让我的机器人始终监听 discord.py 中的特定消息。在这个例子中,它应该监听的消息是 $greet 它应该用 "Say hello" 在 Text To Speech 中大声朗读来响应它。

这工作正常,但是它禁用了我设置的常规命令,如 !play 和 !help。有没有办法绕过这个限制?

示例代码:

@my_bot.event
async def on_message(message, timeout=10,):
    if message.content.startswith('$greet'):
        await my_bot.send_message(message.channel, 'Say hello', tts=True)
        msg = await my_bot.wait_for_message(author=message.author, content='hello')
        await my_bot.send_message(message.channel, 'Hello.')

预期输出:

User: !play
Bot: Now playing...
User: $greet
Bot: Say hello

实际输出:

User: !play
User: $greet
Bot: Say hello

您可以将它们放在单独的文件中。或者你可以让他们使用相同的前缀 '!'

在使用 discord.py 模块的命令部分时,您依赖于 Bot 调用您的命令的实例来使它们中的任何一个发生。这是通过机器人的协程方法 process_commands 以一种我不打算解释的复杂方式完成的。

来自 the source:

# command processing

@asyncio.coroutine
def process_commands(self, message):
    ...

这轮由 on_message 事件调用。

@asyncio.coroutine
def on_message(self, message):
    yield from self.process_commands(message)

当您覆盖 on_message 事件以实现您的自定义行为时,您将替换此默认行为,因此您需要在特殊处理后自行调用 process_commands

来自 the docstringprocess_commands 协程:

By default, this coroutine is called inside the :func:on_message event. If you choose to override the :func:on_message event, then you should invoke this coroutine as well.

您可以通过以下方式做到这一点:

await bot.process_commands(message)

在您的 on_message 活动结束时

我做了这样的事情:

if message.channel.is_private:
    # Handle commands
    await bot.process_commands(message)
    await bot.delete_message(message)

只允许私人消息中的命令,并删除之后的命令消息。