forked from reactiflux/reactibot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
279 lines (242 loc) · 7.75 KB
/
index.ts
File metadata and controls
279 lines (242 loc) · 7.75 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import "dotenv/config";
import {
Client,
Message,
MessageReaction,
User,
PartialMessageReaction,
PartialUser,
Partials,
ActivityType,
IntentsBitField,
} from "discord.js";
import { logger, channelLog } from "./features/log.js";
// import codeblock from './features/codeblock';
import jobsMod, { resetJobCacheCommand } from "./features/jobs-moderation.js";
import { resumeResources } from "./features/resume.js";
import { lookingForGroup } from "./features/looking-for-group.js";
import autoban from "./features/autoban.js";
import commands from "./features/commands.js";
import setupStats from "./features/stats.js";
import emojiMod from "./features/emojiMod.js";
import promotionThread from "./features/promotion-threads.js";
import autothread, { cleanupThreads } from "./features/autothread.js";
import voiceActivity from "./features/voice-activity.js";
import type { ChannelHandlers } from "./types/index.js";
import { scheduleMessages } from "./features/scheduled-messages.js";
import tsPlaygroundLinkShortener from "./features/tsplay.js";
import xCancelGenerator from "./features/x-cancel-generator.js";
import { CHANNELS, initCachedChannels } from "./constants/channels.js";
import { scheduleTask } from "./helpers/schedule.js";
import { discordToken, isProd } from "./helpers/env.js";
import { registerCommand, deployCommands } from "./helpers/deploy-commands.js";
import resumeReviewPdf from "./features/resume-review.js";
import troll from "./features/troll.js";
import { modActivity } from "./features/mod-activity.js";
import {
debugEventButtonHandler,
debugEvents,
} from "./features/debug-events.js";
import { recommendBookCommand } from "./features/book-list.js";
import { mdnSearch } from "./features/mdn.js";
import "./server.js";
import { jobScanner } from "./features/job-scanner.js";
import { messageDuplicateChecker } from "./features/duplicate-scanner/duplicate-scanner.js";
import { getMessage } from "./helpers/discord.js";
export const bot = new Client({
intents: [
IntentsBitField.Flags.Guilds,
IntentsBitField.Flags.GuildMembers,
IntentsBitField.Flags.GuildEmojisAndStickers,
IntentsBitField.Flags.GuildMessages,
IntentsBitField.Flags.GuildMessageReactions,
IntentsBitField.Flags.GuildVoiceStates,
IntentsBitField.Flags.DirectMessages,
IntentsBitField.Flags.DirectMessageReactions,
IntentsBitField.Flags.MessageContent,
],
partials: [Partials.Channel, Partials.Reaction, Partials.GuildMember],
});
registerCommand(resetJobCacheCommand);
registerCommand(recommendBookCommand);
registerCommand(mdnSearch);
if (!isProd()) {
registerCommand(debugEvents);
}
logger.log("INI", "Bootstrap starting…");
bot
.login(discordToken)
.then(async () => {
logger.log("INI", "Bootstrap complete");
bot.user?.setActivity("DMs for !commands", { type: ActivityType.Watching });
scheduleMessages(bot);
try {
const guilds = await bot.guilds.fetch();
guilds.each((guild) =>
logger.log("INI", `Bot connected to Discord server: ${guild.name}`),
);
} catch (error) {
console.log("Something went wrong when fetching the guilds: ", error);
}
if (bot.application) {
const { id } = bot.application;
console.log("Bot started. If necessary, add it to your test server:");
console.log(
`https://discord.com/api/oauth2/authorize?client_id=${id}&permissions=8&scope=applications.commands%20bot`,
);
}
})
.catch((e) => {
console.log({ e });
console.log(
`Failed to log into discord bot. Make sure \`.env.local\` has a discord token. Tried to use '${discordToken}'`,
);
console.log(
'You can get a new discord token at https://discord.com/developers/applications, selecting your bot (or making a new one), navigating to "Bot", and clicking "Copy" under "Click to reveal token"',
);
process.exit(1);
});
export type ChannelHandlersById = {
[channelId: string]: ChannelHandlers[];
};
const channelHandlersById: ChannelHandlersById = {};
const addHandler = (
oneOrMoreChannels: string | string[],
oneOrMoreHandlers: ChannelHandlers | ChannelHandlers[],
) => {
const channels =
typeof oneOrMoreChannels === "string"
? [oneOrMoreChannels]
: [...new Set(oneOrMoreChannels)];
const handlers =
oneOrMoreHandlers instanceof Array
? oneOrMoreHandlers
: [oneOrMoreHandlers];
channels.forEach((channelId) => {
const existingHandlers = channelHandlersById[channelId];
if (existingHandlers) {
// Create a new array to avoid mutating the existing one
channelHandlersById[channelId] = [...existingHandlers, ...handlers];
} else {
channelHandlersById[channelId] = [...handlers];
}
});
};
const handleMessage = async (message: Message) => {
if (message.system) {
return;
}
const msg = await getMessage(message);
if (!msg) {
return;
}
const channel = msg.channel;
const channelId = channel.isThread()
? channel.parentId || channel.id
: channel.id;
if (channelHandlersById[channelId]) {
channelHandlersById[channelId].forEach((channelHandlers) => {
channelHandlers.handleMessage?.({ msg, bot });
});
}
if (channelHandlersById["*"]) {
channelHandlersById["*"].forEach((channelHandlers) => {
channelHandlers.handleMessage?.({ msg, bot });
});
}
};
const handleReaction = (
reaction: MessageReaction | PartialMessageReaction,
user: User | PartialUser,
) => {
// if reaction is in a thread, use the parent channel ID
const { channel } = reaction.message;
const channelId = channel.isThread()
? channel.parentId || channel.id
: channel.id;
const handlers = channelHandlersById[channelId];
if (handlers) {
handlers.forEach((channelHandlers) => {
channelHandlers.handleReaction?.({ reaction, user, bot });
});
}
channelHandlersById["*"].forEach((channelHandlers) => {
channelHandlers.handleReaction?.({ reaction, user, bot });
});
};
initCachedChannels(bot);
logger.add({ id: "botLog", logger: channelLog(bot, CHANNELS.botLog) });
logger.add({ id: "modLog", logger: channelLog(bot, CHANNELS.modLog) });
// Amplitude metrics
setupStats(bot);
// common
addHandler("*", [
commands,
autoban,
emojiMod,
tsPlaygroundLinkShortener,
xCancelGenerator,
troll,
]);
addHandler(
[
CHANNELS.events,
CHANNELS.iBuiltThis,
CHANNELS.iWroteThis,
CHANNELS.techReadsAndNews,
CHANNELS.twitterFeed,
],
promotionThread,
);
addHandler(
[
CHANNELS.helpReact,
CHANNELS.helpJs,
CHANNELS.helpReactNative,
CHANNELS.helpStyling,
CHANNELS.helpBackend,
CHANNELS.generalReact,
CHANNELS.generalTech,
],
jobScanner,
);
const threadChannels: string[] = [];
addHandler(threadChannels, autothread);
addHandler(CHANNELS.resumeReview, resumeReviewPdf);
addHandler(
[CHANNELS.helpReact, CHANNELS.generalReact, CHANNELS.generalTech],
messageDuplicateChecker,
);
bot.on("ready", () => {
deployCommands(bot);
jobsMod(bot);
resumeResources(bot);
lookingForGroup(bot);
voiceActivity(bot);
modActivity(bot);
debugEventButtonHandler(bot);
scheduleTask("help thread cleanup", 1000 * 60 * 30, () => {
cleanupThreads(threadChannels, bot);
});
});
bot.on("messageReactionAdd", handleReaction);
bot.on("threadCreate", (thread) => {
thread.join();
});
bot.on("messageCreate", async (msg) => {
if (msg.author?.id === bot.user?.id) return;
if (msg.content.includes("🙂👍👍")) {
msg.channel.send("heya!");
}
handleMessage(msg);
});
const errorHandler = (error: unknown) => {
if (error instanceof Error) {
logger.log("ERROR", `${error.message} ${error.stack}`);
} else if (typeof error === "string") {
logger.log("ERROR", error);
}
};
bot.on("error", errorHandler);
process.on("uncaughtException", errorHandler);
process.on("unhandledRejection", errorHandler);