-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
630 lines (604 loc) · 19.6 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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
import {config, parse} from 'dotenv';
import {
Client,
Collection,
Guild,
GuildEmojiManager,
GuildMember,
Message,
MessageEmbed,
TextChannel,
User,
} from 'discord.js';
import {Fcal, FcalError} from 'fcal';
import {SphinxException} from './src/error';
import {findChannelId} from './src/channel';
import {SphinxKickCommand} from './src/commands/kick';
import {createDiscordEmbed, randomColor} from './src/embed';
import {SphinxGithubCommand, sphinxRepositoryCommand} from './src/github';
import {
getUserAvatar,
getUserDisplayName,
serverInformation,
serverRoleInformation,
} from './src/commands/server';
import {SphinxUserProfile} from './src/commands/profile';
import {isDuplicateMessage} from './src/duplicate';
import axios, {AxiosResponse} from 'axios';
import {SphinxPollCommand, sphinxSimplePoll} from './src/commands/poll';
import {SphinxRoleAssignment} from './src/commands/roles';
import {botMentioned} from './src/constants';
import {createBotReply} from './src/reply';
import {SphinxDataStore} from './src/store/store';
import {join} from 'path';
import {cwd} from 'process';
import {userScore} from './src/commands/score';
import {SphinxUrlShortener} from './src/commands/url/shorten';
import {expandUrl} from './src/commands/url/expand';
// Take all the variables from the env
// file to process.env
config();
export const store = new SphinxDataStore({
databaseName: 'sphinx',
databasePath: join(cwd(), 'src', 'store', 'json', 'sphinx.json'),
exists: false,
});
// constants
const token = process.env.TOKEN;
const prefix: Array<string> = [
'=',
'!',
';run',
'sphinx',
'github',
'%',
'repo',
'$',
];
export const image = 'http://i.imgur.com/p2qNFag.png';
let speak = false;
// the discord clinet
const client = new Client({ws: {intents: ['GUILD_MESSAGES', 'GUILDS']}});
/**
* Checks whether the message is a commandor not
*
* @param {String} message The message content to check if a command
* @returns An object with type and command
*/
const isBotCommand = (message: string): any => {
for (let index = 0; index < prefix.length; index++) {
if (message.toLowerCase().startsWith(prefix[index])) {
return {
type: prefix[index],
command: true,
};
}
}
return {type: null, command: false};
};
/**
* Fetch random cat images from the catapi
* and send in the channel
*
* @param message The message class
*/
const generateCatImages = (message: Message): void => {
axios
.get('https://api.thecatapi.com/v1/images/search')
.then((data: AxiosResponse<any>) => {
const value: Array<any> = Array.from(data.data);
for (let imgIndex = 0; imgIndex < value.length; imgIndex++) {
message.channel.send(value[imgIndex].url);
}
})
.catch((exception) => {
const error = new SphinxException(
'Failed to fetch cat images',
message
).evokeSphinxException();
});
};
/**
* Fetch some random activities using axios
* and send them as embeds
*
* @param message The message class
*/
const generateActivities = (message: Message): void => {
axios
.get('http://www.boredapi.com/api/activity/')
.then((data: AxiosResponse<any>) => {
const value = data.data;
const embed = createDiscordEmbed({
title: `:busts_in_silhouette: ${value.activity}`,
author: {name: 'Sphinx', image: image},
description: '',
color: '#7289DA',
url: value.link,
thumbnail: '',
})
.addField(':small_blue_diamond: Type', value.type, true)
.addField(
':man_construction_worker::woman_construction_worker: Participants',
value.participants,
true
)
.addField(':moneybag: Price', value.price);
message.channel.send(embed);
})
.catch((err) => {
const error = new SphinxException(
'Nothing for you right now',
message
).evokeSphinxException();
});
};
/**
* Take the last message sent in the server
* before the current message and then react to
* the message with a random emoji
*
* @param {Message} message The message class
*/
export const reactToMessage = (message: Message) => {
let reactList = [
'😉',
'😟',
'🙂',
'😀',
'😐',
'😏',
'😌',
'😵',
'😕',
'☹️',
'☹️',
];
const reactMessage = message.author.lastMessageID;
if (reactMessage != null) {
message.channel.messages
.fetch({limit: 2})
.then((data: any) => {
const reactMessageObject = data.array()[1];
let reactEmoji =
reactList[Math.floor(Math.random() * reactList.length)];
if (reactEmoji == undefined) {
reactEmoji = reactList[0];
}
reactMessageObject.react(reactEmoji);
})
.catch((error) => {
console.log(error);
});
}
};
interface BadWords {
// the message that contains bad word
word: string | null;
// the bad word present in the message
badWord: string | null;
contains: boolean;
}
/**
* Checks if the message contains any bad
* words, if yes return true, else false
*
* @param {string} message The message
* @returns {BadWords}
*/
const hasBadWors = (message: string): BadWords => {
const badWords: Array<string> = ['fuck', 'dumbass', 'ass', 'sex'];
const searchMessageArray = message.split(' ');
for (
let searchIndex = 0;
searchIndex < searchMessageArray.length;
searchIndex++
) {
const currentMessage = searchMessageArray[searchIndex];
for (let idx = 0; idx < badWords.length; idx++) {
if (currentMessage.includes(badWords[idx])) {
return {
word: '`' + message + '`',
badWord: badWords[idx],
contains: true,
};
}
}
}
return {word: null, badWord: null, contains: false};
};
/**
* Send a slight_smile message, edit the message
* to a wink and then back to slight_smile after
* a specific timeout
*
* @param {Message} message The message class that is sent when
* the `sphinx` prefix is used in a message
*/
const sphinxMessage = (message: Message) => {
message.channel.send(':slight_smile:').then((messageData) => {
setTimeout(() => {
messageData.edit(':wink:').then((editMessage) => {
setTimeout(() => {
editMessage.edit(':slight_smile:');
}, 200);
});
}, 500);
});
};
client.on('ready', () => {
console.log('The bot has started');
client.user?.setStatus("idle")
client.user?.setActivity("Watching a bunch of people", { type: "WATCHING"})
});
client.on('message', async (message: Message) => {
if (message.author.bot) {
return null;
}
if (message.guild != null) {
store.addMessage(message.guild.id, message.author.id);
}
const command: any = isBotCommand(message.content);
const bad = hasBadWors(message.content);
if (command.command) {
if (command.type == '=') {
const calculations = message.content.slice(1, message.content.length);
try {
const data = Fcal.eval(calculations);
message.reply(data.toString());
} catch (exception) {
if (exception instanceof FcalError) {
const error = new SphinxException(
'An error occured while parsing your message :frowning:',
message
);
error.evokeSphinxException();
}
}
} else if (command.type == 'sphinx') {
if (bad.contains) {
const warning = createDiscordEmbed({
title: `Don't use bad words in the ${message.guild?.name} server`,
author: {
name: 'Code Roller',
image: image,
},
color: '#e20202',
description: `
${bad.badWord} found in a message
`,
thumbnail: image,
url: '',
});
message.author.send(warning);
message.channel.send(warning);
message.delete();
} else {
const dataLength = message.content.split(' ').length - 1;
if (dataLength > 0) {
let question: string | Array<string> = message.content.split(' ');
question = question.slice(1, question.length).join(' ');
createBotReply(message, question);
} else {
sphinxMessage(message);
}
}
} else if (command.type == '!') {
const sphinxCommand = message.content
.slice(1, message.content.length)
.split(' ');
if (sphinxCommand[0] == 'kick') {
const kick = new SphinxKickCommand(message).kickMember();
} else if (sphinxCommand[0] == 'clear') {
// if the command is to clear messages
// get the argument and validate it
// to be a number
// if the argument is valid, try deleting message
// if an error occurs, throw a sphinxException
const count = sphinxCommand[1];
if (Number.isInteger(parseInt(count))) {
if (parseInt(count) > 100 || parseInt(count) < 1) {
const error = new SphinxException(
'The message count should be between 1 and 100',
message
).evokeSphinxException();
} else {
await message.channel.messages
.fetch({limit: parseInt(count)})
.then((data: any) => {
// Fetches the messages
if (message.channel.type == 'text') {
message.channel.bulkDelete(data);
} else {
const error = new SphinxException(
'An error occured while deleteing messages',
message
).evokeSphinxException();
}
})
.catch((errorData) => {
const error = new SphinxException(
'An error occured while deleting message',
message
).evokeSphinxException();
});
}
} else {
const error = new SphinxException(
'Not a valid argument for clear',
message
).evokeSphinxException();
}
} else if (sphinxCommand[0] == 'react') {
reactToMessage(message);
} else if (sphinxCommand[0] == 'cat') {
generateCatImages(message);
} else if (sphinxCommand[0] == 'bored') {
generateActivities(message);
} else if (sphinxCommand[0] == 'quickpoll') {
if (message.guild != null) {
sphinxSimplePoll(message);
}
} else if (sphinxCommand[0] == 'poll') {
if (message.guild != null) {
const poll = new SphinxPollCommand(message, client);
}
} else if (sphinxCommand[0] == 'count') {
if (message.guild != null) {
const data = message.channel.messages.cache.filter(
(messageData: Message) => {
return messageData.author == message.author;
}
).size;
message.reply(
`You have sent ${data} messages in this channel :slight_smile:`
);
}
} else if (sphinxCommand[0] == 'avatar') {
const mentions = message.mentions;
if (mentions.everyone) {
message.reply("Sorry, you can't mention everyone");
} else {
if (message.mentions.users.size > 0) {
message.mentions.users.forEach((user: User) => {
const avatar = user.avatarURL();
message.channel.send(
avatar == null ? "Sadly, the user doesn't have a dp" : avatar
);
});
} else {
const avatar = message.author.avatarURL();
message.channel.send(
avatar == null ? "Sadly, the user doesn't have a dp" : avatar
);
}
}
} else if (sphinxCommand[0] == 'channel') {
let channels = message.mentions.channels;
if (channels.size == 0) {
if (message.channel.type == 'text') {
channels = new Collection<string, TextChannel>([
[message.channel.id.toString(), message.channel],
]);
}
}
channels.forEach((channel: TextChannel) => {
const lastMessage: string | undefined = channel.messages.cache
.filter((channel: Message) => {
return channel.author.bot == false;
})
.last()?.content;
const embed = new MessageEmbed().setColor('#7289DA');
embed.setTitle(`About #${channel.name}`);
embed.setAuthor('Sphinx', image);
embed.addFields([
{name: ':name_badge: Name', value: channel.name, inline: true},
{
name: ':small_blue_diamond: Type',
value: channel.type,
inline: true,
},
{
name: ':stop_button: Topic',
value:
channel.topic == null
? '**No topic available**'
: channel.topic,
inline: true,
},
{
name: ':speech_balloon: Last Message',
inline: true,
value:
lastMessage == undefined
? '**Idk the what the last message is!!**'
: lastMessage,
},
]);
message.channel.send(embed);
});
} else if (sphinxCommand[0] == 'quote') {
axios
.get('https://api.quotable.io/random')
.then((response: AxiosResponse<any>) => {
const data = response.data;
const embed = new MessageEmbed()
.setColor('#9147ff')
.setDescription(`>>> ${data.content}`)
.addField(':pencil: Author', data.author, true);
message.channel.send(embed);
})
.catch((err) => {
const error = new SphinxException(
'An error occured while fetching quotes for you',
message
).evokeSphinxException();
});
} else if (sphinxCommand[0] == 'score') {
if (message.guild != null) {
if (message.mentions.users.size == 0 && !message.mentions.everyone) {
message.reply(
`Your score is ${userScore(message.guild, message.author, store)}`
);
} else {
if (!message.mentions.everyone) {
const data = message.mentions.users.forEach((data: User) => {
const member = message.guild?.members.cache
.filter((member: GuildMember) => {
return member.id == data.id;
})
.first();
if (!member?.user.bot) {
message.channel.send(
`${getUserDisplayName(member)}'s score is ${userScore(
message.guild,
message.author,
store
)}`
);
console.log('scores');
}
});
} else {
message.reply("You can't mention everyone :slight_frown:");
}
}
}
} else if (sphinxCommand[0] == 'shorten') {
const shortener = new SphinxUrlShortener(message);
} else if (sphinxCommand[0] == 'expand') {
expandUrl(message.content.split(' ').slice(1)[0], message);
}
} else if (command.type == 'github') {
const username = message.content.split(' ')[1];
if (username == undefined) {
const exception = new SphinxException(
'Invalid username',
message
).evokeSphinxException();
} else {
const userData = new SphinxGithubCommand(
username,
message
).fetchUserData();
}
} else if (command.type == 'repo') {
sphinxRepositoryCommand(message);
} else if (command.type == '%') {
const data = message.content.slice(1, message.content.length).split(' ');
if (data[0] == 'server' || data[0] == 'serverinfo') {
if (message.guild != null) {
serverInformation(message.guild, message);
}
} else if (data[0] == 'roles') {
if (message.guild != null) {
serverRoleInformation(message.guild, message);
}
} else if (data[0] == 'profile') {
if (message.guild != null) {
const profile = new SphinxUserProfile(message);
}
}
} else if (command.type == '$') {
const colonCommand = message.content.split(' ');
const commandName = colonCommand[0].slice(1, colonCommand[0].length);
if (commandName == 'role') {
const role = new SphinxRoleAssignment(message, client);
}
}
} else if (bad.contains) {
// Check if the message contains
// any bad words
const warning = createDiscordEmbed({
title: `Don't use bad words in the ${message.guild?.name} server`,
author: {
name: 'Code Roller',
image: image,
},
color: '#e20202',
description: `
${bad.badWord} found in a message
`,
thumbnail: image,
url: '',
});
message.author.send(warning);
message.channel.send(warning);
message.delete();
} else if (
message.content.includes('https://discord.gg') ||
message.content.includes('https://discord.com/invite')
) {
// prevents people from advertising servers
message.author.send(
createDiscordEmbed({
title: `Don't advertise servers in ${message.guild?.name}`,
author: {
name: 'Code Roller',
image: image,
},
color: '#e20202',
description: `Advertising not allowed in ${message.guild?.name}`,
thumbnail: image,
url: '',
})
);
message.delete();
} else {
if (isDuplicateMessage(message)) {
console.log('Found duplicate message');
} else if (botMentioned(message, client)) {
if (message.guild != null) {
message.channel.send(
`Why did you ping me ${getUserDisplayName(
message.guild?.members.cache
.filter((member: GuildMember) => {
return member.id == message.author.id;
})
.first()
)} :angry: ??`
);
}
} else {
console.log(speak);
if (message.content.toLowerCase().includes('sphinx')) {
speak = true;
}
if (
message.content.toLowerCase().includes('stop sphinx') ||
message.content.toLowerCase().includes('sphinx stop')
) {
speak = false;
}
if (speak) {
createBotReply(message, message.content);
}
}
}
});
client.on('guildCreate', (guild: Guild) => {
const channel = guild.systemChannel;
store.joinServer(guild.id);
channel?.send(
createDiscordEmbed({
title: `Thank you for inviting me`,
author: {
name: 'Code Roller',
image: image,
},
color: randomColor(),
description: `I am the Sphinx bot and thank you for inviting me`,
thumbnail: image,
url: '',
})
);
// client.user?.setActivity(`Serving ${client.guilds.cache.size} servers`);
});
client.on('guildMemberAdd', (member: GuildMember) => {
console.log(member);
member.send('Welcome!');
});
client.on('error', (e) => {
console.error('Discord client error!', e);
});
client.login(token);