-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
420 lines (344 loc) · 16.1 KB
/
index.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
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import { config } from 'dotenv';
// configure environment variables
config();
import './api';
import {
savePing,
startVoiceActivity,
endVoiceActivity,
terminateVoiceActivities,
addMessage,
markExpenditurePaid,
getVoiceChannelAuthor,
getStaffLeaderboardEntries,
createLeaderboardEntry,
deleteUnusedLeaderboardEntries,
assignVote
} from './db';
import { Client, MessageEmbed, TextChannel, VoiceChannel, WSEventType, CategoryChannel, Message, Snowflake, GuildMember, Intents } from 'discord.js';
import { SlashCreator, GatewayServer } from 'slash-create';
import { join } from 'path';
import { formatMessageActivityLeaderboard, formatScoreLeaderboard, formatVoiceActivityLeaderboard } from './leaderboards';
import PayPal from 'paypal-api';
import humanizeDuration from 'humanize-duration';
import { getUsers, updateUser } from './sequelize-user';
import { updateUserLastSeenAt } from './sequelize-presence';
import chalk from 'chalk';
const client = new Client({
intents: [Intents.FLAGS.DIRECT_MESSAGES, Intents.FLAGS.GUILD_VOICE_STATES, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_PRESENCES],
partials: ['MESSAGE', 'CHANNEL', 'REACTION', 'GUILD_MEMBER']
});
const paypal = new PayPal({
clientID: process.env.PAYPAL_CLIENT_ID!,
clientSecret: process.env.PAYPAL_CLIENT_SECRET!,
sandboxMode: process.env.PAYPAL_ACCOUNT_TYPE! === 'sandbox'
});
client.on('messageReactionAdd', async (reaction, user) => {
if (reaction.partial) await reaction.fetch();
if (user.id !== process.env.TRANSACTION_APPROVAL_USER_ID) return;
if (reaction.message.channel.id !== process.env.TRANSACTION_CHANNEL) return;
const embed = reaction.message.embeds[0];
if (!embed) return;
const transactionID = embed.fields.find((field) => field.name === 'Transaction ID')?.value!;
const userEmail = embed.fields.find((field) => field.name === 'User email')?.value!;
const productPrice = embed.fields.find((field) => field.name === 'Product price')?.value!;
const paymentStatus = embed.fields.find((field) => field.name === 'Status')?.value!;
if (!paymentStatus.includes('Processing')) return;
else {
reaction.remove();
const newEmbed = embed;
embed.fields = embed.fields.filter((f) => f.name !== 'Status');
embed.addField('Status', 'Completed ✅');
reaction.message.edit({ embeds: [newEmbed] });
markExpenditurePaid(transactionID)
}
});
const creator = new SlashCreator({
applicationID: process.env.APP_ID!,
token: process.env.TOKEN!
});
creator
.withServer(
new GatewayServer(
(handler) => client.ws.on('INTERACTION_CREATE' as WSEventType, handler)
)
)
.registerCommandsIn(join(__dirname, 'commands'))
.syncCommandsIn(process.env.GUILD_ID!);
setInterval(() => savePing(), 5000);
const updateActivityLeaderboard = async () => {
const activityLeaderboardChannel = client.channels.cache.get(process.env.LEADERBOARD_ACTIVITY_ID!) as TextChannel;
const messages = await activityLeaderboardChannel.messages.fetch();
const infoMessageContent = '**Leaderboards are updated every 10 seconds!**';
const infoMessage = messages.find((message) => message.content.includes(infoMessageContent));
if (!infoMessage) await activityLeaderboardChannel.send(infoMessageContent).then((m) => m.edit(`@everyone\n\n${m.content}`));
const voiceEmbedFooter = 'Join a voice channel to appear in the leaderboard!';
const voiceActivityEmbed = messages.find((message) => message.embeds[0]?.footer?.text === voiceEmbedFooter);
const messageEmbedFooter = 'Send some messages to appear in the leaderboard!';
const messageActivityEmbed = messages.find((message) => message.embeds[0]?.footer?.text === messageEmbedFooter);
const formattedVoiceActivityLeaderboard = await formatVoiceActivityLeaderboard(client);
const newVoiceEmbed = new MessageEmbed()
.setTitle('🔊 Voice activity leaderboard 🏆')
.addField('Top 10 (7 days)', '\u200B\n'+formattedVoiceActivityLeaderboard.map((entry, idx) => `#${++idx} **${entry.user.username}** - Time: **${entry.time}**`).join('\n'))
.setFooter(voiceEmbedFooter)
.setColor('#FF0000');
const formattedMessageActivityLeaderboard = await formatMessageActivityLeaderboard(client);
const newMessageEmbed = new MessageEmbed()
.setTitle('📨 Message activity leaderboard 🏆')
.addField('Top 10 (7 days)', '\u200B\n'+formattedMessageActivityLeaderboard.map((entry, idx) => `#${++idx} **${entry.user.username}** - Messages: **${entry.count}**`).join('\n'))
.setFooter(messageEmbedFooter)
.setColor('#FF0000');
if (!voiceActivityEmbed) activityLeaderboardChannel.send({ embeds: [newVoiceEmbed] });
else voiceActivityEmbed.edit({ embeds: [newVoiceEmbed] });
if (!messageActivityEmbed) activityLeaderboardChannel.send({ embeds: [newMessageEmbed] });
else messageActivityEmbed.edit({ embeds: [newMessageEmbed] });
};
export const updateWinsLeaderboard = async () => {
const scoreLeaderboardChannel = client.channels.cache.get(process.env.LEADERBOARD_SCORES_ID!) as TextChannel;
const messages = await scoreLeaderboardChannel.messages.fetch();
const scoreEmbedFooter = 'Play to increase your score!';
const scoreEmbed = messages.find((message) => message.embeds[0]?.footer?.text === scoreEmbedFooter);
const formattedVoiceActivityLeaderboard = await formatScoreLeaderboard(client);
const newScoreEmbed = new MessageEmbed()
.setTitle('🎤 Packing leaderboard 🏆')
.addField('Top 10 (lifetime)', '\u200B\n'+formattedVoiceActivityLeaderboard.map((entry, idx) => `#${++idx} **${entry.user.username}** - Score: **${entry.total}** (${entry.wins} wins / ${entry.losses} losses)`).join('\n'))
.setFooter(scoreEmbedFooter)
.setColor('#FF0000');
if (!scoreEmbed) scoreLeaderboardChannel.send({ embeds: [newScoreEmbed] });
else scoreEmbed.edit({ embeds: [newScoreEmbed] });
};
const emptyChannels = new Set();
const deleteEmptyEvent = () => {
const server = client.guilds.cache.get(process.env.GUILD_ID!);
const category = server?.channels.cache.get(process.env.HOST_CHANNELS_CATEGORY!) as CategoryChannel;
category.children.forEach((channel) => {
if (channel.members.size === 0) {
const shouldBeDeleted = emptyChannels.has(channel.id);
if (shouldBeDeleted) {
console.log(`Event channel ${channel.name} has been deleted!`);
channel.delete();
emptyChannels.delete(channel.id);
} else {
console.log(`Event channel ${channel.name} is going to be deleted!`);
emptyChannels.add(channel.id);
}
} else {
emptyChannels.delete(channel.id);
}
});
}
const checkHunger = () => {
getUsers().then((users) => {
users.forEach((user) => {
let newHunger = user.hunger - 0.023;
let newHealth = user.health;
let newMoney = user.money;
let newFoods = user.foods;
if (newHunger <= 0) {
newHunger = 0;
if (user.hunger > 0) {
// send warning message
client.users.fetch(user.id).then((u) => u.send(':fries: Watch out! You will starve if you do not eat within the next 3 hours!'));
}
newHealth = newHealth - 0.55;
if (newHealth < 0) {
// reset the stats
newHealth = 100;
newHunger = 100;
newMoney = 0;
newFoods = [];
// send warning message
client.users.fetch(user.id).then((u) => u.send(':confused: You starved to death...'));
}
}
updateUser(user.id, {
health: newHealth,
money: newMoney,
foods: newFoods,
hunger: newHunger
});
});
});
}
interface StaffLeaderboardEntry {
user_id: string;
emoji: string;
count: number;
username: string;
}
let staffLeaderboardEntries: StaffLeaderboardEntry[]|null = null;
let staffLeaderboardMessage: Message|null = null;
const getStaffLeaderboardContent = () => {
let content = `**Staff Leaderboard** 🌟\nReact with the right emoji to upvote someone!`;
staffLeaderboardEntries?.forEach((entry) => {
content += `\n\n${entry.emoji} | **${entry.username}** - ${entry.count}`;
});
return content;
}
const synchronizeStaffLeaderboard = async () => {
const circles = ['🔵', '🔴', '🟢', '🟠', '🟣', '⚪', '🟡', '⚫', '🟤', '🎨', '🫒', '🛼', '🌈', '🌊', '🎈', '🎉', '🎊', '🎁', '🎀'];
// this function will fetch all the staff members and create or update the leaderboard
const guild = client.guilds.cache.get(process.env.GUILD_ID!);
const channel = guild?.channels.cache.get(process.env.STAFF_LEADERBOARD_ID!) as TextChannel;
const staffLeaderboardEntriesDB = await getStaffLeaderboardEntries();
staffLeaderboardEntries = [];
const staff = guild?.members.cache.filter(m => m.roles.cache.has(process.env.STAFF_ROLE!)).toJSON()!;
for (let staffMember of staff) {
// check if there is an entry, and if there is not create, it
const entry = staffLeaderboardEntriesDB.find((entry) => entry.user_id === staffMember.id);
if (!entry) {
const entryData = {
user_id: staffMember.id,
emoji: circles.find((c) => !staffLeaderboardEntriesDB.some((e) => e.emoji === c) && !staffLeaderboardEntries?.some((e) => e.emoji === c))!
}
staffLeaderboardEntries.push({
...entryData,
count: 0,
username: staffMember.user.username
});
await createLeaderboardEntry(entryData);
} else staffLeaderboardEntries.push({
...entry,
username: staffMember.user.username
})
}
console.log(`Deleting not in ${staffLeaderboardEntries.map((e) => e.emoji)}`);
await deleteUnusedLeaderboardEntries(staffLeaderboardEntries.map((e) => e.emoji));
const messages = await channel.messages.fetch();
// find the first message sent by the client
const message = messages.find((message) => message.author.id === client.user?.id);
const content = getStaffLeaderboardContent();
if (!message) channel.send(content).then((m) => staffLeaderboardMessage = m);
else {
staffLeaderboardMessage = message;
message?.edit(content);
}
staffLeaderboardEntries.forEach((entry) => {
console.log(`Reacting with ${entry.emoji}`);
message?.react(entry.emoji);
});
}
interface WaitingRole {
value: Snowflake;
time: number;
}
let waitingForRoles: WaitingRole[] = [];
const changeRole = async (member: GuildMember, roleID: Snowflake, type: 'add' | 'remove') => {
if (waitingForRoles.some((element) => element.value === member.id)) {
console.log(chalk.yellow(`${member.user.tag} is still waiting for their roles...`));
}
waitingForRoles.push({
value: member.id,
time: Date.now()
});
const promise = type === 'add' ? member.roles.add(roleID) : member.roles.remove(roleID);
promise.then(() => {
console.log(chalk.green(`[${waitingForRoles.length}] ${member.user.tag} has got their roles!`));
waitingForRoles = waitingForRoles.filter((element) => element.value !== member.id);
});
}
setInterval(() => {
const time = Date.now();
waitingForRoles = waitingForRoles.filter((item) => {
return time < item.time + (30000);
});
}, 500);
const lastAutoroleCheckedAt: number|null = null;
const checkAutoRole = async () => {
const server = client.guilds.cache.get(process.env.GUILD_ID!);
const tgRole = server?.roles.cache.get(process.env.TG_ROLE!)!;
const statusRole = server?.roles.cache.get(process.env.STATUS_ROLE!)!;
if (!lastAutoroleCheckedAt || (lastAutoroleCheckedAt + (60000*10) < Date.now())) {
await server?.members.fetch();
}
server?.members.cache.forEach((member) => {
const hasStatusPresence = member.presence?.activities[0]?.state?.includes('.gg/packing');
const hasStatusRole = member.roles.cache.has(statusRole.id);
if (hasStatusPresence && !hasStatusRole) {
changeRole(member, statusRole.id, 'add');
} else if (!hasStatusPresence && hasStatusRole) {
changeRole(member, statusRole.id, 'remove');
}
});
}
client.on('ready', () => {
console.log(`Ready. Logged in as ${client.user?.username}`);
terminateVoiceActivities();
client.channels.cache.filter((channel) => channel.type === 'GUILD_VOICE').forEach((channel) => {
(channel as VoiceChannel).members.forEach((member) => {
startVoiceActivity(member.user.id, channel.id);
});
});
updateActivityLeaderboard();
updateWinsLeaderboard();
synchronizeStaffLeaderboard();
checkHunger();
checkAutoRole();
setInterval(() => updateActivityLeaderboard(), 10000);
setInterval(() => updateWinsLeaderboard(), 10000);
setInterval(() => deleteEmptyEvent(), 10000);
setInterval(() => synchronizeStaffLeaderboard(), 60 * 1000 * 60);
setInterval(() => checkHunger(), 60 * 1000);
setInterval(() => checkAutoRole(), 30000);
});
client.on('messageReactionAdd', async (reaction, user) => {
const message = reaction.message;
const channel = message.channel as TextChannel;
if (channel.id !== process.env.STAFF_LEADERBOARD_ID) return;
if (user.bot) return;
const staff = staffLeaderboardEntries?.find((entry) => entry.emoji === reaction.emoji.name);
if (!staff) return;
await assignVote(user.id, staff.user_id);
staffLeaderboardEntries = (await getStaffLeaderboardEntries()).map((e) => ({
...e,
username: channel.guild.members.cache.get(e.user_id)?.user.username
}));
const content = getStaffLeaderboardContent();
staffLeaderboardMessage?.edit(content);
});
client.on('voiceStateUpdate', async (oldState, newState) => {
if (!newState.member) return;
if (newState.channelId === process.env.UNMUTE_CHANNEL_ID) {
newState.member.voice.setMute(false);
return;
}
// if someone joined a channel
if (!oldState.channelId && newState.channelId) {
startVoiceActivity(newState.member.id, newState.channelId);
console.log(`[+] New voice activity created for user ${newState.member.user.username}`);
}
// if someone left a channel
else if (oldState.channelId && !newState.channelId) {
endVoiceActivity(newState.member.id);
console.log(`[x] Voice activity ended for user ${newState.member.user.username}`);
}
});
client.on('channelDelete', async (channel) => {
if (channel.type !== 'GUILD_VOICE') return;
const voice = channel as VoiceChannel;
if (voice.parentId !== process.env.HOST_CHANNELS_CATEGORY) return;
const userID = await getVoiceChannelAuthor(channel.id);
const eventDuration = humanizeDuration(Date.now() - channel.createdTimestamp);
const embed = new MessageEmbed()
.setDescription(`The event (${voice.name}) lasted ${eventDuration}`)
.setColor('#000000')
if (userID) {
const user = await client.users.fetch(userID);
embed.setAuthor(`End of event channel created by ${user.tag}`, user.displayAvatarURL());
} else {
embed.setAuthor(`End of event channel created by Unknown#0000`);
}
(client.channels.cache.get(process.env.HOST_LOGS_CHANNEL!)! as TextChannel).send({ embeds: [embed] });
});
client.on('presenceUpdate', async (oldPresence, newPresence) => {
if (oldPresence?.status !== 'offline' && newPresence.status === 'offline') {
console.log(`${newPresence.user?.tag} (${newPresence.userId} moved from ${oldPresence?.status} to ${newPresence.status}`);
updateUserLastSeenAt(newPresence.userId);
}
});
client.on('message', (message) => {
if (message.author.bot) return;
addMessage(message.author.id, message.channel.id);
});
client.login(process.env.TOKEN!);
export default client;