将这段不和谐的bot代码变得更简单

2024-09-29 01:20:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力使这段代码更加简单,但是Python非常区分大小写。是否有办法将此代码清理干净???

@client.event
async def on_message(msg):
    if 'Marcelo' in msg.content:
        print('Keyword found in message')
        await msg.channel.send("oh this shit again!")
    if 'marcelo' in msg.content:
        print('Keyword found in message')
        await msg.channel.send("oh this shit again!")
    if 'MARCELO' in msg.content:
        print('Keyword found in message')
        await msg.channel.send("oh this shit again!")

Tags: insendmessageifchannelmsgcontentawait
1条回答
网友
1楼 · 发布于 2024-09-29 01:20:41

您可以使用<str>.lower,如下所示:

@client.event
async def on_message(msg):
    if 'marcelo' in msg.content.lower():
        print('Keyword found in message')

您可能也不想使用in关键字,因为这意味着如果键入“Hey Marcello”,它仍然会输出。考虑到print语句,我不知道这是否是您想要的,但大多数情况下,使用msg.content.lower().startsWith('marcelo')msg.content.lower() == 'marcelo'会更有意义

相关问题 更多 >