Repository navigation
Expand file tree
/
Copy pathprofanity-filter.js
More file actions
232 lines (183 loc) · 6.02 KB
/
Copy pathprofanity-filter.js
File metadata and controls
232 lines (183 loc) · 6.02 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import { readFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { isScreaming, toSentenceCase } from './caps-filter.js';
import { canManageMessages, canUseWebhook, relayMessage } from './webhook-relay.js';
const WORDS_FILE = fileURLToPath(new URL('./swear-words.txt', import.meta.url));
// Backslash-escaped so Discord renders literal asterisks instead of markdown.
const CENSOR_MASK = '\\*\\*\\*\\*';
// Common endings so "shitty", "fucking", "assholes" etc. are caught by the
// base word alone.
const SUFFIXES = "(?:ings?|in'?|ers?|es|ed|s|y|ies|iest|ier)?";
// Cheap leet-speak coverage: "sh1t", "a$$", "fvck" style spellings.
const LEET = {
a: '[a4@]',
e: '[e3]',
i: '[i1!|]',
o: '[o0]',
s: '[s5$]',
t: '[t7]',
u: '[uv]',
};
let matcher = null;
let loadedWords = [];
function escapeRegExp(text) {
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function wordToPattern(word) {
let pattern = '';
for (const char of word) {
if (char === ' ') {
pattern += '\\s+';
continue;
}
// Allow stretched spellings such as "fuuuck".
pattern += `${LEET[char] ?? escapeRegExp(char)}+`;
}
return pattern;
}
export function buildMatcher(words) {
if (words.length === 0) {
return null;
}
const alternatives = [...words]
.sort((left, right) => right.length - left.length)
.map(wordToPattern)
.join('|');
// Whole-word matching, unicode aware, so "class" and "assess" are left alone.
return new RegExp(`(?<![\\p{L}\\p{N}_])(?:${alternatives})${SUFFIXES}(?![\\p{L}\\p{N}_])`, 'giu');
}
export function parseWordList(contents) {
const words = contents
.split(/\r?\n/)
.map((line) => line.replace(/#.*$/, '').trim().toLowerCase())
.filter(Boolean);
return [...new Set(words)];
}
export async function loadSwearWords() {
let contents;
try {
contents = await readFile(WORDS_FILE, 'utf8');
} catch (error) {
if (error.code === 'ENOENT') {
console.warn('No swear-words.txt found, swear word filter is disabled.');
} else {
console.error('Could not read swear-words.txt, swear word filter is disabled:', error.message);
}
matcher = null;
loadedWords = [];
return 0;
}
loadedWords = parseWordList(contents);
matcher = buildMatcher(loadedWords);
console.log(`Language filter loaded ${loadedWords.length} blacklisted words.`);
return loadedWords.length;
}
export function getSwearWords() {
return [...loadedWords];
}
// Returns the censored text and how many words were replaced.
export function censorText(text) {
if (!matcher || !text) {
return { text: text ?? '', count: 0 };
}
let count = 0;
const censored = text.replace(matcher, () => {
count += 1;
return CENSOR_MASK;
});
return { text: censored, count };
}
export function containsSwearWords(text) {
return censorText(text).count > 0;
}
function buildReminderMessage(message, { censoredCount, shouted }, correctedCopy) {
const problems = [];
const requests = [];
if (censoredCount > 0) {
problems.push(`had some offending word(s) that were replaced with ${CENSOR_MASK}`);
requests.push('Please keep the conversation civil and friendly.');
}
if (shouted) {
problems.push('was written in ALL CAPS, which reads as screaming, so it was changed to normal casing');
requests.push('Writing in all caps is not polite, please use normal casing.');
}
let reminder =
`Hi ${message.author.username}, your message in <#${message.channelId}> ${problems.join(' and ')}. ` +
`${requests.join(' ')} Thanks for understanding!`;
if (correctedCopy) {
reminder +=
`\n\nThe bot could not re-post a corrected copy in that channel, so your message was ` +
`removed. Feel free to post it again. Here is a corrected copy:\n` +
`>>> ${correctedCopy}`;
}
return reminder;
}
// Censors swear words and recases ALL CAPS screaming. Both fixes go into a
// single re-posted copy and a single DM.
export async function enforceLanguagePolicy(message) {
if (message.partial) {
message = await message.fetch();
}
if (!message.inGuild() || message.author?.bot || message.webhookId) {
return false;
}
const shouted = isScreaming(message.content);
const { text: censored, count: censoredCount } = censorText(
shouted ? toSentenceCase(message.content) : message.content,
);
if (censoredCount === 0 && !shouted) {
return false;
}
const botMember = message.guild.members.me;
if (!botMember || !canManageMessages(message.channel, botMember)) {
console.warn(
`Cannot correct message from ${message.author.tag}: missing Manage Messages in #${message.channel.name}.`,
);
return false;
}
let reposted = false;
if (canUseWebhook(message.channel, botMember)) {
try {
await relayMessage(message, message.channel, { content: censored });
reposted = true;
} catch (error) {
console.error(`Could not re-post corrected message from ${message.author.tag}:`, error.message);
}
} else {
console.warn(
`Cannot re-post corrected message in #${message.channel.name}: missing Manage Webhooks. Deleting instead.`,
);
}
try {
await message.delete();
} catch (error) {
console.error(`Could not delete message from ${message.author.tag}:`, error.message);
if (reposted) {
console.error('A corrected copy was already posted, the channel may now show both versions.');
}
return false;
}
try {
await message.author.send(
buildReminderMessage(
message,
{ censoredCount, shouted },
reposted ? null : censored.slice(0, 1500),
),
);
} catch (error) {
console.error(`Could not DM ${message.author.tag}:`, error.message);
}
const fixes = [];
if (censoredCount > 0) {
fixes.push(`censored ${censoredCount} word(s)`);
}
if (shouted) {
fixes.push('recased ALL CAPS');
}
console.log(
`Corrected a message from ${message.author.tag} in #${message.channel.name} (${fixes.join(', ')})` +
(reposted ? '' : ', deleted, no webhook access'),
);
return true;
}