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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 04:30:46