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
+1 -1
View File
@@ -50,7 +50,7 @@ RUN set -eux; \
apt-get install -y --no-install-recommends \ apt-get install -y --no-install-recommends \
build-essential pkg-config default-libmysqlclient-dev git \ build-essential pkg-config default-libmysqlclient-dev git \
libgl1 libglib2.0-0 libsm6 libxext6 libxrender1 libxcb1 libgomp1 \ libgl1 libglib2.0-0 libsm6 libxext6 libxrender1 libxcb1 libgomp1 \
tzdata nodejs npm; \ tzdata nodejs npm fonts-wqy-zenhei; \
rm -rf /var/lib/apt/lists/* rm -rf /var/lib/apt/lists/*
WORKDIR /app WORKDIR /app
+16
View File
@@ -189,6 +189,22 @@ SETTING_SPECS: List[SettingSpec] = [
minimum=1, minimum=1,
maximum=8, 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( SettingSpec(
name="enable_ip_proxy", name="enable_ip_proxy",
scope=SCOPE_PLATFORM, 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. and swallowed.
""" """
import base64
import hashlib
import json import json
from typing import Optional from typing import Optional
@@ -97,6 +99,49 @@ async def send_wecom(webhook_url: str, content: str) -> tuple[bool, str]:
return True, "发送成功" 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: async def get_webhook_url(session: AsyncSession) -> str:
from .models import SETTING_WECOM_WEBHOOK from .models import SETTING_WECOM_WEBHOOK
+68 -1
View File
@@ -59,7 +59,7 @@ from .models import (
MonitorTask, MonitorTask,
) )
from .runner import execute_task 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 POLL_INTERVAL_SECONDS = 20
# Spread tasks sharing an interval so they do not all come due on the same tick. # 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 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: async def reap_stale_runs() -> int:
"""把「早就该结束却还挂在 running」的 run 收掉,返回收了几个。 """把「早就该结束却还挂在 running」的 run 收掉,返回收了几个。
@@ -167,6 +181,11 @@ class MonitorScheduler:
await self._maybe_check_upstream() await self._maybe_check_upstream()
except Exception as exc: # pragma: no cover - keep the loop alive except Exception as exc: # pragma: no cover - keep the loop alive
print(f"[monitor.scheduler] upstream check failed: {exc}") 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) await asyncio.sleep(POLL_INTERVAL_SECONDS)
async def _maybe_check_upstream(self) -> None: async def _maybe_check_upstream(self) -> None:
@@ -204,6 +223,54 @@ class MonitorScheduler:
elif not result.get("ok"): elif not result.get("ok"):
print(f"[monitor.scheduler] 上游检查失败:{result.get('error')}") 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: async def recover(self) -> None:
"""Clean up state left behind by a server restart. """Clean up state left behind by a server restart.
+46 -1
View File
@@ -29,7 +29,17 @@ from tools.time_util import get_current_timestamp
from sqlalchemy import select from sqlalchemy import select
from ..monitor import covers, douyin_api, notify, qrlogin, report, service, tagrules, upstream from ..monitor import (
covers,
digest,
douyin_api,
notify,
qrlogin,
report,
service,
tagrules,
upstream,
)
from ..monitor import identities as identity_pool from ..monitor import identities as identity_pool
from ..monitor.db import get_session from ..monitor.db import get_session
from ..monitor.platforms import PLATFORM_XHS from ..monitor.platforms import PLATFORM_XHS
@@ -896,6 +906,41 @@ async def run_upstream_check():
return await upstream.run_check(notify_when_new=False) return await upstream.run_check(notify_when_new=False)
@router.get("/digest/preview")
async def preview_daily_digest(
platform: str = Query(default=PLATFORM_XHS),
day: Optional[str] = Query(default=None, description="YYYY-MM-DD,省略=今天"),
):
"""把「今天的视频情况」画出来直接返回图片,**不发消息**。
先看一眼图长什么样,再去开定时推送 —— 不必为了验证往群里发一条。
"""
try:
target = date.fromisoformat(day) if day else date.today()
except ValueError:
raise HTTPException(status_code=400, detail="日期格式应为 YYYY-MM-DD")
async with get_session() as session:
rows = await digest.daily_rows(session, platform, target)
label = "抖音" if platform == "dy" else "小红书"
image_bytes = digest.render_table(rows, target, label)
return Response(content=image_bytes, media_type="image/png")
@router.post("/digest/send")
async def send_daily_digest_now(platform: str = Query(default=PLATFORM_XHS)):
"""手动生成并发送「今天的视频情况」图。
定时那条由调度器按设置触发;这个端点存在的意义是**先看一眼图长什么样**,
以及确认 Webhook 通不通 —— 不要等到晚上十点才发现发不出去。
"""
async with get_session() as session:
ok, detail, count = await digest.send_daily_digest(session, platform)
if not ok:
raise HTTPException(status_code=502, detail=detail)
return {"ok": True, "rows": count, "detail": detail}
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# 身份池 # 身份池
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
+183
View File
@@ -0,0 +1,183 @@
# -*- coding: utf-8 -*-
"""每日「视频情况」图:取数、版式、发送前的大小闸门。"""
from datetime import date, datetime, timedelta
import pytest
import pytest_asyncio
from api.monitor import db as monitor_db
from api.monitor import digest
from api.monitor.models import (
MODE_CREATOR,
MonitorNote,
MonitorNoteMetric,
MonitorTask,
)
from tools.time_util import get_current_timestamp
MS_PER_DAY = 86_400_000
@pytest_asyncio.fixture
async def db(tmp_path):
monitor_db.set_sqlite_path(tmp_path / "digest.db")
await monitor_db.init_db()
yield monitor_db
await monitor_db.dispose_engine()
async def _task(platform: str = "dy", name: str = "图") -> int:
async with monitor_db.get_session() as session:
task = MonitorTask(
name=name,
platform=platform,
mode=MODE_CREATOR,
enabled=True,
interval_minutes=60,
max_notes_count=20,
enable_comments=False,
max_comments_count=10,
run_timeout_seconds=3600,
created_at=0,
updated_at=0,
)
session.add(task)
await session.flush()
return task.id
async def _note(task_id: int, note_id: str, name: str, published_at: int) -> None:
async with monitor_db.get_session() as session:
session.add(
MonitorNote(
task_id=task_id,
note_id=note_id,
title=f"标题-{note_id}",
hashtags="",
note_url="",
cover="",
creator_hash="hash-a",
creator_name=name,
source_kind="video",
published_at=published_at,
first_seen_at=published_at,
last_seen_at=published_at,
)
)
async def _metric(task_id: int, note_id: str, run_id: int, liked: int | None) -> None:
async with monitor_db.get_session() as session:
session.add(
MonitorNoteMetric(
task_id=task_id,
note_id=note_id,
run_id=run_id,
captured_at=run_id,
liked_count=liked,
comment_count=liked,
collected_count=liked,
share_count=liked,
)
)
@pytest.mark.asyncio
async def test_only_todays_notes_are_listed(db):
task_id = await _task()
now = get_current_timestamp()
await _note(task_id, "today", "今天", now - 1000)
await _note(task_id, "yesterday", "昨天", now - MS_PER_DAY)
async with monitor_db.get_session() as session:
rows = await digest.daily_rows(session, "dy")
assert [row["note_id"] for row in rows] == ["today"]
@pytest.mark.asyncio
async def test_latest_metric_wins_and_rows_sort_by_likes(db):
task_id = await _task()
now = get_current_timestamp()
await _note(task_id, "a", "博主A", now - 1000)
await _note(task_id, "b", "博主B", now - 2000)
await _metric(task_id, "a", run_id=1, liked=5)
await _metric(task_id, "a", run_id=2, liked=99)
await _metric(task_id, "b", run_id=1, liked=500)
async with monitor_db.get_session() as session:
rows = await digest.daily_rows(session, "dy")
assert [row["note_id"] for row in rows] == ["b", "a"] # 点赞降序
assert rows[1]["likes"] == 99 # 取最近一轮,不是先写进去的那轮
@pytest.mark.asyncio
async def test_the_same_note_under_two_tasks_is_listed_once(db):
first = await _task(name="一")
second = await _task(name="二")
now = get_current_timestamp()
await _note(first, "same", "博主A", now - 1000)
await _note(second, "same", "博主A", now - 1000)
async with monitor_db.get_session() as session:
rows = await digest.daily_rows(session, "dy")
assert len(rows) == 1
def _time_reached(send_at: str, now: datetime) -> bool:
from api.monitor.scheduler import _time_reached as reached
return reached(now, send_at)
def test_time_reached_handles_bad_config():
now = datetime(2026, 10, 23, 21, 30)
assert _time_reached("21:00", now) is True
assert _time_reached("22:00", now) is False
# 写错就按 22:00 算,而不是永远不发
assert _time_reached("十点半", datetime(2026, 10, 23, 22, 1)) is True
assert _time_reached("", datetime(2026, 10, 23, 21, 0)) is False
@pytest.mark.skipif(digest._font_path() is None, reason="本机没有中文字体")
def test_render_table_returns_a_png():
rows = [
{
"note_id": "1",
"creator": "博主A",
"title": "一条标题",
"hashtags": "",
"likes": 12,
"comments": 3,
"collected": 4,
"shares": 5,
}
]
image = digest.render_table(rows, date.today(), "抖音")
assert image.startswith(b"\x89PNG")
assert len(image) > 1000
@pytest.mark.skipif(digest._font_path() is None, reason="本机没有中文字体")
def test_render_table_handles_an_empty_day():
image = digest.render_table([], date.today(), "抖音")
assert image.startswith(b"\x89PNG")
@pytest.mark.asyncio
async def test_image_sender_guards_missing_webhook_and_oversize():
from api.monitor import notify
ok, detail = await notify.send_wecom_image("", b"x")
assert ok is False and "未配置" in detail
ok, detail = await notify.send_wecom_image(
"http://example.invalid", b"x" * (notify.WECOM_IMAGE_MAX_BYTES + 1)
)
assert ok is False and "太大" in detail
+36 -4
View File
@@ -1,9 +1,17 @@
import { useState } from 'react' import { useState } from 'react'
import { Send, Trash2, Webhook } from 'lucide-react' import { Eye, Image, Send, Trash2, Webhook } from 'lucide-react'
import { Badge } from '@/components/ui/badge' import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { useClearWebhook, useSetWebhook, useTestWebhook, useWebhookStatus } from '@/hooks/useMonitor' import { monitorApi } from '@/lib/api'
import { useCurrentPlatform } from '@/hooks/usePlatform'
import {
useClearWebhook,
useSendDailyDigest,
useSetWebhook,
useTestWebhook,
useWebhookStatus,
} from '@/hooks/useMonitor'
/** /**
* 企业微信机器人 Webhook 配置。 * 企业微信机器人 Webhook 配置。
@@ -16,6 +24,8 @@ export function WebhookPanel() {
const setWebhook = useSetWebhook() const setWebhook = useSetWebhook()
const clearWebhook = useClearWebhook() const clearWebhook = useClearWebhook()
const testWebhook = useTestWebhook() const testWebhook = useTestWebhook()
const sendDigest = useSendDailyDigest()
const { platform } = useCurrentPlatform()
const [draft, setDraft] = useState('') const [draft, setDraft] = useState('')
const [editing, setEditing] = useState(false) const [editing, setEditing] = useState(false)
@@ -41,8 +51,29 @@ export function WebhookPanel() {
)} )}
</div> </div>
{status?.configured && (
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
{/* 预览不依赖 Webhook —— 先看图长什么样,再决定要不要开推送。 */}
<Button
variant="outline"
size="sm"
onClick={() =>
window.open(monitorApi.dailyDigestPreviewUrl(platform), '_blank', 'noopener')
}
>
<Eye className="w-3 h-3 mr-1" />
预览今天
</Button>
{status?.configured && (
<>
<Button
variant="outline"
size="sm"
onClick={() => sendDigest.mutate()}
disabled={sendDigest.isPending}
>
<Image className="w-3 h-3 mr-1" />
发今天图
</Button>
<Button <Button
variant="outline" variant="outline"
size="sm" size="sm"
@@ -65,9 +96,10 @@ export function WebhookPanel() {
> >
<Trash2 className="w-3 h-3" /> <Trash2 className="w-3 h-3" />
</Button> </Button>
</div> </>
)} )}
</div> </div>
</div>
{status?.configured && !editing && ( {status?.configured && !editing && (
<p className="text-[11px] font-mono text-cyber-text-secondary break-all"> <p className="text-[11px] font-mono text-cyber-text-secondary break-all">
+11
View File
@@ -427,6 +427,17 @@ export function useTestWebhook() {
}) })
} }
/** 手动推一次「今天的视频情况」图。定时那条由后端调度器负责。 */
export function useSendDailyDigest() {
const platform = usePlatformParam()
return useMutation({
mutationFn: async () => (await monitorApi.sendDailyDigest(platform)).data,
onSuccess: (result) =>
toast.success(`已发送今天的视频情况图(${result.rows} 条),请查看企业微信群`),
onError: (error: Error) => toast.error(`发送失败:${error.message}`),
})
}
// --- 博主备注 -------------------------------------------------------------- // --- 博主备注 --------------------------------------------------------------
export function useSetCreatorAlias() { export function useSetCreatorAlias() {
+8
View File
@@ -308,6 +308,14 @@ export const monitorApi = {
api.get<LoginState>('/monitor/login/state', { params: { force } }), api.get<LoginState>('/monitor/login/state', { params: { force } }),
getWebhook: () => api.get<WebhookStatus>('/monitor/webhook'), getWebhook: () => api.get<WebhookStatus>('/monitor/webhook'),
/** 当天视频情况图:手动发一次(定时那条由后端按设置触发)。 */
sendDailyDigest: (platform?: string) =>
api.post<{ ok: boolean; rows: number; detail: string }>('/monitor/digest/send', null, {
params: { platform },
}),
/** 预览图 —— 直接给 <img>/window.open 用,不带 Authorization 头,靠 cookie。 */
dailyDigestPreviewUrl: (platform?: string) =>
`/api/monitor/digest/preview${platform ? `?platform=${platform}` : ''}`,
setWebhook: (url: string) => api.post('/monitor/webhook', { url }), setWebhook: (url: string) => api.post('/monitor/webhook', { url }),
clearWebhook: () => api.delete('/monitor/webhook'), clearWebhook: () => api.delete('/monitor/webhook'),
testWebhook: (url?: string) => api.post('/monitor/webhook/test', { url: url ?? null }), testWebhook: (url?: string) => api.post('/monitor/webhook/test', { url: url ?? null }),