-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathProgram.cs
588 lines (531 loc) · 26 KB
/
Program.cs
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Ultimate_Splinterlands_Bot_V2;
using System.Threading;
using Pastel;
using System.Drawing;
using System.Reflection;
using Ultimate_Splinterlands_Bot_V2.Utils;
using Ultimate_Splinterlands_Bot_V2.Config;
using Ultimate_Splinterlands_Bot_V2.Api;
using Ultimate_Splinterlands_Bot_V2.Bot;
using Newtonsoft.Json;
using Ultimate_Splinterlands_Bot_V2.Model;
using System.Net;
using System.Net.Http;
using Splinterlands_Battle_REST_API.Model;
namespace Ultimate_Splinterlands_Bot_V2
{
class Program
{
private static object _TaskLock = new();
private static object _SleepInfoLock = new();
static void Main(string[] args)
{
SetStartupPath();
CleanupLegacyFiles();
if (args.Length > 0 && args[0] == "update")
{
Helper.KillInstances();
Helper.UpdateViaArchive(args[2], args[3]);
string versionText = args[5] + Environment.NewLine + args[4];
File.WriteAllText(args[3] + "/config/version.usb", versionText);
Helper.RunProcess(args[1], "");
Environment.Exit(0);
}
else if (Directory.Exists(Settings.StartupPath + "/tmp/"))
{
Thread.Sleep(2000);
Directory.Delete(Settings.StartupPath + "/tmp/", true);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
if (Environment.OSVersion.Version.Major < 10)
{
Console.WriteLine("Legacy mode for old Windows version activated - please update your Windows to Windows 10 or higher / Windows Server 2016 or higher to get maximum bot speed");
Settings.LegacyWindowsMode = true;
ConsoleExtensions.Disable();
}
}
Log.WriteStartupInfoToLog();
// We have to configure the http client early because it might be used in account constructor
SetupHttpClient();
var updateCardDetailsTask = Helper.UpdateCardDetails();
if (!ReadConfig() || !ReadAccountData())
{
Log.WriteToLog("Press any key to close");
Console.ReadKey();
Environment.Exit(0);
}
Helper.CheckForUpdate();
if (HasLegacyApi())
{
Log.WriteToLog("Press any key to close");
Console.ReadKey();
Environment.Exit(0);
}
if (Settings.ClaimSeasonReward)
{
Log.WriteToLog("Season Reward Claiming mode activated - set CLAIM_SEASON_REWARD=false to disable!", Log.LogType.Warning);
Log.WriteToLog("The bot will only claim rewards, it will not fight!", Log.LogType.Warning);
Thread.Sleep(3500);
}
Thread.Sleep(1500); // Sleep 1.5 seconds to read config and welcome message
updateCardDetailsTask.Wait();
Initialize();
CancellationTokenSource cancellationTokenSource = new();
CancellationToken token = cancellationTokenSource.Token;
_ = Task.Run(async () => await BotLoopAsync(token)).ConfigureAwait(false);
string command = "";
while (true)
{
command = Console.ReadLine();
switch (command)
{
case "stop":
Log.WriteToLog("Stopping bot...", Log.LogType.Warning);
cancellationTokenSource.Cancel();
break;
default:
break;
}
}
}
private static void SetupHttpClient()
{
var clientHandler = new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
var httpClient = new HttpClient(clientHandler);
httpClient.Timeout = new TimeSpan(0, 2, 15);
httpClient.DefaultRequestHeaders.Add("User-Agent", "USB");
httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("gzip"));
Settings.HttpClient = httpClient;
}
private static void CleanupLegacyFiles()
{
if (File.Exists(Settings.StartupPath + @"\config\access_tokens.txt"))
{
File.Delete(Settings.StartupPath + @"\config\access_tokens.txt");
}
}
private static bool HasLegacyApi()
{
if (!Settings.PublicAPIUrl.Contains("/v3/"))
{
Log.WriteToLog("This bot version only works with the new API - please change the following in your config.txt file:", Log.LogType.Warning);
Console.WriteLine("");
Console.WriteLine("please change the following in your config.txt file:");
Console.WriteLine("API_URL=http://splinterlandsapi.pcjones.de/v3/");
return true;
}
else if (Settings.UsePrivateAPI && !Settings.PrivateAPIUrl.Contains("/v3/"))
{
Log.WriteToLog("This bot version only works with the new API", Log.LogType.Warning);
Console.WriteLine("");
Console.WriteLine("please change the following in your config.txt file:");
Console.WriteLine("PRIVATE_API_URL=http://splinterlandsapi.pcjones.de/v3/");
return true;
}
// Temporarily replace API url with another one until old API server DNS settings are changed
Settings.PrivateAPIUrl = Settings.PrivateAPIUrl.Replace("/privatesps1.pcjones.de", "/beta-splinterlandsapi.pcjones.de").Replace("/privatesps2.pcjones.de", "/beta-splinterlandsapi.pcjones.de").Replace("/splinterlandsapi.pcjones.de", "/beta-splinterlandsapi.pcjones.de");
Settings.PublicAPIUrl = Settings.PublicAPIUrl.Replace("/splinterlandsapi.pcjones.de", "/beta-splinterlandsapi.pcjones.de");
return false;
}
static async Task BotLoopAsync(CancellationToken token)
{
var instances = new HashSet<Task>();
int nextBotInstance = -1;
bool firstRuntrough = true;
DateTime[] sleepInfo = new DateTime[Settings.BotInstances.Count];
var ts = new CancellationTokenSource();
var cancellationToken = ts.Token;
//DateTime lastResetTime = DateTime.Now;
while (!token.IsCancellationRequested)
{
while (instances.Count < Settings.Threads && !token.IsCancellationRequested)
{
try
{
lock (_TaskLock)
{
if (++nextBotInstance >= Settings.BotInstances.Count)
{
firstRuntrough = false;
Log.LogBattleSummaryToTable();
Log.WriteSupportInformationToLog();
Thread.Sleep(5000);
if ((DateTime.Now - Settings.LastSerialization).TotalMinutes > 30)
{
Settings.LastSerialization = DateTime.Now;
Helper.SerializeBotInstances();
}
nextBotInstance = 0;
while (SplinterlandsAPI.CheckForMaintenance().Result)
{
Log.WriteToLog("Splinterlands maintenance - waiting 3 minutes");
Thread.Sleep(3 * 60000);
}
}
bool sleep = true;
do
{
lock (_SleepInfoLock)
{
if (!Settings.BotInstances.All(x => x.CurrentlyActive
|| ((DateTime)sleepInfo[Settings.BotInstances.IndexOf(x)] > DateTime.Now
&& !Settings.PlannedPowerTransfers.ContainsKey(x.Username))))
{
sleep = false;
}
}
if (sleep)
{
Thread.Sleep(20 * 1000);
}
} while (sleep && !token.IsCancellationRequested);
}
lock (_TaskLock)
{
if (firstRuntrough && !Settings.ClaimSeasonReward)
{
// Delay accounts to avoid them fighting each other
if (Settings.Threads >= 5)
{
Thread.Sleep(Settings._Random.Next(1000, 6000));
}
else
{
Thread.Sleep(Settings._Random.Next(500, 2000));
}
}
while (Settings.BotInstances.ElementAt(nextBotInstance).CurrentlyActive)
{
nextBotInstance++;
nextBotInstance = nextBotInstance >= Settings.BotInstances.Count ? 0 : nextBotInstance;
}
// create local copies for thread safety
int botInstance = nextBotInstance;
instances.Add(Task.Run(async () =>
{
var result = await Settings.BotInstances[botInstance].DoBattleAsync();
lock (_SleepInfoLock)
{
sleepInfo[botInstance] = result;
}
}, cancellationToken));
}
}
catch (Exception ex)
{
Log.WriteToLog("BotLoop Error: " + ex.ToString(), Log.LogType.CriticalError);
}
}
_ = await Task.WhenAny(instances);
instances.RemoveWhere(x => x.IsCompleted);
}
await Task.WhenAll(instances);
Helper.SerializeBotInstances();
Log.WriteToLog("Bot stopped!");
}
static void LoadSplinterlandsSettings()
{
var settings = SplinterlandsAPI.GetSettings().Result;
Settings.SplinterlandsSettings = JsonConvert.DeserializeObject<SplinterlandsSettings>(settings);
}
static bool ReadConfig()
{
try
{
string folder = Settings.StartupPath + @"/config/";
string filePathConfig = folder + "config.txt";
string filePathCardSettings = folder + "card_settings.txt";
string filePathCardSettingsExample = folder + "card_settings-example.txt";
if (!File.Exists(filePathConfig))
{
Log.WriteToLog("No config.txt in config folder - see config-example.txt!", Log.LogType.CriticalError);
return false;
}
if (!File.Exists(filePathCardSettings))
{
// copy card settings example file
if (File.Exists(filePathCardSettingsExample))
{
File.Copy(filePathCardSettingsExample, filePathCardSettings);
}
else
{
Log.WriteToLog("No card_settings.txt in config folder!", Log.LogType.CriticalError);
return false;
}
}
Settings.CardSettings = new CardSettings(File.ReadAllText(filePathCardSettings));
//Settings.CardSettings = new("USE_CARD_SETTINGS=false");
Log.WriteToLog("Reading config...");
foreach (string setting in File.ReadAllLines(filePathConfig))
{
string[] temp = setting.Split('=');
if (temp.Length != 2 || setting[0] == '#')
{
continue;
}
switch (temp[0].Trim().ToUpper())
{
case "PRIORITIZE_QUEST":
Settings.PrioritizeQuest = bool.Parse(temp[1]);
break;
case "SLEEP_BETWEEN_BATTLES":
Settings.SleepBetweenBattles = Convert.ToInt32(temp[1]);
break;
// legacy
case "ECR_THRESHOLD":
Settings.StopBattleBelowECR = Convert.ToInt32(temp[1]);
break;
// legacy:
case "ERC_THRESHOLD":
Settings.StopBattleBelowECR = Convert.ToInt32(temp[1]);
break;
case "STOP_BATTLE_BELOW_ECR":
Settings.StopBattleBelowECR = Convert.ToInt32(temp[1]);
if (Settings.StopBattleBelowECR > 49)
{
Settings.StopBattleBelowECR = 49;
Log.WriteToLog("Set STOP_BATTLE_BELOW_ECR to 49. Consider to update your config.txt file.");
}
break;
case "START_BATTLE_ABOVE_ECR":
Settings.StartBattleAboveECR = Convert.ToInt32(temp[1]);
if (Settings.StartBattleAboveECR > 49)
{
Settings.StartBattleAboveECR = 49;
Log.WriteToLog("Set START_BATTLE_ABOVE_ECR to 49. Consider to update your config.txt file.");
}
break;
case "MINIMUM_BATTLE_POWER":
Settings.MinimumBattlePower = Convert.ToInt32(temp[1]);
break;
case "CLAIM_SEASON_REWARD":
Settings.ClaimSeasonReward = bool.Parse(temp[1]);
break;
case "CLAIM_QUEST_REWARD":
Settings.ClaimQuestReward = bool.Parse(temp[1]);
break;
case "SHOW_SPS_REWARD":
Settings.ShowSpsReward = bool.Parse(temp[1]);
break;
case "ADVANCE_LEAGUE":
Settings.AdvanceLeague = bool.Parse(temp[1]);
break;
case "FOCUS_CHEST_OPTIMISATION":
Settings.FocusChestOptimization = bool.Parse(temp[1]);
break;
case "RANKED_FORMAT":
Settings.RankedFormat = temp[1].ToUpper();
break;
case "MAX_LEAGUE_TIER":
Settings.MaxLeagueTier = Convert.ToInt32(temp[1]);
break;
case "REQUEST_NEW_QUEST":
Settings.BadQuests = temp[1].Split(',');
break;
case "SHOW_BATTLE_RESULTS":
Settings.ShowBattleResults = bool.Parse(temp[1]);
break;
case "THREADS":
Settings.Threads = Convert.ToInt32(temp[1]);
break;
case "USE_BROWSER_MODE":
if (bool.Parse(temp[1]))
{
Log.WriteToLog("Browser mode is no longer supported - will use lightning mode!", Log.LogType.Warning);
}
break;
case "API_URL":
Settings.PublicAPIUrl = temp[1];
break;
case "HIVE_NODE":
Settings.HIVE_NODE = temp[1];
break;
case "DEBUG":
Settings.DebugMode = bool.Parse(temp[1]);
break;
case "WRITE_LOG_TO_FILE":
Settings.WriteLogToFile = bool.Parse(temp[1]);
break;
case "AUTO_UPDATE":
Settings.AutoUpdate = bool.Parse(temp[1]);
break;
case "DISABLE_CONSOLE_COLORS":
if (bool.Parse(temp[1]))
{
Log.WriteToLog("Console colors disabled!");
ConsoleExtensions.Disable();
}
break;
case "SHOW_API_RESPONSE":
Settings.ShowAPIResponse = bool.Parse(temp[1]);
break;
case "USE_PRIVATE_API":
Settings.UsePrivateAPI = bool.Parse(temp[1]);
if (Settings.UsePrivateAPI)
{
string[] loginData = File.ReadAllText(Settings.StartupPath + @"/config/login.txt").Split(':');
Settings.PrivateAPIUsername = loginData[0];
Settings.PrivateAPIPassword = loginData[1];
}
break;
case "PRIVATE_API_SHOP":
Settings.PrivateAPIShop = temp[1];
break;
case "PRIVATE_API_URL":
Settings.PrivateAPIUrl = temp[1];
break;
case "POWER_TRANSFER_BOT":
Settings.PowerTransferBot = bool.Parse(temp[1]);
if (Settings.PowerTransferBot)
{
Settings.AvailablePowerTransfers = new();
}
break;
default:
break;
}
}
Log.WriteToLog("Config loaded!", Log.LogType.Success);
Log.WriteToLog($"Config parameters:{Environment.NewLine}" +
$"MODE: {"LIGHTNING (blockchain)"}{Environment.NewLine}" +
$"DEBUG: {Settings.DebugMode}{Environment.NewLine}" +
$"AUTO_UPDATE: {Settings.AutoUpdate}{Environment.NewLine}" +
$"WRITE_LOG_TO_FILE: {Settings.WriteLogToFile}{Environment.NewLine}" +
$"SHOW_API_RESPONSE: {Settings.ShowAPIResponse}{Environment.NewLine}" +
$"PRIORITIZE_QUEST: {Settings.PrioritizeQuest}{Environment.NewLine}" +
$"CLAIM_QUEST_REWARD: {Settings.ClaimQuestReward}{Environment.NewLine}" +
$"CLAIM_SEASON_REWARD: {Settings.ClaimSeasonReward}{Environment.NewLine}" +
$"SHOW_SPS_REWARD: {Settings.ShowSpsReward}{Environment.NewLine}" +
$"FOCUS_CHEST_OPTIMIZATION: {Settings.FocusChestOptimization}{Environment.NewLine}" +
$"REQUEST_NEW_QUEST: {string.Join(",", Settings.BadQuests)}{Environment.NewLine}" +
$"ADVANCE_LEAGUE: {Settings.AdvanceLeague}{Environment.NewLine}" +
$"SLEEP_BETWEEN_BATTLES: {Settings.SleepBetweenBattles}{Environment.NewLine}" +
$"START_BATTLE_ABOVE_ECR: {Settings.StartBattleAboveECR}{Environment.NewLine}" +
$"STOP_BATTLE_BELOW_ECR: {Settings.StopBattleBelowECR}{Environment.NewLine}" +
$"USE_PRIVATE_API: {Settings.UsePrivateAPI}{ Environment.NewLine}" +
$"POWER_TRANSFER_BOT: {Settings.PowerTransferBot} {Environment.NewLine}" +
$"SHOW_BATTLE_RESULTS: {Settings.ShowBattleResults} {Environment.NewLine}" +
$"THREADS: {Settings.Threads} {Environment.NewLine}" +
$"{Settings.CardSettings}");
return true;
}
catch (Exception ex)
{
Log.WriteToLog("Error at loading config: " + ex.Message);
return false;
}
}
static bool ReadAccountData()
{
string filePathAccountData = Settings.StartupPath + @"/config/account_data.json";
if (File.Exists(filePathAccountData))
{
Log.WriteToLog("Loading account data from account_data.json...");
Settings.BotInstances = JsonConvert.DeserializeObject<List<BotInstance>>(File.ReadAllText(filePathAccountData));
}
if (Settings.BotInstances == null)
{
Settings.BotInstances = new();
}
string filePathAccounts = Settings.StartupPath + @"/config/accounts.txt";
if (!File.Exists(filePathAccounts))
{
Log.WriteToLog("No accounts.txt in config folder - see accounts-example.txt!", Log.LogType.CriticalError);
return false;
}
Log.WriteToLog("Checking for new and removed accounts in accounts.txt...");
int indexCount = 0;
string[] accountLoginData = File.ReadAllLines(filePathAccounts);
foreach (string loginData in accountLoginData)
{
if (loginData.Trim().Length == 0 || loginData[0] == '#')
{
continue;
}
string[] loginDataSplitted = loginData.Split(':');
string username = loginDataSplitted[0];
string postingKey = loginDataSplitted[1];
string activeKey = loginDataSplitted.Length >= 3 ? loginDataSplitted[2] : "";
var botInstance = Settings.BotInstances.FirstOrDefault(x => x.Username == username);
if (botInstance == null)
{
botInstance = new BotInstance(username);
Settings.BotInstances.Add(botInstance);
}
else if (Settings.PowerTransferBot)
{
// Reset sleep times
botInstance.SleepUntil = DateTime.Now;
}
botInstance.Initialize(indexCount++, postingKey, activeKey);
}
// Delete removed accounts
if (accountLoginData.Length != Settings.BotInstances.Count)
{
Settings.BotInstances.RemoveAll(botInstance => accountLoginData.FirstOrDefault(loginData => loginData.Split(':')[0] == botInstance.Username) == null);
}
if (Settings.BotInstances.Count > 0)
{
Log.WriteToLog($"Loaded { Settings.BotInstances.Count.ToString().Pastel(Color.Red) } accounts!", Log.LogType.Success);
return true;
}
else
{
Log.WriteToLog($"Did not load any account", Log.LogType.CriticalError);
return false;
}
}
static void Initialize()
{
LoadSplinterlandsSettings();
if (Settings.Threads > Settings.BotInstances.Count)
{
Log.WriteToLog($"THREADS is larger than total number of accounts, lowering it to {Settings.BotInstances.Count.ToString().Pastel(Color.Red)}", Log.LogType.Warning);
Settings.Threads = Settings.BotInstances.Count;
}
Settings.QuestTypes = new Dictionary<string, string>
{
{"stir", "fire"},
{"pirate", "water"},
{"lyanna", "earth"},
{"defend", "life"},
{"rising", "death"},
{"gloridax", "dragon"}
};
LoadCards();
Settings.LogSummaryList = new List<(int index, string account, string battleResult, string rating, string ECR, string questStatus)>();
Settings.oHived = new HiveAPI.CS.CHived(Settings.HttpClient, Settings.HIVE_NODE);
}
private static void LoadCards()
{
var cardsDetailsRaw = File.ReadAllText(Settings.StartupPath + "/data/cardsDetails.json");
Settings.CardsDetails = JsonConvert.DeserializeObject<DetailedCard[]>(cardsDetailsRaw);
Settings.StarterCards = Settings.CardsDetails.Where(card => card.rarity <= 2 && Settings.STARTER_EDITIONS.Contains(card.editions)).Select(card =>
{
return new UserCard(card.id.ToString(), "starter-" + card.id.ToString() + "-" + Helper.GenerateRandomString(5), "1", false, true);
}).ToArray();
}
static void SetStartupPath()
{
// Setup startup path
string path = Assembly.GetExecutingAssembly().Location;
string directory = Path.GetDirectoryName(path);
if (directory.Length == 0)
{
directory = AppDomain.CurrentDomain.BaseDirectory;
}
Settings.StartupPath = directory;
}
}
}