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

discord.py接入免费词典API运行代码持续报错如何解决

问题修复方案

核心错误原因

  • example字段默认值设置错误:你在代码中写了example = meaningg.get('example',['None']),默认值是列表类型['None'],当词条无示例时,你把列表直接传入Discord Embed的字段值,而Embed要求所有字段值必须为字符串,这就是你截图报错的直接原因。
  • 同步请求阻塞风险:在discord.py的异步执行环境中直接使用同步requests库发送网络请求,会阻塞事件循环,导致机器人无响应,建议替换为异步请求库aiohttp。
  • 索引越界风险:代码直接硬取meanings[0]、definition[0],如果接口返回的词条无对应层级的数据,会触发索引越界报错,建议添加防御性判断。

修复后完整代码

首先安装依赖:
pip install aiohttp
然后替换你的命令代码为以下内容:

import aiohttp

@client.command()
async def mean(ctx, word):  
    async with aiohttp.ClientSession() as session:
        async with session.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}") as response:
            if response.status == 404:
                await ctx.send("No such word")
                return
            wordx = await response.json()
    
    the_dictionary = wordx[0]
    meanings = the_dictionary.get('meanings', [])
    if not meanings:
        await ctx.send("该单词暂无释义数据")
        return
    definitions = meanings[0].get('definitions', [])
    if not definitions:
        await ctx.send("该单词暂无释义数据")
        return
    meaningg = definitions[0]
    meaning = meaningg['definition']
    # 把默认值改为字符串,不要用列表
    example = meaningg.get('example', 'None')
    synonymslist = meaningg.get("synonyms", ['None'])
    if isinstance(synonymslist, str):
        synonymslist = [synonymslist]
    synonyms = ','.join(synonymslist)
    
    deffinal = discord.Embed(title=f"`{word.upper()}`")
    deffinal.add_field(name = "Definition", value=f"{meaning}")
    deffinal.add_field(name = 'Example', value = f"{example}")
    deffinal.add_field(name = "Synonyms", value = f"{synonyms}")
    await ctx.send(embed = deffinal)

验证方法

运行机器人后发送命令!mean test即可正常返回单词释义、示例和同义词。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:18:01