-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathindex.js
608 lines (510 loc) · 20.8 KB
/
index.js
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
const Oceanic = require('oceanic.js')
const Emitter = require('events')
const Filter = require('bad-words')
const Mixpanel = require('mixpanel')
const mongoose = require('mongoose')
const _ = require('lodash')
const asdate = require('add-subtract-date')
const sagiri = require('sagiri')
const commands = require('./commands')
const colors = require('./utils/colors')
const pgn = require('./utils/pagination')
const {check_all} = require('./modules/secondarycheck')
const {
trigger,
con,
} = require('./utils/cmd')
const {
auction,
audit,
user,
guild,
hero,
eval,
meta,
plot,
preferences,
} = require('./modules')
const {
registerTopggVote,
registerDblVote,
registerKofiPayment
} = require("./modules/webhooks")
const {
updateCompletion
} = require("./modules/collection")
const userq = []
const guildq = []
const cardInfos = []
const bot = new Oceanic.Client({ auth: 'Bot ' + process.env.token})
const shards = new Oceanic.ShardManager(bot, {maxShards: parseInt(process.env.shards) })
let mcn, started, config, sauce, ctx
const fillCardOwnerCount = async (carddata) => {
const infos = await meta.fetchAllInfos()
infos.map(x => {
cardInfos[x.id] = x
})
}
const fillCardData = (carddata) => {
config.cards = carddata.map((x, i) => {
const col = config.data.collections.filter(y => y.id == x.col)[0]
const ext = x.animated? 'gif' : (col.compressed? 'jpg' : 'png')
const basePath = `/${col.promo? 'promo':'cards'}/${col.id}/${x.level}_${x.name}.${ext}`
x.url = config.links.baseurl + basePath
x.shorturl = config.links.shorturl + basePath
x.id = i
if(x.added)
x.added = Date.parse(x.added)
return x
})
}
const calculateDistribution = (cards) => {
const claimableCount = {
0: 0,
1: 0,
2: 0,
3: 0,
4: 0,
5: 0
}
cards.map(x => {
const col = config.data.collections.filter(y => y.id == x.col)[0]
if (!col.promo && (!col.rarity || col.rarity > 0)) {
claimableCount[x.level]++
claimableCount[0]++
}
})
return claimableCount
}
/* create our glorious sending fn */
const send = (interaction, content, userid, components, edit = false) => {
if(content.description)
content.description = content.description.replace(/\s\s+/gm, '\n')
if(content.fields)
content.fields.map(x => x.value = x.value.replace(/\s\s+/gm, '\n'))
if(userid)
_.remove(userq, (x) => x.id === userid)
if (edit)
return interaction.editOriginal({ embeds: [content], components: components }).catch(e => process.send({error: e}))
return interaction.createFollowup({ embeds: [content], components: components }).catch(e => process.send({error: e}))
}
const toObj = (user, str, clr) => {
if(typeof str === 'object') {
str.description = `**${user.username}**, ${str.description}`
str.color = colors[clr]
return str
}
return { description: `**${user.username}**, ${str}`, color: colors[clr] }
}
/* create direct reply fn */
const direct = async (user, str, clr = 'default') => {
try {
const ch = await bot.rest.users.createDM(user.discord_id)
return ch.createMessage({embeds: [toObj(user, str, clr)]}).catch(e => console.log(e))
} catch (e) {console.log(e)}
}
const qhelp = (ctx, user, cat) => {
return send(ctx.interaction, {
author: { name: `Something went wrong!` },
description: 'A required argument was not supplied, or something has gone wrong with the command. Check out our documentation page linked with `/help` and if you continue to receive this message please report it in our support discord listed on the main documentation page!',
color: colors.red,
footer: { text: `Get a link to the command documentation by running /help!` }
}, user.discord_id)
}
const symbols = {
tomato: '`🍅`',
vial: '`🍷`',
lemon: '`🍋`',
star: '★',
auc_sbd: '🔹',
auc_lbd: '🔷',
auc_sod: '🔸',
auc_wss: '▫️',
accept: '✅',
decline: '❌',
red_circle: '`🔴`'
}
const sendPgn = async (ctx, user, pgnObject, userqRemove = true) => {
try {
await pgn.addPagination(ctx, pgnObject)
if (userqRemove)
_.remove(userq, (x) => x.id === user.discord_id)
} catch (e) {
process.send({error: {message: e.message, stack: e.stack}})
}
}
const sendCfm = async (ctx, user, cfmObject, userqRemove = true) => {
try {
await pgn.addConfirmation(ctx, cfmObject)
if (userqRemove)
_.remove(userq, (x) => x.id === user.discord_id)
} catch (e) {
process.send({error: {message: e.message, stack: e.stack}})
}
}
const sendCfmPgn = async (ctx, user, cfmPgnObject, userqRemove = true) => {
try {
await pgn.addConfirmPagination(ctx, cfmPgnObject)
if (userqRemove)
_.remove(userq, (x) => x.id === user.discord_id)
} catch (e) {
process.send({error: {message: e.message, stack: e.stack}})
}
}
/* service tick for checks */
const tick = (ctx) => {
const now = new Date()
auction.finish_aucs(ctx, now)
pgn.timeoutTick()
if (ctx.autoAuction.userID && !ctx.settings.aucLock)
auction.autoAuction(ctx)
}
/* service tick for guilds */
const gtick = (ctx) => {
const now = new Date()
guild.bill_guilds(ctx, now)
plot.castlePayments(ctx, now)
}
/* service tick for user checks */
const qtick = () => {
const now = new Date()
_.remove(userq, (x) => x.expires < now)
user.deleteOldQuests(now)
}
/* service tick for hero checks */
const htick = (ctx) => {
const now = new Date()
hero.check_heroes(ctx, now)
hero.checkSlots(ctx, now)
}
/* service tick for audit and transaction cleaning */
const atick = () => {
const now = new Date()
audit.clean_audits(ctx, now)
guild.clean_trans(ctx, now)
}
const etick = () => {
eval.checkQueue(ctx)
}
const notifytick = () => {
preferences.notifyCheck(ctx)
}
let tickArray, reconnecting
const startTicks = () => {
const auctionTick = setInterval(tick.bind({}, ctx), 5000)
const guildTick = setInterval(gtick.bind({}, ctx), 2000)
const userQueueTick = setInterval(qtick.bind({}, ctx), 1000)
const heroTick = setInterval(htick.bind({}, ctx), 60000 * 5)
const auditTick = setInterval(atick.bind({}, ctx), 600000)
const evalTick = setInterval(etick.bind({}, ctx), eval.queueTick)
const notifyTick = setInterval(notifytick.bind({}, ctx), 6000)
tickArray = [auctionTick, guildTick, userQueueTick, heroTick, auditTick, evalTick, notifyTick]
}
const stopTicks = () => {
tickArray.map(x => clearInterval(x))
}
const filter = new Filter()
process.on('message', async (message) => {
const cmd = _.keys(message)
await trigger('con', message, null, cmd)
})
con('startup', async (data) => {
config = data.startup
mcn = await mongoose.connect(config.bot.database)
fillCardData(config.data.cards)
await fillCardOwnerCount(config.cards)
filter.addWords(...config.data.bannedwords)
if(config.sourcing.sauceNaoToken) {
sauce = sagiri(config.sourcing.sauceNaoToken, {
mask: [9],
results: 2,
})
}
let mixpanel = {
track: () => { }
}
if(config.analytics.mixpanel) {
try {
mixpanel = Mixpanel.init(config.analytics.mixpanel)
} catch(e) {
console.log(e)
}
}
/* create our context */
ctx = {
mcn, /* mongoose database connection */
bot, /* created and connected Eris bot instance */
send, /* a sending function to send stuff to a specific channel */
sendPgn, /* a sending function to send pagination messages and remove user from cooldown*/
sendCfm, /* a sending function to send confirmation messages and remove user from cooldown*/
sendCfmPgn, /* a sending function to send a combination confirmation and pagination message and remove user from cooldown*/
cards: config.data.cards, /* data with cards */
collections: config.data.collections, /* data with collections */
help: require('./staticdata/help'),
audithelp: require('./staticdata/audithelp'),
items: require('./staticdata/items'),
achievements: require('./staticdata/achievements'),
quests: require('./staticdata/quests'),
effects: require('./staticdata/effects'),
slashCmd: require('./staticdata/slashcommands'),
adminCmd: require('./staticdata/adminslashcommands'),
adminGuildID: config.bot.adminGuildID,
promos: config.data.promos.map( x => Object.assign({}, x, {starts: Date.parse(x.starts), expires: Date.parse(x.expires)})),
boosts: config.data.boosts.map( x => Object.assign({}, x, {starts: Date.parse(x.starts), expires: Date.parse(x.expires)})),
autoAuction: config.auction.auto,
auctionFeePercent: config.auction.auctionFeePercent,
cardInfos,
filter,
distribution: calculateDistribution(config.cards),
direct, /* DM reply function to the user */
symbols: config.symbols,
baseurl: config.links.baseurl,
pgn,
qhelp,
links: config.links,
invite: config.bot.invite,
prefix: config.bot.prefix,
uniqueFrequency: config.effects.uniqueFrequency,
eval: config.evals,
cafe: 'https://discord.gg/HEqbtpzbHz', /* support server invite */
mixpanel,
sauce,
config,
rng: config.rng,
guildLogChannel: config.channels.guildLog,
reportChannel: config.channels.report,
settings: {
wip: config.bot.maintenance,
wipMsg: 'bot is currently under maintenance. Please check again later |ω・)ノ',
aucLock: config.auction.lock
}
}
await bot.connect()
})
con('shutdown', async () => {
stopTicks()
await bot.disconnect(false)
process.exit()
})
con('autorestart', async () => {
ctx.settings.wip = true
ctx.settings.wipMsg = `the bot is about to undergo a weekly restart. Please try your command again in a few minutes |ω・)ノ`
await new Promise(res=>setTimeout(res,150000))
stopTicks()
await bot.disconnect(false)
process.exit()
})
con('updateCards', async (carddata) => {
fillCardData(carddata.updateCards)
await updateCompletion(ctx, config.cards, ctx.cards)
ctx.cards = config.cards
})
con('updateCols', (coldata) => ctx.collections = coldata.updateCols)
con('updatePromos', (promodata) => ctx.promos = promodata.updatePromos.map( x => Object.assign({}, x, {starts: Date.parse(x.starts), expires: Date.parse(x.expires)})))
con('updateBoosts', (boostdata) => ctx.boosts = boostdata.updateBoosts.map( x => Object.assign({}, x, {starts: Date.parse(x.starts), expires: Date.parse(x.expires)})))
con('updateWords', (wordsdata) => filter.addWords(...wordsdata.updateWords))
con('vote', (voteData) => {
try {
if (voteData.type === 'dbl')
registerDblVote(ctx, voteData.vote)
if (voteData.type === 'topgg')
registerTopggVote(ctx, voteData.vote)
if (voteData.type === 'kofi')
registerKofiPayment(ctx, voteData.vote)
} catch (e) {
process.send({error: {message: e.message, stack: e.stack}})
}
})
bot.once('ready', async () => {
started = true
const guildCommands = await bot.application.getGuildCommands(ctx.adminGuildID)
if (guildCommands.length !== ctx.adminCmd.length)
await bot.application.bulkEditGuildCommands(ctx.adminGuildID, ctx.adminCmd)
const globalCommands = await bot.application.getGlobalCommands()
if (globalCommands.length !== ctx.slashCmd.length)
await bot.application.bulkEditGlobalCommands(ctx.slashCmd)
await bot.editStatus('online', [{ name: 'commands', type: 2}])
process.send({info: `Bot is ready on **${bot.guilds.size} guild(s)** with **${bot.users.size} user(s)** using **${bot.shards.size} shard(s)**`})
ctx.settings.wip = false
startTicks()
})
bot.on('interactionCreate', async (interaction) => {
if (!started)
return
//Slash Commands
if (interaction instanceof Oceanic.CommandInteraction) {
try {
if (interaction.applicationID !== bot.application.id)
return
const interactionUser = interaction.user || interaction.member.user
if (interactionUser.bot)
return
const reply = (user, str, clr = 'default', edit) => send(interaction, toObj(user, str, clr), user.discord_id, [], edit)
let botUser = await user.fetchOnly(interactionUser.id)
const curguild = await guild.fetchGuildById(interaction.guildID)
let base = [interaction.data.name]
let options = []
let cursor = interaction.data
while (cursor.hasOwnProperty('options')) {
cursor = cursor.options.raw? cursor.options.raw : cursor.options
cursor.map(x => {
if (x.type === 1 || x.type === 2) {
base.push(x.name)
cursor = x
} else if ((x.name === 'global' && x.value) || (x.name === 'local' && x.value)) {
base.push(x.name)
} else {
options.push(x)
}
})
}
const setbotmsg = 'guild set bot'
const setreportmsg = 'guild set report'
if (curguild
&& !base.join(' ').includes(setbotmsg)
&& !base.join(' ').includes(setreportmsg)
&& !base.join(' ').includes('summon')
&& !base.join(' ').includes('pat')
&& !curguild.botchannels.some(x => x === interaction.channel.id)) {
await interaction.defer(64)
return await interaction.createFollowup({
embeds: [{
description: `**${interactionUser.username}**, bot commands are only available in these channels:
${curguild.botchannels.map(x => `<#${x}>`).join(' ')}
\nGuild owner or administrator can add a bot channel by typing \`/${setbotmsg}\` in the target channel.`,
color: colors.red
}]
})
}
let capitalMsg = base
let msg = base.map(x => x.toLowerCase())
const isolatedCtx = Object.assign({}, ctx, {
msg, /* current icoming msg object */
capitalMsg,
reply, /* quick reply function to the channel */
globals: {}, /* global parameters */
discord_guild: interaction.member ? interaction.member.guild : null, /* current discord guild */
prefix: '/', /* current prefix */
interaction: interaction,
options,
interactionUser
})
let usr = await user.fetchOrCreate(isolatedCtx, interactionUser.id, interactionUser.globalName || interactionUser.username)
usr.username = usr.username.replace(/\*/gi, '')
const cntnt = msg.map(x => x.trim()).join(' ')
let args = cntnt.split(/ +/)
if (userq.some(x => x.id === interactionUser.id)) {
await interaction.defer(64)
return reply(botUser, 'you are currently on a command cooldown. These last only 5 seconds from your last command, please wait a moment and try your command again!', 'red')
}
userq.push({id: interactionUser.id, expires: asdate.add(new Date(), 5, 'seconds')})
if (ctx.settings.wip && !usr.roles.includes('admin') && !usr.roles.includes('mod')) {
await interaction.defer()
return reply(usr, ctx.settings.wipMsg, 'yellow')
}
if (usr.ban.full) {
await interaction.defer()
return reply(usr, `this account was banned permanently.
For more information please visit [bot discord](${ctx.cafe})`, 'red')
}
usr.exp = Math.min(usr.exp, 10 ** 7)
usr.vials = Math.min(usr.vials, 10 ** 6)
console.log(`${new Date().toLocaleTimeString()} [${usr.username}]: ${cntnt}`)
if (isolatedCtx.discord_guild)
isolatedCtx.guild = curguild || await guild.fetchOrCreate(isolatedCtx, usr, interaction.member.guild)
ctx.mixpanel.track('Command', {
distinct_id: usr.discord_id,
command: args,
guild: isolatedCtx.guild ? isolatedCtx.guild.id : 'direct',
options: options
})
await trigger('cmd', isolatedCtx, usr, args, isolatedCtx.prefix)
} catch (e) {
if(e.message === 'Missing Permissions' || e.message === 'Cannot send messages to this user')
return
process.send({error: {message: e.message, stack: e.stack}})
}
}
//Buttons
if (interaction instanceof Oceanic.ComponentInteraction) {
try {
if (interaction.applicationID !== bot.application.id)
return
const interactionUser = interaction.user || interaction.member.user
const reply = (user, str, clr = 'default', edit) => send(interaction, toObj(user, str, clr), user.discord_id, [], edit)
let isoCtx = Object.assign({}, ctx, {
reply,
interaction: interaction,
discord_guild: interaction.member? interaction.member.guild: null,
prefix: `/`,
interactionUser
})
let usr = await user.fetchOrCreate(isoCtx, interactionUser.id, interactionUser.globalName || interactionUser.username)
usr.username = usr.username.replace(/\*/gi, '')
await trigger('rct', isoCtx, usr, [interaction.data.customID])
} catch (e) {
if(e.message === 'Missing Permissions' || e.message === 'Cannot send messages to this user')
return
process.send({error: {message: e.message, stack: e.stack}})
}
}
if (interaction instanceof Oceanic.ModalSubmitInteraction) {
try {
if (interaction.applicationID !== bot.application.id)
return
const interactionUser = interaction.user || interaction.member.user
let args = []
interaction.data.components.map(x => {
if (x.type === 1)
x.components.map(y => {
args.push(y)
})
else
args.push(x)
})
const reply = (user, str, clr = 'default', edit) => send(interaction, toObj(user, str, clr), user.discord_id, [], edit)
let isoCtx = Object.assign({}, ctx, {
reply,
interaction: interaction,
discord_guild: interaction.member? interaction.member.guild: null,
prefix: `/`,
interactionUser,
args
})
let usr = await user.fetchOrCreate(isoCtx, interactionUser.id, interactionUser.globalName || interactionUser.username)
usr.username = usr.username.replace(/\*/gi, '')
await interaction.defer()
await trigger('mod', isoCtx, usr, [interaction.data.customID])
} catch (e) {
if(e.message === 'Missing Permissions' || e.message === 'Cannot send messages to this user')
return
process.send({error: {message: e.message, stack: e.stack}})
}
}
})
bot.on('guildCreate', async (guild) => {
if (ctx.guildLogChannel)
await bot.rest.channels.createMessage(ctx.guildLogChannel, {embeds: [{
description:`Invited to a new guild!\nGuild Name: **${guild.name}**\nGuild ID: \`${guild.id}\``,
color: colors.green,
thumbnail: {url: guild.iconURL}
}]})
})
bot.on('guildDelete', async (guild) => {
if (ctx.guildLogChannel)
await bot.rest.channels.createMessage(ctx.guildLogChannel, {embeds: [{
description:`Kicked from guild!\nGuild Name: **${guild.name? guild.name: 'Uncached Guild'}**\nGuild ID: \`${guild.id}\``,
color: colors.red
}]})
})
bot.on('error', async (err, sh) => {
process.send({error: {message: err.message, stack: err.stack}})
})
process.on('unhandledRejection', (rej) => {
process.send({unhandled: rej})
})
process.on('uncaughtException', (exc) => {
process.send({uncaught: exc})
})
module.exports.schemas = require('./collections')
module.exports.modules = require('./modules')