forked from oqyh/cs2-Connect-Disconnect-Sound
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CnD_Sound.cs
647 lines (579 loc) · 29.6 KB
/
CnD_Sound.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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
using System.Text.Json.Serialization;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API;
using MaxMind.GeoIP2;
using MaxMind.GeoIP2.Exceptions;
using System.Text;
using System.Drawing;
using Microsoft.Extensions.Localization;
using CounterStrikeSharp.API.Modules.Commands;
namespace CnD_Sound;
public class CnDSoundConfig : BasePluginConfig
{
[JsonPropertyName("InGameSoundDisableCommands")] public string InGameSoundDisableCommands { get; set; } = "!stopsound,!stopsounds";
[JsonPropertyName("InGameSoundConnect")] public string InGameSoundConnect { get; set; } = "sounds/buttons/blip1.vsnd_c";
[JsonPropertyName("InGameSoundDisconnect")] public string InGameSoundDisconnect { get; set; } = "sounds/player/taunt_clap_01.vsnd_c";
[JsonPropertyName("SendLogToText")] public bool SendLogToText { get; set; } = false;
[JsonPropertyName("LogFileFormat")] public string LogFileFormat { get; set; } = ".txt";
[JsonPropertyName("LogFileDateFormat")] public string LogFileDateFormat { get; set; } = "MM-dd-yyyy";
[JsonPropertyName("LogInsideFileTimeFormat")] public string LogInsideFileTimeFormat { get; set; } = "HH:mm:ss";
[JsonPropertyName("LogTextFormatConnect")] public string LogTextFormatConnect { get; set; } = "[{DATE} - {TIME}] {PLAYERNAME} Connected [{SHORTCOUNTRY} - {CITY}] [{STEAMID} - {IP}]";
[JsonPropertyName("LogTextFormatDisconnect")] public string LogTextFormatDisconnect { get; set; } = "[{DATE} - {TIME}] {PLAYERNAME} Disconnected [{SHORTCOUNTRY} - {CITY}] [{STEAMID64}] [{STEAMID} - {IP}] [{REASON}]";
[JsonPropertyName("AutoDeleteLogsMoreThanXdaysOld")] public int AutoDeleteLogsMoreThanXdaysOld { get; set; } = 0;
[JsonPropertyName("SendLogToWebHook")] public int SendLogToWebHook { get; set; } = 0;
[JsonPropertyName("SideColorMessage")] public string SideColorMessage { get; set; } = "00FFFF";
[JsonPropertyName("WebHookURL")] public string WebHookURL { get; set; } = "https://discord.com/api/webhooks/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
[JsonPropertyName("LogDiscordChatFormatConnect")] public string LogDiscordChatFormatConnect { get; set; } = "{PLAYERNAME} Connected [{LONGCOUNTRY} - {CITY}]";
[JsonPropertyName("LogDiscordChatFormatDisconnect")] public string LogDiscordChatFormatDisconnect { get; set; } = "{PLAYERNAME} Disconnected [{LONGCOUNTRY} - {CITY}] [{REASON}]";
[JsonPropertyName("SendLogToServerConsole")] public bool SendLogToServerConsole { get; set; } = false;
[JsonPropertyName("LogServerConsoleFormatConnect")] public string LogServerConsoleFormatConnect { get; set; } = "Gold KingZ | {PLAYERNAME} Connected [{SHORTCOUNTRY} - {CITY}]";
[JsonPropertyName("LogServerConsoleFormatDisconnect")] public string LogServerConsoleFormatDisconnect { get; set; } = "Gold KingZ | {PLAYERNAME} Disconnected [{SHORTCOUNTRY} - {CITY}] [{REASON}]";
}
public class CnDSound : BasePlugin, IPluginConfig<CnDSoundConfig>
{
public override string ModuleName => "Connect Disconnect Sound";
public override string ModuleVersion => "1.0.7";
public override string ModuleAuthor => "Gold KingZ";
public override string ModuleDescription => "Connect , Disconnect , Country , City , Message , Sound , Logs , Discord";
internal static IStringLocalizer? Stringlocalizer;
private static readonly HttpClient _httpClient = new HttpClient();
private static readonly HttpClient httpClient = new HttpClient();
public CnDSoundConfig Config { get; set; } = new CnDSoundConfig();
public ENetworkDisconnectionReason Reason { get; set; }
private Dictionary<int, bool> OnDisabled = new Dictionary<int, bool>();
public void OnConfigParsed(CnDSoundConfig config)
{
Config = config;
Stringlocalizer = Localizer;
if (Config.SendLogToWebHook < 0 || Config.SendLogToWebHook > 3)
{
config.SendLogToWebHook = 0;
Console.WriteLine("|||||||||||||||||||||||||||||||||||| I N V A L I D ||||||||||||||||||||||||||||||||||||");
Console.WriteLine("SendLogToWebHook: is invalid, setting to default value (0) Please Choose 0 or 1 or 2 or 3.");
Console.WriteLine("SendLogToWebHook (0) = Disableis invalid");
Console.WriteLine("SendLogToWebHook (1) = Text Only");
Console.WriteLine("SendLogToWebHook (2) = Text With + Name + Hyperlink To Steam Profile");
Console.WriteLine("SendLogToWebHook (3) = Text With + Name + Hyperlink To Steam Profile + Profile Picture");
Console.WriteLine("|||||||||||||||||||||||||||||||||||| I N V A L I D ||||||||||||||||||||||||||||||||||||");
}
if (Config.SideColorMessage.StartsWith("#"))
{
Config.SideColorMessage = Config.SideColorMessage.Substring(1);
}
}
public override void Load(bool hotReload)
{
RegisterListener<Listeners.OnClientPutInServer>(OnClientPutInServer);
RegisterListener<Listeners.OnMapStart>(OnMapStart);
RegisterEventHandler<EventPlayerDisconnect>(OnPlayerDisconnect);
AddCommandListener("say", OnPlayerSayPublic, HookMode.Post);
AddCommandListener("say_team", OnPlayerSayTeam, HookMode.Post);
}
private HookResult OnPlayerSayPublic(CCSPlayerController? player, CommandInfo info)
{
if (string.IsNullOrEmpty(Config.InGameSoundDisableCommands) || player == null || !player.IsValid || player.IsBot || player.IsHLTV)return HookResult.Continue;
var message = info.GetArg(1);
if (string.IsNullOrWhiteSpace(message)) return HookResult.Continue;
string trimmedMessage1 = message.TrimStart();
string trimmedMessage = trimmedMessage1.TrimEnd();
string[] disableCommands = Config.InGameSoundDisableCommands.Split(',');
if (disableCommands.Any(cmd => cmd.Equals(trimmedMessage, StringComparison.OrdinalIgnoreCase)))
{
if (player.UserId.HasValue)
{
if (OnDisabled.ContainsKey(player.UserId.Value))
{
OnDisabled.Remove(player.UserId.Value);
player.PrintToChat(Localizer["InGame_Command_Enabled"]);
}else
{
OnDisabled.Add(player.UserId.Value, true);
player.PrintToChat(Localizer["InGame_Command_Disabled"]);
}
}
}
return HookResult.Continue;
}
private HookResult OnPlayerSayTeam(CCSPlayerController? player, CommandInfo info)
{
if (string.IsNullOrEmpty(Config.InGameSoundDisableCommands) || player == null || !player.IsValid || player.IsBot || player.IsHLTV)return HookResult.Continue;
var message = info.GetArg(1);
if (string.IsNullOrWhiteSpace(message)) return HookResult.Continue;
string trimmedMessage1 = message.TrimStart();
string trimmedMessage = trimmedMessage1.TrimEnd();
string[] disableCommands = Config.InGameSoundDisableCommands.Split(',');
if (disableCommands.Any(cmd => cmd.Equals(trimmedMessage, StringComparison.OrdinalIgnoreCase)))
{
if (player.UserId.HasValue)
{
if (OnDisabled.ContainsKey(player.UserId.Value))
{
OnDisabled.Remove(player.UserId.Value);
player.PrintToChat(Localizer["InGame_Command_Enabled"]);
}else
{
OnDisabled.Add(player.UserId.Value, true);
player.PrintToChat(Localizer["InGame_Command_Disabled"]);
}
}
}
return HookResult.Continue;
}
private void OnMapStart(string Map)
{
if(Config.AutoDeleteLogsMoreThanXdaysOld > 0)
{
string Fpath = Path.Combine(ModuleDirectory,"../../plugins/CnD_Sound/logs");
DeleteOldFiles(Fpath, "*" + Config.LogFileFormat, TimeSpan.FromDays(Config.AutoDeleteLogsMoreThanXdaysOld));
}
}
private void OnClientPutInServer(int playerSlot)
{
string Fpath = Path.Combine(ModuleDirectory,"../../plugins/CnD_Sound/logs/");
string Time = DateTime.Now.ToString(Config.LogInsideFileTimeFormat);
string Date = DateTime.Now.ToString(Config.LogFileDateFormat);
string fileName = DateTime.Now.ToString(Config.LogFileDateFormat) + Config.LogFileFormat;
string Tpath = Path.Combine(ModuleDirectory,"../../plugins/CnD_Sound/logs/") + $"{fileName}";
if(Config.SendLogToText && !Directory.Exists(Fpath))
{
Directory.CreateDirectory(Fpath);
}
if(Config.SendLogToText && !File.Exists(Tpath))
{
File.Create(Tpath);
}
var player = Utilities.GetPlayerFromSlot(playerSlot);
if (player == null || !player.IsValid || player.IsBot || player.IsHLTV)return;
var JoinPlayer = player.PlayerName;
var steamId2 = (player.AuthorizedSteamID != null) ? player.AuthorizedSteamID.SteamId2 : "InvalidSteamID";
var steamId3 = (player.AuthorizedSteamID != null) ? player.AuthorizedSteamID.SteamId3 : "InvalidSteamID";
var steamId32 = (player.AuthorizedSteamID != null) ? player.AuthorizedSteamID.SteamId32.ToString() : "InvalidSteamID";
var steamId64 = (player.AuthorizedSteamID != null) ? player.AuthorizedSteamID.SteamId64.ToString() : "InvalidSteamID";
var GetIpAddress = NativeAPI.GetPlayerIpAddress(playerSlot);
var ipAddress = GetIpAddress?.Split(':')[0] ?? "InValidIpAddress";
var Country = GetCountry(ipAddress);
var SCountry = GetCountryS(ipAddress);
var City = GetCity(ipAddress);
if (!string.IsNullOrEmpty(Localizer["InGame_Message_Connect"]))
{
Server.PrintToChatAll(Localizer["InGame_Message_Connect", Date, Time, JoinPlayer, steamId2, steamId3, steamId32.ToString(), steamId64.ToString(), ipAddress.ToString(), Country, SCountry, City, string.Empty]);
}
if(Config.SendLogToServerConsole)
{
if (!string.IsNullOrEmpty(Config.LogServerConsoleFormatConnect))
{
var replacer = ReplaceMessages(Config.LogServerConsoleFormatConnect, Date, Time, JoinPlayer, steamId2, steamId3, steamId32.ToString(), steamId64.ToString(), ipAddress.ToString(), Country, SCountry, City, string.Empty);
Server.PrintToConsole(replacer);
}
}
if(Config.SendLogToText)
{
var replacerlog = ReplaceMessages(Config.LogTextFormatConnect, Date, Time, JoinPlayer, steamId2, steamId3, steamId32.ToString(), steamId64.ToString(), ipAddress.ToString(), Country, SCountry, City, string.Empty);
if (!string.IsNullOrEmpty(Config.LogTextFormatConnect) && File.Exists(Tpath))
{
try
{
File.AppendAllLines(Tpath, new[]{replacerlog});
}catch
{
Console.WriteLine("|||||||||||||||||||||||||||||| E R R O R ||||||||||||||||||||||||||||||");
Console.WriteLine("[Error Cant Write] Please Give CnD_Sound.dll Permissions To Write");
Console.WriteLine("|||||||||||||||||||||||||||||| E R R O R ||||||||||||||||||||||||||||||");
}
}
}
var replacerDISCORDlog = ReplaceMessages(Config.LogDiscordChatFormatConnect, Date, Time, JoinPlayer, steamId2, steamId3, steamId32.ToString(), steamId64.ToString(), ipAddress.ToString(), Country, SCountry, City, string.Empty);
if(Config.SendLogToWebHook == 1)
{
if (!string.IsNullOrEmpty(Config.LogDiscordChatFormatConnect))
{
_ = SendToDiscordWebhookNormal(Config.WebHookURL, replacerDISCORDlog);
}
}else if(Config.SendLogToWebHook == 2)
{
if (!string.IsNullOrEmpty(Config.LogDiscordChatFormatConnect))
{
_ = SendToDiscordWebhookNameLink(Config.WebHookURL, replacerDISCORDlog, steamId64.ToString(), JoinPlayer);
}
}else if(Config.SendLogToWebHook == 3)
{
if (!string.IsNullOrEmpty(Config.LogDiscordChatFormatConnect))
{
_ = SendToDiscordWebhookNameLinkWithPicture(Config.WebHookURL, replacerDISCORDlog, steamId64.ToString(), JoinPlayer);
}
}
if (!string.IsNullOrEmpty(Config.InGameSoundConnect))
{
foreach(var players in GetPlayerControllers().FindAll(x => x.Connected == PlayerConnectedState.PlayerConnected && !x.IsBot))
{
if (players.IsValid)
{
if (!string.IsNullOrEmpty(Config.InGameSoundDisableCommands))
{
if (player.UserId.HasValue)
{
if(OnDisabled.ContainsKey(player.UserId.Value) == false)
{
players.ExecuteClientCommand("play " + Config.InGameSoundConnect);
}
}
}else
{
players.ExecuteClientCommand("play " + Config.InGameSoundConnect);
}
}
}
}
}
private HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, GameEventInfo info)
{
string Fpath = Path.Combine(ModuleDirectory,"../../plugins/CnD_Sound/logs/");
string Time = DateTime.Now.ToString(Config.LogInsideFileTimeFormat);
string Date = DateTime.Now.ToString(Config.LogFileDateFormat);
string fileName = DateTime.Now.ToString(Config.LogFileDateFormat) + Config.LogFileFormat;
string Tpath = Path.Combine(ModuleDirectory,"../../plugins/CnD_Sound/logs/") + $"{fileName}";
if(Config.SendLogToText && !Directory.Exists(Fpath))
{
Directory.CreateDirectory(Fpath);
}
if(Config.SendLogToText && !File.Exists(Tpath))
{
File.Create(Tpath);
}
var player = @event.Userid;
var reasonInt = @event.Reason;
if (player == null || !player.IsValid || player.IsBot || player.IsHLTV)return HookResult.Continue;
var playerSlot = player.Slot;
var JoinPlayer = player.PlayerName;
var steamId2 = (player.AuthorizedSteamID != null) ? player.AuthorizedSteamID.SteamId2 : "InvalidSteamID";
var steamId3 = (player.AuthorizedSteamID != null) ? player.AuthorizedSteamID.SteamId3 : "InvalidSteamID";
var steamId32 = (player.AuthorizedSteamID != null) ? player.AuthorizedSteamID.SteamId32.ToString() : "InvalidSteamID";
var steamId64 = (player.AuthorizedSteamID != null) ? player.AuthorizedSteamID.SteamId64.ToString() : "InvalidSteamID";
var GetIpAddress = NativeAPI.GetPlayerIpAddress(playerSlot);
var ipAddress = GetIpAddress?.Split(':')[0] ?? "InValidIpAddress";
var Country = GetCountry(ipAddress);
var SCountry = GetCountryS(ipAddress);
var City = GetCity(ipAddress);
if (!string.IsNullOrEmpty(Localizer["InGame_Message_Disconnect"]))
{
if (Enum.IsDefined(typeof(ENetworkDisconnectionReason), reasonInt))
{
string disconnectReasonString = NetworkDisconnectionReasonHelper.GetDisconnectReasonString((ENetworkDisconnectionReason)reasonInt);
Server.PrintToChatAll(Localizer["InGame_Message_Disconnect", Date, Time, JoinPlayer, steamId2, steamId3, steamId32.ToString(), steamId64.ToString(), ipAddress.ToString(), Country, SCountry, City, disconnectReasonString]);
}
}
if(Config.SendLogToServerConsole)
{
if (!string.IsNullOrEmpty(Config.LogServerConsoleFormatDisconnect))
{
if (Enum.IsDefined(typeof(ENetworkDisconnectionReason), reasonInt))
{
string disconnectReasonString = NetworkDisconnectionReasonHelper.GetDisconnectReasonString((ENetworkDisconnectionReason)reasonInt);
var replacer = ReplaceMessages(Config.LogServerConsoleFormatDisconnect, Date, Time, JoinPlayer, steamId2, steamId3, steamId32.ToString(), steamId64.ToString(), ipAddress.ToString(), Country, SCountry, City, disconnectReasonString);
Server.PrintToConsole(replacer);
}
}
}
if(Config.SendLogToText)
{
if (Enum.IsDefined(typeof(ENetworkDisconnectionReason), reasonInt))
{
string disconnectReasonString = NetworkDisconnectionReasonHelper.GetDisconnectReasonString((ENetworkDisconnectionReason)reasonInt);
var replacerlog = ReplaceMessages(Config.LogTextFormatDisconnect, Date, Time, JoinPlayer, steamId2, steamId3, steamId32.ToString(), steamId64.ToString(), ipAddress.ToString(), Country, SCountry, City, disconnectReasonString);
if (!string.IsNullOrEmpty(Config.LogTextFormatDisconnect) && File.Exists(Tpath))
{
try
{
File.AppendAllLines(Tpath, new[]{replacerlog});
}catch
{
Console.WriteLine("|||||||||||||||||||||||||||||| E R R O R ||||||||||||||||||||||||||||||");
Console.WriteLine("[Error Cant Write] Please Give CnD_Sound.dll Permissions To Write");
Console.WriteLine("|||||||||||||||||||||||||||||| E R R O R ||||||||||||||||||||||||||||||");
}
}
}
}
if (Enum.IsDefined(typeof(ENetworkDisconnectionReason), reasonInt))
{
string disconnectReasonString = NetworkDisconnectionReasonHelper.GetDisconnectReasonString((ENetworkDisconnectionReason)reasonInt);
var replacerDISCORDlog = ReplaceMessages(Config.LogDiscordChatFormatDisconnect, Date, Time, JoinPlayer, steamId2, steamId3, steamId32.ToString(), steamId64.ToString(), ipAddress.ToString(), Country, SCountry, City, disconnectReasonString);
if(Config.SendLogToWebHook == 1)
{
if (!string.IsNullOrEmpty(Config.LogDiscordChatFormatDisconnect))
{
_ = SendToDiscordWebhookNormal(Config.WebHookURL, replacerDISCORDlog);
}
}else if(Config.SendLogToWebHook == 2)
{
if (!string.IsNullOrEmpty(Config.LogDiscordChatFormatDisconnect))
{
_ = SendToDiscordWebhookNameLink(Config.WebHookURL, replacerDISCORDlog, steamId64.ToString(), JoinPlayer);
}
}else if(Config.SendLogToWebHook == 3)
{
if (!string.IsNullOrEmpty(Config.LogDiscordChatFormatDisconnect))
{
_ = SendToDiscordWebhookNameLinkWithPicture(Config.WebHookURL, replacerDISCORDlog, steamId64.ToString(), JoinPlayer);
}
}
}
if (!string.IsNullOrEmpty(Config.InGameSoundDisconnect))
{
foreach(var players in GetPlayerControllers().FindAll(x => x.Connected == PlayerConnectedState.PlayerConnected && !x.IsBot))
{
if (players.IsValid)
{
if (!string.IsNullOrEmpty(Config.InGameSoundDisableCommands))
{
if (player.UserId.HasValue)
{
if(OnDisabled.ContainsKey(player.UserId.Value) == false)
{
players.ExecuteClientCommand("play " + Config.InGameSoundDisconnect);
}
}
}else
{
players.ExecuteClientCommand("play " + Config.InGameSoundDisconnect);
}
}
}
}
return HookResult.Continue;
}
private string ReplaceMessages(string Message, string date, string time, string PlayerName, string SteamId, string SteamId3, string SteamId32, string SteamId64, string ipAddress, string Country, string SCountry, string City, string reason)
{
var replacedMessage = Message
.Replace("{TIME}", time)
.Replace("{DATE}", date)
.Replace("{PLAYERNAME}", PlayerName.ToString())
.Replace("{STEAMID}", SteamId.ToString())
.Replace("{STEAMID3}", SteamId3.ToString())
.Replace("{STEAMID32}", SteamId32.ToString())
.Replace("{STEAMID64}", SteamId64.ToString())
.Replace("{IP}", ipAddress.ToString())
.Replace("{LONGCOUNTRY}", Country)
.Replace("{SHORTCOUNTRY}", SCountry)
.Replace("{CITY}", City)
.Replace("{REASON}", reason);
return replacedMessage;
}
private static List<CCSPlayerController> GetPlayerControllers()
{
var playerList = Utilities.FindAllEntitiesByDesignerName<CCSPlayerController>("cs_player_controller").ToList();
return playerList;
}
private string GetCountryS(string ipAddress)
{
try
{
using (var reader = new DatabaseReader(Path.Combine(ModuleDirectory, "../../plugins/CnD_Sound/GeoLocation/GeoLite2-City.mmdb")))
{
var response = reader.City(ipAddress);
return response.Country.IsoCode ?? "U/C";
}
}
catch (AddressNotFoundException)
{
return "U/C";
}
catch
{
return "U/C";
}
}
private string GetCountry(string ipAddress)
{
try
{
using (var reader = new DatabaseReader(Path.Combine(ModuleDirectory, "../../plugins/CnD_Sound/GeoLocation/GeoLite2-City.mmdb")))
{
var response = reader.City(ipAddress);
return response.Country.Name ?? "Unknown Country";
}
}
catch (AddressNotFoundException)
{
return "Unknown Country";
}
catch
{
return "Unknown Country";
}
}
private string GetCity(string ipAddress)
{
try
{
using (var reader = new DatabaseReader(Path.Combine(ModuleDirectory, "../../plugins/CnD_Sound/GeoLocation/GeoLite2-City.mmdb")))
{
var response = reader.City(ipAddress);
return response.City.Name ?? "Unknown City";
}
}
catch (AddressNotFoundException)
{
return "Unknown City";
}
catch
{
return "Unknown City";
}
}
public async Task SendToDiscordWebhookNormal(string webhookUrl, string message)
{
try
{
var payload = new { content = message };
var jsonPayload = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(webhookUrl, content).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"Failed to send message. Status code: {response.StatusCode}, Response: {await response.Content.ReadAsStringAsync()}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
}
public async Task SendToDiscordWebhookNameLink(string webhookUrl, string message, string steamUserId, string STEAMNAME)
{
try
{
string profileLink = GetSteamProfileLink(steamUserId);
int colorss = int.Parse(Config.SideColorMessage, System.Globalization.NumberStyles.HexNumber);
Color color = Color.FromArgb(colorss >> 16, (colorss >> 8) & 0xFF, colorss & 0xFF);
using (var httpClient = new HttpClient())
{
var embed = new
{
type = "rich",
title = STEAMNAME,
url = profileLink,
description = message,
color = color.ToArgb() & 0xFFFFFF
};
var payload = new
{
embeds = new[] { embed }
};
var jsonPayload = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(webhookUrl, content).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"Failed to send message. Status code: {response.StatusCode}, Response: {await response.Content.ReadAsStringAsync()}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
}
public async Task SendToDiscordWebhookNameLinkWithPicture(string webhookUrl, string message, string steamUserId, string STEAMNAME)
{
try
{
string profileLink = GetSteamProfileLink(steamUserId);
string profilePictureUrl = await GetProfilePictureAsync(steamUserId);
int colorss = int.Parse(Config.SideColorMessage, System.Globalization.NumberStyles.HexNumber);
Color color = Color.FromArgb(colorss >> 16, (colorss >> 8) & 0xFF, colorss & 0xFF);
using (var httpClient = new HttpClient())
{
var embed = new
{
type = "rich",
description = message,
color = color.ToArgb() & 0xFFFFFF,
author = new
{
name = STEAMNAME,
url = profileLink,
icon_url = profilePictureUrl
}
};
var payload = new
{
embeds = new[] { embed }
};
var jsonPayload = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(webhookUrl, content).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"Failed to send message. Status code: {response.StatusCode}, Response: {await response.Content.ReadAsStringAsync()}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
}
private static async Task<string> GetProfilePictureAsync(string steamId64)
{
try
{
string apiUrl = $"https://steamcommunity.com/profiles/{steamId64}/?xml=1";
HttpResponseMessage response = await httpClient.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
string xmlResponse = await response.Content.ReadAsStringAsync();
int startIndex = xmlResponse.IndexOf("<avatarFull><![CDATA[") + "<avatarFull><![CDATA[".Length;
int endIndex = xmlResponse.IndexOf("]]></avatarFull>", startIndex);
string profilePictureUrl = xmlResponse.Substring(startIndex, endIndex - startIndex);
return profilePictureUrl;
}
else
{
Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}");
return null!;
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
return null!;
}
}
static string GetSteamProfileLink(string userId)
{
return $"https://steamcommunity.com/profiles/{userId}";
}
static void DeleteOldFiles(string folderPath, string searchPattern, TimeSpan maxAge)
{
try
{
DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
if (directoryInfo.Exists)
{
FileInfo[] files = directoryInfo.GetFiles(searchPattern);
DateTime currentTime = DateTime.Now;
foreach (FileInfo file in files)
{
TimeSpan age = currentTime - file.LastWriteTime;
if (age > maxAge)
{
file.Delete();
}
}
}
else
{
Console.WriteLine($"Directory not found: {folderPath}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
public override void Unload(bool hotReload)
{
OnDisabled.Clear();
}
}