Adi*_*dib 0 matplotlib discord.py
我正在通过 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)
Run Code Online (Sandbox Code Playgroud)
该数据显示过去 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()
Run Code Online (Sandbox Code Playgroud)
我按照此处的说明进行操作:Matplotlib图形图像到base64将我的图形转换为base64图像,因为我不想将图像保存在服务器上,而是希望有一个可以用来动态构建图像的base64字符串并且对记忆力影响不大。但不幸的是 Discordpy 的embed.set_image()值采用data:image/png;base64,<BASE64 code>.
为了解决这个问题,我做了以下事情:
## Create file
# Reset point back to beginning of stream
data_stream.seek(0)
chart = discord.File(data_stream,filename="unemployment_chart.png")
Run Code Online (Sandbox Code Playgroud)
attachment://协议添加文件embed.set_image(
url="attachment://unemployment_chart.png"
)
Run Code Online (Sandbox Code Playgroud)
await context.send(embed=embed, file=chart)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3067 次 |
| 最近记录: |