@kpostal10/

BugBot

Nodejs

No description

fork
loading
Files
  • index.js
  • api
  • commands
  • routes
  • scripts
  • styles
  • views
  • package-lock.json
  • package.json
  • utils.js

This Plugin Crashed!

Error: Error: must not create an existing file {"type":"CREATE_FILE","wid":"0.7297085675030628","path":"index.js","file":{"path":"index.js","content":{"asEncoding":{"base64":"Y29uc3QgQ29tbWFuZG8gPSByZXF1aXJlKCdkaXNjb3JkLmpzLWNvbW1hbmRvJyk7Cgpjb25zdCBwYXRoID0gcmVxdWlyZSgncGF0aCcpOwp2YXIgZXhwcmVzcyA9IHJlcXVpcmUoJ2V4cHJlc3MnKTsKdmFyIGVtb2ppU3RyaXAgPSByZXF1aXJlKCdlbW9qaS1zdHJpcCcpOwp2YXIgc2Vzc2lvbiA9IHJlcXVpcmUoJ2V4cHJlc3Mtc2Vzc2lvbicpOwpjb25zdCBtb21lbnQgPSByZXF1aXJlKCdtb21lbnQnKQpyZXF1aXJlKCdtb21lbnQtZHVyYXRpb24tZm9ybWF0JykKdmFyIGQgPSBuZXcgRGF0ZSgpOwpjb25zdCBjdXJyZW50U3RhcnREYXRlID0gZC5nZXRUaW1lKCk7Cgp2YXIgbWFpblBhZ2VMb2FkQ291bnQgPSAwOwoKdmFyIGZvcm1hdFBhZ2VMb2FkQ291bnQgPSAwOwoKdmFyIG1vbmdvb3NlID0gcmVxdWlyZSgnbW9uZ29vc2UnKTsKdmFyIF9fZGlybmFtZSA9IHBhdGgucmVzb2x2ZSgpOwpjb25zdCBhcHAgPSBleHByZXNzKCk7CmNvbnN0IGd1aWxkcHJvcGRhdGFiYXNlID0gcmVxdWlyZSgnLi9hcGkvZGF0YWJhc2VHdWlsZC5qcycpCi8vIEFkdmFuY2VkIHVzYWdlCmNvbnN0IGNyeXB0b1JhbmRvbVN0cmluZyA9IHJlcXVpcmUoJ2NyeXB0by1yYW5kb20tc3RyaW5nJyk7CnZhciBib2R5UGFyc2VyID0gcmVxdWlyZSgnYm9keS1wYXJzZXInKTsKY29uc3Qg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1wID0gdHJ1ZTsKICAgICAgfQogICAgfQogIH0pOwogIC8vY29uc29sZS5sb2coIkl0IHNob3VsZCBub3QgYmUgZ2V0dGluZyBoZXJlIikKICByZXR1cm4gdGVtcDsKCn0K"},"asBuffer":null},"loaded":true}}
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
const Commando = require('discord.js-commando');

const path = require('path');
var express = require('express');
var emojiStrip = require('emoji-strip');
var session = require('express-session');
const moment = require('moment')
require('moment-duration-format')
var d = new Date();
const currentStartDate = d.getTime();

var mainPageLoadCount = 0;

var formatPageLoadCount = 0;

var mongoose = require('mongoose');
var __dirname = path.resolve();
const app = express();
const guildpropdatabase = require('./api/databaseGuild.js')
// Advanced usage
const cryptoRandomString = require('crypto-random-string');
var bodyParser = require('body-parser');
const CLIENT_ID = "516125936933011467";

const CLIENT_SECRET = process.env.otherThing;
var csrf = require('csurf');
const secretRandom = cryptoRandomString(10);
const MongoStore = require('connect-mongo')(session);
var cookieParser = require('cookie-parser');

const options = {
  useNewUrlParser: true,

  autoIndex: false, // Don't build indexes
  reconnectTries: 100, // Never stop trying to reconnect
  reconnectInterval: 500, // Reconnect every 500ms
  poolSize: 10, // Maintain up to 10 socket connections
  // If not connected, return errors immediately rather than waiting for reconnect
  bufferMaxEntries: 0
};

mongoose.connect(process.env.LinkN, options).then(() => { console.log('MongoDB connected...') })
  .catch(err => console.log(err));
mongoose.Promise = global.Promise;
const db = mongoose.connection;


app.use(session({
  secret: secretRandom,
  resave: false,
  saveUninitialized: false,
  expires:  1000 * 60 * 60 * 24,
  store: new MongoStore({ mongooseConnection: db, autoRemove: 'native', ttl: 2 * 24 * 60 * 60 })
}));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.enable('trust proxy', 1);
app.use(csrf({ cookie: true }));
app.use(function (req, res, next) {
  res.locals.csrftoken = req.csrfToken();
  res.setHeader('Access-Control-Allow-Origin', 'https://BugBot--kpostal10.repl.co');
  res.setHeader('Access-Control-Allow-Methods', 'POST');
  next();
});
app.use(require('sanitize').middleware);
app.use(express.static(__dirname + '/styles'));
app.use(express.static(__dirname + '/scripts'));
app.set("view engine", "pug");
app.set("views", path.join(__dirname, "views"));
var server = app.listen(3000);
module.exports = { term: terminate }
function terminate() {
  app.close();
};

const router = express.Router();
const routes = require('./routes/index.js');
app.use('/api', routes(router));
app.get('/', function (req, res) {
  mainPageLoadCount++;
  var dataUserName = req.session.username;
  var checkAdmin;
  if (req.session.servers != undefined) {
    checkAdmin = check(req, res);
  }
  get_list_of_reports().then(list => {
    res.render(path.join('index'), {
      list_of_reports: list,
      user: dataUserName,
      admin: checkAdmin
    });
  }).catch((err) => {
    if (err) throw err;
  });


});

app.get('/stats', function(req, res){
  var dataUserName = req.session.username;
  var checkAdmin;
  if (req.session.servers != undefined) {
    checkAdmin = check(req, res);
  }
  if(checkAdmin == false || checkAdmin == undefined){
    return res.redirect('/');
  }
  let da = new Date();
  let currentTime = da.getTime() - currentStartDate;
  let formatedTime = moment.duration(currentTime).format(' D [days], H [hrs], m [mins], s [secs]');
  res.render(path.join('stats'), {
      mainPage: mainPageLoadCount,
      formatPage: formatPageLoadCount,
      user: dataUserName,
      admin: checkAdmin,
      time: formatedTime
  });
});
/* app.get/developers
  app.get('/developers', function(req, res){
    var dataUserName = req.session.username;
    var checkAdmin;
    if (req.session.servers != undefined) {
      checkAdmin = check(req, res);
    }
    get_list_of_reports().then(list => {
      res.render(path.join('dashBoardToken'), {
        user: dataUserName,
        admin: checkAdmin
      });
    }).catch((err) => {
      if (err) throw err;
    });
  });
*/
app.get('/docs', function(req, res){
  var dataUserName = req.session.username;
  var checkAdmin;
  if (req.session.servers != undefined) {
    checkAdmin = check(req, res);
  }
  res.render(path.join('docs'), {
    user: dataUserName,
    admin: checkAdmin
  });
});


app.get('/dev', async function(req, res){
  var dataUserName = req.session.username;
  var checkAdmin;
  if (req.session.servers != undefined) {
    checkAdmin = check(req, res);
    console.log(`Dev ${req.session.d_id}`)
    var query = { id: { $eq: parseInt(req.session.d_id) } };
    let tokenGet = undefined;
    guildpropdatabase.tokenFind(query).then((data) => { 
      console.log(`${query.id} and data ${data}`)
      if(!data[0]){

      }else{
        tokenGet=data[0].token
      }
      //console.log(tokenGet + "test")
      res.render(path.join('dev'), {
        user: dataUserName,
        admin: checkAdmin,
        token: tokenGet
      });
    }).catch((err) => { if (err) throw err; });
    
  }else {
    res.redirect('/login');
  }
 
});



app.get('/legal', function(req, res){
  var dataUserName = req.session.username;
  var checkAdmin;
  if (req.session.servers != undefined) {
    checkAdmin = check(req, res);
  }
  res.render(path.join('legal'), {
    user: dataUserName,
    admin: checkAdmin
  })
})
app.get('/report/delete', function (req, res) {
  if (req.session.servers == undefined) {
    res.send("404: Forbidden.");
    return;
  }
  if (req.session.servers != undefined) {
    checkAdmin = check(req, res);
  }
  if (checkAdmin = false) {
    res.send("404: Forbidden.");
  }
  var num = req.query["reportNumber"];
  num = parseInt(num);
  var query = { reportNumber: { $eq: parseInt(num) } };

  guildpropdatabase.rpRemove(query).then(() => { }).catch((err) => { if (err) throw err; });
  res.redirect('/');
  discordStuffToDelete(num, req);
});

const helper = require('./commands/everyone/helper.js');
async function discordStuffToDelete(reportNumber, req) {
  var approvalId;
  var subId;
  await helper.getID(reportNumber).then((data) => {
    console.log(data)
    approvalId = data[0].messageIdForApp;
    subId = data[0].messageIdForSub;
    bot.guilds.get("437048931827056642").channels.get("520994488680710144").fetchMessage(subId).then(theMessage => {
      theMessage.delete();
    })
  }).catch((err) => {
    console.log(`[ERROR] ${err}`)
  });


}

app.get('/report/inprogress', function (req, res) {
  if (req.session.servers == undefined) {
    res.send("404: Forbidden.");
    return;
  }
  if (req.session.servers != undefined) {
    checkAdmin = check(req, res);
  }
  if (checkAdmin = false) {
    res.send("404: Forbidden.");
  }
  var num = req.query["reportNumber"];
  num = parseInt(num);
  var query = { reportNumber: { $eq: parseInt(num) } };
  var newData = { $set: { progress: "In-Progress" } };
  guildpropdatabase.rpDbUpdate(query, newData).then(() => { }).catch((err) => { if (err) throw err; });
  res.redirect('/');
});
app.get('/report/open', function (req, res) {
  if (req.session.servers == undefined) {
    res.send("404: Forbidden.");
    return;
  }
  if (req.session.servers != undefined) {
    checkAdmin = check(req, res);
  }
  if (checkAdmin = false) {
    res.send("404: Forbidden.");
  }
  var num = req.query["reportNumber"];
  num = parseInt(num);
  var query = { reportNumber: { $eq: parseInt(num) } };
  var newData = { $set: { progress: "Reported" } };
  guildpropdatabase.rpDbUpdate(query, newData).then(() => { }).catch((err) => { if (err) throw err; });
  res.redirect('/');
  discordStuffToOpen(num, req);
})
app.get('/report/close', function (req, res) {
  if (req.session.servers == undefined) {
    res.send("404: Forbidden.");
    return;
  }
  if (req.session.servers != undefined) {
    checkAdmin = check(req, res);
  }
  if (checkAdmin = false) {
    res.send("404: Forbidden.");
  }
  var num = req.query["reportNumber"];
  num = parseInt(num);
  var query = { reportNumber: { $eq: parseInt(num) } };
  var newData = { $set: { progress: "Closed" } };
  guildpropdatabase.rpDbUpdate(query, newData).then(() => { }).catch((err) => { if (err) throw err; });
  res.redirect('/');
  discordStuffToClose(num, req);
})
async function get_list_of_reports() {
  return new Promise(async function (resolve, reject) {
    let query = { reportNumber: { $gt: 3 } }
    await guildpropdatabase.rpDbFind(query).then(results => {
      resolve(results);
      results.forEach(currentTemp => {
        /*console.log(currentTemp);
        currentTemp.fields.forEach(loc =>{
          console.log(loc);
        })
        console.log("---------------------------------------------------")*/
      })
    }).catch((err) => { reject(err) });
  });
}

const fetch = require('node-fetch');
const { catchAsync } = require('./utils');
const btoa = require('btoa');
const redirectURL = encodeURIComponent('https://BugBot.kpostal10.repl.co/callback');
const jwt = require('jsonwebtoken');
app.get('/callback', catchAsync(async (req, res) => {
  console.log("[Event]: loaded /callback")
  if (!req.query.code) throw new Error('NoCodeProvided');
  const code = req.query.code;
  //code is what permssions you allow it to see.
  //console.log(code)
  const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
  //binary representation of that ^
  //console.log(creds)
  var response = await fetch(`https://discordapp.com/api/oauth2/token?grant_type=authorization_code&code=${code}&redirect_url=${redirectURL}`,
    {
      method: 'POST',
      headers: {
        Authorization: `Basic ${creds}`,
      },
    });
  var json = await response.json();
  console.log(json.guilds)
  tmp = json.access_token;
  response = await fetch(`https://discordapp.com/api/users/@me`,
    {
      method: 'GET',
      headers: {
        Authorization: `Bearer ${tmp}`
      }
    });
  var json1 = await response.json();
  //console.log(json1);
  var serverList = await fetch(`https://discordapp.com/api/users/@me/guilds`,
    {
      method: 'GET',
      headers: {
        Authorization: `Bearer ${tmp}`
      }
    }
  );
  var json3 = await serverList.json();
  //console.log(json3);
  //console.log(json1);
  json3.forEach(currentLocation => {
    currentLocation.name = emojiStrip(currentLocation.name);
  });

  var sessData = req.session;
  sessData.servers = json3;
  sessData.username = json1.username;
  sessData.discriminator = json1.discriminator;
  sessData.d_id = json1.id;
  console.log(`${json1.id} Id check`)
  /*
  console.log(`Server list check ${sessData.servers} server list check`)
  console.log(`${sessData.id} Id check`)
  console.log(`${sessData.username} This is a log test`)
  console.log(`${req.session} This is a log test`)
  */

  res.redirect('/');



}));
const rp = require('request-promise');
const url = 'https://BotPinger.kpostal10.repl.co/ping';
app.get('/ping', (req, res) => {
  console.log("[PING] Pinged by bot pinger");
  /*rp(url)
    .then(function(html){
      console.log("[PING] Pinged bot pinger");
    })
    .catch(function(err){
      console.log(err);
    });*/
  res.render(path.join('ping'));
});
app.get('/login', (req, res) => {
  console.log("[Event]: loaded /login")
  res.redirect(`https://discordapp.com/oauth2/authorize?client_id=${CLIENT_ID}&scope=identify%20guilds&response_type=code`);

});
app.get('/logout', function (req, res) {
  req.session.destroy();
  res.redirect(`/`)
});
app.get('/discordinvite', function (req, res) {
  res.redirect('https://discord.gg/5gcPC6B');
});

app.get('/commands', function (req, res) {
  var dataUserName = req.session.username;
  var checkAdmin;
  if (req.session.servers != undefined) {
    checkAdmin = check(req, res);
  }
  res.render(path.join('commands'), {
    user: dataUserName,
    admin: checkAdmin
  })
});

app.get('/format', function (req, res) {
  formatPageLoadCount++;
  var dataUserName = req.session.username;
  var checkAdmin;
  var checkReplServer;
  if (req.session.servers != undefined) {
    checkAdmin = check(req, res);
    checkReplServer = checkRepl(req, res);
  }
  //console.log(`[DEBUG] ${req.csrfToken()}`);
  res.render(path.join('format'), {
    csrf_: req.csrfToken(),
    user: dataUserName,
    admin: checkAdmin,
    onReplit: checkReplServer
  });
});

app.post('/format/report', function(req, res){
  res.redirect('/');
});

app.post('/format/get', function (req, res) {
  console.log(req.body);

  var steps = "[";
  if (typeof req.body.listed === "string") {
    steps += req.body.listed;
  } else {
    req.body.listed.forEach(current => {

      steps += current + ",";


    });
    steps = steps.substring(0, steps.length - 1);
  }
  steps += "]";
  let langFix = null;
  if (req.body.lang != '') {
    langFix = req.body.lang;
  }
  var test = req.body.test;
  /*var test = escape(req.body.test);
  while(test.indexOf("%20") != -1){
    test = test.replace("%20", " ");
  } */
  var description = req.body.description;
  /*var description = escape(req.body.description);
  while(description.indexOf("%20") != -1){
    description = description.replace("%20", " ");
  } */
  var int = req.body.int;
  var attachment = null;
  if (req.body.image != '') {
    attachment = req.body.image;
  }
  /*
  var int = escape(req.body.int);
  while(int.indexOf("%20") != -1){
   int = int.replace("%20", " ");
  } */
  var command = `--report |${test}| |${description}| |${steps}| |${langFix}| |${int}| |${attachment}|`;

  res.render(path.join('formmated'), {
    commandPass: command
  });
});

app.use((err, req, res, next) => {
  console.log(`[Notice]: ${err}`)
  if (err.code === 'EBADCSRFTOKEN') return res.status(403).send({
    status: 'Error',
    error: 'form tampered with'
  });

  switch (err.message) {
    case 'NoCodeProvided':
      return res.status(400).send({
        status: 'ERROR',
        error: err.message,
      });
    default:
      return res.status(500).send({
        status: 'ERROR',
        error: err.message,
      });
  }
  next();
});


async function discordStuffToOpen(reportNumber, req) {
  var approvalId;
  var subId;
  await helper.getID(reportNumber).then((data) => {
    console.log(data)
    approvalId = data[0].messageIdForApp;
    subId = data[0].messageIdForSub;
    bot.guilds.get("437048931827056642").channels.get("520994488680710144").fetchMessage(subId).then(theMessage => {

      var passJson = { name: "Report reopened via website", value: ` Opened by ${req.session.username}#${req.session.discriminator}.` };
      helper.createNewEmbed(theMessage, null, passJson, 123458);
    })
  }).catch((err) => {
    console.log(`[ERROR] ${err}`)
  });


}


async function discordStuffToClose(reportNumber, req) {
  var approvalId;
  var subId;
  await helper.getID(reportNumber).then((data) => {
    console.log(data)
    approvalId = data[0].messageIdForApp;
    subId = data[0].messageIdForSub;
    bot.guilds.get("437048931827056642").channels.get("520994488680710144").fetchMessage(subId).then(theMessage => {

      var passJson = { name: "Report closed via website", value: ` Closed by ${req.session.username}#${req.session.discriminator}.` };
      helper.createNewEmbed(theMessage, null, passJson, 0xf22626);
    })
  }).catch((err) => {
    console.log(`[ERROR] ${err}`)
  });


}



const bot = new Commando.CommandoClient({
  owner: '130548661892546560',
  commandPrefix: '--',
  unknownCommandResponse: false	
});
const MongoClient = require('mongodb').MongoClient;
const MongoDBProvider = require('./api/commando-provider.js');
const optionsTwo = {
  useNewUrlParser: true,

  reconnectTries: 100, // Never stop trying to reconnect
  reconnectInterval: 500, // Reconnect every 500ms
  poolSize: 2, // Maintain up to 10 socket connections
  // If not connected, return errors immediately rather than waiting for reconnect
  bufferMaxEntries: 0
};
bot.setProvider(
  MongoClient.connect(process.env.LinkTest, optionsTwo).then(bot => new MongoDBProvider(bot, 'BugBot')).catch(err => {if(err) throw err})
).catch(err => {if(err) throw err;});

bot.login(process.env.thing).catch(() => {
  bot.setTimeout(() => {
    bot.login(process.env.thing);
  }, 300000);
});
bot.registry.registerGroup('everyone', 'Everyone');
bot.registry.registerGroup('owner', 'Owner');
bot.registry.registerDefaults();
bot.registry.registerCommandsIn(__dirname + "/commands");

bot.on("ready", () => {
  console.log("Generic on ready log");
});
bot.on("unknownCommand", message => {
  if (message.channel.type == 'dm') {
    return;
  }
  
});
bot.on("guildCreate", guild => {
  let approvalid;
  let reportid;
  console.log(`New Guild added : ${guild.name}, owned by ${guild.owner.user.username}`);
  var query = { guildId: guild.id };
  guildpropdatabase.dbFind(query, function (err, results) {
    if (results[0] != null || results[0] != undefined) {
      return;
    }
  });
  let bughunterrole;
  guild.createRole({
    name: 'Bug Hunters',
    color: '#ca3434'
  }).then(role => {
    console.log("Created role");
    bughunterrole = role;
  }).catch(console.error);
  let botUser = guild.members.find(r => r.id === "516125936933011467");
  let everyone = guild.roles.find(r => r.name === '@everyone');
  sleep(2000);
  guild.createChannel("Bugs", "category", [
    {
      id: everyone,
      allow: ['READ_MESSAGES'],
      deny: ['ADD_REACTIONS']
    }
  ], "Created the channel category for all bug bot channels to be in.").then(cat => {

    guild.createChannel("Bug-reports", "text", [
      {
        id: everyone,
        allow: ['READ_MESSAGES']
      }
    ], "Created the channel bug-reports for reports to be submited").then(channel => {
      channel.setParent(cat);
      reportid = channel.id;
      channel.edit({ topic: "This channel is for use of bot commands only." })
    }).catch(console.error);

    guild.createChannel("Bug-approval-queue", "text", [
      {
        id: everyone,
        deny: ['SEND_MESSAGES', 'ATTACH_FILES', "ADD_REACTIONS"]
      },
      {
        id: bughunterrole,
        allow: ['SEND_MESSAGES']
      }
    ], "Created the channel for bug hunters to approve bugs").then(channel => {
      channel.setParent(cat);
      approvalid = channel.id;
      channel.edit({ topic: "This channel is for use of bot commands only." });


      //var safeName = emojiStrip(guild.name);


    }).catch(console.error);

  }).catch(console.error);

  sleep(10000);
  var myobj = { guildName: guild.name, guildId: guild.ownerID, guildOwner: guild.owner.user.username, bugApprovalId: approvalid, bugReportId: reportid };
  //console.log("Here")
  guildpropdatabase.dbInsert(myobj, function (err, result) {
    if (err) {
      console.log(`[Databses error]: ${err}`);
    }
    //console.log("Inserted into db");
  });

});

bot.on('message', message => {
  if (message.channel.type == 'dm') {
    return;
  }

  if (message.author.bot) return;

  if (message.channel.id === "520994488680710144" || message.channel.id === "520994491948204074") {

    if (message.author.bot && message.content.includes(" you a DM ")) {
      message.delete();
    }
    if (message.content.substring(0, 2) === "--" && !message.content.includes("--help")) {
      return;
    } else {
      message.delete();
      return message.channel.send({
        embed: {
          color: 0xFF0000,
          title: "Channel is to be used by commands only",
          timestamp: Date()
        }
      }).then(currentMessage => {
        setTimeout(() => {
          currentMessage.delete();
        }, 5000);
      });
    }
  }

});

function sleep(millis) {
  return new Promise(resolve => setTimeout(resolve, millis));
}

function checkRepl(req, res){
  var dataUserName = req.session.username;
  var dataServerList = req.session.servers;
  var temp = false;
  dataServerList.forEach(dataserverSeaperate => {
      if (dataserverSeaperate.id == "437048931827056642") {
        temp = true;
      }
  });
  //console.log("It should not be getting here")
  return temp;

}

function check(req, res) {
  var dataUserName = req.session.username;
  var dataServerList = req.session.servers;
  var temp = false;
  dataServerList.forEach(dataserverSeaperate => {
    if (dataserverSeaperate.permissions & 0x20 || dataserverSeaperate.permissions & 0x8 || dataserverSeaperate.permissions & 0x2000) {
      //updatedServerlist.push(dataserverSeaperate);
      if (dataserverSeaperate.id == "437048931827056642") {
        //console.log("is admin");
        temp = true;
      }
    }
  });
  //console.log("It should not be getting here")
  return temp;

}
node v10.16.0