-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver-tcp.js
182 lines (157 loc) · 6.42 KB
/
server-tcp.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
require('dotenv').config();
const { createServer } = require('net');
const {
Client,
GatewayIntentBits,
Partials,
Collection,
EmbedBuilder
} = require('discord.js');
const { Guilds, GuildMembers, GuildMessages } = GatewayIntentBits;
const { User, Message, GuildMember, ThreadMember } = Partials;
// Models
const Bot = require('./models/Bot.js');
const Place = require('./models/Place.js');
// Import Functions
const capitalizeWord = require('./Functions/capitalizeWord.js');
const formatCoordinates = require('./Functions/formatCoordinates.js');
const shortString = require('./Functions/shortString.js');
// Import Files
const { loadEvents } = require("./Handlers/eventHandler.js");
require('./database/db.js')();
// Const
const channelId = process.env.BOT_CHANNEL;
const port = process.env.PORT || 30004;
// Create Discord Client
const client = new Client({
intents: [Guilds, GuildMembers, GuildMessages],
partials: [User, Message, GuildMember, ThreadMember]
});
// Load Discord Events && Commands
client.events = new Collection();
client.commands = new Collection();
loadEvents(client);
// Connect Discord Server
client.login(process.env.TOKEN);
// Ensure the client is ready before starting the TCP server
client.once('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
// Create TCP Server
const server = createServer((socket) => {
console.log('Cliente conectado.');
socket.on('data', async (data) => {
try {
const playerInfo = JSON.parse(data.toString());
console.log('Datos recibidos del mod de Minecraft:', playerInfo);
await handlePlayerData(playerInfo);
} catch (e) {
console.log("No fue posible recuperar el JSON data", e);
}
});
// Socket Off
socket.on('end', () => console.log('Cliente desconectado.'));
// Socket Error
socket.on('error', (err) => console.error('Error de conexión:', err.message));
});
// Listen Port
server.listen(port, '0.0.0.0', () => {
console.log(`Servidor escuchando en el purto: ${port}`);
});
});
// Manage Bot Data Function
async function handlePlayerData(playerInfo) {
const { action, name, dimension, coords, uuid, name_player_executor } = playerInfo;
try {
if (action === "joined") {
// Verifica si el bot ya está en la base de datos
const existingBot = await Bot.findOne({ uuid: uuid });
if (existingBot) {
console.log(`El bot ${name} ya está en la base de datos.`);
return; // Si ya está, no hacer nada
}
const botDimension = shortString(dimension);
const coordinates = coords.map(valor => Math.floor(valor));
const { botNearFarm, farmName } = await findFarmProximity(botDimension, coordinates);
console.log(botNearFarm)
console.log(farmName)
const newBot = new Bot({
name: name,
uuid: uuid,
action: action,
dimension: botDimension,
player_executor: name_player_executor,
coords: coordinates,
botNearFarm: botNearFarm,
farmName: botNearFarm ? farmName : null
});
await newBot.save();
await sendDiscordMessage(`Se ha conectado el bot ${name}`, botNearFarm ?
`El bot ${name} está en: \n**${farmName}** (${capitalizeWord(botDimension)}) \nSpawneado por:\n\`${name_player_executor}\`` :
`El bot ${name} está en: \n${formatCoordinates(coordinates)}\nen el **${capitalizeWord(botDimension)}** \nSpawneado por:\n\`${name_player_executor}\``, true);
} else {
const deletedBot = await Bot.findOneAndDelete({ uuid: uuid });
if (deletedBot) {
const { name, dimension, coords, botNearFarm, farmName } = deletedBot;
await sendDiscordMessage(`Se ha desconectado el bot ${name}`, botNearFarm ?
`El bot ${name} estaba en: \n**${farmName}** (${capitalizeWord(dimension)}) \nDesconectado por:\n\`${name_player_executor}\`` :
`El bot ${name} estaba en: \n${formatCoordinates(coords)}\nen el **${capitalizeWord(dimension)}** \nDesconectado por:\n\`${name_player_executor}\``, false);
}
}
} catch (e) {
console.log("No se pudo enviar el bot a la base de datos", e);
}
}
// Calculate Distance Function
function calculateDistance(coordFarm, coordBot) {
const dx = coordFarm[0] - coordBot[0];
const dy = coordFarm[1] - coordBot[1];
const dz = coordFarm[2] - coordBot[2];
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
// Verify Block Distance Function
function verifyBlockDistance(coordFarm, coordBot, blockDistance = 100) {
const distance = calculateDistance(coordFarm, coordBot);
return distance <= blockDistance;
}
// Find Farm Proximity Function
async function findFarmProximity(botCoord, coordinates) {
try {
const placesList = await Place.find({});
let closestFarm = null;
let minDistance = Infinity;
for (const farm of placesList) {
if (farm.dimension === botCoord && verifyBlockDistance(farm.coords, coordinates)) {
const distance = calculateDistance(farm.coords, coordinates);
if (distance < minDistance) {
minDistance = distance;
closestFarm = farm;
}
}
}
if (closestFarm) {
return { botNearFarm: true, farmName: closestFarm.name };
} else {
return { botNearFarm: false, farmName: "" };
}
} catch (error) {
console.error("Error al recuperar las places:", error);
return { botNearFarm: false, farmName: "" };
}
}
// Create Embed Function
async function sendDiscordMessage(title, description, success) {
try {
const embed = new EmbedBuilder()
.setTitle(title)
.setDescription(description)
.setColor(success ? '21CA19' : 'EE192D');
const channel = client.channels.cache.get(channelId);
if (channel) {
await channel.send({ embeds: [embed] });
} else {
console.error('El canal no se encontró en el caché del cliente.');
}
} catch (err) {
console.error('Error al enviar el embed a Discord:', err);
}
}