-
Notifications
You must be signed in to change notification settings - Fork 0
/
spam.ts
74 lines (63 loc) · 1.66 KB
/
spam.ts
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
import { SpamEventKinds } from "./constant.ts";
import { nostr } from "./deps.ts";
export class SpamFilter {
words: Set<string[]> = new Set();
percent = 0.5;
timer = 0;
constructor(percent: number) {
this.percent = percent;
}
async start() {
await this.update();
this.timer = setInterval(() => this.update(), 60000);
}
async update() {
try {
const all = await Promise.all([this.xbol0Words(), this.nostrBandWords()]);
this.words.clear();
for (const i of all.flat()) {
this.words.add(i);
}
console.info(new Date(), "update words", this.words.size);
} catch {
//
}
}
filter(e: nostr.Event) {
if (!SpamEventKinds.has(e.kind)) return true;
for (const words of this.words) {
let count = 0;
for (const w of words) {
if (e.content.includes(w)) count++;
if (count / words.length >= this.percent) return false;
}
}
return true;
}
async nostrBandWords() {
try {
const res = await fetch(
"https://spam.nostr.band/spam_api?method=get_current_spam",
);
if (res.status !== 200) return [];
const json = await res.json();
return json.cluster_words.map((i: { words: string[] }) => i.words);
} catch {
return [];
}
}
async xbol0Words() {
try {
const res = await fetch(
"https://raw.githubusercontent.com/xbol0/nostr-spam-words/main/words.txt",
);
const list = (await res.text()).split("\n").filter((i) => !!i);
return list.map((i) => i.split(" ")).filter((i) => i.length > 1);
} catch {
return [];
}
}
stop() {
clearInterval(this.timer);
}
}