-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathserver.js
326 lines (300 loc) · 13.7 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
console.log("Booting bot...")
require("dotenv").config()
const fs = require("fs")
const db = require("quick.db")
const { fn, getEmoji, ids } = require("./config")
const Sentry = require("@sentry/node")
const Tracing = require("@sentry/tracing")
if (db.fetch("emergencystop")) {
setTimeout(() => {
console.log("Bot has been emergency stopped")
process.exit(0)
}, 10000)
}
const mongo = require("./db.js")
const Discord = require("discord.js")
const client = new Discord.Client({ intents: ["GUILD_MESSAGES", "GUILD_MESSAGE_REACTIONS", "DIRECT_MESSAGES", "GUILDS", "GUILD_MEMBERS", "GUILD_BANS", "GUILD_EMOJIS_AND_STICKERS", "GUILD_PRESENCES"] })
const config = require("./config")
client.db = db
client.dbs = mongo
client.Sentry = Sentry
const { createAppAuth } = require("@octokit/auth-app")
const { Octokit } = require("@octokit/core")
const players = require("./schemas/players.js")
if (process.env.DEBUG) {
client.on("debug", console.debug)
client.on("messageCreate", (x) => console.debug(`${x.content} - ${x.author.tag} ${x.author.id}`))
}
client.commands = new Discord.Collection()
fs.readdir("./commands/", (err, files) => {
files.forEach((file) => {
let path = `./commands/${file}`
fs.readdir(path, (err, files) => {
if (err) console.error(err)
let jsfile = files.filter((f) => f.split(".").pop() === "js")
if (jsfile.length <= 0) {
console.error(`Couldn't find commands in the ${file} category.`)
return
}
jsfile.forEach((f, i) => {
let props = require(`./commands/${file}/${f}`)
props.category = file
try {
client.commands.set(props.name, props)
if (props.aliases) props.aliases.forEach((alias) => client.commands.set(alias, props))
} catch (err) {
if (err) console.error(err)
}
})
})
})
})
client.slashCommands = new Discord.Collection()
fs.readdir("./slashCommands/", (err, files) => {
files.forEach((file) => {
let path = `./slashCommands/${file}`
fs.readdir(path, (err, files) => {
if (err) console.error(err)
let jsfile = files.filter((f) => f.split(".").pop() === "js")
if (jsfile.length <= 0) {
console.error(`Couldn't find slash commands in the ${file} category.`)
}
jsfile.forEach((f, i) => {
let props = require(`./slashCommands/${file}/${f}`)
props.category = file
try {
client.slashCommands.set(props.command.name, props)
} catch (err) {
if (err) console.error(err)
}
})
})
})
})
const eventFiles = fs.readdirSync("./events").filter((file) => file.endsWith(".js"))
for (const file of eventFiles) {
require(`./events/${file}`)(client)
}
client.botAdmin = (id) => {
if (["439223656200273932", "406412325973786624", "263472056753061889", "517335997172809728"].includes(id)) return true
return false
}
client.paginator = async (author, msg, embeds, pageNow, addReactions = true) => {
if (embeds.length === 1) return
if (addReactions) {
await msg.react("⏪")
await msg.react("◀️")
await msg.react("▶️")
await msg.react("⏩")
}
let reaction = await msg.awaitReactions((reaction, user) => user.id == author && ["◀", "▶", "⏪", "⏩"].includes(reaction.emoji.name), { time: 30 * 1000, max: 1, errors: ["time"] }).catch(() => {})
if (!reaction) return msg.reactions.removeAll().catch(() => {})
reaction = reaction.first()
//console.log(msg.member.users.tag)
if (msg.channel.type == "dm" || !msg.guild.me.permissions.has("MANAGE_MESSAGES")) {
if (reaction.emoji.name == "◀️") {
let m = await msg.channel.send(embeds[Math.max(pageNow - 1, 0)])
msg.delete()
client.paginator(author, m, embeds, Math.max(pageNow - 1, 0))
} else if (reaction.emoji.name == "▶️") {
let m = await msg.channel.send(embeds[Math.min(pageNow + 1, embeds.length - 1)])
msg.delete()
client.paginator(author, m, embeds, Math.min(pageNow + 1, embeds.length - 1))
} else if (reaction.emoji.name == "⏪") {
let m = await msg.channel.send(embeds[0])
msg.delete()
client.paginator(author, m, embeds, 0)
} else if (reaction.emoji.name == "⏩") {
let m = await msg.channel.send(embeds[embeds.length - 1])
msg.delete()
client.paginator(author, m, embeds, embeds.length - 1)
}
} else {
if (reaction.emoji.name == "◀️") {
await reaction.users.remove(author)
let m = await msg.edit(embeds[Math.max(pageNow - 1, 0)])
client.paginator(author, m, embeds, Math.max(pageNow - 1, 0), false)
} else if (reaction.emoji.name == "▶️") {
await reaction.users.remove(author)
let m = await msg.edit(embeds[Math.min(pageNow + 1, embeds.length - 1)])
client.paginator(author, m, embeds, Math.min(pageNow + 1, embeds.length - 1), false)
} else if (reaction.emoji.name == "⏪") {
await reaction.users.remove(author)
let m = await msg.edit(embeds[0])
client.paginator(author, m, embeds, 0, false)
} else if (reaction.emoji.name == "⏩") {
await reaction.users.remove(author)
let m = await msg.edit(embeds[embeds.length - 1])
client.paginator(author, m, embeds, embeds.length - 1, false)
}
}
}
client.buttonPaginator = async (authorID, msg, embeds, page, addButtons = true) => {
if (embeds.length <= 1) return
// buttons
let buttonBegin = { type: 2, style: 3, emoji: { name: "⏪" }, custom_id: "begin" }
let buttonBack = { type: 2, style: 3, emoji: { name: "◀" }, custom_id: "back" }
let buttonNext = { type: 2, style: 3, emoji: { name: "▶" }, custom_id: "next" }
let buttonEnd = { type: 2, style: 3, emoji: { name: "⏩" }, custom_id: "end" }
// rows
let activeRow = { type: 1, components: [buttonBegin, buttonBack, buttonNext, buttonEnd] }
// adding buttons
if (addButtons) msg.edit({ components: [activeRow] })
// collecting interactions
let filter = (interaction) => interaction.isButton() === true
let collector = msg.createMessageComponentCollector({ filter, idle: 15 * 1000 })
let p = --page
collector.on("collect", async (button) => {
if (button.user.id !== authorID) button.reply({ content: "This is not your message. Please request your own one.", ephemeral: true })
else {
if (button.customId === "begin") p = 0
else if (button.customId === "back") {
if (p != 0) p--
else p = embeds.length - 1
} else if (button.customId === "next") {
if (p != embeds.length - 1) p++
else p = 0
} else if (button.customId === "end") p = embeds.length - 1
await button.update({ embeds: [embeds[p]] })
}
})
collector.on("end", () => {
buttonBegin.disabled = true
buttonBack.disabled = true
buttonNext.disabled = true
buttonEnd.disabled = true
let deadRow = { type: 1, components: [buttonBegin, buttonBack, buttonNext, buttonEnd] }
msg.edit({ components: [deadRow] })
})
}
client.debug = async (options = { game: false }) => {
let data = {}
data.night = Math.floor(db.get(`gamePhase`) / 3) + 1
data.day = Math.floor(db.get(`gamePhase`) / 3) + 1
data.gamePhase = db.get(`gamePhase`)
let alive = client.guilds.cache.get(config.ids.server.game).roles.cache.find((r) => r.name === "Alive")
let dead = client.guilds.cache.get(config.ids.server.game).roles.cache.find((r) => r.name === "Dead")
let players = []
alive.members.forEach((x) => players.push({ status: "alive", id: x.id, tag: x.user.tag, role: db.get(`role_${x.id}`) }))
dead.members.forEach((x) => players.push({ status: "dead", id: x.id, tag: x.user.tag, role: db.get(`role_${x.id}`) }))
data.players = players
return data
}
//Bot on startup
client.once("ready", async () => {
client.config = {}
let commit = require("child_process").execSync("git rev-parse --short HEAD").toString().trim()
let branch = require("child_process").execSync("git rev-parse --abbrev-ref HEAD").toString().trim()
client.user.setActivity(client.user.username.toLowerCase().includes("beta") ? "testes gae on branch " + branch + " and commit " + commit : "Wolvesville Simulation!")
console.log("Connected!")
client.userEmojis = client.emojis.cache.filter((x) => config.ids.emojis.includes(x.guild.id))
client.channels.cache.get("832884582315458570").send(`Bot has started, running commit \`${commit}\` on branch \`${branch}\``)
let restarted = db.get("botRestart")
if (restarted) {
client.channels
.fetch(restarted.split("/")[0])
.then((c) => {
c.messages
.fetch(restarted.split("/")[1])
.then((m) => {
m.edit("Bot has restarted!")
})
.catch(() => {
console.log("Could not find message to edit")
})
})
.finally(() => {
db.delete("botRestart")
})
}
if (!client.user.username.includes("Beta")) {
Sentry.init({
dsn: process.env.SENTRY,
tracesSampleRate: 1.0,
})
let privateKey = fs.readFileSync("./ghnb.pem")
client.github = new Octokit({
authStrategy: createAppAuth,
auth: {
appId: 120523,
privateKey,
clientSecret: process.env.GITHUB,
installationId: 17541999,
},
})
if (restarted) {
client.channels
.fetch("606123881824256000")
.then((c) => {
c.send(`The Bot restarted. All timers were deleted.`)
})
.catch(() => {
console.log("Could not find channel to send message to")
})
}
}
setInterval(async () => {
let lottery = require("./schemas/lottery")
let lotteries = await lottery.find()
if (lotteries.length != 0) {
let lot = lotteries[0]
if (new Date().getTime() > lot.endDate) {
let chan = client.channels.cache.get("947930500725616700")
let logs = client.channels.cache.get("949248776500031508")
if (lot.participants.length == 0) {
chan.send(`No one has joined this lottery, so no winner.`)
} else {
let winner = fn.randomWeight(lot.participants)
let person = client.users.cache.find((u) => u.id === winner)
chan.send(`Congratulations to ${person} for winning the lottery! You have won ${lot.pot} ${getEmoji("coin", client)}, they have been added to your balance.`)
let msg = await chan.messages.fetch(lot.msg)
msg.edit({ components: [] })
let player = await players.findOne({ user: person.id })
player.coins += lot.pot
if (!client.guilds.resolve(ids.server.sim).members.cache.get(winner).roles.cache.has("947629828771831888")) client.guilds.resolve(ids.server.sim).members.cache.get(winner).roles.add("947629828771831888")
let part = []
lot.participants.forEach(async (p) => {
let arr = Object.entries(p)
let userTag = client.users.cache.get(arr[0][0])?.tag || "N/A"
part.push(`${userTag} (${arr[0][0]}): ${arr[0][1]}`)
})
logs.send({
embeds: [
{
description: `**Pot:** ${lot.pot}\n` + `**Max Tickets:** ${lot.max}\n` + `**Cost:** ${lot.cost}\n` + `**Total Tickets:** ${lot.ticketsBought}\n` + `**End Date:** <t:${Math.floor(lot.endDate / 1000)}:f>\n` + `**Message ID:** ${lot.msg}\n\n` + `**Participants:**\n` + `${part.join(",\n")}`,
color: 0x00ff00,
},
],
})
player.save()
lot.remove()
}
}
}
}, 2000)
setInterval(async () => {
// collect all members and put them in an array
let stats = require("./schemas/stats")
let stat = await stats.find()
stat = stat[0]
if (new Date().getTime() > stat?.newFetch) {
let members = await client.guilds.cache.get(config.ids.server.sim).members.fetch()
let arr = []
members.forEach((x) => arr.push(x.id))
if (stat.members.length != 0) stat.previousFetch.push({ [new Date()]: stat.members })
stat.members = arr
stat.newFetch = new Date().getTime() + 3600000
stat.save()
}
}, 2000)
//Invite Tracker
// client.allInvites = await client.guilds.cache.get(config.ids.server.sim).invites.fetch()
})
let maint = db.get("maintenance")
if (typeof maint == "string" && maint.startsWith("config-")) {
client.channels.cache.get(maint.split("-")[1])?.send("Config has successfully been reloaded!")
db.set("maintenance", false)
}
client.on("error", (e) => console.error(e))
client.login(process.env.TOKEN)
module.exports = { client }