-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzomboidScript.cpp
More file actions
385 lines (343 loc) · 13.9 KB
/
zomboidScript.cpp
File metadata and controls
385 lines (343 loc) · 13.9 KB
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
#include <iostream>
#include <curl/curl.h>
#include <libconfig.h++>
#include <fstream>
#include <string>
#include <chrono>
#include <ctime>
#include <string>
#include <sstream>
#include <regex>
#include <vector>
#include <tgbot/tgbot.h>
#include <rconpp/rcon.h>
// GeoVersion 1.0.0
//g++ zomboidScript.cpp -o zomboidScript -I/usr/local/include -L/usr/local/lib -lTgBot -lboost_system -lssl -lcrypto -lpthread -lcurl -lrconpp -lconfig++
// variables
// FTP
std::string ftpUsername;
std::string ftpPassword;
std::string ftpAddress;
int ftpPort;
// rcon
std::string rconAddress;
int rconPort;
std::string rconPassword;
std::atomic<bool> connected{false};
// telegram
std::string telegramToken;
int chat_id = 0;
// words
std::string wordsArray;
// file downloaded
std::string localLogName;
// get the variables from a .config file
void get_config()
{
//check if config file exists
std::ifstream file("config.cfg");
if (!file)
{
std::cerr << "Error: Unable to open config file or file dont exist\n";
exit(1);
}
std::cout << "Reading config file" << std::endl;
libconfig::Config cfg;
try {
cfg.readFile("config.cfg");
} catch(const libconfig::ParseException &pex) {
std::cerr << "Parse error at " << pex.getLine() << " - " << pex.getError() << std::endl;
exit(1);
}
// FTP
std::cout << "Reading FTP variables" << std::endl;
ftpUsername = cfg.lookup("ftp_username").c_str();
ftpPassword = cfg.lookup("ftp_password").c_str();
ftpAddress = cfg.lookup("ftp_addressnfile").c_str();
ftpPort = cfg.lookup("ftp_port");
// rcon
std::cout << "Reading RCON variables" << std::endl;
rconAddress = cfg.lookup("rcon_address").c_str();
rconPort = cfg.lookup("rcon_port");
rconPassword = cfg.lookup("rcon_password").c_str();
// telegram
std::cout << "Reading Telegram variables" << std::endl;
telegramToken = cfg.lookup("telegram_token").c_str();
chat_id = cfg.lookup("telegram_chat_id");
// words
std::cout << "Reading words array" << std::endl;
wordsArray = cfg.lookup("words_array").c_str();
// file name
std::cout << "Reading local log file name" << std::endl;
localLogName = cfg.lookup("local_log_file_name").c_str();
std::cout << "Config file read" << std::endl;
}
//no idea what this does
size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
size_t totalSize = size * nmemb;
std::ofstream *file = static_cast<std::ofstream *>(userp);
file->write(static_cast<char *>(contents), totalSize);
return totalSize;
}
// download log file
void get_log()
{
std::cout << "Downloading log file" << std::endl;
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if (curl)
{
// FTP username and password
curl_easy_setopt(curl, CURLOPT_USERNAME, ftpUsername.c_str());
curl_easy_setopt(curl, CURLOPT_PASSWORD, ftpPassword.c_str());
std::string outputFilePath = localLogName;
std::ofstream outputFile(outputFilePath, std::ios::binary);
if (!outputFile)
{
std::cerr << "Failed to open output file." << std::endl;
exit(1);
}
// FTP address
curl_easy_setopt(curl, CURLOPT_URL, ftpAddress.c_str());
// FTP port
curl_easy_setopt(curl, CURLOPT_PORT, ftpPort);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &outputFile);
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
std::cerr << "Failed to download file: " << curl_easy_strerror(res) << std::endl;
exit(1);
}
curl_easy_cleanup(curl);
outputFile.close();
}
curl_global_cleanup();
std::cout << "Log file downloaded" << std::endl;
}
//log functions
// Function to parse the timestamp from a log line
long long parseTimestamp(const std::string &logLine)
{
size_t pos = logLine.find('>');
if (pos != std::string::npos)
{
std::string timestampStr = logLine.substr(0, pos);
timestampStr = timestampStr.substr(timestampStr.find_last_of(' ') + 1);
return std::stoll(timestampStr);
}
throw std::invalid_argument("Invalid log line format: " + logLine);
}
// Function to check if a log line contains the specified text after the prefix
bool containsText(const std::string &logLine, const std::string &searchText)
{
size_t pos = logLine.find("LOG : General");
if (pos != std::string::npos)
{
pos = logLine.find(">", pos);
if (pos != std::string::npos)
{
pos = logLine.find(">", pos + 1);
if (pos != std::string::npos)
{
std::string message = logLine.substr(pos + 1);
return message.find(searchText) != std::string::npos;
}
}
}
return false;
}
// analize log file to check if the specified text is present
bool analazingLogFile()
{
std::cout << "Opening log file" << std::endl;
std::ifstream logFile(localLogName);
if (!logFile)
{
std::cerr << "Error: Unable to open log file\n";
return 1;
}
std::cout << "Done" << std::endl;
std::cout << "Getting current time" << std::endl;
// Get current time
auto currentTime = std::chrono::system_clock::now();
auto currentTimeStamp = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime.time_since_epoch()).count();
std::cout << "Current time: " << currentTimeStamp << std::endl;
// Vector to store log lines from 5 minutes ago
std::vector<std::string> logLinesFiveMinutesAgo;
std::cout << "Filtering log file" << std::endl;
std::string line;
while (std::getline(logFile, line))
{
if (line.find("LOG : General") == 0)
{ // Check if the line starts with "LOG : General"
long long timestamp = parseTimestamp(line);
// Check if the timestamp is within the last 5 minutes
if (currentTimeStamp - timestamp <= 5 * 60 * 1000)
{
logLinesFiveMinutesAgo.push_back(line);
}
}
}
// Define the text to match
std::string searchText = wordsArray;
std::cout << "Searching for text: " << searchText << std::endl;
// Compare the last lines from 5 minutes ago with the specified text
bool foundMatch = false;
// Compare the last lines from 5 minutes ago with the specified text
for (const auto &logLine : logLinesFiveMinutesAgo)
{
if (containsText(logLine, searchText))
{
std::cout << "Match found: " << logLine << std::endl;
foundMatch = true;
// If you need to take some action here, you can do it.
}
}
if (foundMatch)
{
// Trigger the action if at least one match was found
std::cout << "At least one match was found." << std::endl;
return true;
}
else
{
// Do nothing if no matches were found
std::cout << "No matches were found." << std::endl;
return false;
}
}
// look number of players connected
int getNumberOfPlayers(const std::string& response) {
std::cout << "Getting number of players connected" << std::endl;
size_t pos = response.find("Players connected (");
if (pos == std::string::npos) {
// No player information found in the response
std::cout << "No player information found in the response" << std::endl;
return 0;
}
pos += 19; // Move past "Players connected ("
// Find the closing parenthesis
size_t endPos = response.find(')', pos);
if (endPos == std::string::npos) {
std::cout << "Invalid response format" << std::endl;
// Invalid response format
return 0;
}
// Extract the number of players as a substring
std::string numPlayersStr = response.substr(pos, endPos - pos);
// Convert the substring to an integer
int numPlayers = std::stoi(numPlayersStr);
std::cout << "Number of players connected: " << numPlayers << std::endl;
return numPlayers;
}
int main()
{
// get variables from config file
get_config();
//telegram bot
TgBot::Bot bot(telegramToken);
// attempt to connect to RCON
std::cout << "Connecting to RCON with address: " << rconAddress << " port: " << rconPort << " password: " << rconPassword << std::endl;
rconpp::rcon_client client(rconAddress, rconPort, rconPassword);
client.on_log = [](const std::string_view &log)
{
std::cout << log << "\n";
};
client.start(true);
bool isConnected = client.connected.load();
if (isConnected == false)
{
std::cout << "Failed to connect to RCON server" << std::endl;
exit(1);
}
rconpp::response response;
// i hate send_data, send_data_sync rules
// send command to check if mods need update
//this generates the log file in the server
std::cout << "Checking if mods need update. sending command to server" << std::endl;
response = client.send_data_sync("checkModsNeedUpdate", 3, rconpp::data_type::SERVERDATA_EXECCOMMAND, true);
std::cout << response.data << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
// get the log file
get_log();
// check if the log file contains the specified text
if (analazingLogFile())
{
std::cout << "Mods Need update" << std::endl;
std::cout << "Sendig alerts to connected users and George via telegram" << std::endl;
//telegram notify
bot.getApi().sendMessage(chat_id, "Estamos reiniciando el server");
//check if they are any players connected
std::cout << "Checking if are players connected " << std::endl;
response = client.send_data_sync("players", 3, rconpp::data_type::SERVERDATA_EXECCOMMAND, true);
std::cout << response.data << std::endl;
int numPlayers = getNumberOfPlayers(response.data);
if (numPlayers == 0)
{
std::cout << "No players connected" << std::endl;
bot.getApi().sendMessage(chat_id, "No hay jugadores conectados, reiniciando a la fuerza");
response = client.send_data_sync("save", 3, rconpp::data_type::SERVERDATA_EXECCOMMAND, true);
std::cout << response.data << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
response = client.send_data_sync("quit", 3, rconpp::data_type::SERVERDATA_EXECCOMMAND, true);
std::cout << response.data << std::endl;
std::cout << "Server restarted" << std::endl;
bot.getApi().sendMessage(chat_id, "Server reiniciado");
exit(1);
}
response = client.send_data_sync("servermsg Los_Mods_necesitan_update!__Reinicio_Inminente__", 3, rconpp::data_type::SERVERDATA_EXECCOMMAND, true);
std::cout << response.data << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(10));
response = client.send_data_sync("servermsg Reiniciando_server_en_5_min", 3, rconpp::data_type::SERVERDATA_EXECCOMMAND, true);
std::cout << response.data << std::endl;
std::cout << "Waiting 5 minutes" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(60));
response = client.send_data_sync("servermsg Reiniciando_server_en_4_min", 3, rconpp::data_type::SERVERDATA_EXECCOMMAND, true);
std::cout << response.data << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(60));
std::cout << "Checking if players still connected " << std::endl;
response = client.send_data_sync("players", 3, rconpp::data_type::SERVERDATA_EXECCOMMAND, true);
std::cout << response.data << std::endl;
numPlayers = getNumberOfPlayers(response.data);
if (numPlayers == 0)
{
std::cout << "Players already disconnected, skipping timeout" << std::endl;
response = client.send_data_sync("save", 3, rconpp::data_type::SERVERDATA_EXECCOMMAND, true);
std::cout << response.data << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
response = client.send_data_sync("quit", 3, rconpp::data_type::SERVERDATA_EXECCOMMAND, true);
std::cout << response.data << std::endl;
bot.getApi().sendMessage(chat_id, "Server reiniciado");
exit(1);
}
std::cout << "Players still connected, continuing countdown" << std::endl;
response = client.send_data_sync("servermsg Reiniciando_server_en_3_min", 3, rconpp::data_type::SERVERDATA_EXECCOMMAND, true);
std::cout << response.data << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(60));
response = client.send_data_sync("servermsg Reiniciando_server_en_2_min", 3, rconpp::data_type::SERVERDATA_EXECCOMMAND, true);
std::cout << response.data << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(60));
response = client.send_data_sync("servermsg Reiniciando_server_en_1_min", 3, rconpp::data_type::SERVERDATA_EXECCOMMAND, true);
std::cout << response.data << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(30));
response = client.send_data_sync("servermsg Reiniciando_server_en_30_seg", 3, rconpp::data_type::SERVERDATA_EXECCOMMAND, true);
std::cout << response.data << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(30));
response = client.send_data_sync("save", 3, rconpp::data_type::SERVERDATA_EXECCOMMAND, true);
std::cout << response.data << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
response = client.send_data_sync("quit", 3, rconpp::data_type::SERVERDATA_EXECCOMMAND, true);
std::cout << response.data << std::endl;
bot.getApi().sendMessage(chat_id, "Save Realizado, Server reiniciado");
std::cout << "Server restarted" << std::endl;
}
else
{
std::cout << "No match found terminating program" << std::endl;
}
return 0;
}