我尝试制作一个随机引用命令,但它不起作用?

时间:2021-05-19 16:46:16

标签: python discord discord.py

所以,我正在尝试创建一个命令,它会给出一个随机的动漫报价,这是代码:

@client.command()
async def animequote(ctx):
  response = requests.get("https://some-random-api.ml/animu/quote")
  data = response.json()
  jsontxt = json.loads(data)
  quote = jsontxt["sentence"]
  char = jsontxt["characther"]
  anime = jsontxt["anime"]
  embed = discord.Embed(title="Quote", description=f"{quote} - {char} from {anime}")
  await ctx.send(embed=embed)

当我运行代码并尝试命令时,它给了我这个错误:

Ignoring exception in command animequote:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 130, in animequote
    jsontxt = json.loads(data)
  File "/usr/lib/python3.8/json/__init__.py", line 341, in loads
    raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not dict

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: the JSON object must be str, bytes or bytearray, not dict

有谁知道这意味着什么或我如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您正在尝试从 dict 加载 dict 对象。因此,您需要从代码中删除 json.loads(data)

@client.command()
async def animequote(ctx):
    response = requests.get("https://some-random-api.ml/animu/quote")
    data = response.json()
    quote = data["sentence"]
    char = data["characther"]
    anime = data["anime"]
    embed = discord.Embed(
        title = "Quote",
        description = f"{quote} - {char} from {anime}"
    )
    await ctx.send(embed=embed)