python 从URL获取GIF文件并通过Discord Bot发送

wwodge7n  于 2023-03-28  发布在  Python
关注(0)|答案(3)|浏览(167)

我不知道如何让它工作(也许我只是不擅长编程)。
顾名思义,当我说“!radar”时,我想用我的Discord机器人发送一个gif图像。gif位于https://radar.weather.gov/ridge/standard/CONUS_0.gif

代码

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)

错误

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
6yjfywim

6yjfywim1#

对于r = requests.get(url, allow_redirects=True)行,您将获得Response object,而不是JSON。
试试response_parsed = json.loads(r.json()),应该能解决问题。

vof42yt1

vof42yt12#

该URL根本不返回JSON,它只是一个GIF(* 作为文件扩展名建议 *)。您无法将其解析/加载为JSON,也无法获取其thumbnailBase64字段。因为它是GIF。而不是JSON文件。

wydwbb8l

wydwbb8l3#

这是可能的
就是这样~
我们可以获取gif并将其保存到urllib目录(每次都会覆盖)。
然后,我们只需像往常一样使用bot发布一个图像。(在GeeksforGeeks找到了我的基础)
下面是最终代码:

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)

相关问题