-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapp.js
More file actions
517 lines (458 loc) · 18.5 KB
/
app.js
File metadata and controls
517 lines (458 loc) · 18.5 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
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
require("console-stamp")(console, {
colors: {
stamp: "yellow",
label: "cyan",
label: true,
metadata: "green"
}
});
const Discord = require("discord.js");
const {
prefix,
token,
colors,
paypal_redirect,
mongoURI,
ownerRole,
memberRoleID,
memberRole
} = require("./config.json");
const client = new Discord.Client();
const uuid = require("uuid/v4");
const fs = require("fs");
const schedule = require("node-schedule");
const moment = require("moment");
const mongoose = require("mongoose");
const User = require("./db");
var guild = null;
var availableRoles = [];
var licenses = [];
function generateLicense(quantity) {
for (let i = 0; i < quantity; i++) {
licenses.push(uuid());
}
}
mongoose.connect(
mongoURI,
{ useNewUrlParser: true, useCreateIndex: true },
err => {
if (!err) {
client.on("ready", () => {
client.user.setPresence({
game: {
name: "Playing with Authentication Bot",
type: "Playing"
}
});
console.log(
`Logged in as ${client.user.tag}! Successfully connected bot!`
);
if (client.guilds.array().length > 1) {
console.log("Your Key bot can only belong to one server.");
process.exit(1);
} else if (client.guilds.array().length === 0) {
console.log(
"Your Key bot must be assigned to a server in order to be used."
);
process.exit(1);
} else {
guild = client.guilds.array()[0];
guild.roles.forEach(r => {
availableRoles.push({
title: r.title,
id: r.id,
color: r.color
});
});
console.log("Server:", guild.name);
console.log("Member Count:", guild.members.array().length);
console.log("Available Roles:", availableRoles.length);
}
});
client.on("disconnect", () => {
console.error(
"An error has occured while trying to establish a connection with your Discord Bot. Please check you special keys in your config.json file and try again."
);
process.exit(1);
});
client.on("error", console.error);
// reconnectting
client.on("reconnecting", () => console.log("Server is reconnecting..."));
// if client is destryoed, you can catch that by reconnecting or relogging the bot back in the server
client.destroy().then(() => client.login(token));
// login bot
client.login(token);
client.on("message", msg => {
// ping bot
if (
msg.channel.type == "dm" &&
msg.content.startsWith(prefix + "ping")
) {
const successEmbed = new Discord.RichEmbed()
.setAuthor("Authentication Bot ( ONLINE )")
.setColor("#9b42f4")
.addField("Online: ", true)
.addField("Ping", `${Math.round(client.ping)}ms`);
return msg.author.send(successEmbed);
}
// help
if (
msg.channel.type == "dm" &&
msg.content.startsWith(prefix + "help")
) {
let helpEmbed = new Discord.RichEmbed()
.setAuthor("Authentication Instruction ( DM ONLY )")
.setColor("#9b42f4")
.setDescription(
"Please use the following commands to authenicate yourself..."
)
.addField("Activiation Command: ", "+activate <license>")
.addField("Renewal Command: ", "+renew")
.addField(
"Membership Creator ( ONLY ADMIN USAGE ): ",
"+add <membership role>"
)
.addField(
"Membership Removal ( ONLY ADMIN USAGE ): ",
"+remove <membership role>"
)
.addField("List of memberships: ", "+show")
.addField(
"Admin Generate Licenses ( ONLY ADMIN USAGE ): ",
"+gen <quantity>"
)
.addField("Check if bot is online: ", "+ping");
return msg.author.send(helpEmbed);
}
/* Activiate License */
if (
msg.channel.type == "dm" &&
msg.content.startsWith(prefix + "activate")
) {
const license = msg.content.split(" ")[1];
const discordUserID = msg.author.id;
fs.readFile("keys.txt", "utf-8", (err, data) => {
if (!err) {
client.guilds.array()[0].members.forEach(member => {
let isMember = member.roles.find(
role => role.name === memberRole
); // check if user has role
if (member.user.id === msg.author.id && isMember) {
const failureEmbed = new Discord.RichEmbed()
.setAuthor("Activation ( FAILURE )")
.setColor("#cc0000")
.addField("Failed to authenticate: ", license)
.addField(
"Reason: ",
"It looks like you're already a member of the group :smile:"
);
return msg.author.send(failureEmbed);
}
if (member.user.id === msg.author.id && !isMember) {
if (msg.content.split(" ").length !== 2) {
return msg.author.send(
`Hey, please authenicated yourself, by typing +activate <license>.`
);
}
// license pool
const licensePool = data.split("\r\n");
// check if user key exist && check if any user has that key or already authenicated
if (licensePool.indexOf(license) > -1) {
User.findOne({ userKey: license })
.then(user => {
if (!user) {
/* generate a new user with that license and other credentials */
const newUser = new User({
userKey: license,
authenicated: true,
discordUserID: discordUserID,
currentDate: new Date(),
expiredDate: new Date(
new Date().setDate(new Date().getDate() + 30)
)
});
// save user
newUser
.save()
.then(() => {
const member = guild.member(msg.author);
if (member) {
// after successfully authenicated, give user role => access for only 30 days
member.addRole(memberRoleID);
const successEmbed = new Discord.RichEmbed()
.setAuthor("Authentication Bot ( SUCCESS )")
.setColor("#9b42f4")
.addField(
"Activated: ",
`${license} :white_check_mark:`
);
return msg.author.send(successEmbed);
}
})
.catch(err => {
if (err) return err;
});
} else {
// check if user key already is activiated if it is, then display error...
const failureEmbed = new Discord.RichEmbed()
.setAuthor("Authentication Bot ( FAILURE )")
.setColor("#cc0000")
.addField("Failed to authenticate: ", license)
.addField(
"Reason: ",
"License has already been verified :anguished:"
)
.addField(
"Error?",
"Please contact admin if you think that was an error"
);
return msg.author.send(failureEmbed);
}
})
.catch(err => {
if (err) return err;
});
} else {
const failureEmbed = new Discord.RichEmbed()
.setAuthor("Authentication Bot ( FAILURE )")
.setColor("#cc0000")
.addField("Failed to authenticate: ", license)
.addField(
"Reason: ",
"License does not exist :anguished:"
);
return msg.author.send(failureEmbed);
}
// check if user membership is over
// once user membership is over, he or she is allowed to renew - they will be unauthenicated
}
});
}
});
}
/* Renewal Membership */
if (
msg.channel.type == "dm" &&
msg.content.startsWith(prefix + "renew")
) {
const infoEmbed = new Discord.RichEmbed()
.setAuthor("Authentication Bot ( RENEWAL )")
.setColor("#9b42f4")
.setDescription(
`To renew membership please click on [this](${paypal_redirect}) following link!`
);
return msg.author.send(infoEmbed);
// check if user is not authenticated if user is not authenticated then give them your paypal redirect link
// then simply replace the old key with new key
// then add role back
}
/* Memberships Creator */
if (
msg.channel.type == "dm" &&
msg.content.startsWith(prefix + "add")
) {
const option = msg.content.split(" ")[1];
client.guilds.array()[0].members.forEach(member => {
let isStaff = member.roles.find(role => role.name === ownerRole);
if (member.user.id === msg.author.id && isStaff) {
fs.readFile("config.example.json", "utf-8", (err, data) => {
if (!err) {
const parsedJSON = JSON.parse(data);
parsedJSON["memberships"].push(option);
fs.writeFile(
"config.example.json",
JSON.stringify(parsedJSON),
err => {
if (!err) {
const successEmbed = new Discord.RichEmbed()
.setAuthor("Bundle Creator ( SUCCESS )")
.setColor("#9b42f4")
.addField("Membership Created: ", option);
return msg.author.send(successEmbed);
}
}
);
}
});
}
// check if user isn't staff role
if (member.user.id === msg.author.id && !isStaff) {
const failureEmbed = new Discord.RichEmbed()
.setAuthor("Bundle Creator ( FAILURE )")
.setColor("#cc0000")
.addField("Failed to add: ", option)
.addField("Reason: ", "Staff Permission Required!");
return msg.author.send(failureEmbed);
}
});
}
/* Remove memberships */
if (
msg.channel.type == "dm" &&
msg.content.startsWith(prefix + "remove")
) {
const option = msg.content.split(" ")[1];
client.guilds.array()[0].members.forEach(member => {
let isStaff = member.roles.find(role => role.name === ownerRole);
if (member.user.id === msg.author.id && isStaff) {
fs.readFile("config.example.json", "utf-8", (err, data) => {
if (!err) {
const parsedJSON = JSON.parse(data);
const index = parsedJSON["memberships"].findIndex(
val => val === option
);
if (index !== -1) {
parsedJSON["memberships"].splice(index, 1);
fs.writeFile(
"config.example.json",
JSON.stringify(parsedJSON),
err => {
if (!err) {
const successEmbed = new Discord.RichEmbed()
.setAuthor("Bundle Creator ( SUCCESS )")
.setColor("#9b42f4")
.addField("Membership Removed: ", option);
return msg.author.send(successEmbed);
}
}
);
} else {
const failureEmbed = new Discord.RichEmbed()
.setAuthor("Bundle Creator ( FAILURE )")
.setColor("#cc0000")
.addField("Failed to remove: ", option)
.addField("Reason: ", `${option} does not exist`);
return msg.author.send(failureEmbed);
}
}
});
}
// check if user isn't staff role
if (member.user.id === msg.author.id && !isStaff) {
const failureEmbed = new Discord.RichEmbed()
.setAuthor("Bundle Creator ( FAILURE )")
.setColor("#cc0000")
.addField("Failed to remove: ", option)
.addField("Reason: ", "Staff Permission Required!");
return msg.author.send(failureEmbed);
}
});
}
/* Show all current memberships */
if (
msg.channel.type == "dm" &&
msg.content.startsWith(prefix + "show")
) {
fs.readFile("config.example.json", "utf-8", (err, data) => {
if (!err) {
const parsedJSON = JSON.parse(data);
const memberships = parsedJSON["memberships"];
const listEmbed = new Discord.RichEmbed()
.setAuthor("Bundle Creator ( SUCCESS )")
.setColor("#9b42f4")
.addField(
"List of memberships: ",
memberships.length === 0 ? undefined : memberships
);
return msg.author.send(listEmbed);
}
});
}
/* Generate licenses */
if (
msg.channel.type == "dm" &&
msg.content.startsWith(prefix + "gen")
) {
client.guilds.array()[0].members.forEach(member => {
// member.user.id === msg.author.id
// msg.members.roles.has("488838473298477068")
// console.log(member.roles.find(role => role.name === 'Dev'))
let isStaff = member.roles.find(role => role.name === ownerRole); // check if user has role
if (member.user.id === msg.author.id && isStaff) {
const quantity = parseInt(msg.content.split(" ")[1]);
if (quantity > 0) {
generateLicense(quantity);
fs.appendFile("keys.txt", licenses.join("\r\n"), err => {
if (!err) {
// licenses = []; // clearing remain licenses...
return msg.author.send(
`Successfully generated ${quantity} licenses...`
);
}
});
}
}
if (member.user.id === msg.author.id && !isStaff) {
return msg.author.send(
"Sorry, only admin are allow to use this command. Please try again! :x: "
);
}
});
}
});
} else {
console.log("Failed to connect to mongodb server...");
return process.exit();
}
}
);
// check everyday to see if any user membership is over... every 12 hours
function checkDaily() {
schedule.scheduleJob({ hour: 11, minute: 59 }, () => {
let tokens = [];
fs.readFile("keys.txt", "utf-8", (err, data) => {
if (!err) {
const keys = data.split("\r\n");
for (let i = 0; i < keys.length; i++) {
User.find({ userKey: keys[i] })
.then(users => {
if (users) {
users.map(user => {
const currentDate = new Date();
const expiredDate = user["expiredDate"];
const userID = user["discordUserID"];
const isAuthenicated = user["authenicated"];
if (currentDate == expiredDate || currentDate > expiredDate) {
// set them unauthenicated
user.set({ authenicated: false });
// save it to the db
user
.save()
.then(err => {
if (!err) {
client.guilds.array()[0].members.forEach(member => {
let isMember = member.roles.find(
role => role.name === memberRole
);
if (member.user.id == userID) {
// remove all roles
member.removeRole(memberRoleID); // remove member role
const infoEmbed = new Discord.RichEmbed()
.setAuthor(
"Authentication Bot ( NOTIFICATION )"
)
.setColor("#0040ff")
.setDescription(
`Your membership has expired. If you would like to renew please type !renew <youremail@gmail.com> and follow further instruction. Thank you!`
);
// send user a notification about their membership
return member.send(infoEmbed);
}
});
}
})
.catch(err => console.debug(err));
} else {
console.debug(`All user is authenicated...`);
}
});
}
})
.catch(err => console.log(err));
}
}
});
});
}
// check daily every 12 hours
checkDaily();