-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
221 lines (191 loc) · 8.33 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
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
const Discord = require("discord.js")
require("dotenv").config()
const { Client, GatewayIntentBits, ActivityType, ChannelType, PermissionsBitField } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildVoiceStates
]
})
const { readdirSync } = require("fs")
const moment = require("moment")
moment.locale('es')
client.slash = new Discord.Collection()
const { REST } = require("@discordjs/rest")
const { Routes } = require("discord-api-types/v9")
const path = require("path")
const commands = []
const Timeout = new Set()
const humanizeDuration = require("humanize-duration")
const dbConnection = require('./database/connection');
const PomodoroContainer = require('./models/PomodoroContainer');
client.pomodoroContainer = PomodoroContainer;
const PomodoroSession = require('./models/PomodoroSession');
const randomEmoji = require('./utils/randomEmoji');
readdirSync("./commands/").map(async dir => {
readdirSync(`./commands/${dir}/`).map(async (cmd) => {
commands.push(require(path.join(__dirname, `./commands/${dir}/${cmd}`)))
})
})
const rest = new REST({ version: "9" }).setToken(process.env.TOKEN);
(async () => {
try {
await rest.put(
Routes.applicationCommands(process.env.BOT_ID),
{ body: commands }
)
console.log("\x1b[34m%s\x1b[0m", "Successfully reloaded application (/) commands.")
} catch (error) {
console.error(error)
}
})();
["slash", "anticrash"].forEach(handler => {
require(`./handlers/${handler}`)(client)
})
client.on("ready", () => {
console.log("\x1b[34m%s\x1b[0m", `Conectado como ${client.user.tag}!`)
client.user.setPresence({
activities: [{ name: "Pomodoro", type: ActivityType.Playing }],
status: 'idle',
});
const connection = new dbConnection();
connection.query(`CREATE TABLE IF NOT EXISTS pomodoro_sessions (
id INT NOT NULL AUTO_INCREMENT,
user_id VARCHAR(255) NOT NULL,
voice_channel_id VARCHAR(255) NOT NULL,
embed_message_id VARCHAR(255) NULL,
status INT NULL DEFAULT 0,
start_time DATETIME NOT NULL,
end_time DATETIME NULL,
PRIMARY KEY (id))`).then(result => {
if (result.warningCount === 0) {
console.log("\x1b[32m%s\x1b[0m", "Tabla pomodoro_sessions creada correctamente.");
}
else {
console.log("\x1b[33m%s\x1b[0m", "Tabla pomodoro_sessions ya existente.");
}
connection.close();
}).catch((error) => {
console.log("\x1b[31m%s\x1b[0m", `Error al crear la tabla pomodoro_sessions: ${error}`)
connection.close();
})
})
client.on("interactionCreate", async (interaction) => {
if (interaction.isButton()) {
switch (interaction.customId) {
case "resume":
await interaction.reply({ content: "Reanudando pomodoro...", ephemeral: true })
var pomodoroSession = client.pomodoroContainer.getPomodoroSessionByUser(interaction.user);
if (pomodoroSession) {
pomodoroSession.resumePomodoro();
await interaction.editReply({ content: "Pomodoro reanudado.", ephemeral: true })
} else {
await interaction.editReply({ content: "No puedes reanudar esta sesión pomodoro.", ephemeral: true })
}
setTimeout(() => {
interaction.deleteReply();
}, 5000);
break;
case "pause":
await interaction.reply({ content: "Pausando pomodoro...", ephemeral: true })
var pomodoroSession = client.pomodoroContainer.getPomodoroSessionByUser(interaction.user);
if (pomodoroSession) {
pomodoroSession.pausePomodoro();
await interaction.editReply({ content: "Pomodoro pausado.", ephemeral: true })
} else {
await interaction.editReply({ content: "No puedes pausar esta sesión pomodoro.", ephemeral: true })
}
setTimeout(() => {
interaction.deleteReply();
}, 5000);
break;
case "cancel":
await interaction.reply({ content: "Cancelando pomodoro...", ephemeral: true })
var pomodoroSession = client.pomodoroContainer.getPomodoroSessionByUser(interaction.user);
if (pomodoroSession) {
pomodoroSession.cancelPomodoro();
client.pomodoroContainer.removePomodoroSession(pomodoroSession);
// await interaction.editReply({ content: "Pomodoro cancelado.", ephemeral: true })
} else {
await interaction.editReply({ content: "No puedes cancelar esta sesión pomodoro.", ephemeral: true })
}
break;
default:
break;
}
}
else if (interaction.isCommand() || interaction.isContextMenu()) {
if (!client.slash.has(interaction.commandName)) return
if (!interaction.guild) return
const command = client.slash.get(interaction.commandName)
try {
if (command.timeout) {
if (Timeout.has(`${interaction.user.id}${command.name}`)) {
return interaction.reply({ content: `Tienes que esperar **${humanizeDuration(command.timeout, { round: true })}** para usar el comando otra vez.`, ephemeral: true })
}
}
if (command.permissions) {
if (!interaction.member.permissions.has(command.permissions)) {
return interaction.reply({ content: `:x: Necesitas \`${command.permissions}\` para usar este comando.`, ephemeral: true })
}
}
command.run(interaction, client)
Timeout.add(`${interaction.user.id}${command.name}`)
setTimeout(() => {
Timeout.delete(`${interaction.user.id}${command.name}`)
}, command.timeout)
} catch (error) {
console.error(error)
await interaction.reply({ content: ":x: Ha habido algún error al ejecutar el comando.", ephemeral: true })
}
}
})
client.on("voiceStateUpdate", (oldState, newState) => {
if (newState.channelId === process.env.DISCORD_VOICECHANNEL_CREATEROOM) {
var pomodoroSession = client.pomodoroContainer.getPomodoroSessionByUser(newState.member.user);
if (pomodoroSession !== undefined) {
client.channels.fetch(pomodoroSession.voiceChannel.id).then(channel => {
newState.setChannel(channel);
})
} else {
newState.guild.channels.create({
name: `${randomEmoji.get()} Sesión de ${newState.member.displayName}`,
type: ChannelType.GuildVoice,
parent: process.env.DISCORD_CATEGORY_ID,
bitrate: 64000,
permissionOverwrites: [
{
id: newState.member.id,
allow: [PermissionsBitField.Flags.ViewChannel, PermissionsBitField.Flags.Connect, PermissionsBitField.Flags.Speak],
},
{
id: newState.guild.roles.everyone.id,
allow: [PermissionsBitField.Flags.ViewChannel],
deny: [PermissionsBitField.Flags.Connect, PermissionsBitField.Flags.Speak],
},
],
}).then(channel => {
pomodoroSession = new PomodoroSession(client, newState.member.user, channel)
pomodoroSession.startPomodoro();
client.pomodoroContainer.addPomodoroSession(pomodoroSession);
newState.setChannel(channel);
})
}
}
}),
client.on("guildCreate", guild => {
})
client.on("guildDelete", guild => {
})
if (!process.env.TOKEN) {
console.error("[ERROR]", "Token not found please visit: https://discord.com/developers/application to get token")
process.exit(0)
}
client.login(process.env.TOKEN)
process.on("SIGINT", () => {
console.log("\x1b[36m%s\x1b[0m", "SIGINT detected, exiting...")
process.exit(0)
})