Discord.py机器人开发报错TypeError:消息匹配词汇时提示'in'需要字符串左操作数而非列表的求助
解决Discord机器人匹配词汇时报错TypeError的问题
我来帮你排查下这个问题!你遇到的TypeError: 'in' requires string as left operand, not list错误,根源出在读取bruh.txt文件的逻辑上。
错误原因分析
你当前的代码里:
bruh_mo = [(line.strip()).split() for line in bruh_file]
这段代码会把文件里的每一行内容分割成一个列表(比如一行写了"hello world",就会变成["hello", "world"]),最终bruh_mo是一个嵌套列表(结构类似[[词1], [词2, 词3]])。
当你执行any(word in msg for word in bruh_mo)时,这里的word其实是一个个小列表,而Python无法判断“列表是否存在于字符串中”,所以直接抛出了类型错误。
修复方案
根据你的bruh.txt格式,分两种情况调整代码:
情况1:文件里每行一个触发词
如果你的bruh.txt是每行单独放一个词汇(比如每行只有一个要匹配的词),直接读取每行内容即可,不需要split():
# 用with语句自动管理文件,避免忘记关闭 with open("bruh.txt", "r") as bruh_file: # 过滤空行,同时去掉每行首尾的空白字符 bruh_mo = [line.strip() for line in bruh_file if line.strip()]
情况2:文件里一行包含多个触发词(空格分隔)
如果你的bruh.txt里一行有多个用空格分开的词汇,需要把所有词汇平铺成一维列表:
with open("bruh.txt", "r") as bruh_file: bruh_mo = [] for line in bruh_file: # 分割每行的词汇,添加到总列表中 words = line.strip().split() bruh_mo.extend(words) # 或者用更简洁的列表推导式写法: # bruh_mo = [word for line in bruh_file for word in line.strip().split()]
调整后的消息匹配逻辑
修复完bruh_mo的结构后,根据你的需求选择匹配方式:
- 如果要完全匹配用户发送的整条消息(比如用户发"bruh"才回复,发"bruh haha"不回复):
@client.event async def on_message(message): msg = message.content.strip() if message.author == client.user: return if msg in bruh_mo: await message.channel.send("bruh") - 如果要消息中包含任意触发词就回复(比如用户发"what's up bruh"也会触发):
@client.event async def on_message(message): msg = message.content if message.author == client.user: return if any(word in msg for word in bruh_mo): await message.channel.send("bruh")
内容的提问来源于stack exchange,提问作者vp cume
相关产品推荐
相关产品推荐

