133 Commits
Author SHA1 Message Date
SowinskiBraeden 24576ca981 Update README.md 2024-11-07 16:24:16 -08:00
SowinskiBraeden 6c19a50f87 Update README.md 2024-11-07 16:20:18 -08:00
SowinskiBraeden c6563ca2cd update README.md and .gitignore 2024-11-07 15:42:05 -08:00
SowinskiBraeden 5ddd430cbc update stats command to reflect all shards 2024-10-27 16:10:51 -07:00
SowinskiBraeden 4a22b36aa0 fix/duplicate + broken reset-channels command 2024-04-11 18:12:55 -07:00
SowinskiBraeden 56180a7f4b actually ping role with pingOnPanic 2024-01-24 12:15:35 -08:00
SowinskiBraeden 3355302994 handle undefined allowedRoles 2024-01-23 22:29:22 -08:00
SowinskiBraeden 4435f0b2df fix role verification 2024-01-23 18:26:10 -08:00
SowinskiBraeden 358f1f560d fix role verification 2024-01-23 17:40:06 -08:00
SowinskiBraeden 7bfecb3624 fix role verification 2024-01-23 17:13:27 -08:00
SowinskiBraeden 574ead8f4a fix role verification 2024-01-23 17:01:29 -08:00
SowinskiBraeden 86104599a1 fix role verification 2024-01-23 16:37:43 -08:00
SowinskiBraeden f6ebb43317 fix role verification 2024-01-23 16:36:19 -08:00
SowinskiBraeden 7366c299cc fix role verification 2024-01-23 16:31:25 -08:00
SowinskiBraeden a24a616459 clean my code + fix permissions error? 2024-01-23 13:59:11 -08:00
SowinskiBraeden b396cd742b fix deleted role detection 2024-01-22 20:57:30 -08:00
SowinskiBraeden 9d9a764b1d clear any deleted roles still stored in allowedRoles during verification 2024-01-22 20:08:36 -08:00
SowinskiBraeden 13e66b29ad clean my code because its bad + fix bot not responding when activating panic when pingOnPanic is disabled 2024-01-22 19:21:14 -08:00
SowinskiBraeden 2cd8185c0a clean my own code 2024-01-22 12:27:33 -08:00
SowinskiBraeden 4c51956f59 update/allow sharding 2023-09-26 08:42:09 -07:00
SowinskiBraeden 6dae712074 fix reset-channel.js 2023-07-01 18:55:56 -07:00
SowinskiBraeden 86acd5ea7a fix reset-channel.js 2023-07-01 18:55:20 -07:00
SowinskiBraeden 21e1eec514 reset channels 2023-07-01 18:53:21 -07:00
SowinskiBraeden 83aca4b7b0 Debug updateStatus not logged in check 2023-06-10 15:27:37 -07:00
SowinskiBraeden ef85183f1c debug reset_channels command 2023-02-28 15:33:30 -08:00
SowinskiBraeden 39160ab3dd debug reset_channel 2023-02-28 14:02:45 -08:00
SowinskiBraeden d7d2928aea reset channel feature 2023-02-27 10:45:55 -08:00
SowinskiBraeden df3ec26f13 reset channel feature 2023-02-27 10:45:33 -08:00
SowinskiBraeden 8997b5de01 debug delays 2023-02-01 19:12:41 -08:00
SowinskiBraeden abc078eab8 delay updating slash commands 2023-02-01 16:56:24 -08:00
SowinskiBraeden a653b8d394 3.1.7 bug fixes 2023-01-23 15:41:22 -08:00
SowinskiBraeden 5dcd737189 minor code refactor 2023-01-23 13:56:08 -08:00
SowinskiBraeden 14ea5a56c4 3.1.5 Improved Interaction / Error Handling 2023-01-23 08:50:22 -08:00
SowinskiBraeden 05930e8d33 use interaction handler 2023-01-21 16:03:55 -08:00
SowinskiBraeden 2a8252289c 3.1.3 minor bug fix 2023-01-21 14:05:28 -08:00
SowinskiBraeden db9dc35912 include dotenv 2022-12-03 12:31:50 -08:00
SowinskiBraeden cb118a886f fix bot activity 2022-11-21 14:21:42 -08:00
SowinskiBraeden 3ce08793c9 add website shortcut 2022-11-11 12:17:10 -08:00
SowinskiBraeden d88cbb7241 fix /channels bug 2022-11-10 20:58:22 -08:00
SowinskiBraeden ef72b58921 add missing data check 2022-10-05 20:21:37 -07:00
SowinskiBraeden 56bdecc872 remove deprecated attribute 2022-10-03 19:38:48 -07:00
SowinskiBraeden 2e463c480a don't use client.error 2022-10-03 19:35:08 -07:00
SowinskiBraeden 8a22560357 remove all no dict message bugs 2022-10-03 18:10:12 -07:00
SowinskiBraeden 93dfd8c6da fix not using dict error 2022-10-03 18:08:22 -07:00
SowinskiBraeden deb5f90654 fix bot error message 2022-10-02 12:57:47 -07:00
SowinskiBraeden c972d3610d remove debug 2022-09-30 13:33:39 -07:00
SowinskiBraeden 00d7ccb631 update color 2022-09-30 13:32:21 -07:00
SowinskiBraeden f04f6ba211 fix setAuthor deprecation? 2022-09-30 13:29:51 -07:00
SowinskiBraeden 481f012d6a reformat command data structure 2022-09-30 13:18:57 -07:00
SowinskiBraeden fd811f30ab fix setFooter deprecation issues 2022-09-30 11:19:38 -07:00
SowinskiBraeden 21811a18a9 fix even more deprecation issues 2022-09-30 11:11:27 -07:00
SowinskiBraeden 7b13df2c73 fix more deprecation issues 2022-09-30 11:08:58 -07:00
SowinskiBraeden a1cc29c43c fix deprecation issues 2022-09-30 10:52:40 -07:00
SowinskiBraeden 4b0d89899a debug channels command 2022-08-07 23:11:17 -07:00
SowinskiBraeden aa5ee4f8e3 debug 2022-08-07 09:31:16 -07:00
SowinskiBraeden ce905463f5 only get used data 2022-08-06 20:33:21 -07:00
SowinskiBraeden 75b685cab4 fix undefined err 2022-08-06 14:31:42 -07:00
SowinskiBraeden 418645ebd8 debug 2022-08-06 13:14:57 -07:00
SowinskiBraeden 6245826c6f update handle error 2022-08-06 12:35:01 -07:00
SowinskiBraeden f33853e698 hide debug 2022-08-06 11:01:36 -07:00
SowinskiBraeden d6df756eca remove deprecated file 2022-08-06 10:21:31 -07:00
SowinskiBraeden eeebd59817 Merge branch 'master' of https://github.com/SowinskiBraeden/police-cad-bot 2022-08-06 10:20:28 -07:00
SowinskiBraeden 88f89eae11 deprecate prefix commands 2022-08-06 10:19:41 -07:00
SowinskiBraeden f456891373 Update messageCreate.js 2022-07-25 21:19:39 -07:00
SowinskiBraeden 0d69c6c79d fix crash bug 2022-07-03 13:27:57 -07:00
SowinskiBraeden 9d6be863ad update message/discord verision 2022-06-06 18:17:21 -07:00
SowinskiBraeden 295744fbe0 Merge branch 'master' of https://github.com/SowinskiBraeden/police-cad-bot 2022-06-06 17:31:53 -07:00
SowinskiBraeden d1d86c2e26 cache undefined fix 2022-06-06 17:31:38 -07:00
SowinskiBraeden 13fabf2839 Merge pull request #12 from SowinskiBraeden/dependabot/npm_and_yarn/minimist-1.2.6
Bump minimist from 1.2.5 to 1.2.6
2022-05-31 12:16:37 -07:00
dependabot[bot] b3db586a7f Bump minimist from 1.2.5 to 1.2.6
Bumps [minimist](https://github.com/substack/minimist) from 1.2.5 to 1.2.6.
- [Release notes](https://github.com/substack/minimist/releases)
- [Commits](https://github.com/substack/minimist/compare/1.2.5...1.2.6)

---
updated-dependencies:
- dependency-name: minimist
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-05-31 19:13:58 +00:00
SowinskiBraeden f7b8d06bd1 fix interaction acknowledged bug 2022-05-22 10:10:19 -07:00
SowinskiBraeden ec0096cdd3 improper return 2022-05-15 09:46:41 -07:00
SowinskiBraeden 66966c7fd6 Trigger Heroku deploy after enabling collectstatic 2022-05-13 16:14:27 -07:00
SowinskiBraeden 6b1f010f32 fix plateSearch GuildDB undefined err 2022-05-11 14:02:45 -07:00
SowinskiBraeden 62077831b4 fix channel provide args 2022-05-10 21:06:11 -07:00
SowinskiBraeden 7ab1b78de1 fix interaction send not in comm 2022-05-10 11:42:53 -07:00
SowinskiBraeden 8e80c38255 Trigger Heroku deploy after enabling collectstatic 2022-05-06 22:33:32 -07:00
SowinskiBraeden d39e0226fc fix incorrect message ping in firearm search 2022-05-06 22:22:39 -07:00
SowinskiBraeden 759a1032c3 fix sockets and remove deprecated version 2022-05-06 22:15:25 -07:00
SowinskiBraeden 424d5721b5 fix panic feedback 2022-05-06 14:20:55 -07:00
SowinskiBraeden a0a2308270 add objectid def 2022-05-06 14:12:11 -07:00
SowinskiBraeden a1edacd4db remove debug 2022-05-06 13:58:29 -07:00
SowinskiBraeden 8ace046edf fix check status 2022-05-06 13:56:31 -07:00
SowinskiBraeden b07139bda9 bug fixes 2022-05-06 13:52:06 -07:00
SowinskiBraeden 449131e990 fix undefined exists func 2022-05-06 13:42:50 -07:00
SowinskiBraeden cd799a8974 fix undefined exists func 2022-05-06 13:39:38 -07:00
SowinskiBraeden c41849eb51 add log message 2022-03-28 17:21:56 -07:00
SowinskiBraeden adb40b3bb8 bot leave server 2022-03-28 17:20:48 -07:00
SowinskiBraeden 7565a75575 fix client not respond on /account 2022-03-21 16:47:40 -07:00
SowinskiBraeden e79ba906af update procfile 2022-03-19 14:26:00 -07:00
SowinskiBraeden a4025837a7 change error output to log 2022-03-19 14:14:54 -07:00
SowinskiBraeden 9c835a2503 fix version display and DefaultPrefix 2022-03-17 16:47:05 -07:00
SowinskiBraeden 2e43637d67 fix configs 2022-03-17 16:24:31 -07:00
SowinskiBraeden 50fcd6900c clean 2022-03-17 16:10:23 -07:00
SowinskiBraeden 96fc4f8fe4 update .gitignore 2022-03-17 16:00:49 -07:00
SowinskiBraeden 9a4bd50dd6 remove logs 2022-03-17 16:00:25 -07:00
SowinskiBraeden 98ea99e879 Merge pull request #11 from SowinskiBraeden/reformat-code
Reformat code
2022-03-17 15:59:14 -07:00
SowinskiBraeden 41411856f2 Merge branch 'master' into reformat-code 2022-03-17 15:59:05 -07:00
SowinskiBraeden 81732072ba update initialization 2022-03-17 15:51:36 -07:00
SowinskiBraeden 47fec8ccb0 update initializers 2022-03-17 15:34:40 -07:00
SowinskiBraeden 63667c30b8 update configs 2022-03-17 15:33:40 -07:00
SowinskiBraeden 8d5584d097 update/verify user has role 2022-03-17 15:30:49 -07:00
SowinskiBraeden e1c599d3c6 update presence 2022-03-17 12:48:02 -07:00
SowinskiBraeden 9edb6b98d7 use client.exists 2022-03-17 12:16:52 -07:00
SowinskiBraeden 1cbe4356bc update/fix pingonpanic 2022-03-17 12:06:55 -07:00
SowinskiBraeden 3df8bc70e8 update/ping on panic status 2022-03-16 21:33:48 -07:00
SowinskiBraeden 698f04195a update/toggle ping on panic 2022-03-16 21:31:00 -07:00
SowinskiBraeden 21b17797d7 update/channels 2022-03-16 21:17:36 -07:00
SowinskiBraeden 03ee421432 update/remove channel 2022-03-16 21:07:32 -07:00
SowinskiBraeden 4caccd74d4 update/set channel 2022-03-16 21:00:41 -07:00
SowinskiBraeden d9855048c6 update/roles 2022-03-16 20:53:51 -07:00
SowinskiBraeden 0bd83dad87 update/remove role and exists func 2022-03-16 20:15:50 -07:00
SowinskiBraeden dcbaf23828 update/set role 2022-03-16 19:07:46 -07:00
SowinskiBraeden ee23d59a44 update/community 2022-03-16 18:27:16 -07:00
SowinskiBraeden a8f4785478 update/leave community 2022-03-16 18:24:08 -07:00
SowinskiBraeden 5242344db3 update/join community 2022-03-16 18:19:50 -07:00
SowinskiBraeden 495c4755ae update/update license 2022-03-16 17:58:54 -07:00
SowinskiBraeden 441bb0672c update/add panic control 2022-03-09 16:45:14 -08:00
SowinskiBraeden 76467288f5 update/add update status 2022-03-09 13:04:39 -08:00
SowinskiBraeden cb22a8fe80 update/check status 2022-03-08 21:04:45 -08:00
SowinskiBraeden d116ea9c8c update/add firearm search and use config.IconUrl 2022-03-08 20:29:12 -08:00
SowinskiBraeden 3e2fe386c3 update/add plateSearch 2022-03-08 20:20:12 -08:00
SowinskiBraeden 68120d1e60 update/add nameSearch and debug control 2022-03-08 19:58:56 -08:00
SowinskiBraeden 6cbd981a00 uppdate/add name search 2022-03-08 14:06:29 -08:00
SowinskiBraeden 5a8753357e update/add account view 2022-03-08 13:52:34 -08:00
SowinskiBraeden 6e6dbd2c3b update/add logout command 2022-03-08 13:42:09 -08:00
SowinskiBraeden 55912cb29e update/add remote login 2022-03-08 13:31:00 -08:00
SowinskiBraeden 2c1d15cfc4 update/add logs and update prefix 2022-03-08 13:27:23 -08:00
SowinskiBraeden 0495577b3c begin reformat code structur 2022-03-07 22:50:29 -08:00
SowinskiBraeden d0cb22b54e Merge pull request #8 from SowinskiBraeden/dependabot/npm_and_yarn/node-fetch-2.6.7
Bump node-fetch from 2.6.1 to 2.6.7
2022-02-17 22:24:56 -08:00
dependabot[bot] 19cf2a4d8f Bump node-fetch from 2.6.1 to 2.6.7
Bumps [node-fetch](https://github.com/node-fetch/node-fetch) from 2.6.1 to 2.6.7.
- [Release notes](https://github.com/node-fetch/node-fetch/releases)
- [Commits](https://github.com/node-fetch/node-fetch/compare/v2.6.1...v2.6.7)

---
updated-dependencies:
- dependency-name: node-fetch
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-02-18 06:20:05 +00:00
SowinskiBraeden 64efe3f772 debug/fix spelling mistakes causing crash 2022-02-17 09:43:13 -08:00
SowinskiBraeden 495c356d41 update/command-help-list 2022-01-25 20:58:02 -08:00
46 changed files with 4111 additions and 2392 deletions

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
# MongoDB connection URI as set in police-cad .env
dbo=knoldus
mongoURI=mongodb://localhost/knoldus
# Discord Bot Token
token=
+4 -7
View File
@@ -1,11 +1,8 @@
# dependencies
node_modules/*
# test file
test.js
# logs
logs/*
# Dev Launch
dev.js
# Dev config
dev-config.json
# environment variables
.env
-881
View File
@@ -1,881 +0,0 @@
const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectID
const randomstring = require('randomstring');
const io = require('socket.io-client');
const Discord = require('discord.js');
const client = new Discord.Client();
class Bot {
constructor(dev, token, config, mongoURI, dbo) {
this.dev = dev;
this.token = token;
this.config = require(config);
this.connectMongo(mongoURI, dbo);
}
async connectMongo(mongoURI, dbo) {
this.db = await MongoClient.connect(mongoURI,{useUnifiedTopology:true});
this.dbo = this.db.db(dbo);
}
// Updates Prefix
async newPrefix(message, n) {
if (n[0]==undefined) return message.channel.send(`You must provide a \`new prefix\` ${message.author}`);
if (n[0].length<1) return message.channel.send('Your new prefix must be \`1\` character!')
this.dbo.collection("prefixes").updateOne({"server.serverID":message.guild.id},{$set:{"server.prefix":n[0]}},function(err, res) {
if (err) throw err;
message.channel.send(`The new prefix is now **\`${n}\`**`);
});
}
// Remote Login
async remoteLogin(message, args) {
return message.channel.send('Login from Lines Police CAD account management https://www.linespolice-cad.com/');
}
async remoteLogout(message) {
let user = await this.dbo.collection("users").findOne({"user.discord.id":message.author.id}).then(user => user);
if (!user) return message.channel.send(`You cannot logout if your not logged in ${message.author}`);
this.dbo.collection("users").updateOne({"user.discord.id":message.author.id},{$unset:{"user.discord":""}, $set:{"user.discordConnected":false}},function(err,res) {
if (err) throw err;
message.channel.send(`Succesfully disconnected you Discord account ${message.author}`);
});
}
async account(message) {
let user = await this.dbo.collection("users").findOne({"user.discord.id":message.author.id}).then(user => user);
if (user==null) return message.channel.send(`You are not logged in ${message.author}`);
message.author.send(`${message.author} Logged in as **${user.user.username}** | **${user.user.email}**`);
}
async nameSearch(message, args) {
let user = await this.dbo.collection("users").findOne({"user.discord.id":message.author.id}).then(user => user);
if (!user) return message.channel.send(`You are not logged in ${message.author}`);
let data;
if (user.user.activeCommunity=='' || user.user.activeCommunity==null) {
if (args.length==0) return message.channel.send(`You must provide a \`First Name\`, \`Last Name\` and \`DOB\`(yyyy-mm-dd) ${message.author}`);
if (args.length==1) return message.channel.send(`You're missing a \`Last Name\` and \`DOB\`(yyyy-mm-dd) ${message.author}`);
if (args.length==2) return message.channel.send(`You're missing a \`DOB\`(yyyy-mm-dd) ${message.author}`);
}
if (args.length==0) return message.channel.send(`You must provide a \`First Name\` and \`Last Name\` ${message.author}`);
if (args.length==1) return message.channel.send(`You're missing a \`Last Name\` ${message.author}`);
if (user.user.activeCommunity=='' || user.user.activeCommunity==null) {
data = {
user: user,
query: {
firstName: args[0],
lastName: args[1],
dateOfBirth: args[2],
activeCommunityID: user.user.activeCommunity
}
}
} else {
data = {
user: user,
query: {
firstName: args[0],
lastName: args[1],
activeCommunityID: user.user.activeCommunity
}
}
}
const socket = io.connect(this.config.socket);
socket.emit("bot_name_search", data);
socket.on("bot_name_search_results", results => {
if (results.user._id==user._id) {
if (results.civilians.length == 0) {
return message.channel.send(`Name \`${args[0]} ${args[1]}\` not found ${message.author}`);
}
for (let i = 0; i < results.civilians.length; i++) {
// Get Drivers Licence Status
let licenceStatus;
if (results.civilians[i].civilian.licenseStatus == 1) licenceStatus = 'Valid';
if (results.civilians[i].civilian.licenceStatus == 2) licenceStatus = 'Revoked';
if (results.civilians[i].civilian.licenceStatus == 3) licenceStatus = 'None';
// Get Firearm Licence Status
let firearmLicence = results.civilians[i].civilian.firearmLicense;
if (firearmLicence == undefined || firearmLicence == null) firearmLicence = 'None';
if (firearmLicence == '2') firearmLicence = 'Valid';
if (firearmLicence == '3') firearmLicence = 'Revoked';
let nameResult = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle(`**${results.civilians[i].civilian.firstName} ${results.civilians[i].civilian.lastName} | ${results.civilians[i]._id}**`)
.setURL('https://discord.gg/jgUW656v2t')
.setAuthor('LPS Website Support', 'https://raw.githubusercontent.com/Linesmerrill/police-cad/master/lines-police-server.png', 'https://discord.gg/jgUW656v2t')
.setDescription('Name Search Results')
.addFields(
{ name: `**First Name**`, value: `\`${results.civilians[i].civilian.firstName}\``, inline: true },
{ name: `**Last Name**`, value: `\`${results.civilians[i].civilian.lastName}\``, inline: true },
{ name: `**DOB**`, value: `\`${results.civilians[i].civilian.birthday}\``, inline: true },
{ name: `**Drivers License**`, value: `\`${licenceStatus}\``, inline: true },
{ name: `**Firearm Licence**`, value: `\`${firearmLicence}\``, inline: true },
{ name: `**Gender**`, value: `\`${results.civilians[i].civilian.gender}\``, inline: true }
)
// Check Other details
let address = results.civilians[i].civilian.address;
let occupation = results.civilians[i].civilian.occupation;
let height = results.civilians[i].civilian.height;
let weight = results.civilians[i].civilian.weight;
let eyeColor = results.civilians[i].civilian.eyeColor;
let hairColor = results.civilians[i].civilian.hairColor;
if (address != null && address != undefined && address != '') nameResult.addFields({ name: `**Address**`, value: `\`${address}\``, inline: true });
if (occupation != null && occupation != undefined && occupation != '') nameResult.addFields({ name: `**Occupation**`, value: `\`${occupation}\``, inline: true });
if (height!=null&&height!=undefined&&height!="NaN"&&height!='') {
if (results.civilians[i].civilian.heightClassification=='imperial') {
let ft = Math.floor(height/12);
let inch = height%12;
nameResult.addFields({ name: '**Height**', value: `\`${ft}'${inch}"\``, inline: true });
} else {
nameResult.addFields({ name: '**Height**', value: `\`${height}cm\``, inline: true });
}
}
if (weight!=null&&weight!=undefined&&weight!='') {
if (results.civilians[i].civilian.weightClassification=='imperial') {
nameResult.addFields({ name: '**Weight**', value: `\`${weight}lbs.\``, inline: true });
} else {
nameResult.addFields({ name: '**Weight**', value: `\`${weight}kgs.\``, inline: true });
}
}
if (eyeColor!=null&&eyeColor!=undefined&&eyeColor!='') nameResult.addFields({name:'**Eye Color**',value:`\`${eyeColor}\``,inline:true});
if (hairColor!=null&&hairColor!=undefined&&hairColor!='') nameResult.addFields({name:'**Hair Color**',value:`\`${hairColor}\``,inline:true});
nameResult.addFields({name:'**Organ Donor**',value:`\`${results.civilians[i].civilian.organDonor}\``,inline:true});
nameResult.addFields({name:'**Veteran**',value:`\`${results.civilians[i].civilian.veteran}\``,inline:true});
message.channel.send(nameResult);
}
}
socket.disconnect();
});
}
async plateSearch(message, args) {
let user = await this.dbo.collection("users").findOne({"user.discord.id":message.author.id}).then(user => user);
if (!user) return message.channel.send(`You are not logged in ${message.author}`);
if (args.length==0) return message.channel.send(`You are missing a \`Plate #\` ${message.author}`);
let data = {
user: user,
query: {
plateNumber: args[0],
activeCommunityID: user.user.activeCommunity
}
}
const socket = io.connect(this.config.socket);
socket.emit('bot_plate_search', data);
socket.on('bot_plate_search_results', results => {
if (results.user._id==user._id) {
if (results.vehicles.length == 0) {
return message.channel.send(`Plate Number \`${args[0]}\` not found ${message.author}`);
}
for (let i = 0; i < results.vehicles.length; i++) {
let plateResult = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle(`**${results.vehicles[i].vehicle.plate} | ${results.vehicles[i]._id}**`)
.setURL('https://discord.gg/jgUW656v2t')
.setAuthor('LPS Website Support', 'https://raw.githubusercontent.com/Linesmerrill/police-cad/master/lines-police-server.png', 'https://discord.gg/jgUW656v2t')
.setDescription('Plate Search Results')
.addFields(
{ name: `**Plate #**`, value: `\`${results.vehicles[i].vehicle.plate}\``, inline: true },
{ name: `**Vin #**`, value: `\`${results.vehicles[i].vehicle.vin}\``, inline: true },
{ name: `**Model**`, value: `\`${results.vehicles[i].vehicle.model}\``, inline: true },
{ name: `**Color**`, value: `\`${results.vehicles[i].vehicle.color}\``, inline: true },
{ name: `**Owner**`, value: `\`${results.vehicles[i].vehicle.registeredOwner}\``, inline: true },
)
// Other details
let validRegistration = results.vehicles[i].vehicle.validRegistration;
let validInsurance = results.vehicles[i].vehicle.validInsurance;
let stolen = results.vehicles[i].vehicle.isStolen;
if (validRegistration=='1') plateResult.addFields({ name: `**Registration**`, value: `\`Valid\``, inline: true });
if (validRegistration=='2') plateResult.addFields({ name: `**Registration**`, value: `\`InValid\``, inline: true });
if (validInsurance=='1') plateResult.addFields({ name: `**Insurance**`, value: `\`Valid\``, inline: true });
if (validInsurance=='2') plateResult.addFields({ name: `**Insurance**`, value: `\`InValid\``, inline: true });
if (stolen=='1') plateResult.addFields({ name: `**Stolen**`, value: `\`No\``, inline: true });
if (stolen=='2') plateResult.addFields({ name: `**Stolen**`, value: `\`Yes\``, inline: true });
message.channel.send(plateResult);
}
}
socket.disconnect();
});
}
async firearmSearch(message, args) {
let user = await this.dbo.collection("users").findOne({"user.discord.id":message.author.id}).then(user => user);
if (!user) return message.channel.send(`You are not logged in ${message.author}`);
if (args.length==0) return message.channel.send(`You are missing a \`Serial Number\` ${message.author}`);
let data = {
user: user,
query: {
serialNumber: args[0],
activeCommunityID: user.user.activeCommunity
}
}
const socket = io.connect(this.config.socket);
socket.emit('bot_firearm_search', data);
socket.on('bot_firearm_search_results', results => {
if (results.user._id==user._id) {
if (results.firearms.length==0) {
return message.channel.send(`No Firearms found ${message.author}`);
}
for (let i = 0; i < results.firearms.length; i++) {
let firearmResult = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle(`**${results.firearms[i].firearm.serialNumber} | ${results.firearms[i]._id}**`)
.setURL('https://discord.gg/jgUW656v2t')
.setAuthor('LPS Website Support', 'https://raw.githubusercontent.com/Linesmerrill/police-cad/master/lines-police-server.png', 'https://discord.gg/jgUW656v2t')
.setDescription('Firearm Search Results')
.addFields(
{ name: `**Serial Number**`, value: `\`${results.firearms[i].firearm.serialNumber}\``, inline: true },
{ name: `**Type**`, value: `\`${results.firearms[i].firearm.weaponType}\``, inline: true },
{ name: `**Owner**`, value: `\`${results.firearms[i].firearm.registeredOwner}\``, inline: true },
)
// Other details
let isStolen = results.firearms[i].firearm.isStolen;
if (isStolen=="false"||isStolen==false) firearmResult.addFields({name:`**Stolen**`,value:'\`No\`',inline: true});
if (isStolen=="true"||isStolen==true) firearmResult.addFields({name:`**Stolen**`,value:'\`Yes\`',inline: true});
message.channel.send(firearmResult);
}
}
socket.disconnect();
});
}
async checkStatus(message, args) {
let user = await this.dbo.collection("users").findOne({"user.discord.id":message.author.id}).then(user => user);
if (!user) return message.channel.send(`You are not logged in ${message.author}`);
if (user.user.activeCommunity == null) return message.channel.send(`You must join a community to use this command ${message.author}`);
if (args.length == 0) {
message.channel.send(`${message.author}'s status: \`${user.user.dispatchStatus}\` | Set by: \`${user.user.dispatchStatusSetBy}\``);
} else {
let targetUserID = args[0].replace('<@!', '').replace('>', '');
let targetUser = await this.dbo.collection("users").findOne({"user.discord.id":targetUserID}).then(user => user);
// This lame line of code to get username without ping on discord
const User = client.users.cache.get(args[0].replace('<@!', '').replace('>', ''));
if (!targetUser) return message.channel.send(`Cannot find **${User.tag}** ${message.author}`);
if (targetUser.user.activeCommunity!=user.user.activeCommunity) {
return message.channel.send(`You are not in the same community as \`${User.tag}\` ${message.author}`);
}
return message.channel.send(`${message.author}, \`${User.tag}'s\` status: \`${targetUser.user.dispatchStatus}\` | Set by: \`${targetUser.user.dispatchStatusSetBy}\``);
}
}
async updateStatus(message, args, prefix) {
let validStatus=['10-8','10-7','10-6','10-11','10-23','10-97','10-15','10-70','10-80', 'Panic', '10-41', '10-42'];
let user = await this.dbo.collection("users").findOne({"user.discord.id":message.author.id}).then(user => user);
if (!user) return message.channel.send(`You are not logged in ${message.author}`);
if (user.user.activeCommunity==null) return message.channel.send(`You must join a community to use this command ${message.author}`);
if (args.length==0) return message.channel.send(`You must provide a new status ${message.author} | To see a list of valid statuses, use command \`${prefix}validStatus\`.`);
if (!validStatus.includes(args[0])) return message.channel.send(`\`${args[0]}\` is a Invalid Status ${message.author}! To see a list of valid statuses, use command \`${prefix}validStatus\`.`);
let onDuty=null;
let updateDuty=false;
let status = args[0]
if (args[0]=='10-41') {
onDuty=true;
updateDuty=true;
status='Online';
}
if (args[0]=='10-42') {
onDuty=false;
updateDuty=true;
status='Offline';
}
let req={
userID: user._id,
status: status,
setBy: 'Self',
onDuty: onDuty,
updateDuty: updateDuty
};
const socket = io.connect(this.config.socket);
socket.emit('bot_update_status', req);
socket.on('bot_updated_status', (res) => {
message.channel.send(`Succesfully updated status to \`${args[0]}\` ${message.author}`);
socket.disconnect();
});
}
async enablePanic(message) {
let user = await this.dbo.collection("users").findOne({"user.discord.id":message.author.id}).then(user => user);
if (!user) return message.channel.send(`You are not logged in ${message.author}`);
if (user.user.activeCommunity==null) return message.channel.send(`You must join a community to use this command ${message.author}`);
const socket = io.connect(this.config.socket);
// If panic is enabled, disable panic
if (user.user.dispatchStatus=='Panic') {
let myReq = {
userID: user._id,
communityID: user.user.activeCommunity
};
socket.emit('clear_panic', myReq);
let myUpdateReq = {
userID: user._id,
status: '10-8',
setBy: 'System',
onDuty: null,
updateDuty: false
};
socket.emit('bot_update_status', myUpdateReq);
socket.on('bot_updated_status', (res) => {
message.channel.send(`Disabled Panic ${message.author} and set status to \`10-8\`.`);
socket.disconnect();
});
return;
// If panic is disabled, enable panic
} else {
this.updateStatus(message, ['Panic'], null);
let myReq = {
userID: user._id,
userUsername: user.user.username,
activeCommunity: user.user.activeCommunity
}
socket.emit('panic_button_update', myReq);
socket.disconnect();
let guild = await this.dbo.collection("prefixes").findOne({"server.serverID":message.guild.id}).then(guild => guild);
if (guild.server.pingOnPanic) return message.channel.send(`Attention <@&${guild.server.pingRole}>! \`${user.user.username}\` has activated panic`);
return;
}
}
async updateLicense(message, args) {
let user = await this.dbo.collection("users").findOne({"user.discord.id":message.author.id}).then(user => user);
if (!user) return message.channel.send(`You are not logged in ${message.author}`);
let data;
if (user.user.activeCommunity=='' || user.user.activeCommunity==null) {
if (args.length==0) return message.channel.send(`You must provide a \`License Status\`, \`First Name\`, \`Last Name\`, \`DOB\`(yyyy-mm-dd) ${message.author}`);
if (args.length==1) return message.channel.send(`You're missing a \`First Name\`, \`Last Name\` and \`DOB\`(yyyy-mm-dd) ${message.author}`);
if (args.length==2) return message.channel.send(`You're missing a \`Last Name\` and \`DOB\`(yyyy-mm-dd) ${message.author}`);
if (args.length==3) return message.channel.send(`You're missing a \`DOB\`(yyyy-mm-dd) ${message.author}`);
if (args[0].toLowerCase()!='revoke'&&args[0].toLowerCase()!='reinstate') return message.channel.send(`Invalid License Status, choose \`revoke\` or \`reinstate\` ${message.author}`);
}
if (args.length==0) return message.channel.send(`You must provide a \`License Status\`, \`First Name\` and \`Last Name\` ${message.author}`);
if (args.length==1) return message.channel.send(`You're missing a \`First Name\` and \`Last Name\` ${message.author}`);
if (args.length==2) return message.channel.send(`You're missing a \`Last Name\` ${message.author}`);
if (args[0].toLowerCase()!='revoke'&&args[0].toLowerCase()!='reinstate') return message.channel.send(`Invalid License Status, choose \`revoke\` or \`reinstate\` ${message.author}`);
if (user.user.activeCommunity=='' || user.user.activeCommunity==null) {
data = {
user: user,
query: {
firstName: args[1],
lastName: args[2],
dateOfBirth: args[3],
activeCommunityID: user.user.activeCommunity
}
}
} else {
data = {
user: user,
query: {
firstName: args[1],
lastName: args[2],
activeCommunityID: user.user.activeCommunity
}
}
}
const socket = io.connect(this.config.socket);
socket.emit("bot_name_search", data);
socket.on("bot_name_search_results", (results) => {
if (results.user._id==user._id) {
if (results.civilians.length == 0) {
return message.channel.send(`Name \`${args[1]} ${args[2]}\` not found ${message.author}`);
}
}
let query = {
_id: results.civilians[0]._id,
status: null,
bot_request: true
};
if (args[0]=='revoke') query.status = 2;
if (args[0]=='reinstate') query.status = 1;
socket.emit("update_drivers_license_status", query);
socket.on("bot_updated_drivers_license_status", (res) => {
if (!res.success) return message.channel.send(`Failed to update license of \`${args[1]} ${args[2]}\` ${message.author}`);
message.channel.send(`Successfully updated license of \`${args[1]} ${args[2]}\` ${message.author}`);
socket.disconnect();
return;
});
});
}
async joinCommunity(message, args) {
let user = await this.dbo.collection("users").findOne({"user.discord.id":message.author.id}).then(user => user);
if (!user) return message.channel.send(`You are not logged in ${message.author}`);
if (args.length==0) return message.channel.send(`You must provide a \`Community Code\` ${message.author}`);
let myReq = {
userID: user._id,
communityCode: args[0]
};
const socket = io.connect(this.config.socket);
socket.emit('bot_join_community', myReq);
socket.on('bot_joined_community', (data) => {
socket.disconnect()
if (data.error) {
return message.channel.send(`${data.error} ${message.author}`);
}
return message.channel.send(`Successfully joined the community \` ${data.commName} \` ${message.author}`)
});
}
async leaveCommunity(message) {
let user = await this.dbo.collection("users").findOne({"user.discord.id":message.author.id}).then(user => user);
if (!user) return message.channel.send(`You are not logged in ${message.author}`);
let myReq = {
userID: user._id
};
const socket = io.connect(this.config.socket);
socket.emit('bot_leave_community', myReq);
socket.on('bot_left_community', (data) => {
socket.disconnect()
if (data.error) {
return message.channel.send(`${data.error} ${message.author}`);
}
return message.channel.send(`${data.message} ${message.author}`)
});
}
async community(message) {
let user = await this.dbo.collection("users").findOne({"user.discord.id":message.author.id}).then(user => user);
if (!user) return message.channel.send(`You are not logged in ${message.author}`);
if (user.user.activeCommunity==null) return message.channel.send(`You are not in a community ${message.author}`);
let community = await this.dbo.collection("communities").findOne({_id:ObjectId(user.user.activeCommunity)}).then(community => community);
if (!community) return message.channel.send(`Community not found ${message.author}`);
return message.channel.send(`You are in the community \`${community.community.name}\` ${message.author}`);
}
async setRole(message, args) {
if (args.length==0) return message.channel.send(`You must provide a role ${message.author}`);
let roleid = args[0].replace('<@&', '').replace('>', '');
let role = message.guild.roles.cache.find(x => x.id == roleid);
if (role == undefined) {
return message.channel.send(`Uh Oh! The role ${args[0]} connot be found.`);
} else {
let guild = await this.dbo.collection("prefixes").findOne({"server.serverID":message.guild.id}).then(guild => guild);
if (guild.server.allowedRole!=undefined&&guild.server.allowedRoles.includes(roleid)) return message.channel.send(`The role ${args[0]} has already been added ${message.author}`);
this.dbo.collection("prefixes").updateOne({"server.serverID":message.guild.id},{$push:{"server.allowedRoles":roleid},$set:{"server.hasCustomRoles":true}},function(err, res) {
if (err) throw err;
return message.channel.send(`Successfully added ${args[0]} to allowed roles ${message.author}`);
});
}
}
async removeRole(message, args) {
if (args.length==0) return message.channel.send(`You must provide a role ${message.author}`);
let roleid = args[0].replace('<@&', '').replace('>', '');
let role = message.guild.roles.cache.find(x => x.id == roleid);
if (role == undefined) {
return message.channel.send(`Uh Oh! The role ${args[0]} connot be found.`);
} else {
let guild = await this.dbo.collection("prefixes").findOne({"server.serverID":message.guild.id}).then(guild => guild);
if (guild.server.hasCustomRoles==false) return message.channel.send(`There are no roles to be removed ${message.author}`);
if (!guild.server.allowedRoles.includes(roleid)) return message.channel.send(`The role ${args[0]} is not added to your roles ${message.author}`);
for (let i = 0; i < guild.server.allowedRoles.length; i++) {
if (guild.server.allowedRoles[i]==roleid) {
if ((guild.server.allowedRoles.length-1)==0) {
this.dbo.collection("prefixes").updateOne({"server.serverID":message.guild.id},{$pull:{"server.allowedRoles":roleid},$set:{"server.hasCustomRoles":false}},function(err, res) {
if (err) throw err;
return message.channel.send(`Successfully removed ${args[0]} from allowed roles ${message.author}! There are no more allowed roles.`);
});
} else if ((guild.server.allowedRoles.length-1)>0) {
this.dbo.collection("prefixes").updateOne({"server.serverID":message.guild.id},{$pull:{"server.allowedRoles":roleid}},function(err, res) {
if (err) throw err;
return message.channel.send(`Successfully removed ${args[0]} from allowed roles ${message.author}`);
});
}
}
}
}
}
async roles(message) {
let guild = await this.dbo.collection("prefixes").findOne({"server.serverID":message.guild.id}).then(guild => guild);
if (guild.server.hasCustomRoles==false) {
return message.channel.send('There are no roles set for the bot.');
}
let roles = "Allowed Roles:";
for (let i = 0; i < guild.server.allowedRoles.length; i++) {
if (guild.server.allowedRoles[i] == undefined) break;
roles += `\n<@&${guild.server.allowedRoles[i]}>`;
}
return message.channel.send(roles);
}
async setChannel(message, args) {
if (args.length==0) return message.channel.send(`You must provide a channel ${message.author}`);
let channelid = args[0].replace('<#', '').replace('>', '');
let channel = client.channels.cache.get(channelid);
if (!channel) return message.channel.send(`Cannot find that channel ${message.author}`);
if (channel.type=="voice") return message.channel.send(`Connot set voice channel to preferred channel ${message.author}`);
if (channel.deleted) return message.channel.send(`Connot set deleted channel to preferred channel ${message.author}`);
let guild = await this.dbo.collection("prefixes").findOne({"server.serverID":message.guild.id}).then(guild => guild);
if (guild.server.allowedChannels!=undefined&&guild.server.allowedChannels.includes(channelid)) return message.channel.send(`The channel ${args[0]} has already been added ${message.author}`);
this.dbo.collection("prefixes").updateOne({"server.serverID":message.guild.id},{$push:{"server.allowedChannels":channelid},$set:{"server.hasCustomChannels":true}},function(err, res) {
if (err) throw err;
return message.channel.send(`Successfully added ${args[0]} to allowed channels ${message.author}`);
});
}
async removeChannel(message, args) {
if (args.length==0) return message.channel.send(`You must provide a channel ${message.author}`);
let channelid = args[0].replace('<#', '').replace('>', '');
let channel = client.channels.cache.get(channelid);
if (!channel) return message.channel.send(`Uh Oh! The channel ${args[0]} connot be found.`);
let guild = await this.dbo.collection("prefixes").findOne({"server.serverID":message.guild.id}).then(guild => guild);
if (guild.server.hasCustomChannels==false) return message.channel.send(`There are no channels to be removed ${message.author}`);
if (!guild.server.allowedChannels.includes(channelid)) return message.channel.send(`The channel ${args[0]} is not added to your roles ${message.author}`);
for (let i = 0; i < guild.server.allowedChannels.length; i++) {
if (guild.server.allowedChannels[i]==channelid) {
if ((guild.server.allowedChannels.length-1)==0) {
this.dbo.collection("prefixes").updateOne({"server.serverID":message.guild.id},{$pull:{"server.allowedChannels":channelid},$set:{"server.hasCustomChannels":false}},function(err, res) {
if (err) throw err;
return message.channel.send(`Successfully removed ${args[0]} from allowed channels ${message.author}! There are no more allowed channels.`);
});
} else if ((guild.server.allowedChannels.length-1)>0) {
this.dbo.collection("prefixes").updateOne({"server.serverID":message.guild.id},{$pull:{"server.allowedChannels":channelid}},function(err, res) {
if (err) throw err;
return message.channel.send(`Successfully removed ${args[0]} from allowed channels ${message.author}`);
});
}
}
}
}
async channels(message) {
let guild = await this.dbo.collection("prefixes").findOne({"server.serverID":message.guild.id}).then(guild => guild);
if (guild.server.hasCustomChannels==false) {
return message.channel.send('There are no channels set for the bot.');
}
let channels = "Allowed Channels:";
for (let i = 0; i < guild.server.allowedChannels.length; i++) {
if (guild.server.allowedChannels[i] == undefined) break;
channels += `\n<#${guild.server.allowedChannels[i]}>`;
}
return message.channel.send(channels);
}
async getGuildPresets(message) {
let prefix;
let channelId;
let customRoleStatus;
let customChannelStatus;
let allowedChannels;
if (message.channel.type!="dm") {
let guild = await this.dbo.collection("prefixes").findOne({"server.serverID":message.guild.id}).then(guild => guild);
// If guild not found, generate guild default
if (!guild) {
let newGuild = {
server: {
serverID: message.guild.id,
prefix: this.config.defaultPrefix,
hasCustomRoles: false,
hasCustomChannels: false,
}
}
this.dbo.collection("prefixes").insertOne(newGuild, function(err, res) {
if (err) throw err;
});
prefix = newGuild.server.prefix;
customRoleStatus = newGuild.server.hasCustomRoles;
customChannelStatus = newGuild.server.hasCustomChannels;
allowedChannels = null;
} else {
prefix = guild.server.prefix;
customRoleStatus = guild.server.hasCustomRoles;
customChannelStatus = guild.server.hasCustomChannels;
if (guild.server.allowedChannels!=undefined||guild.server.allowedChannels!=null&&guild.server.allowedChannels.length>0) {
allowedChannels = guild.server.allowedChannels;
} else allowedChannels = null;
}
} else {
prefix = this.config.defaultPrefix;
customRoleStatus = false;
customChannelStatus = false;
allowedChannels = null;
}
return {prefix, channelId, customRoleStatus, customChannelStatus, allowedChannels};
}
async checkRoleStatus(message) {
let hasRole = false;
let guild = await this.dbo.collection("prefixes").findOne({"server.serverID":message.guild.id}).then(guild => guild);
// If user has one of any in the list of allowed roles, hasRole is true
for (let i = 0; i < guild.server.allowedRoles.length; i++) {
if (message.member.roles.cache.some(role => role.id == guild.server.allowedRoles[i])) hasRole = true;
}
return hasRole;
}
async togglePingOnPanic(message, args) {
if (args.length==0) return message.channel.send(`You must provide a \`Ping On Role Status\` and a \`role\` to ping ${message.author}`);
if (args[0]=="false") {
// disable ping on panic and remove ping role
this.dbo.collection("prefixes").updateOne({"server.serverID":message.guild.id},{$set:{"server.pingOnPanic":false,"server.pingRole":null}},function(err, res) {
if (err) throw err;
return message.channel.send(`Successfully disabled ping role on panic ${message.author}`);
});
} else if (args[0]=="true") {
let roleid = args[1].replace('<@&', '').replace('>', '');
let role = message.guild.roles.cache.find(x => x.id == roleid);
if (role == undefined) {
return message.channel.send(`Uh Oh! The role ${args[1]} connot be found.`);
} else {
this.dbo.collection("prefixes").updateOne({"server.serverID":message.guild.id},{$set:{"server.pingRole":roleid,"server.pingOnPanic":true}},function(err, res) {
if (err) throw err;
return message.channel.send(`Successfully set ${args[1]} to be pinged on panic ${message.author}`);
});
}
} else return message.channel.send(`\`${args[0]}\` is an invalid status, use \`true\` or \`false\` ${message.author}`);
}
async getPingOnPanicStatus(message) {
let guild = await this.dbo.collection("prefixes").findOne({"server.serverID":message.guild.id}).then(guild => guild);
return message.channel.send(`Current Ping on Panic Status: ${guild.server.pingOnPanic} ${message.author}`);
}
main() {
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}`);
});
// Basic Commands
client.on('message', async (message) => {
let { prefix, channelId, customRoleStatus, customChannelStatus, allowedChannels } = await this.getGuildPresets(message);
if (!message.content.startsWith(prefix) || message.author.bot) return;
if (customChannelStatus==true&&!allowedChannels.includes(message.channel.id)) {
return message.channel.send(`This is not the preferred channel, please one of the allowed channels. Use \`${prefix}channels\` to see a list of allowed channels ${message.author}`);
}
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
// Valid Statuses Embed
const validStatus = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('Lines Police CAD')
.setURL('https://www.linespolice-cad.com/')
.setAuthor('LPS Website Support', 'https://raw.githubusercontent.com/Linesmerrill/police-cad/master/lines-police-server.png', 'https://discord.gg/jgUW656v2t')
.setDescription('Valid Statuses')
.addFields(
{ name: 'Statuses:', value: `
10-8 | \`On Duty\`
10-7 | \`Off Duty\`
10-6 | \`Busy\`
10-11 | \`Traffic Stop\`
10-23 | \`Arrive on Scene\`
10-97 | \`In Route\`
10-15 | \`Subject in Custody\`
10-70 | \`Foot Pursuit\`
10-80 | \`Vehicle Pursiut\`
`
}
)
// Help Embed
const help = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('**Commands:**')
.setURL('https://discord.gg/w2g2FFmHbF')
.setAuthor('LPS Website & Bot Support', 'https://raw.githubusercontent.com/Linesmerrill/police-cad/master/lines-police-server.png', 'https://discord.gg/jgUW656v2t')
.setDescription('Lines Police CAD Bot Commands')
.addFields({
name: `**__Bot Commands:__**`,
value: `
**${prefix}help** - \`Displays this help page\`
**${prefix}stats** - \`Displays current Bot statistics\`
**${prefix}ping** - \`Responds with Pong to check Bot responce\`
`,
inline: false
},
{
name: `**__LPC Commands (1/2):__**`,
value: `
**${prefix}login** <email> <login token> - \`Login to LPS account (DM only command)\`
**${prefix}logout** - \`Logs out of your current logged in account\`
**${prefix}validStatus** - \`Shows list of valid statuses to updade to\`
**${prefix}checkStatus** <user> - \`Check your own or other status\`
**${prefix}updateStatus** <status> - \`Updates your status\`
**${prefix}account** - \`returns logged in account\`
**${prefix}penalCodes** - \`Provides Link to penal codes\`
**${prefix}namedb** <firstName> <lastName> <dob> - \`Searches for Civilian by Name\`
**${prefix}platedb** <licence plate #> - \`Searches for Vehicle by Licence Plate #\`
**${prefix}firearmdb** <Serial #> - \`Searches for Firearms by Serial #\`
**${prefix}panic** - \`Enables/Disables your panic button\`
**${prefix}license** <revoke|reinstate> <firstName> <lastName> <dob> - \`Revoke/Reinstate License\`
`,
inline: true
},
{
name: `**__LPC Command (2/2):__**`,
value: `
**${prefix}roles** - \`Shows a list of allowed roles\`
**${prefix}channels** - \`Shows a list of allowed channels\`
**${prefix}joincommunity** <community code> - \`Joins a community with the given code\`
**${prefix}leavecommunity** - \`Leaves your current active community\`
**${prefix}community** - \`Returns the name of the Community your currenty in\`
`,
inline: false
},
{
name: `**__Admin Commands:__**`,
value: `
**${prefix}setPrefix** <new prefix> - \`Sets new prefix\`
**${prefix}setChannel** <channel> - \`Adds channel to list of allowed channels\`
**${prefix}removeChannel** <channel> - \`Removes channel from list of allowed channels\`
**${prefix}setRole** <role> - \`Adds role to list of allowed roles\`
**${prefix}removeRole** <role> - \`Removes role from list of allowed roles\`
**${prefix}togglePingOnPanic** <true|false> <role> - \`Enable/disable ping role on panic\`
`,
inline: false
})
const stats = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle("Current LPC-Bot Statistics")
.setURL('https://discord.gg/w2g2FFmHbF')
.addField(" \u200B ", "**Channels** : ` " + `${client.channels.cache.size}` + " `")
.addField(" \u200B ", "**Servers** : ` " + `${client.guilds.cache.size}` + " `")
.addField(" \u200B ", "**Users** : ` " + `${client.users.cache.size}` + " `")
if (command == 'ping') message.channel.send('Pong!');
if (command == 'help') message.channel.send(help);
if (command == 'stats') message.channel.send(stats);
if (command == 'setprefix') {
if (message.channel.type=="dm") return message.author.send(`You cannot set a prefix in a dm ${message.author}`);
if(!message.member.hasPermission(["ADMINISTRATOR","MANAGE_GUILD"])) return message.channel.send(`You don't have permission to used this command ${message.author}`);
this.newPrefix(message, args);
}
if (command == 'setchannel') {
if (message.channel.type=="dm") return message.author.send(`You cannot set a channel in a dm ${message.author}`);
if (!message.member.hasPermission(["ADMINISTRATOR","MANAGE_GUILD"])) return message.channel.send(`You don't have permission to used this command ${message.author}`);
this.setChannel(message, args);
}
if (command == 'removechannel') {
if (message.channel.type=="dm") return message.author.send(`You cannot remove a channel in a dm ${message.author}`);
if (!message.member.hasPermission(["ADMINISTRATOR","MANAGE_GUILD"])) return message.channel.send(`You don't have permission to used this command ${message.author}`);
this.removeChannel(message, args);
}
if (command == 'setrole') {
if (message.channel.type=="dm") return message.author.send(`You cannot set a role in a dm ${message.author}`);
if (!message.member.hasPermission(["ADMINISTRATOR","MANAGE_GUILD"])) return message.channel.send(`You don't have permission to used this command ${message.author}`);
this.setRole(message, args);
}
if (command == 'removerole') {
if (message.channel.type=="dm") return message.author.send(`You cannot remove a role in a dm ${message.author}`);
if (!message.member.hasPermission(["ADMINISTRATOR","MANAGE_GUILD"])) return message.channel.send(`You don't have permission to used this command ${message.author}`);
this.removeRole(message, args);
}
if (command == 'togglepingonpanic') {
if (message.channel.type=="dm") return message.author.send(`You cannot remove a role in a dm ${message.author}`);
if (!message.member.hasPermission(["ADMINISTRATOR","MANAGE_GUILD"])) return message.channel.send(`You don't have permission to used this command ${message.author}`);
this.togglePingOnPanic(message, args);
}
if (command == 'roles') {
if (message.channel.type=="dm") return message.author.send(`You cannot see allowed roles in a dm ${message.author}`);
this.roles(message);
}
if (command == 'channels') {
if (message.channel.tpye=="dm") return message.channel.send(`You cannot see allowed channels in a dm ${message.author}`);
this.channels(message);
}
if (command == 'pingonpanic') {
if (message.channel.type=="dm") return message.channel.send(`You cannot see allowed channels in a dm ${message.author}`);
this.getPingOnPanicStatus(message);
}
// Login
if (command == 'login') {
if (message.channel.type=="text") return message.channel.send(`You must direct message me to use this command ${message.author}`);
this.remoteLogin(message, args);
}
if (command == 'logout') this.remoteLogout(message);
if (command == 'validstatus') message.channel.send(validStatus);
if (command == 'checkstatus') {
if (customRoleStatus) {
let hasRole = await this.checkRoleStatus(message);
if (hasRole) {
this.checkStatus(message, args);
} else return message.channel.send(`You don't have permission to use this command ${message.author}`);
} else this.checkStatus(message, args);
}
if (command == 'updatestatus') {
if (customRoleStatus) {
let hasRole = await this.checkRoleStatus(message);
if (hasRole) {
this.updateStatus(message, args, prefix);
} else return message.channel.send(`You don't have permission to use this command ${message.author}`);
} else this.updateStatus(message, args, prefix);
}
if (command == 'account') this.account(message);
if (command == 'penalcodes') return message.channel.send('https://www.linespolice-cad.com/penal-code');
if (command == 'namedb') {
if (customRoleStatus) {
let hasRole = await this.checkRoleStatus(message);
if (hasRole) {
this.nameSearch(message, args);
} else return message.channel.send(`You don't have permission to use this command ${message.author}`);
} else this.nameSearch(message, args);
}
if (command == 'platedb') {
if (customRoleStatus) {
let hasRole = await this.checkRoleStatus(message);
if (hasRole) {
this.plateSearch(message, args);
} else return message.channel.send(`You don't have permission to use this command ${message.author}`);
} else this.plateSearch(message, args);
}
if (command == 'firearmdb') {
if (customRoleStatus) {
let hasRole = await this.checkRoleStatus(message);
if (hasRole) {
this.firearmSearch(message, args);
} else return message.channel.send(`You don't have permission to use this command ${message.author}`);
} else this.firearmSearch(message, args);
}
if (command == 'panic') {
if (customRoleStatus) {
let hasRole = await this.checkRoleStatus(message);
if (hasRole) {
this.enablePanic(message);
} else return message.channel.send(`You don't have permission to use this command ${message.author}`);
} else this.enablePanic(message);
}
if (command == 'license') {
if (customRoleStatus) {
let hasRole = await this.checkRoleStatus(message);
if (hasRole) {
this.updateLicense(message, args);
} else return message.channel.send(`You don't have permission to use this command ${message.author}! `);
} else this.updateLicense(message, args);
}
if (command == 'joincommunity') this.joinCommunity(message, args);
if (command == 'leavecommunity') this.leaveCommunity(message);
if (command == 'community') this.community(message);
// Dev Commands (not visible in help) && easter egg commands
if (command == 'version') message.channel.send(`**LPS-BOT Version : ${this.dev}-${this.config.version}**`)
if (command == 'whatisthemeaningoflife') message.channel.send('42');
if (command == 'whatareyou' || command == 'whoareyou') message.channel.send('Im your friendly neighborhood Lines Police CAD Bot');
if (command == 'whocreatedyou') message.channel.send('Lines Police CAD Developer McDazzzled | https://github.com/SowinskiBraeden');
if (command == 'pingserver') {
const socket = io.connect(this.config.socket);
socket.emit('botping', {message:'hello there'});
socket.on('botpong', (data) => {
console.log(data);
socket.disconnect();
});
}
});
client.login(this.token);
}
}
module.exports = {Bot};
-2
View File
@@ -1,2 +0,0 @@
Worker: node index.js
BetaWorker: node beta.js
+10 -30
View File
@@ -1,32 +1,12 @@
### Lines Police CAD Discord Bot
![lines police cad logo](https://github.com/Linesmerrill/police-cad/blob/master/lines-police-cad.png)
# Lines Police CAD Discord Bot
This is the official Lines Police CAD bot for discord integration. It allows you to use Lines Police CAD website features right in your discord channel!
### Requirements :
1. [Node.js](https://nodejs.org/en/)
1. [MongoDB](https://docs.mongodb.com/manual/administration/install-community/)
### Getting Started with Code :
1. [Set Up MongoDB](#setting-up-mongodb) and start mongodb
2. Clone repo from https://github.com/SowinskiBraeden/LPC-Bot.git
3. Run `npm install` to install dependencies.
4. Edit the `index.js` file to have the your correct parameters to run the bot.
The parameters are as follows:
1. Version
2. Bot Token
3. path to config
4. mongoURI
5. mongoDBO
1. Run `npm start` to run the `index.js` file and start the bot.
1. The bot is now ready to use.
### Setting up MongoDB
1. Install mongodb via brew [Step by step instructions](https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/)
1. Start mongodb via brew [Step by step instructions](https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/#run-mongodb-community-edition)
### Accessing the Database
1. Locally this will use the knoldus db (or whatever you specify manually)
1. launch mongo via your command-line: `mongo`
1. Use `show dbs` to see all that are available. You should see `knoldus` in the list.
1. Lets use that db: `use knoldus`.
> [!WARNING]
>
> Migrating to Organization repository.
> ---
>
> ***Notice:*** This repository will transition to read-only mode starting on **November 7, 2024**.
>
> All new commits, issues, feature requests and more will take place on the organization repository.
> Visit our [organization!](https://github.com/Lines-Police-CAD/)
-5
View File
@@ -1,5 +0,0 @@
{
"defaultPrefix": "?",
"version": "Beta 2.0.0",
"socket": "https://police-cad-dev.herokuapp.com/"
}
-4
View File
@@ -1,4 +0,0 @@
const Bot = require('./LPS').Bot;
let client = new Bot('DEVELOPMENT', process.env.token, './beta-config', process.env.mongoURI, process.env.dbo);
client.main()
+6
View File
@@ -0,0 +1,6 @@
const LinesPoliceCadBot = require('./structures/LinesPoliceCadBot');
const { GatewayIntentBits } = require('discord.js');
const config = require('./config/config');
let client = new LinesPoliceCadBot({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages] }, config);
client.build()
+32
View File
@@ -0,0 +1,32 @@
const { EmbedBuilder } = require('discord.js');
module.exports = {
name: "account",
description: "View connected Lines Police CAD account",
usage: "",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").Message} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
let user = await client.dbo.collection("users").findOne({"user.discord.id":interaction.member.user.id}).then(user => user);
if (user==null) return interaction.send({ content: `You are not logged in.` });
client.users.fetch(interaction.member.user.id)
.then(duser => duser.send(`<@${interaction.member.user.id}> Logged in as **${user.user.username}** | **${user.user.email}**`).catch(err => {client.log(err)}))
.catch(err => {client.log(err)});
return interaction.send({ content: 'Your account details have been sent in your dm.' });
},
},
}
+45
View File
@@ -0,0 +1,45 @@
const { EmbedBuilder } = require('discord.js');
module.exports = {
name: "channels",
description: "View a list of allowed channels",
usage: "",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").MessageCreate} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
let guild = await client.dbo.collection("prefixes").findOne({"server.serverID":interaction.guild.id}).then(guild => guild);
if (!GuildDB.customChannelStatus) {
return interaction.send({ content: 'There are no channels set for the bot.' });
}
let channels = ``;
for (let i = 0; i < guild.server.allowedChannels.length; i++) {
if (!client.exists(guild.server.allowedChannels[i])) continue;
else channels += `\n<#${guild.server.allowedChannels[i]}>`;
}
let channelsEmbed = new EmbedBuilder()
.setColor('#0099ff')
.setDescription('**Allowed Channels to use the Bot**')
.addFields(
{ name: `There are currently ${guild.server.allowedChannels.length} allowed channels.`, value: `Channels:${channels}`, inline: true },
)
.setFooter({ text: 'LPS Website Support', iconURL: client.config.IconURL, proxyIconURL: 'https://discord.gg/jgUW656v2t' })
return interaction.send({ embeds: [channelsEmbed] });
},
},
}
+54
View File
@@ -0,0 +1,54 @@
const { EmbedBuilder } = require('discord.js');
module.exports = {
name: "checkstatus",
description: "Check your own or another officer status",
usage: "[user]",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [
{
name: "user",
description: "Discord Username",
value: "user",
type: 6,
required: false,
},
],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").Message} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
let useCommand = await client.verifyUseCommand(GuildDB.serverID, interaction.member.roles);
if (!useCommand) return interaction.send({ content: "You don't have permission to use this command" });
let user = await client.dbo.collection("users").findOne({"user.discord.id":interaction.member.user.id}).then(user => user);
if (!user) return interaction.send({ content: `You are not logged in.` });
if (user.user.activeCommunity == null) return interaction.send({ content: `You must join a community to use this command.` });
if (!client.exists(args)) {
return interaction.send({ content: `<@${interaction.member.user.id}>'s status: \`${user.user.dispatchStatus}\` | Set by: \`${user.user.dispatchStatusSetBy}\`` });
} else {
let targetUserID = args[0].value.replace('<@!', '').replace('>', '');
let targetUser = await client.dbo.collection("users").findOne({"user.discord.id":targetUserID}).then(user => user);
// This lame line of code to get username without ping on discord
const User = client.users.cache.get(targetUserID);
if (!targetUser) return interaction.send({ content: `Cannot find **${args[0].value}** <@${interaction.member.user.id}>` });
if (targetUser.user.activeCommunity!=user.user.activeCommunity) {
return interaction.send({ content: `You are not in the same community as \`${User.tag}\` <@${interaction.member.user.id}>` });
}
return interaction.send({ content: `<@${interaction.member.user.id}>, \`${User.tag}'s\` status: \`${targetUser.user.dispatchStatus}\` | Set by: \`${targetUser.user.dispatchStatusSetBy}\`` });
}
},
},
}
+34
View File
@@ -0,0 +1,34 @@
const { EmbedBuilder } = require('discord.js');
const ObjectId = require('mongodb').ObjectId;
module.exports = {
name: "community",
description: "Check active community",
usage: "",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").MessageCreate} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
let user = await client.dbo.collection("users").findOne({"user.discord.id":interaction.member.user.id}).then(user => user);
if (!user) return interaction.send({ content: `You are not logged in.` });
if (user.user.activeCommunity==null) return interaction.send({ content: `You are not in a community.` });
let community = await client.dbo.collection("communities").findOne({_id:ObjectId(user.user.activeCommunity)}).then(community => community);
if (!community) return interaction.send({ content: `Community not found.` });
return interaction.send({ content: `You are in the community \`${community.community.name}\`` });
},
},
}
+27
View File
@@ -0,0 +1,27 @@
const { EmbedBuilder } = require('discord.js');
module.exports = {
name: "connect_account",
description: "Connect your Discord Account to the Lines Police CAD Database",
usage: "",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").Message} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
return interaction.send({ content: 'Login from Lines Police CAD `account_management` https://www.linespolice-cad.com/' });
},
},
}
+80
View File
@@ -0,0 +1,80 @@
const { EmbedBuilder } = require('discord.js');
const io = require('socket.io-client');
module.exports = {
name: "debug",
description: "Debug for bot admin",
usage: "command",
debug: true,
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [
{
name: "command",
description: "The debug command to execute",
value: "command",
type: 3,
required: true,
},
{
name: "consoleoutput",
description: "Output debug messages to console (deault=false)",
value: "consoleoutput",
type: 5,
required: true,
},
],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").Message} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (!client.config.Admins.includes(interaction.member.user.id)) return;
if (args.length==0) return message.channel.send({ content: 'Debug Error: Provide a debug command' });
if (!client.exists(args[0].value)) return interaction.send({ content: 'Debug Error: Provide a valid debug command' });
let debugConsole = args[1].value;
let command = args[0].value.toLowerCase();
if (command == 'server' || args[0] == 'guild') {
if (debugConsole) client.log("Debug: Guild >> ");console.debug(GuildDB);
return interaction.send({ content: "Debug: guild >> read log output" })
} else if (command == "interaction") {
if (debugConsole) {
client.log("Debug: interaction >> ");
console.debug(interaction);
}
return interaction.send({ content: "Debug: interaction >> read log output" });
} else if (command == "message") {
return interaction.send({ content: `Use command with prefix to debug \`message\`` });
} else if (command == "pingserver") {
const socket = io.connect(client.config.socket);
socket.emit('botping', {message:'hello there'});
socket.on('botpong', (data) => {
if (debugConsole) client.log('Debug: Socket responded')
socket.disconnect();
return interaction.send({ content: `Debug: Socket responded` })
});
} else if (command == "apicheck") {
// TODO: Make axios call to api and get api health
return interaction.send({ content: 'Debug Notice: \`apicheck\` is currently unavailable' });
} else {
return interaction.send({ content: 'Debug Error: Provide a valid debug command' });
}
},
},
}
+32
View File
@@ -0,0 +1,32 @@
const { EmbedBuilder } = require('discord.js');
module.exports = {
name: "disconnect_account",
description: "Disconnect your Discord account from the Lines Police CAD Database",
usage: "",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").Message} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
let user = await client.dbo.collection("users").findOne({"user.discord.id":interaction.member.user.id}).then(user => user);
if (!user) return interaction.send({ content: `You cannot logout if your not logged in.` });
client.dbo.collection("users").updateOne({"user.discord.id":interaction.member.user.id},{$unset:{"user.discord":""}, $set:{"user.discordConnected":false}},function(err,res) {
if (err) throw err;
return interaction.send({ content: `Succesfully disconnected you Discord account.` });
});
},
},
}
+77
View File
@@ -0,0 +1,77 @@
const { EmbedBuilder } = require('discord.js');
const io = require('socket.io-client');
module.exports = {
name: "firearmsearch",
description: "Search registered firearms",
usage: "[Serial #]",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [
{
name: "serialnumber",
description: "Firearms's serial number",
value: "serialnumber",
type: 3,
required: true,
},
],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").Message} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
let useCommand = await client.verifyUseCommand(GuildDB.serverID, interaction.member.roles);
if (!useCommand) return interaction.send({ content: "You don't have permission to use this command" });
let user = await client.dbo.collection("users").findOne({"user.discord.id":interaction.member.user.id}).then(user => user);
if (!user) return interaction.send({ content: `You are not logged in.` });
let data = {
user: user,
query: {
serialNumber: args[0].value,
activeCommunityID: user.user.activeCommunity
}
}
const socket = io.connect(client.config.socket);
socket.emit('bot_firearm_search', data);
socket.on('bot_firearm_search_results', results => {
if (results.user._id==user._id) {
if (results.firearms.length==0) {
return interaction.send({ content: `No Firearms found <@${interaction.member.user.id}>` });
}
for (let i = 0; i < results.firearms.length; i++) {
let firearmResult = new EmbedBuilder()
.setColor('#0099ff')
.setTitle(`**${results.firearms[i].firearm.serialNumber} | ${results.firearms[i]._id}**`)
.setURL('https://discord.gg/jgUW656v2t')
.setAuthor({ name: 'LPS Website Support', iconURL: client.config.IconURL, url: 'https://discord.gg/jgUW656v2t' })
.setDescription('Firearm Search Results')
.addFields(
{ name: `**Serial Number**`, value: `\`${results.firearms[i].firearm.serialNumber}\``, inline: true },
{ name: `**Type**`, value: `\`${results.firearms[i].firearm.weaponType}\``, inline: true },
{ name: `**Owner**`, value: `\`${results.firearms[i].firearm.registeredOwner}\``, inline: true },
)
// Other details
let isStolen = results.firearms[i].firearm.isStolen;
if (isStolen=="false"||isStolen==false) firearmResult.addFields({name:`**Stolen**`,value:'\`No\`',inline: true});
if (isStolen=="true"||isStolen==true) firearmResult.addFields({name:`**Stolen**`,value:'\`Yes\`',inline: true});
interaction.send({ embeds: [firearmResult] });
}
}
socket.disconnect();
});
},
},
}
+80
View File
@@ -0,0 +1,80 @@
const { EmbedBuilder, ButtonStyle } = require("discord.js");
module.exports = {
name: "help",
description: "Get information on a specific command",
usage: "[command]",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [
{
name: "command",
description: "Get information on a specific command",
value: "command",
type: 3,
required: false,
},
],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").Message} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
let Commands = client.commands.filter((cmd) => {
if (client.exists(cmd.debug)) return !cmd.debug
else return true
}).map((cmd) =>
`\`/${cmd.name}${cmd.usage ? " " + cmd.usage : ""}\` - ${cmd.description}`
);
let Embed = new EmbedBuilder()
.setColor(client.config.EmbedColor)
.setDescription(`${Commands.join("\n")}
LPC Bot Version: v${client.config.Version}`);
if (!args) return interaction.send({ embeds: [Embed] });
else {
let cmd =
client.commands.get(args[0].value) ||
client.commands.find(
(x) => x.aliases && x.aliases.includes(args[0].value)
);
if (!cmd)
return client.sendTime(
interaction,
`❌ | Unable to find that command.`
);
let embed = new EmbedBuilder()
.setAuthor({ name: `Command: ${cmd.name}`, iconURL: client.config.IconURL })
.setDescription(cmd.description)
.setColor(ButtonStyle.Success) // Green
.addFields({
name: "Usage",
value: `\`/${cmd.name}${cmd.usage ? " " + cmd.usage : ""}\``,
inline: true
})
.addFields({
name: "Permissions",
value: "Member: " +
cmd.permissions.member.join(", ") +
"\nBot: " +
cmd.permissions.channel.join(", "),
inline: true
})
return interaction.send({ embeds: [embed] });
}
},
},
};
+51
View File
@@ -0,0 +1,51 @@
const { EmbedBuilder } = require('discord.js');
const io = require('socket.io-client');
module.exports = {
name: "joincommunity",
description: "Join a community",
usage: "[code]",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [
{
name: "code",
description: "Join community with community code",
value: "code",
type: 3,
required: true,
},
],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").MessageCreate} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
let user = await client.dbo.collection("users").findOne({"user.discord.id":interaction.member.user.id}).then(user => user);
if (!user) return interaction.send({ content: `You are not logged in.` });
let myReq = {
userID: user._id,
communityCode: args[0].value
};
const socket = io.connect(client.config.socket);
socket.emit('bot_join_community', myReq);
socket.on('bot_joined_community', (data) => {
socket.disconnect()
if (data.error) {
return interaction.send({ content: `${data.error}` });
}
return interaction.send({ content: `Successfully joined the community \` ${data.commName} \`` })
});
},
},
}
+42
View File
@@ -0,0 +1,42 @@
const { EmbedBuilder } = require('discord.js');
const io = require('socket.io-client');
module.exports = {
name: "leavecommunity",
description: "Leave your active community",
usage: "",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").MessageCreate} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
let user = await client.dbo.collection("users").findOne({"user.discord.id":interaction.member.user.id}).then(user => user);
if (!user) return interaction.send({ content: `You are not logged in.` });
let myReq = {
userID: user._id
};
const socket = io.connect(client.config.socket);
socket.emit('bot_leave_community', myReq);
socket.on('bot_left_community', (data) => {
socket.disconnect()
if (data.error) {
return interaction.send({ content: `${data.error}` });
}
return interaction.send({ content: `${data.message}` });
});
},
},
}
+132
View File
@@ -0,0 +1,132 @@
const { EmbedBuilder } = require('discord.js');
const io = require('socket.io-client');
module.exports = {
name: "namesearch",
description: "Search a civilian",
usage: "[First Name] [Last Name] [yyyy-mm-dd]",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [
{
name: "firstname",
description: "Civilian's First Name",
value: "firstname",
type: 3,
required: true,
},
{
name: "lastname",
description: "Civilian's Last Name",
value: "lastname",
type: 3,
required: true,
},
{
name: "dob",
description: "Civilian's DOB (yyyy-mm-dd)",
value: "dob",
type: 3,
required: true,
},
],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").Message} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
let useCommand = await client.verifyUseCommand(GuildDB.serverID, interaction.member.roles);
if (!useCommand) return interaction.send({ content: "You don't have permission to use this command" });
let user = await client.dbo.collection("users").findOne({"user.discord.id":interaction.member.user.id}).then(user => user);
if (!user) return interaction.send({ content: `You are not logged in.` });
let data;
data = {
user: user,
query: {
firstName: args[0].value,
lastName: args[1].value,
dateOfBirth: args[2].value,
activeCommunityID: user.user.activeCommunity
}
}
const socket = io.connect(client.config.socket);
socket.emit("bot_name_search", data);
socket.on("bot_name_search_results", results => {
if (results.user._id==user._id) {
if (results.civilians.length == 0) {
return interaction.send({ content: `Name \`${args[0].value} ${args[1].value}\` not found.` });
}
for (let i = 0; i < results.civilians.length; i++) {
// Get Drivers Licence Status
let licenceStatus;
if (results.civilians[i].civilian.licenseStatus == 1) licenceStatus = 'Valid';
if (results.civilians[i].civilian.licenceStatus == 2) licenceStatus = 'Revoked';
if (results.civilians[i].civilian.licenceStatus == 3) licenceStatus = 'None';
// Get Firearm Licence Status
let firearmLicence = results.civilians[i].civilian.firearmLicense;
if (firearmLicence == undefined || firearmLicence == null) firearmLicence = 'None';
if (firearmLicence == '2') firearmLicence = 'Valid';
if (firearmLicence == '3') firearmLicence = 'Revoked';
let nameResult = new EmbedBuilder()
.setColor('#0099ff')
.setTitle(`**${results.civilians[i].civilian.firstName} ${results.civilians[i].civilian.lastName} | ${results.civilians[i]._id}**`)
.setURL('https://discord.gg/jgUW656v2t')
.setAuthor({ name: 'LPS Website Support', iconURL: client.config.IconURL, url: 'https://discord.gg/jgUW656v2t' })
.setDescription('Name Search Results')
.addFields(
{ name: `**First Name**`, value: `\`${results.civilians[i].civilian.firstName}\``, inline: true },
{ name: `**Last Name**`, value: `\`${results.civilians[i].civilian.lastName}\``, inline: true },
{ name: `**DOB**`, value: `\`${results.civilians[i].civilian.birthday}\``, inline: true },
{ name: `**Drivers License**`, value: `\`${licenceStatus}\``, inline: true },
{ name: `**Firearm Licence**`, value: `\`${firearmLicence}\``, inline: true },
{ name: `**Gender**`, value: `\`${results.civilians[i].civilian.gender}\``, inline: true }
)
// Check Other details
let address = results.civilians[i].civilian.address;
let occupation = results.civilians[i].civilian.occupation;
let height = results.civilians[i].civilian.height;
let weight = results.civilians[i].civilian.weight;
let eyeColor = results.civilians[i].civilian.eyeColor;
let hairColor = results.civilians[i].civilian.hairColor;
if (address != null && address != undefined && address != '') nameResult.addFields({ name: `**Address**`, value: `\`${address}\``, inline: true });
if (occupation != null && occupation != undefined && occupation != '') nameResult.addFields({ name: `**Occupation**`, value: `\`${occupation}\``, inline: true });
if (height!=null&&height!=undefined&&height!="NaN"&&height!='') {
if (results.civilians[i].civilian.heightClassification=='imperial') {
let ft = Math.floor(height/12);
let inch = height%12;
nameResult.addFields({ name: '**Height**', value: `\`${ft}'${inch}"\``, inline: true });
} else {
nameResult.addFields({ name: '**Height**', value: `\`${height}cm\``, inline: true });
}
}
if (weight!=null&&weight!=undefined&&weight!='') {
let units = results.civilians[i].civilian.weightClassification=='imperial' ? 'lbs.' : 'kgs.';
nameResult.addFields({ name: '**Weight**', value: `\`${weight}${units}\``, inline: true });
}
if (eyeColor!=null&&eyeColor!=undefined&&eyeColor!='') nameResult.addFields({name:'**Eye Color**',value:`\`${eyeColor}\``,inline:true});
if (hairColor!=null&&hairColor!=undefined&&hairColor!='') nameResult.addFields({name:'**Hair Color**',value:`\`${hairColor}\``,inline:true});
nameResult.addFields({name:'**Organ Donor**',value:`\`${results.civilians[i].civilian.organDonor}\``,inline:true});
nameResult.addFields({name:'**Veteran**',value:`\`${results.civilians[i].civilian.veteran}\``,inline:true});
interaction.send({ embeds: [nameResult] });
}
}
socket.disconnect();
});
},
},
}
+86
View File
@@ -0,0 +1,86 @@
const { EmbedBuilder } = require('discord.js');
const io = require('socket.io-client');
module.exports = {
name: "panic",
description: "Enables users panic button",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").Message} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus == true && !GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.`, flags: (1 << 6) });
}
let useCommand = await client.verifyUseCommand(GuildDB.serverID, interaction.member.roles);
if (!useCommand) return interaction.send({ content: "You don't have permission to use this command", flags: (1 << 6) });
let user = await client.dbo.collection("users").findOne({"user.discord.id": interaction.member.user.id}).then(user => user);
if (!user) return interaction.send({ content: `You are not logged in. Go to https://linespolice-cad.com/ to login, and connect your Discord account.`, flags: (1 << 6) });
if (user.user.activeCommunity == null) return interaction.send({ content: `You must join a community to use this command.`, flags: (1 << 6) });
// If panic is enabled, disable panic
if (user.user.dispatchStatus == 'Panic') {
const socket = io.connect(client.config.socket);
socket.emit('clear_panic', {
userID: user._id,
communityID: user.user.activeCommunity
});
let myUpdateReq = {
userID: user._id,
status: '10-8',
setBy: 'System',
onDuty: null,
updateDuty: false
};
socket.emit('bot_update_status', myUpdateReq);
socket.on('bot_updated_status', (res) => {
if (res.userID == user._id) {
interaction.send({ content: `Disabled Panic and set status to \`10-8\`.`, flags: (1 << 6) });
socket.disconnect();
}
});
return;
// If panic is disabled, enable panic
} else {
if (user.user.activeCommunity == null) return interaction.send({ content: `You must join a community to use this command.`, flags: (1 << 6) });
client.forceUpdateStatus('Panic', user);
let req = {
userID: user._id,
userUsername: user.user.username,
activeCommunity: user.user.activeCommunity
}
const socket = io.connect(client.config.socket);
socket.emit('panic_button_update', req);
socket.disconnect();
let guild = await client.dbo.collection("prefixes").findOne({"server.serverID": GuildDB.serverID}).then(guild => guild);
if (guild.server.pingOnPanic) {
const channel = client.channels.cache.get(interaction.channel_id);
channel.send({ content: `Attention <@&${guild.server.pingRole}> \`${user.user.username}\` has activated panic` });
}
return interaction.send({ content: 'Successfully activated Panic', flags: (1 << 6) });
}
},
},
}
+27
View File
@@ -0,0 +1,27 @@
const { EmbedBuilder } = require('discord.js');
module.exports = {
name: "ping",
description: "check the bots responce",
usage: "",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").Message} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
interaction.send({ content: 'Pong!' });
},
},
}
+29
View File
@@ -0,0 +1,29 @@
const { EmbedBuilder } = require('discord.js');
module.exports = {
name: "pingonpanic",
description: "Get ping on panic status",
usage: "",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").MessageCreate} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
let guild = await client.dbo.collection("prefixes").findOne({"server.serverID":interaction.guild.id}).then(guild => guild);
return interaction.send({ content: `Current Ping on Panic Status: \` ${guild.server.pingOnPanic} \`` });
},
},
}
+86
View File
@@ -0,0 +1,86 @@
const { EmbedBuilder } = require('discord.js');
const io = require('socket.io-client');
module.exports = {
name: "platesearch",
description: "Search for a registered Vehicle",
usage: "[Plate #]",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [
{
name: "platenumber",
description: "Vehicle's license plate number",
value: "platenumber",
type: 3,
required: true,
},
],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").Message} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
let useCommand = await client.verifyUseCommand(GuildDB.serverID, interaction.member.roles);
if (!useCommand) return interaction.send({ content: "You don't have permission to use this command" });
let user = await client.dbo.collection("users").findOne({"user.discord.id":interaction.member.user.id}).then(user => user);
if (!user) return interaction.send({ content: `You are not logged in.` });
let data = {
user: user,
query: {
plateNumber: args[0].value,
activeCommunityID: user.user.activeCommunity
}
}
const socket = io.connect(client.config.socket);
socket.emit('bot_plate_search', data);
socket.on('bot_plate_search_results', results => {
if (results.user._id==user._id) {
if (results.vehicles.length == 0) {
return interaction.send({ content: `Plate Number \`${args[0].value}\` not found.` });
}
for (let i = 0; i < results.vehicles.length; i++) {
let plateResult = new EmbedBuilder()
.setColor('#0099ff')
.setTitle(`**${results.vehicles[i].vehicle.plate} | ${results.vehicles[i]._id}**`)
.setURL('https://discord.gg/jgUW656v2t')
.setAuthor({ name: 'LPS Website Support', iconURL: client.config.IconURL, url: 'https://discord.gg/jgUW656v2t' })
.setDescription('Plate Search Results')
.addFields(
{ name: `**Plate #**`, value: `\`${results.vehicles[i].vehicle.plate}\``, inline: true },
{ name: `**Vin #**`, value: `\`${results.vehicles[i].vehicle.vin}\``, inline: true },
{ name: `**Model**`, value: `\`${results.vehicles[i].vehicle.model}\``, inline: true },
{ name: `**Color**`, value: `\`${results.vehicles[i].vehicle.color}\``, inline: true },
{ name: `**Owner**`, value: `\`${results.vehicles[i].vehicle.registeredOwner}\``, inline: true },
)
// Other details
let validRegistration = results.vehicles[i].vehicle.validRegistration;
let validInsurance = results.vehicles[i].vehicle.validInsurance;
let stolen = results.vehicles[i].vehicle.isStolen;
if (validRegistration=='1') plateResult.addFields({ name: `**Registration**`, value: `\`Valid\``, inline: true });
if (validRegistration=='2') plateResult.addFields({ name: `**Registration**`, value: `\`InValid\``, inline: true });
if (validInsurance=='1') plateResult.addFields({ name: `**Insurance**`, value: `\`Valid\``, inline: true });
if (validInsurance=='2') plateResult.addFields({ name: `**Insurance**`, value: `\`InValid\``, inline: true });
if (stolen=='1') plateResult.addFields({ name: `**Stolen**`, value: `\`No\``, inline: true });
if (stolen=='2') plateResult.addFields({ name: `**Stolen**`, value: `\`Yes\``, inline: true });
return interaction.send({ embeds: [plateResult] });
}
}
socket.disconnect();
});
},
},
}
+57
View File
@@ -0,0 +1,57 @@
const { EmbedBuilder } = require('discord.js');
module.exports = {
name: "removechannel",
description: "Remove channel from allowed channels",
usage: "[channel]",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: ["remove_role"],
},
options: [
{
name: "channel",
description: "Channel to remove from allowed channles",
value: "channel",
type: 7,
required: true,
},
],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").MessageCreate} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
if (args.length==0) return interaction.send({ content: `You must provide a channel.` });
let channelid = args[0].value;
let channel = client.channels.cache.get(channelid);
if (!channel) return interaction.send({ content: `Uh Oh! The channel <#${args[0].value}> connot be found.` });
let guild = await client.dbo.collection("prefixes").findOne({"server.serverID":interaction.guild.id}).then(guild => guild);
if (guild.server.hasCustomChannels==false) return interaction.send({ content: `There are no channels to be removed.` });
if (!guild.server.allowedChannels.includes(channelid)) return interaction.send({ content: `The channel <#${args[0].value}> is not added to your channels.` });
for (let i = 0; i < guild.server.allowedChannels.length; i++) {
if (guild.server.allowedChannels[i]==channelid) {
if ((guild.server.allowedChannels.length-1)==0) {
client.dbo.collection("prefixes").updateOne({"server.serverID":interaction.guild.id},{$pull:{"server.allowedChannels":channelid},$set:{"server.hasCustomChannels":false}},function(err, res) {
if (err) throw err;
return interaction.send({ content: `Successfully removed <#${args[0].value}> from allowed channels! There are no more allowed channels.` });
});
} else if ((guild.server.allowedChannels.length-1)>0) {
client.dbo.collection("prefixes").updateOne({"server.serverID":interaction.guild.id},{$pull:{"server.allowedChannels":channelid}},function(err, res) {
if (err) throw err;
return interaction.send({ content: `Successfully removed <#${args[0].value}> from allowed channels.` });
});
}
}
}
},
},
}
+59
View File
@@ -0,0 +1,59 @@
const { EmbedBuilder } = require('discord.js');
module.exports = {
name: "removerole",
description: "Remove a role allowed to use the bot",
usage: "[role]",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: ["MANAGE_GUILD"],
},
options: [
{
name: "role",
description: "Role to remove from allowed roles",
value: "role",
type: 8,
required: true,
},
],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").MessageCreate} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
let roleid = args[0].value;
let role = interaction.guild.roles.cache.find(x => x.id == roleid);
if (role == undefined) {
return interaction.send({ content: `Uh Oh! The role <@&${args[0].value}> connot be found.` });
} else {
let guild = await client.dbo.collection("prefixes").findOne({"server.serverID":interaction.guild.id}).then(guild => guild);
if (!client.exists(guild.server.hasCustomRoles) || !guild.server.hasCustomRoles) return interaction.send({ content: `There are no roles to be removed.` });
if (!guild.server.allowedRoles.includes(roleid)) return interaction.send({ content: `The role <@&${args[0].value}> is not added to your roles.` });
for (let i = 0; i < guild.server.allowedRoles.length; i++) {
if (guild.server.allowedRoles[i]==roleid) {
if ((guild.server.allowedRoles.length-1)==0) {
client.dbo.collection("prefixes").updateOne({"server.serverID":interaction.guild.id},{$pull:{"server.allowedRoles":roleid},$set:{"server.hasCustomRoles":false}},function(err, res) {
if (err) throw err;
return interaction.send({ content: `Successfully removed <@&${args[0].value}> from allowed roles! There are no more allowed roles.` });
});
} else if ((guild.server.allowedRoles.length-1)>0) {
client.dbo.collection("prefixes").updateOne({"server.serverID":interaction.guild.id},{$pull:{"server.allowedRoles":roleid}},function(err, res) {
if (err) throw err;
return interaction.send({ content: `Successfully removed <@&${args[0].value}> from allowed roles.` });
});
}
}
}
}
},
},
}
+30
View File
@@ -0,0 +1,30 @@
const { EmbedBuilder } = require('discord.js');
const bitfieldCalculator = require('discord-bitfield-calculator');
module.exports = {
name: "reset_channels",
description: "Reset the configured channels for the bot",
usage: "[channel]",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: ["MANAGE_GUILD"],
},
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").MessageCreate} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
const permissions = bitfieldCalculator.permissions(interaction.member.permissions);
if (!permissions.includes("MANAGE_GUILD")) return interaction.send({ content: 'You don\'t have the permissions to use this command.' });
client.dbo.collection("prefixes").updateOne({"server.serverID":interaction.guild.id},{$set:{"server.allowedChannels": [], "server.hasCustomChannels": false}},function(err, res) {
if (err) throw err;
return interaction.send({ content: `Successfully reset all configured channels` });
});
},
},
}
+47
View File
@@ -0,0 +1,47 @@
const { EmbedBuilder } = require('discord.js');
module.exports = {
name: "roles",
description: "View allowed roles",
usage: "",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").MessageCreate} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
let guild = await client.dbo.collection("prefixes").findOne({"server.serverID":interaction.guild.id}).then(guild => guild);
if (!client.exists(guild.server.hasCustomRoles) || !guild.server.hasCustomRoles) {
return interaction.send({ content: 'There are no roles set for the bot.' });
}
let roles = ``;
for (let i = 0; i < guild.server.allowedRoles.length; i++) {
if (guild.server.allowedRoles[i] == undefined) break;
let role = interaction.guild.roles.cache.find(r => r.id == guild.server.allowedRoles[i]);
if (roles.length==0) roles += `@${role.name}`;
else roles += `\n@${role.name}`;
}
let rolesEmbed = new EmbedBuilder()
.setColor('#0099ff')
.setDescription('|**Allowed Roles to use the Bot**')
.addFields(
{ name: `There are currently **${guild.server.allowedRoles.length}** allowed roles.`, value: `\`${roles}\``, inline: true },
)
.setFooter({ text: 'LPS Website Support', iconURL: client.config.IconURL, proxyIconURL: 'https://discord.gg/jgUW656v2t' })
return interaction.send({ embeds: [rolesEmbed] });
},
},
}
+46
View File
@@ -0,0 +1,46 @@
const { EmbedBuilder } = require('discord.js');
module.exports = {
name: "setchannel",
description: "Add channel to allowed channels",
usage: "[channel]",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: ["MANAGE_GUILD"],
},
options: [
{
name: "channel",
description: "Channel to add to allowed channles",
value: "channel",
type: 7,
required: true,
},
],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").MessageCreate} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
let channelid = args[0].value;
let channel = client.channels.cache.get(channelid);
if (!channel) return interaction.send({ content: `Cannot find that channel.` });
if (channel.type=="voice") return interaction.send({ content: `Connot set voice channel to preferred channel.` });
if (channel.deleted) return interaction.send({ content: `Connot set deleted channel to preferred channel.` });
let guild = await client.dbo.collection("prefixes").findOne({"server.serverID":interaction.guild.id}).then(guild => guild);
if (client.exists(guild.server.allowedChannels)&&guild.server.allowedChannels.includes(channelid)) return interaction.send({ content: `The channel <#${args[0].value}> has already been added.` });
client.dbo.collection("prefixes").updateOne({"server.serverID":interaction.guild.id},{$push:{"server.allowedChannels":channelid},$set:{"server.hasCustomChannels":true}},function(err, res) {
if (err) throw err;
return interaction.send({ content: `Successfully added <#${args[0].value}> to allowed channels.` });
});
},
},
}
+47
View File
@@ -0,0 +1,47 @@
const { EmbedBuilder } = require('discord.js');
module.exports = {
name: "setrole",
description: "Add a role allowed to use the bot",
usage: "[role]",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: ["MANAGE_GUILD"],
},
options: [
{
name: "role",
description: "Role to add to allowed roles",
value: "role",
type: 8,
required: true,
},
],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").MessageCreate} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
let roleid = args[0].value;
let role = interaction.guild.roles.cache.find(x => x.id == roleid);
if (role == undefined) {
return interaction.send({ content: `Uh Oh! The role <@&${args[0].value}> connot be found.` });
} else {
let guild = await client.dbo.collection("prefixes").findOne({"server.serverID":interaction.guild.id}).then(guild => guild);
if (client.exists(guild.server.allowedRoles)&&guild.server.allowedRoles.includes(roleid)) return interaction.send({ content: `The role <@&${args[0].value}> has already been added.` });
client.dbo.collection("prefixes").updateOne({"server.serverID":interaction.guild.id},{$push:{"server.allowedRoles":roleid},$set:{"server.hasCustomRoles":true}},function(err, res) {
if (err) throw err;
return interaction.send({ content: `Successfully added <@&${args[0].value}> to allowed roles.` });
});
}
},
},
}
+38
View File
@@ -0,0 +1,38 @@
const { EmbedBuilder } = require("discord.js");
require("moment-duration-format");
module.exports = {
name: "stats",
description: "Displays current Bot statistics",
usage: "",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").Message} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
const { version } = require("discord.js");
const totalGuilds = await client.shard.fetchClientValues("guilds.cache.size").then(results => {
return results.reduce((acc, guildCount) => acc + guildCount, 0)
});
const totalMembers = await client.shard.broadcastEval(c => c.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0)).then(data => data.reduce((acc, memberCount) => acc + memberCount, 0));
const stats = new EmbedBuilder()
.setColor('#0099ff')
.setTitle("Current LPC-Bot Statistics")
.setURL(client.config.SupportServer)
.setDescription(`**Servers** : \`${totalGuilds}\`\n**Users** : \`${totalMembers}\``)
interaction.send({ embeds: [stats] })
},
},
};
+60
View File
@@ -0,0 +1,60 @@
const { EmbedBuilder } = require('discord.js');
module.exports = {
name: "togglepingonpanic",
description: "Enable or Disable ping on panic",
usage: "[true/false] [role]",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [
{
name: "toggle",
description: "Toggle ping on panic",
value: "toggle",
type: 5,
required: true,
},
{
name: "role",
description: "Role to ping on panic",
value: "role",
type: 8,
required: true,
},
],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").MessageCreate} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
if (!args[0].value) {
// disable ping on panic and remove ping role
client.dbo.collection("prefixes").updateOne({"server.serverID":interaction.guild.id},{$set:{"server.pingOnPanic":false,"server.pingRole":null}},function(err, res) {
if (err) throw err;
return interaction.send({ content: `Successfully disabled ping role on panic.` });
});
} else if (args[0].value) {
let roleid = args[1].value;
let role = interaction.guild.roles.cache.find(x => x.id == roleid);
if (role == undefined) {
return interaction.send({ content: `Uh Oh! The role <@&${args[1].value}> connot be found.` });
} else {
client.dbo.collection("prefixes").updateOne({"server.serverID":interaction.guild.id},{$set:{"server.pingRole":roleid,"server.pingOnPanic":true}},function(err, res) {
if (err) throw err;
return interaction.send({ content: `Successfully set <@&${args[1].value}> to be pinged on panic.` });
});
}
}
},
},
}
+138
View File
@@ -0,0 +1,138 @@
const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js');
const io = require('socket.io-client');
module.exports = {
name: "updatelicense",
description: "Update Drivers License Status",
usage: "[firstName] [lastName] [DOB]",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [
{
name: "firstname",
description: "Civilian's First Name",
value: "firstname",
type: 3,
required: true,
},
{
name: "lastname",
description: "Civilian's Last Name",
value: "lastname",
type: 3,
required: true,
},
{
name: "dob",
description: "Civilian's DOB (yyyy-mm-dd)",
value: "dob",
type: 3,
required: true,
},
],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").Message} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
let useCommand = await client.verifyUseCommand(GuildDB.serverID, interaction.member.roles);
if (!useCommand) return interaction.send({ content: "You don't have permission to use this command" });
let user = await client.dbo.collection("users").findOne({"user.discord.id":interaction.member.user.id}).then(user => user);
if (!user) return interaction.send({ content: `You are not logged in.` });
let data = {
user: user,
query: {
firstName: args[0].value,
lastName: args[1].value,
dateOfBirth: args[2].value,
activeCommunityID: user.user.activeCommunity
}
}
const socket = io.connect(client.config.socket);
socket.emit("bot_name_search", data);
socket.on("bot_name_search_results", (results) => {
if (results.user._id==user._id) {
if (results.civilians.length == 0) {
return interaction.send({ content: `Name \`${args[0].value} ${args[1].value}\` not found.` });
}
}
let nameResult;
let row;
for (let i = 0; i < results.civilians.length; i++) {
// Get Drivers Licence Status
let licenseStatus;
if (results.civilians[i].civilian.licenseStatus == 1) licenseStatus = 'Valid';
if (results.civilians[i].civilian.licenseStatus == 2) licenseStatus = 'Revoked';
if (results.civilians[i].civilian.licenseStatus == 3) licenseStatus = 'None';
nameResult = new EmbedBuilder()
.setColor('#0099ff')
.setTitle(`**${results.civilians[i].civilian.firstName} ${results.civilians[i].civilian.lastName} | ${results.civilians[i]._id}**`)
.setURL('https://discord.gg/jgUW656v2t')
.setAuthor({ name: 'LPS Website Support', iconURL: client.config.IconURL, url: 'https://discord.gg/jgUW656v2t' })
.setDescription('Name Search Results')
.addFields(
{ name: `**First Name**`, value: `\`${results.civilians[i].civilian.firstName}\``, inline: true },
{ name: `**Last Name**`, value: `\`${results.civilians[i].civilian.lastName}\``, inline: true },
{ name: `**DOB**`, value: `\`${results.civilians[i].civilian.birthday}\``, inline: true },
{ name: `**Drivers License**`, value: `\`${licenseStatus}\``, inline: true },
{ name: `**Gender**`, value: `\`${results.civilians[i].civilian.gender}\``, inline: true }
)
row = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId(`license-revoke-${results.civilians[i]._id}`)
.setLabel("Revoke")
.setStyle(ButtonStyle.Danger),
new ButtonBuilder()
.setCustomId(`license-reinstate-${results.civilians[i]._id}`)
.setLabel("Reinstate")
.setStyle(ButtonStyle.Success)
)
}
return interaction.send({ embeds: [nameResult], components: [row], flags: (1 << 6) });
});
},
},
Interactions: {
license: {
run: async (client, ButtonInteraction, { GuildDB }) => {
const socket = io.connect(client.config.socket);
let queryString = ButtonInteraction.customId;
let query = {
_id: "",
status: null,
bot_request: true
};
if (queryString.split('-')[1]=='revoke') {
query.status = 2;
query._id = queryString.split('-')[2];
} else if (queryString.split('-')[1]=='reinstate') {
query.status = 1;
query._id = queryString.split('-')[2];
}
socket.emit("update_drivers_license_status", query);
socket.on("bot_updated_drivers_license_status", (res) => {
socket.disconnect();
if (!res.success) return ButtonInteraction.update({ content: 'Failed to update license.', embeds: [], components: [] });
});
return ButtonInteraction.update({ content: 'Successfully updated license.', embeds: [], components: [] });
}
}
}
}
+75
View File
@@ -0,0 +1,75 @@
const { EmbedBuilder } = require('discord.js');
const io = require('socket.io-client');
module.exports = {
name: "updatestatus",
description: "Change User status",
usage: "[status]",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [
{
name: "status",
description: "New Status Value",
value: "status",
type: 3,
required: true,
choices: [
{ name: '10-8 (In Service)', value: '10-8', }, { name: '10-7 (Out of Service)', value: '10-7', }, { name: '10-6 (Busy)', value: '10-6', },
{ name: '10-11 (Traffic Stop)', value: '10-11', }, { name: '10-23 (Arrive on Scene', value: '10-23', }, { name: '10-97 (In Route)', value: '10-97' },
{ name: '10-15 (Subject in Custody)', value: '10-15', }, { name: '10-70 (Foot Pursuit)', value: '10-70', }, { name: '10-80 (Vehicle Pursuit)', value: '10-80' },
{ name: '10-41 (Log in to CAD)', value: '10-41', }, { name: '10-42 (Log out of CAD)', value: '10-42' },
],
},
],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").Message} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
let useCommand = await client.verifyUseCommand(GuildDB.serverID, interaction.member.roles);
if (!useCommand) return interaction.send({ content: "You don't have permission to use this command" });
let user = await client.dbo.collection("users").findOne({"user.discord.id":interaction.member.user.id}).then(user => user);
if (!user) return interaction.send({ content: `You are not logged in <@${interaction.member.user.id}>` });
if (user.user.activeCommunity==null) return interaction.send({ content: `You must join a community to use this command.` });
let onDuty=null;
let updateDuty=false;
let status = args[0].value;
if (args[0].value=='10-41') {
onDuty=true;
updateDuty=true;
status='Online';
}
if (args[0].value=='10-42') {
onDuty=false;
updateDuty=true;
status='Offline';
}
let req={
userID: user._id,
status: status,
setBy: 'Self',
onDuty: onDuty,
updateDuty: updateDuty
};
const socket = io.connect(client.config.socket);
socket.emit('bot_update_status', req);
socket.on('bot_updated_status', (res) => {
socket.disconnect();
return interaction.send({ content: `Succesfully updated <@${interaction.member.user.id}>'s status to \`${args[0].value}\`` });
});
return;
},
},
}
+27
View File
@@ -0,0 +1,27 @@
const { EmbedBuilder } = require('discord.js');
module.exports = {
name: "website",
description: "Link to the Lines Police CAD website",
usage: "",
permissions: {
channel: ["VIEW_CHANNEL", "SEND_MESSAGES", "EMBED_LINKS"],
member: [],
},
options: [],
SlashCommand: {
/**
*
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {import("discord.js").Message} message
* @param {string[]} args
* @param {*} param3
*/
run: async (client, interaction, args, { GuildDB }) => {
if (GuildDB.customChannelStatus==true&&!GuildDB.allowedChannels.includes(interaction.channel_id)) {
return interaction.send({ content: `You are not allowed to use the bot in this channel.` });
}
return interaction.send({ content: 'Lines Police CAD Website-> https://www.linespolice-cad.com/' });
},
},
}
-5
View File
@@ -1,5 +0,0 @@
{
"defaultPrefix": "?",
"version": "2.0.0",
"socket": "https://www.linespolice-cad.com/"
}
+28
View File
@@ -0,0 +1,28 @@
require('dotenv').config()
module.exports = {
Dev: "PRODUCTION",
Version: "3.2.3",
Admins: ["362791661274660874"], // Admins of the bot
DefaultPrefix: "?",
socket: "https://www.linespolice-cad.com/",
SupportServer: "https://discord.gg/w2g2FFmHbF", //Support Server Link
Token: process.env.token || "", //Discord Bot Token
Scopes: ["identify", "guilds", "applications.commands"], //Discord OAuth2 Scopes
IconURL: "https://raw.githubusercontent.com/Linesmerrill/police-cad/master/lines-police-cad.png",
EmbedColor: "#0099ff",
Permissions: 2205281600,
Website: "https://linespolice-cad.com",
api_url: process.env.API_URL || "",
api_token: process.env.API_TOKEN || "",
mongoURI: process.env.mongoURI || "mongodb://localhost:27017",
dbo: process.env.dbo || "knoldus",
Colors: {
Red: "#ba0f0f"
},
Presence: {
status: "online", // You can show online, idle, and dnd
name: "Grand Theft Auto V", // The message shown
type: "PLAYING", // PLAYING, WATCHING, LISTENING, STREAMING
},
}
+3
View File
@@ -0,0 +1,3 @@
module.exports = (client, guild) => {
require("../util/RegisterSlashCommands")(client, guild.id);
};
+13
View File
@@ -0,0 +1,13 @@
module.exports = async (client, interaction) => {
if (interaction.isCommand()) return;
/*
This file hanldes all button interactions from any command
*/
let GuildDB = await client.GetGuild(interaction.guildId);
const interactionName = interaction.customId.split('-')[0];
let interactionHandler = client.interactionHandlers.get(interactionName);
interactionHandler.run(client, interaction, GuildDB);
}
+10
View File
@@ -0,0 +1,10 @@
module.exports = async (client) => {
(client.Ready = true),
client.user.setActivity(
client.config.Presence.name,
client.config.Presence.type
)
client.log(`Successfully Logged in as ${client.user.tag}`); // You can change the text if you want, but DO NOT REMOVE "client.user.tag"
client.log(`Ready to serve in ${client.channels.cache.size} channels on ${client.guilds.cache.size} servers, for a total of ${client.users.cache.size} users.`)
client.RegisterSlashCommands();
};
+7 -3
View File
@@ -1,4 +1,8 @@
const Bot = require('./LPS').Bot;
const { ShardingManager } = require('discord.js');
const config = require('./config/config');
let client = new Bot('PRODUCTION', process.env.token, './config', process.env.mongoURI, process.env.dbo);
client.main()
const manager = new ShardingManager('./bot.js', { token: config.Token });
manager.on('shardCreate', shard => console.log(`Launched shard ${shard.id}`));
manager.spawn();
+2089 -1448
View File
File diff suppressed because it is too large. Load diff
+13 -7
View File
@@ -5,16 +5,22 @@
"main": "LPS.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon dev.js"
"dev": "node dev.js",
"dev-active": "nodemon dev.js"
},
"author": "Braeden Sowinski",
"license": "ISC",
"dependencies": {
"discord.js": "^12.5.3",
"express": "^4.17.1",
"mongodb": "^3.6.8",
"nodemon": "^2.0.14",
"randomstring": "^1.2.1",
"socket.io-client": "^4.1.2"
"@discordjs/rest": "^1.7.0",
"colors": "^1.4.0",
"concat-stream": "^2.0.0",
"discord-bitfield-calculator": "^1.0.0",
"discord.js": "^14.9.0",
"dotenv": "^16.0.3",
"form-data": "^4.0.0",
"moment-duration-format": "^2.3.2",
"mongodb": "^4.12.1",
"socket.io-client": "^4.1.2",
"winston": "^3.8.1"
}
}
+302
View File
@@ -0,0 +1,302 @@
const { Collection, Client, EmbedBuilder, Routes } = require('discord.js');
const MongoClient = require('mongodb').MongoClient;
const { REST } = require('@discordjs/rest');
const Logger = require("../util/Logger");
const io = require('socket.io-client');
const path = require("path");
const fs = require('fs');
class LinesPoliceCadBot extends Client {
constructor(options, config) {
super(options)
this.config = config;
this.commands = new Collection();
this.interactionHandlers = new Collection();
this.logger = new Logger(path.join(__dirname, "..", "logs/Logs.log"));
if (this.config.Token === "") return new TypeError(
"The config.js is missing a token, please ensure the token is provided."
);
this.db;
this.dbo;
this.connectMongo(this.config.mongoURI, this.config.dbo);
this.databaseConnected = false;
this.LoadCommandsAndInteractionHandlers();
this.LoadEvents();
this.Ready = false;
this.ws.on("INTERACTION_CREATE", async (interaction) => {
if (interaction.type!=3) {
let GuildDB = await this.GetGuild(interaction.guild_id);
const command = interaction.data.name.toLowerCase();
const args = interaction.data.options;
client.log(`Interaction - ${command}`)
//Easy to send respnose so ;)
interaction.guild = await this.guilds.fetch(interaction.guild_id);
interaction.send = async (message) => {
const rest = new REST({ version: '10' }).setToken(client.config.Token);
return await rest.post(Routes.interactionCallback(interaction.id, interaction.token), {
body: {
type: 4,
data: message,
}
});
};
if (!this.databaseConnected) {
let dbFailedEmbed = new EmbedBuilder()
.setDescription(`**Internal Error:**\nUh Oh D: Its not you, its me.\nThe bot has failed to connect to the database 5 times!\nContact the Developers`)
.setColor(client.config.Colors.Red);
return interaction.send({ embeds: [dbFailedEmbed] });
}
let cmd = client.commands.get(command);
try {
cmd.SlashCommand.run(this, interaction, args, { GuildDB });
} catch (err) {
this.sendInternalError(interaction, err);
}
}
});
const client = this;
}
async connectMongo(mongoURI, dbo) {
let failed = false;
let dbLogDir = path.join(__dirname, '..', 'logs', 'database-logs.json');
let databaselogs;
try {
databaselogs = JSON.parse(fs.readFileSync(dbLogDir));
} catch (err) {
databaselogs = {
attempts: 0,
connected: false,
};
}
if (databaselogs.attempts >= 5) {
this.error('Failed to connect to mongodb after multiple attempts');
return; // prevent further attempts
}
try {
// Connect to Mongo database.
this.db = await MongoClient.connect(mongoURI, { useUnifiedTopology: true, connectTimeoutMS: 1000 });
this.dbo = this.db.db(dbo);
this.log('Successfully connected to mongoDB');
databaselogs.connected = true;
databaselogs.attempts = 0;
this.databaseConnected = true;
} catch (err) {
databaselogs.attempts++;
let db = (mongoURI.includes("@") ? mongoURI.split("@")[1] : mongoURI.split("//")[1]).endsWith("/") ? mongoURI.slice(0, -1) : mongoURI;
this.error(`Failed to connect to mongodb (mongodb://${db}/${dbo}): attempt ${databaselogs.attempts} - ${err}`);
failed = true;
}
// write JSON string to a file
fs.writeFileSync(dbLogDir, JSON.stringify(databaselogs));
if (failed) process.exit(-1);
}
// This is for the 'panic' command when enabling panic
// May be used by other interaction
async forceUpdateStatus(status, user) {
let onDuty = null;
let updateDuty = false;
// If the are off duty, make them on duty + online
if (status == '10-41') {
onDuty = true;
updateDuty = true;
status = 'Online';
}
// If they are on duty,
if (status == '10-42') {
onDuty = false;
updateDuty = true;
status = 'Offline';
}
let req = {
userID: user._id,
status: status,
setBy: 'Self',
onDuty: onDuty,
updateDuty: updateDuty
};
const socket = io.connect(this.config.socket);
socket.emit('bot_update_status', req);
socket.on('bot_updated_status', (res) => {
if (res.userID == user._id) socket.disconnect(); // ensure success response is for us
});
}
exists(n) {return null != n && undefined != n && "" != n}
LoadCommandsAndInteractionHandlers() {
let CommandsDir = path.join(__dirname, '..', 'commands');
fs.readdir(CommandsDir, (err, files) => {
if (err) this.error(err);
else
files.forEach((file) => {
let cmd = require(CommandsDir + "/" + file);
if (!cmd.name || !cmd.description)
return this.log(
"Unable to load Command: " +
file.split(".")[0] +
", Reason: File doesn't had run/name/desciption"
);
this.commands.set(file.split(".")[0].toLowerCase(), cmd);
if (this.exists(cmd.Interactions)) {
for (let [interaction, handler] of Object.entries(cmd.Interactions)) {
this.interactionHandlers.set(interaction, handler);
}
}
this.log("Command Loaded: " + file.split(".")[0]);
});
});
}
LoadEvents() {
let EventsDir = path.join(__dirname, '..', 'events');
fs.readdir(EventsDir, (err, files) => {
if (err) this.log(err);
else
files.forEach((file) => {
const event = require(EventsDir + "/" + file);
if (file.split(".")[0] == 'interactionCreate') this.on(file.split(".")[0], i => event(this, i));
else this.on(file.split(".")[0], event.bind(null, this));
this.logger.log("Event Loaded: " + file.split(".")[0]);
});
});
}
sendInternalError(Interaction, Error) {
this.error(Error);
const embed = new EmbedBuilder()
.setDescription(`**Internal Error:**\nUh Oh D: Its not you, its me.\nThis command has crashed\nCOntact the Developers`)
.setColor(this.config.Colors.Red)
Interaction.send({ embeds: [embed] });
}
sendTime(Channel, Error) {
let embed = new EmbedBuilder()
.setColor(this.config.EmbedColor)
.setDescription(Error);
Channel.send({ embeds: [embed] });
}
RegisterSlashCommands() {
let p = Promise.resolve()
this.guilds.cache.forEach((guild) => {
p = p.then(() => {
require("../util/RegisterSlashCommands")(this, guild.id);
return new Promise((resolve) => {
setTimeout(resolve, 500);
})
})
});
}
async checkRoleStatus(rolesCache, allowedRoles) {
if (allowedRoles.length == 0) return true; // If we are in this function, and there are no roles to compare to, return true as if we had the role anyway
for (let i = 0; i < allowedRoles.length; i++) {
if (rolesCache.includes(allowedRoles[i])) return true; // they have at least one matching role
else continue;
}
return false; // they have no matching roles.
}
async GetGuild(GuildId) {
let guild = await this.dbo.collection("prefixes").findOne({"server.serverID":GuildId}).then(guild => guild);
// If guild not found, generate guild default
if (!guild) {
guild = {
server: {
serverID: GuildId,
allowedChannels: [],
allowedRoles: [],
}
}
this.dbo.collection("prefixes").insertOne(guild, function(err, res) {
if (err) throw err;
});
}
if (guild.server.allowedRoles == undefined) guild.server.allowedRoles = [];
let guildData = {
allowedChannels: guild.server.allowedChannels,
customChannelStatus: guild.server.allowedChannels.length > 0 ? true : false,
customRoleStatus: guild.server.allowedRoles.length > 0 ? true : false,
allowedRoles: guild.server.allowedRoles,
serverID: GuildId
}
return guildData;
}
/*
This command is to verify a user
has the correct role to use a
command ie. has cop role to use
name-search
*/
async verifyUseCommand(serverID, rolesCache) {
let guildDB = await this.GetGuild(serverID);
if (!guildDB.customRoleStatus) return true; // There is no role limits, can use command
// Clear any deleted roles
let filteredRoles = [];
let update = false;
const guild = await this.guilds.cache.get(serverID);
for (let i = 0; i < guildDB.allowedRoles.length; i++) {
let role = guild.roles.cache.find(role => role.id == guildDB.allowedRoles[i])
if (!role) update = true; // this role no longer exists, we need to update, dont add to list
else filteredRoles.push(guildDB.allowedRoles[i]); // this role exists, add to list in case of update
}
// If some roles no longer exists, update
// or if customRoleStatus is true but no roles exist, update
if (update || (filteredRoles.length == 0 && customRoleStatus)) {
let newHasCustomRoles = filteredRoles.length > 0;
await this.dbo.collection("prefixes").updateOne({ 'server.serverID': serverID }, { $set: {
'server.allowedRoles': filteredRoles,
'server.hasCustomRoles': newHasCustomRoles,
}}, (err, res) => {
if (err) throw err;
});
}
let hasRole = await this.checkRoleStatus(rolesCache, filteredRoles);
return hasRole;
}
log(Text) { this.logger.log(Text); }
error(Text) { this.logger.error(Text); }
build() {
this.login(this.config.Token);
}
}
module.exports = LinesPoliceCadBot;
+44
View File
@@ -0,0 +1,44 @@
const winston = require("winston");
const colors = require("colors");
class Logger {
constructor(LoggingFile) {
this.logger = winston.createLogger({
transports: [new winston.transports.File({ filename: LoggingFile })],
});
}
log(Text) {
let d = new Date();
this.logger.log({
level: "info",
message:
`${d.getHours()}:${
d.getMinutes
} - ${d.getDate()}:${d.getMonth()}:${d.getFullYear()} | Info: ` + Text,
});
console.log(
colors.green(
`${d.getDate()}:${d.getMonth()}:${d.getFullYear()} - ${d.getHours()}:${d.getMinutes()}`
) + colors.yellow(" | Info: " + Text)
);
}
error(Text) {
let d = new Date();
this.logger.log({
level: "error",
message:
`${d.getHours()}:${
d.getMInutes
} - ${d.getDate()}:${d.getMonth()}:${d.getFullYear()} | Error: ` + Text,
});
console.log(
colors.green(
`${d.getDate()}:${d.getMonth()}:${d.getFullYear()} - ${d.getHours}:${d.getMinutes()}`
) + colors.yellow(" | Error: ") + colors.red(Text)
);
}
}
module.exports = Logger;
+38
View File
@@ -0,0 +1,38 @@
const fs = require("fs");
const path = require("path");
const { Routes } = require('discord.js');
const { REST } = require('@discordjs/rest');
/**
* Register slash commands for a guild
* @param {require("../structures/LinesPoliceCadBot")} client
* @param {string} guild
*/
module.exports = async function(client, guild) {
const commands = [];
const commandFiles = fs.readdirSync(path.join(__dirname, "..", "commands")).filter(file => file.endsWith('.js'));
// Place your client and guild ids here
const clientId = client.application.id;
const guildId = guild;
for (const file of commandFiles) {
const command = require(`../commands/${file}`);
commands.push(command);
}
const rest = new REST({ version: '10' }).setToken(client.config.Token);
try {
client.log(`[${guildId}] Started refreshing guild (/) commands.`);
await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);
client.log(`[${guildId}] Successfully reloaded guild (/) commands.`);
} catch (error) {
client.error(error);
}
};