删除从 API python 中提取的部分引用

Removing parts of a quote pulled from an API python

我正在开发一个不和谐的机器人,我决定制作一个引用命令,我正在使用这个引用 API:https://github.com/lukePeavey/quotable - and this is the link that the bot accesses: https://api.quotable.io/random.

机器人成功发送报价,这是它发送内容的示例:

{'_id': 'O_jlFdjUtHPT', 'tags': ['famous-quotes'], 'content': 'Every person, all the events of your life are there because you have drawn them there. What you choose to do with them is up to you.', 'author': 'Richard Bach', 'length': 132}

问题是,我想不出我会怎么做,所以它只包括引用和作者。

这是我发送上述内容的代码。

    @commands.command()
    async def quote(self, ctx):
        """fetches a random quote."""
        async with aiohttp.ClientSession() as session:
            async with session.get('https://api.quotable.io/random') as q:
                if q.status == 200:
                    js = await q.json()
                    await ctx.send(js)

我尝试将其更改为:

    @commands.command()
    async def quote(self, ctx):
        """fetches a random quote."""
        async with aiohttp.ClientSession() as session:
            async with session.get('https://api.quotable.io/random') as q:
                if q.status == 200:
                    js = await q.json()
                    await ctx.send(f'> {js.content}\n- {js.author}')

但这只是 returns 错误:

gnoring exception in command quote:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/Users/Goldilocks/Desktop/CodeStuff/b1nzyBotRepo/cogs/bettersimple.py", line 108, in quote
    await ctx.send(f'{js.content}\n-{js.author}')
AttributeError: 'dict' object has no attribute 'content'

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

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 903, in invoke
    await ctx.command.invoke(ctx)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 859, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/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: AttributeError: 'dict' object has no attribute 'content'

我在这里做错了什么,我应该改变什么来修复它?

如果我正确理解了您的意图,那么您将从 link 获取 JSON 数据,然后从中获取作者和内容。您的代码应该看起来像这样:

@commands.command()
async def quote(self, ctx):
"""fetches a random quote."""
async with aiohttp.ClientSession() as session:
    async with session.get('https://api.quotable.io/random') as quote_json:
        q = quote_json.json()  # Make sure to import json
    if q['status'] == 200:
        await ctx.send(f'{q["content"]}\n~ {q["author"]}')
    else:
        await ctx.send('An error occurred')

上面的代码所做的是从网站API获取信息,但是返回时,返回的是字符串,而不是JSON对象。然后我们使用 q = json.loads(quote_json)。确保你 import json 在顶部。在那之后,我们得到状态,如果它是 200,这是我们想要的,我们继续代码。否则,将发送一条错误消息。如果代码是 200,我们从 JSON 对象中得到 contentauthor,然后按以下形式发送:

This is the amazing quote received from the API.
~ IPSDSILVA#1849

从错误来看,q是一个字典。通过在方括号中指定相应的键而不是点来从字典中检索值。因此,要获取引用的内容,您必须这样做:q['content'],而不是 q.content。所以这将是理想的代码:

@commands.command()
    async def quote(self, ctx):
        """fetches a random quote."""
        async with aiohttp.ClientSession() as session:
            async with session.get('https://api.quotable.io/random') as q:
                if q['status'] == 200:
                    js = await q.json()
                    await ctx.send(f'> {js['content']}\n- {js['author']}')