You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord Bot执行!radar命令发送GIF时出现TypeError报错求助

解决Discord Bot发送GIF时的TypeError问题

问题重现

需求是当用户发送!radar命令时,Discord Bot发送指定URL的GIF图片,但运行代码时触发TypeError,错误信息如下:

TypeError: the JSON object must be str, bytes or bytearray, not Response

假设原错误代码如下:

import discord
import requests
from discord.ext import commands

bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())

@bot.command()
async def radar(ctx):
    response = requests.get("https://radar.weather.gov/ridge/standard/CONUS_0.gif")
    await ctx.send(json=response)

bot.run("YOUR_BOT_TOKEN")

错误原因

错误根源是ctx.send(json=response)这行代码:

  • json参数要求传入可序列化为JSON的Python对象,或者JSON格式的字符串/字节数组
  • 你直接传入了requests库返回的Response对象,该类型无法被解析为JSON,因此触发TypeError
  • 更关键的是:发送GIF图片不需要处理JSON,完全用错了参数和处理方式

修复方案

方案一:直接发送图片URL(最简实现)

Discord支持直接解析图片链接并显示,无需下载图片,直接发送URL即可:

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())

@bot.command()
async def radar(ctx):
    radar_url = "https://radar.weather.gov/ridge/standard/CONUS_0.gif"
    await ctx.send(radar_url)

bot.run("YOUR_BOT_TOKEN")

方案二:下载图片后以文件形式发送(适合需本地处理场景)

如果需要先下载图片(比如缓存、修改),可通过BytesIO包装图片内容,用discord.File发送:

import discord
import requests
from io import BytesIO
from discord.ext import commands

bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())

@bot.command()
async def radar(ctx):
    radar_url = "https://radar.weather.gov/ridge/standard/CONUS_0.gif"
    response = requests.get(radar_url)
    
    if response.status_code == 200:
        # 将图片内容转为可读取的文件对象
        img_file = discord.File(BytesIO(response.content), filename="radar.gif")
        await ctx.send(file=img_file)
    else:
        await ctx.send("获取雷达图失败,请稍后重试。")

bot.run("YOUR_BOT_TOKEN")

验证说明

两种方案都能实现!radar命令触发后发送目标GIF的需求,方案一更高效(无需下载),方案二更灵活(支持后续图片处理)。

内容的提问来源于stack exchange,提问作者Tyler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 22:02:15