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
相关产品推荐
相关产品推荐

