gpt4 book ai didi

discord.py - 在discord.py中实现免费字典Api时出错

转载 作者:行者123 更新时间:2023-12-04 07:14:08 26 4
gpt4 key购买 nike

我正在尝试实现这个 api,但代码每次都说错误。
到目前为止我的代码:

@client.command()
async def mean(ctx,word):
response = requests.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}")
if response.status_code == 404:
await ctx.send("No such word")
return
else:
wordx = response.json()
the_dictionary = wordx[0]
meanings = the_dictionary['meanings']
definitions = meanings[0]
definition = definitions['definitions']
meaningg = definition[0]
meaning = meaningg['definition']
example = meaningg.get('example',['None'])
synonymslist = meaningg.get("synonyms",['None'])
if isinstance(synonymslist,str):
synonymslist = [synonymslist]
pass
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.channel.send(embed = deffinal)
这是错误消息:
error message

最佳答案

您的错误不是来自对字典 api 的 API 调用,而是来自您对 discord api 的调用。
错误消息说 discord.errors.HTTPException: [...] In embed.fields.2.value: This field is required .
所以错误来自嵌入中的空字段!该字段具有索引 2所以实际上是第三个字段( Synonyms )导致了问题。
在添加字段之前,您可以简单地检查字符串是否为空。如果它是空的,就不要添加它。

deffinal= discord.Embed(title=f"`{word.upper()}`")
if meaning:
deffinal.add_field(name = "Definition", value=f"{meaning}")

if example:
deffinal.add_field(name = 'Example', value = f"{example}")

if synonyms:
deffinal.add_field(name = "Synonyms", value = f"{synonyms}")

@client.command()
async def mean(ctx,word):
response = requests.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}")
if response.status_code == 404:
await ctx.send("No such word")
return
else:
wordx = response.json()
the_dictionary = wordx[0]
meanings = the_dictionary['meanings']
definitions = meanings[0]
definition = definitions['definitions']
meaningg = definition[0]
meaning = meaningg['definition']
example = meaningg.get('example',['None'])
synonymslist = meaningg.get("synonyms",['None'])
if isinstance(synonymslist,str):
synonymslist = [synonymslist]
pass
synonyms = ','.join(synonymslist)

deffinal= discord.Embed(title=f"`{word.upper()}`")
if meaning:
deffinal.add_field(name = "Definition", value=f"{meaning}")

if example:
deffinal.add_field(name = 'Example', value = f"{example}")

if synonyms:
deffinal.add_field(name = "Synonyms", value = f"{synonyms}")

await ctx.channel.send(embed = deffinal)

关于discord.py - 在discord.py中实现免费字典Api时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68888133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com