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
import { fetchJSON } from "https://esm.town/v/stevekrouse/fetchJSON?v=41";
import { redditNotifierState } from "https://esm.town/v/bnorick/redditNotifierState";
export async function redditAlertBackup({ lastRunAt }) {
let subreddit_matches = {};
for (const subreddit in redditNotifierState) {
console.log(`processing subreddit ${subreddit}`);
let state = redditNotifierState[subreddit];
let last = state.last;
let matches = [];
let data = await fetchJSON(
`https://www.reddit.com/r/${subreddit}/new/.json?before=${last}`
);
let new_posts = 0;
let count = data.data.dist;
while (count > 0) {
new_posts += count;
for (const post of data.data.children) {
let post_data = post.data;
for (const pattern_str of state.patterns) {
let pattern = RegExp(pattern_str, "gi");
if (
post_data.title.match(pattern) ||
post_data.selftext.match(pattern)
) {
matches.push({
url: post_data.url,
title: post_data.title,
pattern: pattern_str,
});
console.log(`found match ${post_data.url}`);
break;
}
}
}
last = data.data.children[0].data.name;
data = await fetchJSON(
`https://www.reddit.com/r/${subreddit}/new/.json?before=${last}`
);
count = data.data.dist;
}
console.log(`processed ${new_posts} posts`);
redditNotifierState[subreddit].last = last;
if (matches.length) {
subreddit_matches[subreddit] = matches;
}
}
let text = [];
let total_matches = 0;
let first = true;
for (let subreddit in subreddit_matches) {
if (!first) {
text.push("\n\n");
}
text.push(
`${subreddit}\nfound ${subreddit_matches[subreddit].length} matches\n`
);
for (let match of subreddit_matches[subreddit]) {
text.push(`${match.title}\n${match.url}\n`);
}
total_matches += subreddit_matches[subreddit].length;
first = false;
}
console.log(text.join("\n"));
if (text.length)
console.email(
text.join("\n"),
`Reddit Notifier (${total_matches} matches)`
);
}
👆 This is a val. Vals are TypeScript snippets of code, written in the browser and run on our servers. Create scheduled functions, email yourself, and persist small pieces of data — all from the browser.