Get a Gif File from URL and Send It via a Discord Bot

Question:

I cannot figure out how to get this to work (maybe I’m just bad at programming).

As the name suggests, I want to send an gif image with my Discord bot when I say “!radar”. The gif is located at https://radar.weather.gov/ridge/standard/CONUS_0.gif

Code

import os, discord, requests, json
from base64 import b64decode
from discord.ext import commands

DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")

client = commands.Bot(command_prefix="!", intents= discord.Intents.all())

@client.event
async def on_ready():
    print(f'We have logged in as {client.user}')

@client.event
async def on_message(message):
    print("message was: " + message.content)
    if message.author == client.user:
        return
    if message.content == '!radar':
        url = 'https://radar.weather.gov/ridge/standard/CONUS_0.gif'
        r = requests.get(url, allow_redirects=True)
        response_parsed = json.loads(r)
        thumbnail_bytes = b64decode(response_parsed['thumbnailBase64'])
        await message.channel.send(file=thumbnail_bytes)
@client.command()
async def ng(ctx):
  await ctx.send('Pong!')

def start():
    client.run(DISCORD_TOKEN)

Error

Traceback (most recent call last):
  File "/home/runner/StormyBot/venv/lib/python3.10 /site-packages/discord/client.py", tine 441, in _r un_event
    await coro(*args, **kwargs)
  File "/home/runner/StormyBot/bot.py", tine 21, i n on_message
    response_parsed = json.loads(r)
  File "inix/store/hd4cc9rh83j291r5539hkf6qd8lgiik b-python3-3.10.8/lib/python3.10/json/__init__.py", tine 339, 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 Response 
Asked By: Tyler

||

Answers:

With the line r = requests.get(url, allow_redirects=True) you are getting a Response object, not a JSON.

try response_parsed = json.loads(r.json()), it should solve the problem.

Answered By: alec_djinn

That URL doesn’t return JSON at all, it’s just a GIF (as the file extension suggests). You can’t parse/load it as JSON, and you can’t get its thumbnailBase64 field. Because it’s a GIF. And not a JSON file.

Answered By: stijndcl
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.