Search code examples
pythondiscord.pypixabay

Is there a way to get an image that you search using Pixabay and send it using discord.py?


I am using the Pixabay API to search for an image, then I want my discord.py bot to say it. However, I don't know what function you have to call to be able to get the image so the discord bot can actually send it in an embed. Here is my current code.

@bot.command(name='otter', help='Generates a random otter!')
async def otter(ctx):
    r = requests.get('https://pixabay.com/api/?key=keyisherebutforprivacyreasonsiamremovingitlol&q=otter&image_type=photo')
    r = r.json()
    for item in r['hits']:
        print(item['type'])
        embed = discord.Embed(title='Otter test', color=discord.Color.from_rgb(226, 22, 31))
        embed.set_image(url=item[random.choice(range(0, 5))]) # The problem is here, as I took the image bit away and the embed sent fine.
        embed.set_footer(text='Powered by pixabay.')


    await ctx.send(embed=embed)

Pretty much, it just prints out: photo over and over, which is good, because that means the search works. As a test, I removed the set image part, and the embed sent fine, so I know it is a problem with the embed.set_image. If anyone knows the correct way to actually get the image and send it, I would be really appreciative. Thanks! I get no error message in the console, either.


Solution

  • Make sure that you're grabbing the right content from the response (r). If you run into any 404 errors, you can check if the url contains image extensions (.jpg, .png, etc.).

    For future reference, to easily visualise jsons, you can use this website.

    Good luck with the otters!