forked from base/node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrss.js
More file actions
86 lines (71 loc) · 2.18 KB
/
Copy pathrss.js
File metadata and controls
86 lines (71 loc) · 2.18 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const Parser = require("rss-parser");
const axios = require("axios");
const crypto = require("crypto");
const RSS_URL = process.env.RSS_BOT_URL;
const BOT_TOKEN = process.env.RSS_BOT_TG_BOT_TOKEN;
const CHANNEL_ID = process.env.RSS_BOT_TG_CHANNEL_ID;
// default to 15 mins
const POLL_INTERVAL = parseFloat(process.env.RSS_BOT_POLL_INTERVAL || "0.25") * 60 * 60 * 1000;
// skip if env not set
if (!process.env.RSS_BOT_TG_BOT_TOKEN || !process.env.RSS_BOT_TG_CHANNEL_ID || !process.env.RSS_BOT_URL) {
console.log("env vars are required, skipping rss-bot.");
process.exit(0);
}
const feedParser = new Parser();
// fetch start time is since 3 days ago
const StartTime = Date.now() - (3 * 24 * 60 * 60 * 1000)
// guid -> feed hash
const state = new Map();
/**
* @typedef {{
* title: string,
* link: string,
* pubDate: string,
* content: string,
* contentSnippet: string,
* guid: string,
* isoDate: string
* }} Feed Type definition for a feed object
*/
/**
* Posts to telegram
* @param {Feed} feed
*/
async function sendTelegram(feed) {
await axios.post(
`https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`,
{
chat_id: CHANNEL_ID,
text: `📰 *${feed.title}*\n*${feed.pubDate}*\n\n${feed.contentSnippet}\n\n${feed.link}`,
parse_mode: "markdown"
}
);
}
async function checkFeed() {
try {
const result = await feedParser.parseURL(RSS_URL);
/**
* @type {Array<Feed>}
*/
const feeds = [...result.items].reverse();
for (const feed of feeds) {
// skip if older than start time
const feedTime = Date.parse(feed.isoDate);
if (feedTime < StartTime) continue;
const feedHash = crypto
.createHash("sha256")
.update(feed.content ?? "" + feed.contentSnippet ?? "")
.digest("hex");
// skip if already exists in state
const prev = state.get(feed.guid);
if (prev) continue;
state.set(feed.guid, feedHash);
// post to telegram
await sendTelegram(feed).catch((e) => console.log("Telegram error:", e));
}
} catch (err) {
console.error("Feed error:", err.message);
}
}
checkFeed();
setInterval(checkFeed, POLL_INTERVAL);