refactor: migrate TikTok polling from external cron to internal Next.js instrumentation interval

This commit is contained in:
2026-07-03 23:50:56 +07:00 Unverified
parent 46360826b6
commit d8437ae39a
4 changed files with 26 additions and 45 deletions
+59
View File
@@ -0,0 +1,59 @@
import { getRedisClient } from "@/lib/redis";
import { sendDiscordNotification } from "@/lib/discord";
import { getLatestTiktokVideo, getTiktokProfile } from "@/lib/followers/tiktok";
async function checkTiktokFeed() {
try {
const latestVideo = await getLatestTiktokVideo();
if (!latestVideo) return;
const redis = await getRedisClient();
const redisKey = "erika:tiktok_last_video_id";
const lastVideoId = await redis.get(redisKey);
if (lastVideoId === latestVideo.id) {
return; // Already notified
}
let officialAuthorName = "TikTok";
let officialAvatarUrl: string | undefined = undefined;
try {
const profile = await getTiktokProfile();
if (profile.displayName) officialAuthorName = profile.displayName;
if (profile.avatarUrl) officialAvatarUrl = profile.avatarUrl;
} catch (e) {
console.error("[TikTok Feed] Failed to fetch profile:", e);
}
const message = `ลงคลิปใหม่แล้วววสสสสส ${latestVideo.shareUrl}`;
const embed = {
title: latestVideo.title || "คลิปใหม่จาก TikTok",
url: latestVideo.shareUrl || undefined,
color: 0xff0050,
author: {
name: officialAuthorName,
url: latestVideo.shareUrl || "https://www.tiktok.com/",
icon_url: officialAvatarUrl || undefined
},
image: latestVideo.coverImageUrl ? { url: latestVideo.coverImageUrl } : undefined
};
await sendDiscordNotification(message, embed);
await redis.set(redisKey, latestVideo.id);
} catch (error) {
console.error("[TikTok Feed] Error processing:", error);
}
}
export function startTiktokFeedInterval() {
if (!(global as any).tiktokFeedIntervalStarted) {
(global as any).tiktokFeedIntervalStarted = true;
console.log("[TikTok Feed] Starting 5-minute interval check in background...");
// Run immediately on start
checkTiktokFeed();
// Then every 5 minutes
setInterval(checkTiktokFeed, 5 * 60 * 1000);
}
}
+1 -10
View File
@@ -1,12 +1,3 @@
/**
* Fetches TikTok follower count using the official TikTok API v2.
*
* Required env vars:
* - TIKTOK_CLIENT_KEY
* - TIKTOK_CLIENT_SECRET
* - TIKTOK_REFRESH_TOKEN (obtained via one-time OAuth flow at /api/auth/tiktok)
*/
let cachedAccessToken: string | null = null;
let tokenExpiresAt = 0;
@@ -143,4 +134,4 @@ export async function getLatestTiktokVideo(): Promise<TiktokVideo | null> {
console.error("[TikTok API] Error fetching latest video via TikWM:", e);
return null;
}
}
}