Skip to content

Commit 8513466

Browse files
committed
stability improvement
1 parent 8f849f9 commit 8513466

File tree

2 files changed

+82
-50
lines changed

2 files changed

+82
-50
lines changed

index.ts

+81-44
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Client, Intents } from 'discord.js'
1+
import { Client, Guild, Intents } from 'discord.js'
22
import { insertCommands } from './deploy-commands'
33
import { open, getCollections, getMongoClientObj } from './mongoDB'
44
import sphelp from './Commands/sphelp'
@@ -46,18 +46,57 @@ declare global {
4646
}
4747

4848

49-
const firstTimeSetup = async (configOptions: any): Promise<void> => {
49+
const updateFirstTimeSetup = async (newInstance: boolean): Promise<void> => {
5050
// Run first-time setup
5151
const collections = getCollections()
5252
insertCommands()
5353

54-
if (!configOptions || !("password" in configOptions)) {
54+
if (newInstance) {
5555
const password = crypto.randomBytes(32).toString('hex')
5656
console.info("Generated a random password since none was previously set: " + password + ". You can change this using /spsetpassword via the bot")
5757
await collections.config.insertOne({ version: currentVersion, password: await argon2.hash(password) })
58+
console.log("Completed first-time setup")
5859
}
59-
else await collections.config.updateOne({}, { $set: { version: currentVersion } })
60-
console.info("First time setup/update completed.")
60+
else {
61+
await collections.config.updateOne({}, { $set: { version: currentVersion } })
62+
console.info("Completed Storeman Bot update")
63+
}
64+
65+
}
66+
67+
const guildCreateEventHandler = async (guild: Guild) => {
68+
// The bot has joined a new server
69+
console.log("Bot has joined a new server named: " + guild.name)
70+
const collections = getCollections(guild.id)
71+
const password = crypto.randomBytes(32).toString('hex')
72+
await collections.config.insertOne({ password: await argon2.hash(password) })
73+
74+
// Insert commands into that guild
75+
insertCommands(guild.id)
76+
77+
// Add the server record into the global settings list
78+
const globalCollection = getCollections("global-settings")
79+
await globalCollection.config.updateOne({}, { $push: { serverIDList: guild.id } })
80+
}
81+
82+
const guildDeleteEventHandler = async (guild: Guild) => {
83+
console.log("Bot has been kicked (or deleted) from the server named : " + guild.name)
84+
const mongoClient = getMongoClientObj()
85+
const db = mongoClient.db('stockpiler-' + guild.id)
86+
await db.dropDatabase()
87+
88+
const collections = getCollections("global-settings")
89+
const configObj = await collections.config.findOne({})
90+
let found = false
91+
for (let i = 0; i < configObj.serverIDList.length; i++) {
92+
if (configObj.serverIDList[i] === guild.id) {
93+
found = true
94+
configObj.serverIDList.splice(i, 1)
95+
break
96+
}
97+
}
98+
if (found) await collections.config.updateOne({}, { $set: { serverIDList: configObj.serverIDList } })
99+
console.log("Deleted the database and config records of the guild successfully")
61100
}
62101

63102
const main = async (): Promise<void> => {
@@ -167,11 +206,38 @@ const main = async (): Promise<void> => {
167206

168207
const collections = getCollections("global-settings")
169208
const configObj = await collections.config.findOne()
209+
210+
// Obtain list of guild IDs from Discord API to check if it matches with the one stored in the DB
211+
const guildObjs = client.guilds.cache.toJSON()
212+
let listOfGuildObjs: Guild[] = []
213+
let listOfGuildIDs: string[] = []
214+
for (let i = 0; i < guildObjs.length; i++) {
215+
listOfGuildObjs.push(guildObjs[i])
216+
listOfGuildIDs.push(guildObjs[i].id)
217+
}
218+
170219
if (configObj) {
220+
// Check if the guildID list has changed since the bot was down
221+
for (let i = 0; i < listOfGuildObjs.length; i++) {
222+
const currentID = listOfGuildObjs[i].id
223+
if (configObj.serverIDList.indexOf(currentID) === -1) {
224+
// guildID from discord API not found inside our storage, execute createFunction
225+
guildCreateEventHandler(listOfGuildObjs[i])
226+
}
227+
}
228+
for (let i = 0; i < configObj.serverIDList.length; i++) {
229+
const currentID = configObj.serverIDList
230+
if (listOfGuildIDs.indexOf(currentID) === -1) {
231+
// guildID from our database no longer exists in discord API, execute destroyFunction
232+
guildDeleteEventHandler(listOfGuildObjs[i])
233+
}
234+
}
235+
171236
if (configObj.version < currentVersion) {
172237
// Update all the commands since the version has changed
173238
for (let i = 0; i < configObj.serverIDList.length; i++) {
174239
insertCommands(configObj.serverIDList[i])
240+
await collections.config.updateOne({}, { version: currentVersion })
175241
}
176242
}
177243

@@ -186,7 +252,7 @@ const main = async (): Promise<void> => {
186252
if ("prettyName" in serverCollections.config) prettyName[configObj.serverIDList[i]] = serverCollections.config.prettyName
187253
else prettyName[configObj.serverIDList[i]] = {}
188254

189-
255+
190256
const stockpiles = await serverCollections.stockpiles.find({}).toArray()
191257
for (let y = 0; y < stockpiles.length; y++) {
192258
if ("timeLeft" in stockpiles[y]) {
@@ -210,44 +276,15 @@ const main = async (): Promise<void> => {
210276
NodeCacheObj.set("stockpileTimes", stockpileTime)
211277
}
212278
else {
213-
await collections.config.insertOne({ version: currentVersion, serverIDList: [] })
279+
for (let i = 0; i < listOfGuildObjs.length; i++) {
280+
guildCreateEventHandler(listOfGuildObjs[i])
281+
}
282+
await collections.config.insertOne({ version: currentVersion, serverIDList: listOfGuildIDs })
214283
}
215284

216-
client.on('guildCreate', async (guild) => {
217-
// The bot has joined a new server
218-
console.log("Bot has joined a new server named: " + guild.name)
219-
const collections = getCollections(guild.id)
220-
const password = crypto.randomBytes(32).toString('hex')
221-
await collections.config.insertOne({ password: await argon2.hash(password) })
222-
223-
// Insert commands into that guild
224-
insertCommands(guild.id)
225-
226-
// Add the server record into the global settings list
227-
const globalCollection = getCollections("global-settings")
228-
await globalCollection.config.updateOne({}, { $push: { serverIDList: guild.id } })
229-
})
230-
231-
client.on('guildDelete', async (guild) => {
232-
console.log("Bot has been kicked (or deleted) from the server named : " + guild.name)
233-
const mongoClient = getMongoClientObj()
234-
const db = mongoClient.db('stockpiler-' + guild.id)
235-
await db.dropDatabase()
236-
237-
const configObj = await collections.config.findOne({})
238-
let found = false
239-
for (let i = 0; i < configObj.serverIDList.length; i++) {
240-
if (configObj.serverIDList[i] === guild.id) {
241-
found = true
242-
configObj.serverIDList.splice(i, 1)
243-
break
244-
}
245-
}
246-
if (found) await collections.config.updateOne({}, { $set: { serverIDList: configObj.serverIDList } })
247-
console.log("Deleted the database and config records of the guild successfully")
248-
})
285+
client.on('guildCreate', (guild) => { guildCreateEventHandler(guild) })
249286

250-
// Custom prettyName handler
287+
client.on('guildDelete', async (guild) => { guildDeleteEventHandler(guild) })
251288
}
252289
else {
253290
// Create list of timeLefts till the stockpile expires
@@ -286,12 +323,12 @@ const main = async (): Promise<void> => {
286323

287324

288325
if (configOptions.version) {
289-
if (configOptions.version < currentVersion) firstTimeSetup(configOptions)
326+
if (configOptions.version < currentVersion) updateFirstTimeSetup(false)
290327
}
291-
else firstTimeSetup(configOptions)
328+
else updateFirstTimeSetup(true)
292329

293330
}
294-
else firstTimeSetup(configOptions)
331+
else updateFirstTimeSetup(true)
295332
}
296333

297334

mongoDB.ts

+1-6
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,5 @@
1-
import { Db, MongoClient, Collection, WithId } from 'mongodb'
1+
import { Db, MongoClient} from 'mongodb'
22
let db: Db
3-
interface collectionList {
4-
stockpiles: Collection,
5-
targets: Collection,
6-
config: Collection
7-
}
83
let mongoClientObj: any;
94

105

0 commit comments

Comments
 (0)