-
Notifications
You must be signed in to change notification settings - Fork 8
/
app.js
194 lines (166 loc) · 6.6 KB
/
app.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
/**
* Copyright 2019-2023 John H. Nguyen
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the 'Software'), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
require('dotenv').config()
process.setMaxListeners(0)
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits, REST, Routes } = require('discord.js');
const winston = require('winston')
const express = require('express')
const app = express()
const port = process.env.port
const clientId = process.env.client_id
global.resolveModule = (filePath) => {
const modulePath = path.resolve(__dirname, filePath);
return require(modulePath);
}
const logger = winston.createLogger({
level: 'debug',
format: winston.format.json(),
defaultMeta: {
service: 'user-service',
},
transports: [new winston.transports.Console()],
})
const processError = error => {
const code = error?.code || 'no error code'
const message = error?.message || 'no message found'
const stack = error?.stack || 'no stack found'
const url = error?.url || 'no url found'
const msg = `code: ${code}, message: ${message}, stack: ${stack} url: ${url}`
console.error(msg)
logger.error(msg)
}
process.on('unhandledRejection', error => processError(error))
global.logger = logger
try {
// Initialize Discord Bot
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildEmojisAndStickers,
]
})
client.login(process.env.token)
client.commands = new Collection()
const rest = new REST({ version: '10' }).setToken(process.env.token);
const getCommands = (cmdPath) => {
const commandsPath = path.join(__dirname, cmdPath);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
const commands = [];
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
commands.push(command.data.toJSON());
if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required 'data' or 'execute' property.`);
}
}
return commands;
};
const registerCmds = async (guildId, reset) => {
try {
const commands = getCommands('commands')
const isStaFeature = process.env.feature_sta
const is2d20Feature = process.env.feature_2d20
if (isStaFeature) {
commands.push(...getCommands('commands/sta'))
}
if (is2d20Feature) {
commands.push(...getCommands('commands/2d20'))
}
if (reset) {
rest.put(
Routes.applicationGuildCommands(clientId, guildId), { body: [] },
);
} else {
// The put method is used to fully refresh all commands in the guild with the current set
rest.put(
Routes.applicationGuildCommands(clientId, guildId), { body: commands },
);
}
} catch (error) {
// console.error(error)
}
}
const refreshCmdForAllServers = async () => {
client.guilds.cache.forEach(async guild => {
await registerCmds(guild.id)
})
}
client.on(Events.ClientReady, async () => {
logger.info('Connected')
logger.info('Logged in as: ')
logger.info(client.user.username + ' - (' + client.user.id + ')')
logger.info('Starting command registration')
await refreshCmdForAllServers()
logger.info('Command registration completed')
})
client.on(Events.ChannelUpdate, async () => {
await refreshCmdForAllServers()
})
client.on(Events.GuildCreate, async (guild) => {
await registerCmds(guild.id)
})
client.on(Events.InteractionCreate, async interaction => {
let command = interaction.client.commands.get(interaction.commandName);
if (!interaction.isChatInputCommand()) {
try {
await interaction.reply({
content: `This interaction is no longer supported.`
});
} catch (error) {
processError(error)
}
}
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
logger.error(`No command matching ${interaction.commandName} was found.`)
return;
}
try {
await command.execute(interaction);
} catch (error) {
processError(error)
}
})
client.on(Events.MessageCreate, async msg => {
if (msg.guildId === process.env.dev_guild_id) {
if (msg.author.id === process.env.dev_author_id) {
if (msg.content.includes('refresh')) {
await refreshCmdForAllServers()
}
}
}
})
client.on(Events.Error, (error) => processError(error))
app.get('/', (req, res) => {
res.send(`${process.env.bot_name} is up and running. Testing.`)
})
app.listen(port, () => {
logger.info(`${process.env.bot_name} listening on port ${port}`)
})
} catch (error) {
processError(error)
}