Discord机器人on_message事件致命令失效及短语匹配问题求助
Discord机器人命令修复与短语匹配实现
一、修复命令无法运行的问题
你的代码导致所有命令失效的核心原因是重写on_message事件后未调用await client.process_commands(message)——Discord.py 需要这个方法来触发已注册的命令,和你怀疑的map处理行无关。
修复后的基础代码:
@client.event async def on_message(message): if message.author == client.user: return # 必须先处理命令,避免阻塞命令执行 await client.process_commands(message) phrases = open("D:/code/code/DIscord bot/myFile.txt").readlines() phrases = list(map(lambda item: item.strip(), phrases)) if message.content in phrases: msg = 'REAL!' await message.reply(msg)
额外优化点:
- 避免每次收到消息都重复读取文件,建议在机器人启动时一次性读取并缓存短语:
# 全局缓存短语列表 phrases = [] @client.event async def on_ready(): global phrases # 用with语句自动管理文件资源,避免内存泄漏 with open("D:/code/code/DIscord bot/myFile.txt", "r", encoding="utf-8") as f: # 过滤空行,只保留有效短语 phrases = [line.strip() for line in f if line.strip()] @client.event async def on_message(message): if message.author == client.user: return await client.process_commands(message) if message.content in phrases: await message.reply('REAL!')
二、实现句子中匹配短语的功能
将精确匹配逻辑改为检查短语是否为消息内容的子串,还可以添加大小写忽略提升匹配灵活性:
@client.event async def on_message(message): if message.author == client.user: return await client.process_commands(message) # 统一转为小写,实现大小写不敏感匹配 msg_content = message.content.lower() for phrase in phrases: if phrase.lower() in msg_content: await message.reply('REAL!') break # 匹配到第一个短语后停止,避免重复回复
内容的提问来源于stack exchange,提问作者Isohel
相关产品推荐
相关产品推荐

