feat(digest): 每天把当天视频情况画成一张图推到企业微信
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s

运营要看的是「他们今天发了什么」,文字版在企业微信手机上没法对齐,
所以直接用 PIL 画成表:博主 / 标题 / 点赞 / 评论 / 收藏 / 分享,
按发布时间取当天,指标取最近一轮,按点赞降序。

- 播放量没进表:抖音对普通作品恒返回 0,摆一列 0 只会误导
- 定时按「今天发过没有」判断,进程重启也不会重复推
- 发送失败不写标记,下一拍继续重试
- 设置页有开关和时间;Webhook 面板加了「预览今天」和「发今天图」
- 容器需要中文字体,Dockerfile 装上 fonts-wqy-zenhei
This commit is contained in:
2026-10-23 08:24:19 +08:00
parent ae9af5e53f
commit 6ea8f24041
10 changed files with 738 additions and 30 deletions
+16
View File
@@ -189,6 +189,22 @@ SETTING_SPECS: List[SettingSpec] = [
minimum=1,
maximum=8,
),
SettingSpec(
name="daily_digest_enabled",
scope=SCOPE_PLATFORM,
type=TYPE_BOOL,
label="每天推送视频情况图",
help="到点后把当天发布的视频整理成一张表格图片,发到企业微信群(用的是上面的 Webhook)。",
default=False,
),
SettingSpec(
name="daily_digest_time",
scope=SCOPE_PLATFORM,
type=TYPE_STR,
label="推送时间",
help="24 小时制 HH:MM,例如 22:00。当天已发过就不会重复发。",
default="22:00",
),
SettingSpec(
name="enable_ip_proxy",
scope=SCOPE_PLATFORM,
+301
View File
@@ -0,0 +1,301 @@
# -*- coding: utf-8 -*-
"""「今天的视频情况」—— 生成一张表格图片,发到企业微信。
**为什么是图片而不是文字。** 企业微信的 markdown 在手机上不支持表格,用空格对齐的
文本会被挤成一团;运营要的是扫一眼今天各号的数据,所以直接画成图。
**为什么没有播放量。** 抖音的 `statistics.play_count` 对普通作品恒为 0(见
`platforms.py` 的说明),所以表里不摆这一列 —— 宁可少一列,也不要一整列 0。
"""
import io
from datetime import date, datetime
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence
from PIL import Image, ImageDraw, ImageFont
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from . import notify
from .models import MonitorNote, MonitorNoteMetric, MonitorTask
# 按出现顺序找第一个能用的。容器里装的是 wqy(见 Dockerfile);开发机上是微软雅黑。
FONT_CANDIDATES = (
"/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
"/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
"C:/Windows/Fonts/msyh.ttc",
"C:/Windows/Fonts/simhei.ttf",
)
# --- 版式 -------------------------------------------------------------------
WIDTH = 1080
MARGIN = 24
TITLE_FONT = 30
BODY_FONT = 19
SMALL_FONT = 16
HEADER_H = 40
ROW_H = 44
MAX_ROWS = 40 # 再多就只是一张长图,手机上一屏看不完;超出部分用文字交代
# 列:左边界 + 宽度。右边界 = MARGIN + sum(widths) = WIDTH - MARGIN
COLS = (
("博主", 24, 200, "left"),
("标题", 224, 530, "left"),
("点赞", 754, 80, "right"),
("评论", 834, 70, "right"),
("收藏", 904, 70, "right"),
("分享", 974, 82, "right"),
)
BG = (255, 255, 255)
INK = (15, 23, 42)
MUTED = (100, 116, 139)
LINE = (226, 232, 240)
HEAD_BG = (15, 23, 42)
HEAD_INK = (255, 255, 255)
ALT_BG = (248, 250, 252)
ACCENT = (14, 165, 233)
def _font_path() -> Optional[str]:
for candidate in FONT_CANDIDATES:
if Path(candidate).is_file():
return candidate
return None
def _font(size: int) -> ImageFont.FreeTypeFont:
path = _font_path()
if path is None:
raise RuntimeError(
"找不到中文字体,无法生成图片。容器需要 fonts-wqy-zenhei(见 Dockerfile)。"
)
try:
return ImageFont.truetype(path, size, index=0)
except OSError:
return ImageFont.truetype(path, size)
def _fit(draw: ImageDraw.ImageDraw, text: str, font, max_width: int) -> str:
"""超出列宽就截断并加省略号 —— 不能让文字压到下一列上。"""
if draw.textlength(text, font=font) <= max_width:
return text
trimmed = text
while trimmed and draw.textlength(trimmed + "…", font=font) > max_width:
trimmed = trimmed[:-1]
return trimmed + "…" if trimmed else "…"
def _number(value: Optional[int]) -> str:
if value is None:
return "—"
return f"{value:,}"
async def daily_rows(
session: AsyncSession, platform: str, day: Optional[date] = None
) -> List[Dict[str, Any]]:
"""当天发布的作品 + 各自最近一轮的指标,按点赞降序。
「当天」按**发布时间**算(不是首次采到):这张图回答的是「他们今天发了什么」。
"""
target_day = day or date.today()
start = int(datetime.combine(target_day, datetime.min.time()).timestamp() * 1000)
end = start + 86_400_000
task_ids = list(
await session.scalars(select(MonitorTask.id).where(MonitorTask.platform == platform))
)
if not task_ids:
return []
notes = (
await session.execute(
select(
MonitorNote.task_id,
MonitorNote.note_id,
MonitorNote.title,
MonitorNote.creator_name,
MonitorNote.hashtags,
MonitorNote.published_at,
)
.where(
MonitorNote.task_id.in_(task_ids),
MonitorNote.published_at.is_not(None),
MonitorNote.published_at >= start,
MonitorNote.published_at < end,
)
.order_by(MonitorNote.published_at.desc())
)
).all()
if not notes:
return []
note_ids = {row.note_id for row in notes}
metric_rows = (
await session.execute(
select(
MonitorNoteMetric.task_id,
MonitorNoteMetric.note_id,
MonitorNoteMetric.run_id,
MonitorNoteMetric.liked_count,
MonitorNoteMetric.comment_count,
MonitorNoteMetric.collected_count,
MonitorNoteMetric.share_count,
).where(
MonitorNoteMetric.task_id.in_(task_ids),
MonitorNoteMetric.note_id.in_(note_ids),
)
)
).all()
latest: Dict[tuple, Any] = {}
for metric in metric_rows:
key = (metric.task_id, metric.note_id)
current = latest.get(key)
if current is None or metric.run_id > current.run_id:
latest[key] = metric
rows: List[Dict[str, Any]] = []
seen: set = set()
for note in notes:
# 同一个作品挂在多个任务下时只算一次。
if note.note_id in seen:
continue
seen.add(note.note_id)
metric = latest.get((note.task_id, note.note_id))
rows.append(
{
"note_id": note.note_id,
"creator": note.creator_name or "",
"title": note.title or "",
"hashtags": note.hashtags or "",
"likes": metric.liked_count if metric else None,
"comments": metric.comment_count if metric else None,
"collected": metric.collected_count if metric else None,
"shares": metric.share_count if metric else None,
}
)
# 点赞降序,取不到指标的沉底 —— 图的最上面应该是最值得看的。
rows.sort(key=lambda item: (item["likes"] is None, -(item["likes"] or 0)))
return rows
def render_table(
rows: Sequence[Dict[str, Any]], day: date, platform_label: str = "抖音"
) -> bytes:
"""把当天的数据画成 PNG。没有数据也画一张 —— 「今天没发」本身就是要报的信息。"""
title_font = _font(TITLE_FONT)
body_font = _font(BODY_FONT)
small_font = _font(SMALL_FONT)
shown = list(rows[:MAX_ROWS])
overflow = max(0, len(rows) - len(shown))
head_height = 120
table_h = HEADER_H + ROW_H * len(shown) if shown else 120
footer_h = 56
height = head_height + table_h + footer_h
image = Image.new("RGB", (WIDTH, height), BG)
draw = ImageDraw.Draw(image)
# --- 标题 ---
draw.text(
(MARGIN, 26),
f"{platform_label} · {day.isoformat()} 视频情况",
font=title_font,
fill=INK,
)
if rows:
totals = {
"条数": len(rows),
"点赞": sum(row["likes"] or 0 for row in rows),
"评论": sum(row["comments"] or 0 for row in rows),
"收藏": sum(row["collected"] or 0 for row in rows),
"分享": sum(row["shares"] or 0 for row in rows),
}
summary = " · ".join(f"{key} {value:,}" for key, value in totals.items())
else:
summary = "今天没有新作品"
draw.text((MARGIN, 76), summary, font=small_font, fill=MUTED)
# --- 表头 ---
top = head_height
draw.rectangle((MARGIN, top, WIDTH - MARGIN, top + HEADER_H), fill=HEAD_BG)
for name, x, width, align in COLS:
if align == "right":
draw.text(
(x + width - 10, top + 10),
name,
font=small_font,
fill=HEAD_INK,
anchor="ra",
)
else:
draw.text((x + 6, top + 10), name, font=small_font, fill=HEAD_INK)
# --- 数据行 ---
y = top + HEADER_H
if not shown:
draw.text(
(WIDTH // 2, y + 34),
"今天没有新作品",
font=body_font,
fill=MUTED,
anchor="ma",
)
y += 100
for index, row in enumerate(shown):
if index % 2 == 1:
draw.rectangle((MARGIN, y, WIDTH - MARGIN, y + ROW_H), fill=ALT_BG)
draw.line((MARGIN, y + ROW_H, WIDTH - MARGIN, y + ROW_H), fill=LINE, width=1)
baseline = y + 12
for name, x, width, align in COLS:
if name == "博主":
text = _fit(draw, row["creator"] or "—", body_font, width - 10)
draw.text((x + 6, baseline), text, font=body_font, fill=INK)
elif name == "标题":
text = _fit(draw, row["title"] or "—", body_font, width - 10)
draw.text((x + 6, baseline), text, font=body_font, fill=INK)
else:
key = {"点赞": "likes", "评论": "comments", "收藏": "collected", "分享": "shares"}[name]
value = row[key]
draw.text(
(x + width - 10, baseline + 2),
_number(value),
font=small_font,
fill=INK if value else MUTED,
anchor="ra",
)
y += ROW_H
# --- 页脚 ---
footer = f"共 {len(rows)} 条"
if overflow:
footer += f",图中只列点赞最高的 {len(shown)} 条,另有 {overflow} 条未列出"
footer += " · 播放量抖音未提供,故未统计"
draw.text((MARGIN, y + 16), footer, font=small_font, fill=MUTED)
buffer = io.BytesIO()
image.save(buffer, format="PNG", optimize=True)
return buffer.getvalue()
async def send_daily_digest(
session: AsyncSession, platform: str, day: Optional[date] = None
) -> tuple[bool, str, int]:
"""生成并发送。返回 (ok, detail, 作品条数)。"""
target_day = day or date.today()
rows = await daily_rows(session, platform, target_day)
webhook = await notify.get_webhook_url(session)
if not webhook:
return False, "Webhook 未配置", len(rows)
label = "抖音" if platform == "dy" else "小红书"
image_bytes = render_table(rows, target_day, label)
ok, detail = await notify.send_wecom_image(webhook, image_bytes)
return ok, detail, len(rows)
+45
View File
@@ -27,6 +27,8 @@ Two rules shape this module:
and swallowed.
"""
import base64
import hashlib
import json
from typing import Optional
@@ -97,6 +99,49 @@ async def send_wecom(webhook_url: str, content: str) -> tuple[bool, str]:
return True, "发送成功"
# 企业微信图片消息的上限就是 2MB;超了会被直接拒掉,所以发送前先挡一道。
WECOM_IMAGE_MAX_BYTES = 2 * 1024 * 1024
async def send_wecom_image(webhook_url: str, image_bytes: bytes) -> tuple[bool, str]:
"""Post an image to a WeCom group robot.
WeCom wants the raw base64 **and** the MD5 of the original bytes (not of the
base64 string) -- getting that wrong produces a bare `errcode=40058` with no
hint about which field is wrong.
"""
if not webhook_url:
return False, "Webhook 未配置"
if not image_bytes:
return False, "图片内容为空"
if len(image_bytes) > WECOM_IMAGE_MAX_BYTES:
return False, f"图片太大({len(image_bytes)} 字节),企业微信上限 2MB"
payload = {
"msgtype": "image",
"image": {
"base64": base64.b64encode(image_bytes).decode("ascii"),
"md5": hashlib.md5(image_bytes).hexdigest(),
},
}
try:
async with httpx.AsyncClient(timeout=WEBHOOK_TIMEOUT_SECONDS) as client:
response = await client.post(webhook_url, json=payload)
response.raise_for_status()
body = response.json()
except httpx.HTTPError as exc:
return False, f"请求失败:{exc}"
except json.JSONDecodeError:
return False, "返回内容不是合法 JSON,请检查 Webhook 地址"
errcode = body.get("errcode")
if errcode != 0:
return False, f"企业微信返回 errcode={errcode} {body.get('errmsg', '')}"
return True, "发送成功"
async def get_webhook_url(session: AsyncSession) -> str:
from .models import SETTING_WECOM_WEBHOOK
+68 -1
View File
@@ -59,7 +59,7 @@ from .models import (
MonitorTask,
)
from .runner import execute_task
from .settings import get_cookie
from .settings import get_cookie, get_setting, platform_key, set_setting
POLL_INTERVAL_SECONDS = 20
# Spread tasks sharing an interval so they do not all come due on the same tick.
@@ -69,6 +69,20 @@ JITTER_SECONDS = 60
REAP_GRACE_SECONDS = 300
def _time_reached(now: datetime, send_at: str) -> bool:
"""``HH:MM`` 到了没有。
配置写错(空串、``"22"``、``"十点"``)时按 22:00 算 —— 一个手滑的配置不该让
推送永远发不出去。
"""
try:
hour_text, minute_text = send_at.split(":", 1)
target = (int(hour_text), int(minute_text))
except (AttributeError, ValueError):
target = (22, 0)
return (now.hour, now.minute) >= target
async def reap_stale_runs() -> int:
"""把「早就该结束却还挂在 running」的 run 收掉,返回收了几个。
@@ -167,6 +181,11 @@ class MonitorScheduler:
await self._maybe_check_upstream()
except Exception as exc: # pragma: no cover - keep the loop alive
print(f"[monitor.scheduler] upstream check failed: {exc}")
# 每日推送和采集、上游检查互不相干,各占一段 try。
try:
await self._maybe_send_digest()
except Exception as exc: # pragma: no cover - keep the loop alive
print(f"[monitor.scheduler] daily digest failed: {exc}")
await asyncio.sleep(POLL_INTERVAL_SECONDS)
async def _maybe_check_upstream(self) -> None:
@@ -204,6 +223,54 @@ class MonitorScheduler:
elif not result.get("ok"):
print(f"[monitor.scheduler] 上游检查失败:{result.get('error')}")
async def _maybe_send_digest(self) -> None:
"""到点推一张「今天的视频情况」图到企业微信。
每个平台独立配置。**按「今天发过没有」判断,而不是按「距上次多久」** ——
进程重启、tick 抖动都不会让它重复推。
"""
from . import adapters, digest
now = datetime.now()
today = now.strftime("%Y-%m-%d")
for platform in (adapters.PLATFORM_DY, adapters.PLATFORM_XHS):
async with get_session() as session:
if not await app_settings.get_value(
session, "daily_digest_enabled", platform, False
):
continue
send_at = str(
await app_settings.get_value(
session, "daily_digest_time", platform, "22:00"
)
).strip()
last_sent = await get_setting(
session, platform_key(platform, "daily_digest_last_sent")
)
if last_sent == today or not _time_reached(now, send_at):
continue
async with get_session() as session:
ok, detail, count = await digest.send_daily_digest(session, platform)
if ok:
async with get_session() as session:
await set_setting(
session, platform_key(platform, "daily_digest_last_sent"), today
)
print(
f"[monitor.scheduler] 已推送 {platform} 的视频情况图({count} 条)",
flush=True,
)
else:
# 不写 last_sent:下一拍还会重试,直到发出去为止。
print(
f"[monitor.scheduler] 视频情况图发送失败({platform}):{detail}",
flush=True,
)
async def recover(self) -> None:
"""Clean up state left behind by a server restart.