有没有更好/更快的方法来实现这样的多个 if 语句?

时间:2021-02-24 20:36:44

标签: python discord.py

我让我的 Discord 机器人阅读短信并回复某些文字或图片。因为我可能会让它对很多词做出反应,所以我想知道是否有更好的方法来实现这样的多个 if 语句:

@client.event
    async def on_message(message):
        print(message.author.id, message.author)
        if client.user.id != message.author.id:
            if 'foo' in message.content:
                await message.channel.send('bar')
            if 'hello' in message.content:
                await message.channel.send('hey')
            if 'cat' in message.content:
                await message.channel.send(file=discord.File('cat.png'))
        await client.process_commands(message)

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

在我看来,还可以。

你也可以使用字典来处理这些事情。像这样:

reactions_dict={'foo': 'bar',
                'hello': 'hey',
                'cat': discord.File('cat.png')}
for k,v in reactions_dict.items():
    if k in message.content:
        message.channel.send(v)

但我并不是说这在任何情况下都是最佳选择。这取决于条件的逻辑和复杂性。

附注: 另外,在python 3.10中,会有“case”和“match”语法” https://www.python.org/dev/peps/pep-0634/

答案 1 :(得分:1)

你可以使用这样的列表

@client.event
async def on_message(message):
    print(message.author.id, message.author)
    if client.user.id != message.author.id:
        msg = ['foo', 'hello', 'cat']
        res = ['bar', 'hey', discord.File('cat.png')]
        if message.content in msg:
            a = msg.index(message.content)
            await message.channel.send(res[a])
    await client.process_commands(message)
相关问题