toot_bot/heatmap.py
Ching 062b12166e fix(heatmap): 使用绝对路径并去掉热力图月份和星期标签
- 文件路径改为基于 __file__ 的绝对路径,确保 cron 运行时正确保存
- 去掉 weekday_label 和 month_label 避免文字挤在一起

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 06:38:21 +00:00

101 lines
3.0 KiB
Python

import datetime
import logging
import matplotlib.pyplot as plt
import os
import pytz
import time
from mastodon import Mastodon
import july
# logging.basicConfig(filename='/home/captain/dev/log/heatmap.log', level=logging.INFO)
# logger = logging.getLogger('/home/captain/dev/log/heatmap.log')
banner_id = 108361439460735817
client = Mastodon(
access_token="Ug_bUMWCk3RLamOnqYIytmeB0nO6aNfjdmf06mAj2bE",
api_base_url="https://nofan.xyz",
)
base_dir = os.path.dirname(os.path.abspath(__file__))
fn = os.path.join(base_dir, "heatmap.txt")
# read from file if exists
date = []
data = []
if os.path.exists(fn):
with open(fn) as f:
data_list = f.read().splitlines()
f.close()
for data_ in data_list:
date_, count = data_.split(" ")
date.append(date_)
data.append(int(count))
me = client.me()
tl = client.account_statuses(me.id)
zh = pytz.timezone("Asia/Shanghai")
while tl:
print(tl[0].created_at)
break_flag = False
for status in tl:
date_ = status.created_at.astimezone(zh).date().strftime("%Y-%m-%d")
yesterday = datetime.datetime.now(
pytz.timezone("Asia/Shanghai")
).date() - datetime.timedelta(days=1)
# break if date is not yesterday
if date_ != yesterday.strftime("%Y-%m-%d"):
break_flag = True
break
if date_ not in date:
date.append(date_)
data.append(0)
data[date.index(date_)] += 1
if break_flag:
break
time.sleep(1)
tl = client.fetch_next(tl)
else:
# init
me = client.me()
tl = client.account_statuses(me.id)
zh = pytz.timezone("Asia/Shanghai")
while tl:
print(tl[0].created_at)
for status in tl:
date_ = status.created_at.astimezone(zh).date().strftime("%Y-%m-%d")
if date_ not in date:
date.append(date_)
data.append(0)
data[date.index(date_)] += 1
time.sleep(1)
tl = client.fetch_next(tl)
# write to file
with open(fn, "w") as f:
for i in range(len(date)):
f.write(date[i] + " " + str(data[i]) + "\n")
f.close()
cleaned_date, cleaned_data = july.utils.preprocess_inputs(date, data)
july.heatmap(cleaned_date, cleaned_data, cmap="BuGn", month_grid=False, weekday_label=False, month_label=False)
img_path = os.path.join(base_dir, "heatmap.png")
plt.savefig(img_path, bbox_inches="tight")
# upload image to mastodon
media = client.media_post(img_path)
headers = {}
headers["Authorization"] = "Bearer " + client.access_token
params = {"status": "今天浑浑噩噩了吗", "media_ids": [media.id]}
kwargs = dict(headers=headers, files={}, timeout=client.request_timeout, json=params)
url = client.api_base_url + "/api/v1/statuses/%s/" % banner_id
resp = client.session.request("PUT", url, **kwargs)
if resp.status_code == 200:
client.session.request(
"GET", "https://up.tunpok.com/api/push/qku6CYquGu?msg=OK&ping="
)