【问题标题】:How do I allow for multiple possible responses in a discord.py command?如何在 discord.py 命令中允许多个可能的响应?
【发布时间】:2019-04-07 06:06:15
【问题描述】:

我正在尝试设置 Discord 机器人,同时对 discord.py(实际上是 Python 3)相对较新。我想添加命令“greet”,它会提示用户对它说“hello”。但是,当我希望它同时响应“hello”和“Hello”时,它只会响应“hello”。

我唯一能想到的解决办法就是将它们放在 or 语句中,理论上这应该让 Python 3 和机器人在两个响应之间进行选择(如下所示)。

@client.event
async def on_message(message):
    if message.content.startswith('~greet'):
        await client.send_message(message.channel, 'Say hello')
        msg = await client.wait_for_message(author=message.author, content=('hello' or 'Hello'))
        await client.send_message(message.channel, 'Hello.')

我的原始代码很简单,只允许hello 的一个响应。

@client.event
async def on_message(message):
    if message.content.startswith('~greet'):
        await client.send_message(message.channel, 'Say hello')
        msg = await client.wait_for_message(author=message.author, content=('hello' or 'Hello'))
        await client.send_message(message.channel, 'Hello.')

由于某种原因,我无法绕开我的脑袋,它仍然无法识别 'Hello',并且只允许我说 'hello' 作为回应。

【问题讨论】:

  • 这是重写还是异步分支?

标签: python-3.6 discord.py


【解决方案1】:

or 的行为不像你想象的那样。 'hello' or 'Hello' 在传递给 wait_for_message 之前进行评估,等于 'hello'

相反,您可以向wait_for_message 提供check 函数:

def is_hello(message):
    return message.content.lower() == 'hello'

msg = await client.wait_for_message(author=message.author, check=is_hello)

【讨论】:

  • 谢谢!这个答案绝对最直接地解决了我的问题。
【解决方案2】:

您应该使用command 表示法,而不是使用on_message 检查每条消息,因为它会使您的代码更具可读性。如果你有 10 个命令会发生什么?你会检查on_message 中的 10 个字符串吗?

如果那是重写分支,那么commands.Bot 接受不区分大小写的参数:

bot = commands.Bot(command_prefix='!', case_insensitive=True)

或者,如果您想对同一命令使用多个单词,您可以使用别名,例如:

@bot.command(aliases=['info', 'stats', 'status'])
    async def about(self):
        # your code here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 2023-02-10
    相关资源
    最近更新 更多