-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
199 lines (162 loc) · 6.32 KB
/
index.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
const { Client, Collection, Intents, MessageEmbed } = require('discord.js');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const yaml = require('js-yaml');
const fs = require("fs");
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
let usedRooms = [];
//Load the config file
let Config = null;
try {
let fileContents = fs.readFileSync('./config.yml', 'utf8');
Config = yaml.load(fileContents);
}
catch (e) {
console.log(e);
}
//Create a collection of commands and commandData
const commands = new Collection();
//Command data is a list of JSON objects that need to be sent to register the slash commands
const commandsData = [];
//We load all the command files and save the command and the commandData
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
//Load the file
const command = require(`./commands/${file}`);
//Add to command collection
commands.set(command.info.name, command);
//Load the commandData
const commandData = require(`./commands/${file}`);
var json = commandData.info
commandsData.push(json);
}
//Load the rest API for registering slash commands, auto deals with rate limits
const rest = new REST({ version: '9' }).setToken(Config.Token);
//Send all the slash commandData to the discord API to register the commands for the guild only
(async () => {
if(Config.Commands.SetupCommands){
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(Config.ClientID, Config.GuildID),
{ body: commandsData },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
}
})();
//creates data files if they dont exist
const data = new Uint8Array(Buffer.from('{}'));
fs.access("data.json", fs.F_OK, (err) => {
if (err) {
if(err.code == "ENOENT"){
fs.writeFile("data.json", data, (err) => {
if (err) throw err;
console.log("Created data.json as it didnt exist")
return
})
}else{
console.error(err)
return
}
}else{
console.log("data.json already exists")
}
})
// D.JS Client listeners
client.on("error", (e) => console.error(e));
client.on("warn", (e) => console.warn(e));
//client.on("debug", (e) => console.info(e));
client.on('reconnecting', () => console.log('Reconnecting WS...'));
client.on('disconnect', () => {
console.log('Disconnected, trying to restart...');
process.exit();
});
// NodeJS process listeners
process.on('unhandledRejection', console.error);
process.on('warning', console.warn);
// On ready statment
client.on("ready", async() => {
console.log("Online!")
console.log("^ The above message is for Pterodactyl to pickup and mark the server as online. ^\n")
console.log("------------------------------------------------------------------------------------------------------")
console.log("The bot is now online")
console.log(`Logged in as ${client.user.username} || ${client.user.id}`)
console.log("------------------------------------------------------------------------------------------------------")
console.log(`Invite me to a server with the following link.\nhttps://discordapp.com/api/oauth2/authorize?client_id=${client.user.id}&permissions=125952&scope=bot`);
console.log("------------------------------------------------------------------------------------------------------")
main(true)
});
//Listen for commands coming from chat and context menus
client.on('interactionCreate', async interaction => {
if (!(interaction.isCommand() || interaction.isContextMenu())) return;
if(!interaction.inGuild()){
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true })
return;
}
//Find the commands we want to run
const command = commands.get(interaction.commandName);
if (!command) return;
try {
//Run the command
await command.run(interaction, Config, client);
} catch (error) {
console.error(error);
}
});
//Listen for autocomplete
client.on('interactionCreate', async interaction => {
if (!interaction.isAutocomplete()) return;
//Find the commands we want to auto complete for
const command = commands.get(interaction.commandName);
if (!command) return;
try {
//Run the autocomplete resolver
await command.autocomplete(interaction, Config, client);
} catch (error) {
console.error(error);
}
});
client.login(Config.Token);
async function main(){
let ms = msToNextHour()
setTimeout(send, (ms+100) - 900000)
}
async function send(){
let guild = await client.guilds.cache.find(i => i.id == Config.GuildID)
let channel = await guild.channels.fetch(Config.ChannelID)
let room = getNotRecentlyUsedRoom()
let course = Config.Maps[Math.floor(Math.random() * Config.Maps.length)]
usedRooms.push(room)
if(usedRooms.length > 2){
usedRooms.shift()
}
let embed = new MessageEmbed()
.setTitle("Game starting soon!")
.setDescription(`
The next scheduled game will start in 15 minutes (at the top of the hour) in room **${room}**. If this is full, try **${room}1** or **${room}2**, etc.
The course will be **${course}**. If you want to join, drop a :thumbsup: reaction on this message so people know there are enough players.
`)
.setTimestamp();
channel.send({embeds: [embed]}).then(function (message) {message.react("👍")})
//console.log("-----------------------------------------")
//console.log(` Message Sent`)
//console.log(`Room: ${room}`)
//console.log(`Map: ${course}`)
//console.log(`Used Rooms ${usedRooms}`)
//console.log(new Date().toUTCString())
//console.log("-----------------------------------------")
setTimeout(main, 1800000)
}
function msToNextHour() {
return (3600000 - new Date().getTime() % 3600000);
}
function getNotRecentlyUsedRoom(){
let room = Config.RoomIDs[Math.floor(Math.random() * Config.RoomIDs.length)]
while (room in usedRooms){
room = Config.RoomIDs[Math.floor(Math.random() * Config.RoomIDs.length)]
}
return room
}