Repository navigation
Expand file tree
/
Copy pathschedule.ts
More file actions
56 lines (53 loc) · 1.51 KB
/
Copy pathschedule.ts
File metadata and controls
56 lines (53 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import type { Bot } from "gramio";
import type Database from "better-sqlite3";
import type { ButtonInput } from "../types.js";
import {
createScheduledPost,
getDuePosts,
listUpcoming,
markScheduledPost,
} from "../db/client.js";
import { publishPost } from "./publish.js";
export function schedulePost(
db: Database.Database,
text: string,
buttons: ButtonInput[],
destinationChatIds: string[],
publishAt: Date
): number {
return createScheduledPost(
db,
text,
buttons,
destinationChatIds,
Math.floor(publishAt.getTime() / 1000)
);
}
export function getUpcomingSchedule(db: Database.Database) {
return listUpcoming(db);
}
/**
* Publishes every scheduled post whose time has arrived (doc section 15,
* "Scheduled Publishing"). Intended to be called on a recurring timer -
* see src/scheduler.ts.
*/
export async function runDueSchedules(bot: Bot, db: Database.Database) {
const due = getDuePosts(db);
for (const post of due) {
const buttons: ButtonInput[] = post.buttons_json ? JSON.parse(post.buttons_json) : [];
const destinations: string[] = JSON.parse(post.destinations);
try {
await publishPost(bot, db, {
label: `Scheduled #${post.id}`,
text: post.text,
buttons,
destinationChatIds: destinations,
});
markScheduledPost(db, post.id, "published");
} catch (err) {
console.error(`Failed to publish scheduled post ${post.id}:`, err);
markScheduledPost(db, post.id, "failed");
}
}
return due.length;
}