You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py如何在单个if x in message.content判断中匹配多关键词

问题原因

Python 中or逻辑运算符的运算规则是:如果左侧表达式为真值(非空字符串属于真值)会直接返回左侧表达式的值,不会计算右侧。所以你写的('among us' or 'impostor')实际返回的只有'among us',逻辑等价于只判断消息里有没有'among us',完全不会触发'impostor'的匹配。

正确实现方式

方法1:直接拆分判断(适合关键词少的场景)

直接把两个匹配逻辑用or连接即可:

if 'among us' in message.content or 'impostor' in message.content:
    await message.channel.send('Do I see an Among Us reference?')

方法2:用any()函数批量匹配(适合关键词多、需要灵活扩展的场景)

把所有要匹配的关键词放到一个列表里,配合生成器表达式做批量判断,后续新增关键词只需修改列表即可:

# 可随意扩展关键词列表
match_keywords = ['among us', 'impostor']
if any(keyword in message.content for keyword in match_keywords):
    await message.channel.send('Do I see an Among Us reference?')

如果需要实现大小写不敏感的匹配(比如匹配AMONG US、Impostor这类大小写混合的内容),可以把消息内容统一转为小写再判断:

match_keywords = ['among us', 'impostor']
if any(keyword in message.content.lower() for keyword in match_keywords):
    await message.channel.send('Do I see an Among Us reference?')

内容的提问来源于stack exchange,提问作者Jarek Marczewski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 00:27:05