【问题标题】:How to embed images from MatPlotlib to Discord.py using Embed set_image without storing the image?如何使用 Embed set_image 将图像从 MatPlotlib 嵌入到 Discord.py 而不存储图像?
【发布时间】:2021-04-08 03:21:02
【问题描述】:

我正在通过 DiscordPy 创建一个机器人,当用户写 !unemployment 时,该机器人会向美国劳工统计局网站发出服务器调用,并收集最新失业人数的 JSON 文件。

@commands.command(name="unemployment")
async def unemployment(self, context):
    headers = {'Content-type': 'application/json'}
    data = json.dumps({"seriesid": ['LNS14000000']})
    url = "https://api.bls.gov/publicAPI/v2/timeseries/data/"
    # Async HTTP request
    async with aiohttp.ClientSession() as session:
        raw_response = await session.post(url, data=data, headers=headers)
        response = await raw_response.text()
        r = json.loads(response)

数据显示过去 24 个月的逐月数据。我使用 Pandas 将信息格式化为我喜欢的格式,然后将信息提供给 Matplotlib 以生成图表。

# Initialize IO
data_stream = io.BytesIO()

# Plot graph
plt.figure(figsize=(1,1))
ax = df.plot(x="period",y="value")
plt.gca().invert_xaxis()
ax.yaxis.set_major_formatter(mtick.PercentFormatter(1))
ax.get_legend().remove()

# Save content into the data stream
plt.savefig(data_stream, format='png', bbox_inches="tight", dpi = 80)
plt.close()

我按照此处的说明进行操作:Matplotlib graphic image to base64 将我的图形转换为 base64 图像,因为我不想将图像保存在服务器上,而是希望有一个 base64 字符串可以用来在飞,对记忆影响不大。但不幸的是,Discordpy 的embed.set_image() 值的格式为data:image/png;base64,<BASE64 code>

【问题讨论】:

    标签: matplotlib discord.py


    【解决方案1】:

    为了解决这个问题,我做了以下事情:

    1. 保存图像后,我使用 DiscordPy 的 File 类创建了一个文件,并为其指定了一个简单的名称。名字很重要!
    ## Create file
    # Reset point back to beginning of stream
    data_stream.seek(0)
    chart = discord.File(data_stream,filename="unemployment_chart.png")
    
    1. 使用set_image,使用attachment://协议添加文件
    embed.set_image(
       url="attachment://unemployment_chart.png"
    )
    
    1. 使用 Discordpy 发送文件时,请确保在发送调用中同时发送嵌入和文件。
    await context.send(embed=embed, file=chart)
    

    结果将是这样的:

    【讨论】:

      猜你喜欢
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      • 2018-07-09
      • 2019-08-09
      • 2020-12-22
      • 2019-09-29
      • 2012-03-26
      相关资源
      最近更新 更多