discord.py - пытается получить изображения из imgur - PullRequest
0 голосов
/ 18 июня 2020
@bot.command()
async def album(ctx):
    r = requests.get(f'https://api.imgur.com/3/album/ADDTHISAFTER?client_id={imgur_key}').json()
    em = discord.Embed(title="Title")
    em.set_image(url=str(r[0]["link"]))
    try:
        await ctx.send(embed=em)
    except:
        await ctx.send(str(r[0]["link"]))

Это код, который у меня есть.

Я пытаюсь подключиться к указанному c альбому и получить случайное изображение изнутри. На данный момент я даже не могу заставить его подключиться к чертовому альбому.

Размещение ссылки прямо в браузере дает следующий результат от API:

{"data":[{"id":"Vb89pCO","title":null,"description":null,"datetime":1586816920,"type":"image\/png","animated":false,"width":1920,"height":1080,"size":3073384,"views":214,"bandwidth":657704176,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":null,"is_ad":false,"in_most_viral":false,"has_sound":false,"tags":[],"ad_type":0,"ad_url":"","edited":"0","in_gallery":false,"deletehash":"bcSfUCo8qxv1Hvn","name":"image.png","link":"https:\/\/i.imgur.com\/Vb89pCO.png"},{"id":"JTXOKjK","title":null,"description":null,"datetime":1586816865,"type":"image\/png","animated":false,"width":1920,"height":1080,"size":1763552,"views":224,"bandwidth":395035648,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":null,"is_ad":false,"in_most_viral":false,"has_sound":false,"tags":[],"ad_type":0,"ad_url":"","edited":"0","in_gallery":false,"deletehash":"FtBYQpOrtkkWQHs","name":"image.png","link":"https:\/\/i.imgur.com\/JTXOKjK.png"},{"id":"392h92v","title":null,"description":null,"datetime":1586816875,"type":"image\/png","animated":false,"width":1920,"height":1080,"size":3857695,"views":214,"bandwidth":825546730,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":null,"is_ad":false,"in_most_viral":false,"has_sound":false,"tags":[],"ad_type":0,"ad_url":"","edited":"0","in_gallery":false,"deletehash":"k1dN3s99ctNjHFJ","name":"image.png","link":"https:\/\/i.imgur.com\/392h92v.png"},{"id":"gNWBnHy","title":null,"description":null,"datetime":1586816890,"type":"image\/png","animated":false,"width":1920,"height":1080,"size":4825975,"views":167,"bandwidth":805937825,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":null,"is_ad":false,"in_most_viral":false,"has_sound":false,"tags":[],"ad_type":0,"ad_url":"","edited":"0","in_gallery":false,"deletehash":"5pNW6XdSS8ozkvL","name":"image.png","link":"https:\/\/i.imgur.com\/gNWBnHy.png"},{"id":"ugAZxFQ","title":null,"description":null,"datetime":1586816907,"type":"image\/png","animated":false,"width":1920,"height":1080,"size":3106895,"views":132,"bandwidth":410110140,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":null,"is_ad":false,"in_most_viral":false,"has_sound":false,"tags":[],"ad_type":0,"ad_url":"","edited":"0","in_gallery":false,"deletehash":"hDNCb6PaKximuIR","name":"image.png","link":"https:\/\/i.imgur.com\/ugAZxFQ.png"}],"success":true,"status":200}

из которых важные биты, которые мне нужны, - это все ссылки, как в примере, показанном ниже:

"link":"https:\/\/i.imgur.com\/Vb89pCO.png"

Я хотел бы временно сохранить все ссылки на изображения из данного API в массиве и случайным образом выбрать ссылку, а затем вывести ее as am image to Discord, используя что-то вроде:

em = discord.Embed(title="Image")
em.set_image(url="IMAGEURLHERE")
await ctx.send(embed=em)

К сожалению, я продолжаю получать KeyError: 0 и не могу найти, что это означает в Интернете.

Заранее благодарим за любую помощь.

Ответы [ 2 ]

0 голосов
/ 18 июня 2020

Спасибо за вашу помощь! Теперь все готово и вычищено. Решение приведено ниже на тот случай, если кто-то застрянет и случайно наткнется на этот пост.

@bot.command()
async def album(ctx):
    r = requests.get(f"https://api.imgur.com/3/album/{album_id}/images?client_id={imgur_key}").json()
    em = discord.Embed(title="Album")
    indexmax = len(r['data']) - 1
    size = random.randrange(0, indexmax, 1)
    em.set_image(url=str(r['data'][size]['link']))
    try:
        await ctx.send(embed=em)
    except:
        await ctx.send(str(r['data'][size]['link']))

Вероятно, есть лучший способ сделать это, но он отлично подходит для меня :)

Еще раз спасибо за всю помощь!

0 голосов
/ 18 июня 2020

Ваша проблема заключается в следующем шаге:

str(r[0]["link"]))

# To show you what is happening:

d = {"list": "foo"}
d["list"]
>> foo
d[0]
>> KeyError: 0

Ответ представляет собой словарь, поэтому вы получаете KeyError, поскольку этот dict не имеет в качестве ключа 0.

На основе на этом:

{"data":[{"id":"Vb89pCO","title":null,"description":null,"datetime":1586816920,"type":"image\/png","animated":false,"width":1920,"height":1080,"size":3073384,"views":214,"bandwidth":657704176,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":null,"is_ad":false,"in_most_viral":false,"has_sound":false,"tags":[],"ad_type":0,"ad_url":"","edited":"0","in_gallery":false,"deletehash":"bcSfUCo8qxv1Hvn","name":"image.png","link":"https:\/\/i.imgur.com\/Vb89pCO.png"},{"id":"JTXOKjK","title":null,"description":null,"datetime":1586816865,"type":"image\/png","animated":false,"width":1920,"height":1080,"size":1763552,"views":224,"bandwidth":395035648,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":null,"is_ad":false,"in_most_viral":false,"has_sound":false,"tags":[],"ad_type":0,"ad_url":"","edited":"0","in_gallery":false,"deletehash":"FtBYQpOrtkkWQHs","name":"image.png","link":"https:\/\/i.imgur.com\/JTXOKjK.png"},{"id":"392h92v","title":null,"description":null,"datetime":1586816875,"type":"image\/png","animated":false,"width":1920,"height":1080,"size":3857695,"views":214,"bandwidth":825546730,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":null,"is_ad":false,"in_most_viral":false,"has_sound":false,"tags":[],"ad_type":0,"ad_url":"","edited":"0","in_gallery":false,"deletehash":"k1dN3s99ctNjHFJ","name":"image.png","link":"https:\/\/i.imgur.com\/392h92v.png"},{"id":"gNWBnHy","title":null,"description":null,"datetime":1586816890,"type":"image\/png","animated":false,"width":1920,"height":1080,"size":4825975,"views":167,"bandwidth":805937825,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":null,"is_ad":false,"in_most_viral":false,"has_sound":false,"tags":[],"ad_type":0,"ad_url":"","edited":"0","in_gallery":false,"deletehash":"5pNW6XdSS8ozkvL","name":"image.png","link":"https:\/\/i.imgur.com\/gNWBnHy.png"},{"id":"ugAZxFQ","title":null,"description":null,"datetime":1586816907,"type":"image\/png","animated":false,"width":1920,"height":1080,"size":3106895,"views":132,"bandwidth":410110140,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":null,"is_ad":false,"in_most_viral":false,"has_sound":false,"tags":[],"ad_type":0,"ad_url":"","edited":"0","in_gallery":false,"deletehash":"hDNCb6PaKximuIR","name":"image.png","link":"https:\/\/i.imgur.com\/ugAZxFQ.png"}],"success":true,"status":200}

Вам нужно изменить свой код на:

r["data"][0]["link"]
# Or perhaps more accurately

for row in r["data"]:
    do_something_with(row["link"])
...