目的
データをmatplotlibを使って可視化した後、その結果を定期的にTypetalkに送りたいと思ったので作りました。
ローカルに作成した画像を保存せずにそのまま送信する方法になります。
必要なライブラリ
作り方
import requests
import json
import matplotlib.pyplot as plt
import io
image_buffer = io.BytesIO()
plt.plot([1,2,3]) # 折れ線グラフを書く
plt.savefig(image_buffer, format='jpeg') # ここで書き出し
token = '<Typetalkのbotのトークンを取得して代入してください>'
topic_id = '<Typetalkの投稿するトピックIDを代入してください>'
# メッセージ送信用のURL
message_url = f"https://typetalk.com/api/v1/topics/{topic_id}?typetalkToken={token}"
# ファイルアップロード用のURL
upload_file_url = f'https://typetalk.com/api/v1/topics/{topic_id}/attachments?typetalkToken={token}'
files = {'file': ('line.jpeg', image_buffer.getvalue(), 'image/jpeg')}
upload_file_result = requests.post(upload_file_url, files=files)
# 実行の確認
print(upload_file_result.status_code)
print(upload_file_result.content)
fileKey = json.loads(upload_file_result.content)['fileKey']
message_result = requests.post(url_message, {'message': '今日の結果!', 'fileKeys[0]': fileKey})
# 実行の確認
print(message_result.status_code)
print(message_result.content)
実行結果

これで定期的なデータのモニタリングができる!