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

如何获取Discord文本机器人字典参数中的匹配词?

Discord机器人重构:解决"unresolved reference 'word'"错误

你遇到的问题是因为any()函数仅返回布尔值,生成器表达式里的word是局部变量,在if语句的代码块中无法访问,因此会触发未定义引用错误。

修复方案

方法1:遍历字典匹配(直观易读)

直接遍历replace字典的键,检查每个词是否存在于消息内容中,找到匹配项后发送回复并终止循环:

@commands.Cog.listener()
async def on_message(self, message):
    content_lower = message.content.lower()
    for word in replace:
        if word in content_lower:
            await message.channel.send(replace[word]["answer"])
            break  # 找到第一个匹配后停止,避免重复发送回复

方法2:用next()获取首个匹配词

通过生成器结合next()快速提取第一个匹配的词,同时处理无匹配的边界情况:

@commands.Cog.listener()
async def on_message(self, message):
    content_lower = message.content.lower()
    # 找到第一个匹配词,无匹配则返回None
    matched_word = next((word for word in replace if word in content_lower), None)
    if matched_word:
        await message.channel.send(replace[matched_word]["answer"])

错误原因说明

原代码中的any(word in message.content.lower() for word in replace)仅做存在性判断,不会保存匹配到的具体word值。当你在await语句中引用word时,该变量在当前作用域并未定义,因此触发"unresolved reference"错误。

内容的提问来源于stack exchange,提问作者Malte Kube

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 09:03:21