-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
361 lines (321 loc) · 12.5 KB
/
main.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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
const Discord = require('discord.js')
const { EmbedBuilder, REST, Routes, ActivityType } = require('discord.js');
const bot = new Discord.Client({intents: 3276799})
const config = require('./config')
const commands = require('./commands')
const registrationManager = require('./registration/registration_manager')
const fs = require('fs');
const request = require('request');
const mcServer = require('minecraft-server-util');
const Rcon = require('rcon-client').Rcon;
const Query = require("minecraft-query");
const q = new Query({host: config.mc_server_ip, port: config.mc_query_port, timeout: 7500});
const client = new Rcon({
host: config.mc_server_ip,
port: config.rcon_port,
password: config.rcon_password,
});
const Tail = require('tail').Tail;
const tail = new Tail(config.minecraft_logs_file);
const webhookUrl = config.dicord_webhook_url;
const axios = require('axios')
//load {/} commands
const rest = new REST({ version: '10' }).setToken(config.token);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(Routes.applicationCommands(config.client_id), { body: commands.commandsList });
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
const prefix = "!"
bot.login(config.token)
bot.on("ready", async() => {
console.log(`${bot.user.tag} est connecté`)
tail.on('line', (line) => {
// Filters
if(line.split(" ").includes("RCON")) return;
if(line.replace(/[\]/]/g, ' ').includes('WARN')) return;
if(line.replace(/[\]/]/g, ' ').includes('voicechat')) return;
if(line.includes("logged in with entity")) return;
if(line.split(" ").includes("/tell")) return;
if(line.split(" ").includes("/tp")) return;
if(line.split(" ").includes("issued")) return;
if(line.includes("Teleported")) return;
if(line.includes("UUID")) return;
if(line.includes("Disconnected")) return;
newLine = line.replace(/\[Async Chat Thread - #\d+\/INFO\]: /, '')
newLine = newLine.replace(/\[Server thread+\/INFO\]: /, '')
axios.post(webhookUrl, { content: newLine })
.then(response => {
console.log('Message sent!');
})
.catch(error => {
console.error(error);
});
});
async function setStatus() {
let status = 0;
while(true){
switch(status) {
case 0: {
// {
// motd: 'A Minecraft Server',
// gametype: 'SMP',
// game_id: 'MINECRAFT',
// version: '1.21.1',
// plugins: 'Paper on 1.21.1-R0.1-SNAPSHOT',
// map: 'world',
// online_players: '0',
// max_players: '20',
// port: '25566',
// players: []
// }
// {
// motd: 'A Minecraft Server',
// gametype: 'SMP',
// map: 'world',
// online_players: '0',
// max_players: '20'
// }
q.fullStat().then((result) => {
bot.user.setPresence(
{
activities: [
{
type: ActivityType.Watching,
name:`serveur mc: ${result.online_players}/${result.max_players} joueurs connectés`
}
]
}
)
status = 1;
}).catch((error) => console.error(error));
break;
}
case 1: {
bot.user.setPresence({activities: [{type: ActivityType.Playing, name:`/help`}]})
status = 0;
}
}
await new Promise(resolve => setTimeout(resolve, 15000));
//console.log(`updated`)
}
}
setStatus();
})
//{/} commands handle
bot.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
const guild = bot.guilds.cache.get(interaction.guildId);
const member = guild.members.cache.get(interaction.user.id);
if (interaction.commandName === 'ping') {
await interaction.reply('Pong!');
}
if(interaction.commandName === 'players'){
q.fullStat().then((result) => {
message = "";
players = result.players;
if(players[0] != undefined){
for(let i=0;i<players.length; i++){
message += players[i];
if(i != players.length-1){
message += ", "
}
}
interaction.reply(`Liste des joueurs: ${message}`)
} else {
interaction.reply(`Aucun joueur n'est connecté`)
}
}).catch((error) => console.error(error));
}
if(interaction.commandName === 'register'){
if(interaction.channelId === config.register_channel){
try {
registrationManager.add(interaction.user.id, interaction.options.get('player').value)
interaction.reply(`Votre compte minecraft a été lié à votre compte discord`)
//ajoute le joueur au serveur whitelist
client.connect().then(() => {
command = `whitelist add ${interaction.options.get('player').value}`
client.send(command).then((res) => {
console.log(res)
client.end()
}).catch((err) => {
console.error(err)
client.end()
})
}
).catch((error) => {
console.error(`Failed to connect to Minecraft server via RCON: ${error}`)
})
//ajoute le role minecraft au joueur
//trouver le role minecraft via l'id
const role = guild.roles.cache.find(role => role.id === config.whitelisted_role_id);
member.roles.add(role).catch(console.error);
} catch (error) {
if (error == 'Player already registered') {
interaction.reply(`Ce compte minecraft est déjà lié à un compte discord`)
} else {
interaction.reply(`Une erreur est survenue contactez un administrateur: ${error}`)
}
}
} else {
interaction.reply(`Vous ne pouvez pas utiliser cette commande ici`)
}
}
if(interaction.commandName === 'unregister'){
if(interaction.channelId === config.register_channel){
try {
registrationManager.remove(interaction.user.id)
interaction.reply(`Votre compte minecraft a été supprimé de votre compte discord`)
//supprime le joueur du serveur whitelist
client.connect().then(() => {
command = `whitelist remove ${interaction.options.get('player').value}`
client.send(command).then((res) => {
console.log(res)
client.end()
}).catch((err) => {
console.error(err)
client.end()
})
}
).catch((error) => {
console.error(`Failed to connect to Minecraft server via RCON: ${error}`)
})
//supprime le role minecraft au joueur
//trouver le role minecraft via l'id
const role = guild.roles.cache.find(role => role.id === config.whitelisted_role_id);
member.roles.remove(role).catch(console.error);
} catch (error) {
interaction.reply(`Une erreur est survenue contactez un administrateur: ${error}`)
}
} else {
interaction.reply(`Vous ne pouvez pas utiliser cette commande ici`)
}
}
// if (interaction.commandName === 'edit') {
// if (interaction.channelId === config.register_channel) {
// try {
// // Supprime l'ancien joueur du serveur whitelist
// client.connect().then(() => {
// const registration = registrationManager.get(interaction.user.id);
// if (!registration) {
// throw new Error("Aucune inscription trouvée pour cet utilisateur.");
// }
// const oldPlayer = registration.player;
// const command = `whitelist remove ${oldPlayer}`;
// client.send(command).then((res) => {
// console.log(res);
// client.end();
// }).catch((err) => {
// console.error(err);
// client.end();
// });
// }).catch((error) => {
// console.error(`Failed to connect to Minecraft server via RCON: ${error}`);
// });
// // Édition du joueur
// const newPlayer = interaction.options.get('player').value;
// const result = registrationManager.edit(interaction.user.id, newPlayer);
// if (!result) {
// throw new Error("Échec de l'édition de l'enregistrement.");
// }
// interaction.reply(`Votre compte Minecraft a été édité`);
// // Ajoute le nouveau joueur au serveur whitelist
// client.connect().then(() => {
// const command = `whitelist add ${newPlayer}`;
// client.send(command).then((res) => {
// console.log(res);
// client.end();
// }).catch((err) => {
// console.error(err);
// client.end();
// });
// }).catch((error) => {
// console.error(`Failed to connect to Minecraft server via RCON: ${error}`);
// });
// } catch (error) {
// interaction.reply(`Une erreur est survenue, contactez un administrateur: ${error.message}`);
// }
// } else {
// interaction.reply(`Vous ne pouvez pas utiliser cette commande ici`);
// }
// }
if(interaction.commandName === 'help'){
const keys = Object.keys(commands.commandsList);
var embed = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('Liste des commandes')
.addFields(
commands.commandsList.map(command => ({
name: command.name,
value: command.description,
}))
);
interaction.reply({embeds: [embed]})
}
if(interaction.commandName === 'source'){
interaction.reply('voici le lien vers mon code source: https://github.com/Darukity/Minecraft-Discord-RCON')
}
if(interaction.commandName === 'roll'){
if(interaction.options.get('int')){
let res = randomIntFromZeroToInt(interaction.options.get('int').value)
interaction.reply(`${interaction.user.username} a obtenu ${res} points`)
} else {
let res = randomIntFromZeroToInt(10)
interaction.reply(`${interaction.user.username} a obtenu ${res} points`)
}
}
function randomIntFromZeroToInt(int) {
return Math.floor(Math.random() * (Math.abs(int) + 1));
}
});
bot.on("messageCreate", async (msg) => {
if(msg.author.id == bot.application.id){return}
if(msg.webhookId) return;
console.log(msg.content)
//Rcon Console
if(msg.channelId === config.rcon_channel) {
if(!msg.content.startsWith(prefix)){
const mcChatChannel = bot.channels.cache.get(config.rcon_channel)
command = msg.content
client.connect().then(() => {
console.log('Connected to Minecraft server via RCON')
// Envoie la commande "log" pour afficher les derniers messages de la console
const now = new Date();
// formater l'heure
const hours = now.getHours().toString().padStart(2, '0');
const minutes = now.getMinutes().toString().padStart(2, '0');
const seconds = now.getSeconds().toString().padStart(2, '0');
const timeString = `[${hours}:${minutes}:${seconds}]`;
client.send(command).then((res) => {
console.log(res)
newRes = res.replace("/", '')
axios.post(webhookUrl, { content: newRes.replace(/§./g, '').split('\n').map(
line => {
if (!line == "") {
return `${timeString} ${line}`;
} else {
return line;
}
}).join('\n') })
.then(response => {
console.log('Message sent!');
})
.catch(error => {
console.error(error);
});
client.end()
}).catch((err) => {
console.error(err)
mcChatChannel.send(err)
client.end()
})
}).catch((error) => {
console.error(`Failed to connect to Minecraft server via RCON: ${error}`)
})
}
}
})