Search code examples
pythondiscorddiscord.pygif

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


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 

Solution

  • IT IS POSSIBLE

    Here’s how ~

    We can fetch the gif and save it to the directory (will overwrite every time) with urllib.

    Then we simply post an image with the bot as usual. (Found my basis at GeeksforGeeks)

    Here is the final code:

    
    import os, discord, requests, json, urllib.request
    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':
            urllib.request.urlretrieve('https://radar.weather.gov/ridge/standard/CONUS_loop.gif', "rdr.gif")
            await message.channel.send(file=discord.File('rdr.gif'))
    @client.event
    async def ng(ctx):
      await ctx.send('Pong!')
    
    def start():
        client.run(DISCORD_TOKEN)