From 44d235317ff9a6e23c8c4bad6cf22dc28872d6ed Mon Sep 17 00:00:00 2001 From: Gold KingZ <48490385+oqyh@users.noreply.github.com> Date: Sat, 18 May 2024 04:14:32 +0400 Subject: [PATCH] 1.0.7 --- Chat-Logger-GoldKingZ.cs | 219 ++++++++++++++++++ Chat-Logger-GoldKingZ.csproj | 18 ++ Config/Configs.cs | 180 +++++++++++++++ Config/Globals.cs | 7 + Config/Helper.cs | 425 +++++++++++++++++++++++++++++++++++ 5 files changed, 849 insertions(+) create mode 100644 Chat-Logger-GoldKingZ.cs create mode 100644 Chat-Logger-GoldKingZ.csproj create mode 100644 Config/Configs.cs create mode 100644 Config/Globals.cs create mode 100644 Config/Helper.cs diff --git a/Chat-Logger-GoldKingZ.cs b/Chat-Logger-GoldKingZ.cs new file mode 100644 index 0000000..5c1a9c8 --- /dev/null +++ b/Chat-Logger-GoldKingZ.cs @@ -0,0 +1,219 @@ +using CounterStrikeSharp.API; +using CounterStrikeSharp.API.Core; +using CounterStrikeSharp.API.Modules.Cvars; +using Chat_Logger_GoldKingZ.Config; + +namespace Chat_Logger_GoldKingZ; + + +public class ChatLoggerGoldKingZ : BasePlugin +{ + public override string ModuleName => "Chat Logger (Log Chat To Text Or Discord WebHook)"; + public override string ModuleVersion => "1.0.7"; + public override string ModuleAuthor => "Gold KingZ"; + public override string ModuleDescription => "https://github.com/oqyh"; + + + + public override void Load(bool hotReload) + { + Configs.Load(ModuleDirectory); + Configs.Shared.CookiesModule = ModuleDirectory; + RegisterEventHandler(OnEventPlayerChat, HookMode.Post); + RegisterListener(OnMapStart); + RegisterEventHandler(OnPlayerDisconnect); + RegisterListener(OnMapEnd); + } + public void OnMapStart(string Map) + { + if(Configs.GetConfigData().Text_AutoDeleteLogsMoreThanXdaysOld > 0) + { + string Fpath = Path.Combine(ModuleDirectory,"../../plugins/Chat-Logger-GoldKingZ/logs"); + Helper.DeleteOldFiles(Fpath, "*" + ".txt", TimeSpan.FromDays(Configs.GetConfigData().Text_AutoDeleteLogsMoreThanXdaysOld)); + } + } + public HookResult OnEventPlayerChat(EventPlayerChat @event, GameEventInfo info) + { + if(@event == null)return HookResult.Continue; + var eventplayer = @event.Userid; + var eventmessage = @event.Text; + var eventteamonly = @event.Teamonly; + var player = Utilities.GetPlayerFromUserid(eventplayer); + + if (player == null || !player.IsValid)return HookResult.Continue; + string Fpath = Path.Combine(ModuleDirectory,"../../plugins/Chat-Logger-GoldKingZ/logs/"); + string fileName = DateTime.Now.ToString(Configs.GetConfigData().Text_DateFormat) + ".txt"; + string Tpath = Path.Combine(ModuleDirectory,"../../plugins/Chat-Logger-GoldKingZ/logs/") + $"{fileName}"; + + var vplayername = 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 = player.IpAddress; + var ipAddress = GetIpAddress?.Split(':')[0] ?? "InValidIpAddress"; + var playerid = player.SteamID; + + if (string.IsNullOrWhiteSpace(eventmessage)) return HookResult.Continue; + string trimmedMessageStart = eventmessage.TrimStart(); + string message = trimmedMessageStart.TrimEnd(); + + if (!Globals.Client_Text1.ContainsKey(playerid)) + { + Globals.Client_Text1.Add(playerid, message); + } + if (!Globals.Client_Text2.ContainsKey(playerid)) + { + Globals.Client_Text2.Add(playerid, string.Empty); + } + + if (Globals.Client_Text1.ContainsKey(playerid)) + { + Globals.Client_Text1[playerid] = Globals.Client_Text2[playerid]; + } + if (Globals.Client_Text2.ContainsKey(playerid)) + { + Globals.Client_Text2[playerid] = message; + } + + if(Configs.GetConfigData().Text_EnableLoggingMessages) + { + if(Configs.GetConfigData().Text_PrivateTeamMessagesOnly && !eventteamonly)return HookResult.Continue; + string chatteam = eventteamonly ? "[TEAM]" : "[ALL]"; + if (!string.IsNullOrEmpty(Configs.GetConfigData().Text_ExcludeFlagsMessages) && Helper.IsPlayerInGroupPermission(player,Configs.GetConfigData().Text_ExcludeFlagsMessages))return HookResult.Continue; + if (!string.IsNullOrEmpty(Configs.GetConfigData().Text_IncludeFlagsMessagesOnly) && !Helper.IsPlayerInGroupPermission(player,Configs.GetConfigData().Text_IncludeFlagsMessagesOnly))return HookResult.Continue; + if(!string.IsNullOrEmpty(Configs.GetConfigData().Text_ExcludeMessageContains) && Helper.IsStringValid(message)) return HookResult.Continue; + if (Configs.GetConfigData().Text_ExcludeMessageContainsLessThanXLetters > 0 && Helper.CountLetters(message) <= Configs.GetConfigData().Text_ExcludeMessageContainsLessThanXLetters) return HookResult.Continue; + + if(Configs.GetConfigData().Text_ExcludeMessageDuplicate && Globals.Client_Text2[playerid] == Globals.Client_Text1[playerid]) return HookResult.Continue; + string Time = DateTime.Now.ToString(Configs.GetConfigData().Text_TimeFormat); + string Date = DateTime.Now.ToString(Configs.GetConfigData().Text_DateFormat); + var replacerlog = !string.IsNullOrEmpty(Configs.GetConfigData().Text_MessageFormat) + ? Helper.ReplaceMessages( + Configs.GetConfigData().Text_MessageFormat, + Time, + Date, + message, + vplayername, + steamId2, + steamId3, + steamId32.ToString(), + steamId64.ToString(), + ipAddress.ToString(), + chatteam ?? "[----]" + ): string.Empty; + + if(!string.IsNullOrEmpty(Configs.GetConfigData().Text_MessageFormat)) + { + if(!Directory.Exists(Fpath)) + { + Directory.CreateDirectory(Fpath); + } + + if(!File.Exists(Tpath)) + { + using (File.Create(Tpath)) { } + } + try + { + File.AppendAllLines(Tpath, new[]{replacerlog}); + }catch + { + + } + } + + } + + if(Configs.GetConfigData().Discord_EnableLoggingMessagesOnMode != 0) + { + if(Configs.GetConfigData().Discord_PrivateTeamMessagesOnly && !eventteamonly)return HookResult.Continue; + string chatteam = eventteamonly ? "[TEAM]" : "[ALL]"; + if (!string.IsNullOrEmpty(Configs.GetConfigData().Discord_ExcludeFlagsMessages) && Helper.IsPlayerInGroupPermission(player,Configs.GetConfigData().Discord_ExcludeFlagsMessages))return HookResult.Continue; + if (!string.IsNullOrEmpty(Configs.GetConfigData().Discord_IncludeFlagsMessagesOnly) && !Helper.IsPlayerInGroupPermission(player,Configs.GetConfigData().Discord_IncludeFlagsMessagesOnly))return HookResult.Continue; + if(!string.IsNullOrEmpty(Configs.GetConfigData().Discord_ExcludeMessageContains) && Helper.IsStringValid(message)) return HookResult.Continue; + if (Configs.GetConfigData().Discord_ExcludeMessageContainsLessThanXLetters > 0 && Helper.CountLetters(message) <= Configs.GetConfigData().Discord_ExcludeMessageContainsLessThanXLetters) return HookResult.Continue; + if(Configs.GetConfigData().Discord_ExcludeMessageDuplicate && Globals.Client_Text2[playerid] == Globals.Client_Text1[playerid]) return HookResult.Continue; + + string Time = DateTime.Now.ToString(Configs.GetConfigData().Discord_TimeFormat); + string Date = DateTime.Now.ToString(Configs.GetConfigData().Discord_DateFormat); + int hostPort = ConVar.Find("hostport")!.GetPrimitiveValue(); + var replacerDiscord = !string.IsNullOrEmpty(Configs.GetConfigData().Discord_MessageFormat) + ? Helper.ReplaceMessages( + Configs.GetConfigData().Discord_MessageFormat, + Time, + Date, + message, + vplayername, + steamId2, + steamId3, + steamId32.ToString(), + steamId64.ToString(), + ipAddress.ToString(), + chatteam ?? "[----]" + ): string.Empty; + + if(!string.IsNullOrEmpty(replacerDiscord)) + { + if(Configs.GetConfigData().Discord_EnableLoggingMessagesOnMode == 1) + { + Task.Run(() => + { + _ = Helper.SendToDiscordWebhookNormal(Configs.GetConfigData().Discord_WebHookURL, replacerDiscord); + }); + }else if(Configs.GetConfigData().Discord_EnableLoggingMessagesOnMode == 2) + { + Task.Run(() => + { + _ = Helper.SendToDiscordWebhookNameLink(Configs.GetConfigData().Discord_WebHookURL, replacerDiscord, playerid.ToString(), vplayername); + }); + }else if(Configs.GetConfigData().Discord_EnableLoggingMessagesOnMode == 3) + { + Task.Run(() => + { + _ = Helper.SendToDiscordWebhookNameLinkWithPicture(Configs.GetConfigData().Discord_WebHookURL, replacerDiscord, playerid.ToString(), vplayername); + }); + }else if(Configs.GetConfigData().Discord_EnableLoggingMessagesOnMode == 4) + { + Task.Run(() => + { + _ = Helper.SendToDiscordWebhookNameLinkWithPicture2(Configs.GetConfigData().Discord_WebHookURL, replacerDiscord, playerid.ToString(), vplayername); + }); + }else if(Configs.GetConfigData().Discord_EnableLoggingMessagesOnMode == 5) + { + Task.Run(() => + { + string serverIp = Helper.GetServerPublicIPAsync().Result; + _ = Helper.SendToDiscordWebhookNameLinkWithPicture3(Configs.GetConfigData().Discord_WebHookURL, replacerDiscord, playerid.ToString(), vplayername, $"{serverIp}:{hostPort}"); + }); + } + } + + } + + + return HookResult.Continue; + } + + public HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, GameEventInfo info) + { + if (@event == null) return HookResult.Continue; + var player = @event.Userid; + + if (player == null || !player.IsValid || player.IsBot || player.IsHLTV) return HookResult.Continue; + var playerid = player.SteamID; + + Globals.Client_Text1.Remove(playerid); + Globals.Client_Text2.Remove(playerid); + + return HookResult.Continue; + } + public void OnMapEnd() + { + Helper.ClearVariables(); + } + public override void Unload(bool hotReload) + { + Helper.ClearVariables(); + } +} \ No newline at end of file diff --git a/Chat-Logger-GoldKingZ.csproj b/Chat-Logger-GoldKingZ.csproj new file mode 100644 index 0000000..9cc4e2c --- /dev/null +++ b/Chat-Logger-GoldKingZ.csproj @@ -0,0 +1,18 @@ + + + net8.0 + enable + enable + false + false + + + + + + + + + PreserveNewest + + \ No newline at end of file diff --git a/Config/Configs.cs b/Config/Configs.cs new file mode 100644 index 0000000..3684e2b --- /dev/null +++ b/Config/Configs.cs @@ -0,0 +1,180 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Chat_Logger_GoldKingZ.Config +{ + public static class Configs + { + public static class Shared { + public static string? CookiesModule { get; set; } + } + + private static readonly string ConfigDirectoryName = "config"; + private static readonly string ConfigFileName = "config.json"; + private static string? _configFilePath; + private static ConfigData? _configData; + + private static readonly JsonSerializerOptions SerializationOptions = new() + { + Converters = + { + new JsonStringEnumConverter() + }, + WriteIndented = true, + AllowTrailingCommas = true, + ReadCommentHandling = JsonCommentHandling.Skip, + }; + + public static bool IsLoaded() + { + return _configData is not null; + } + + public static ConfigData GetConfigData() + { + if (_configData is null) + { + throw new Exception("Config not yet loaded."); + } + + return _configData; + } + + public static ConfigData Load(string modulePath) + { + var configFileDirectory = Path.Combine(modulePath, ConfigDirectoryName); + if(!Directory.Exists(configFileDirectory)) + { + Directory.CreateDirectory(configFileDirectory); + } + + _configFilePath = Path.Combine(configFileDirectory, ConfigFileName); + if (File.Exists(_configFilePath)) + { + _configData = JsonSerializer.Deserialize(File.ReadAllText(_configFilePath), SerializationOptions); + } + else + { + _configData = new ConfigData(); + } + + if (_configData is null) + { + throw new Exception("Failed to load configs."); + } + + SaveConfigData(_configData); + + return _configData; + } + + private static void SaveConfigData(ConfigData configData) + { + if (_configFilePath is null) + { + throw new Exception("Config not yet loaded."); + } + string json = JsonSerializer.Serialize(configData, SerializationOptions); + + + File.WriteAllText(_configFilePath, json); + } + + public class ConfigData + { + public bool Text_EnableLoggingMessages { get; set; } + public bool Text_PrivateTeamMessagesOnly { get; set; } + public string Text_IncludeFlagsMessagesOnly { get; set; } + public string Text_ExcludeFlagsMessages { get; set; } + public string Text_ExcludeMessageContains { get; set; } + public int Text_ExcludeMessageContainsLessThanXLetters { get; set; } + public bool Text_ExcludeMessageDuplicate { get; set; } + public string Text_MessageFormat { get; set; } + public string Text_DateFormat { get; set; } + public string Text_TimeFormat { get; set; } + public int Text_AutoDeleteLogsMoreThanXdaysOld { get; set; } + public string empty { get; set; } + private int _Discord_EnableLoggingMessagesOnMode; + public int Discord_EnableLoggingMessagesOnMode + { + get => _Discord_EnableLoggingMessagesOnMode; + set + { + _Discord_EnableLoggingMessagesOnMode = value; + if (_Discord_EnableLoggingMessagesOnMode < 0 || _Discord_EnableLoggingMessagesOnMode > 5) + { + Discord_EnableLoggingMessagesOnMode = 0; + Console.WriteLine("|||||||||||||||||||||||||||||||||||||||||||||||| I N V A L I D ||||||||||||||||||||||||||||||||||||||||||||||||"); + Console.WriteLine("[Chat-Logger-GoldKingZ] Discord_EnableLoggingMessagesOnMode: is invalid, setting to default value (0) Please Choose 0 or 1 or 2 or 3 or 4 or 5."); + Console.WriteLine("[Chat-Logger-GoldKingZ] Discord_EnableLoggingMessagesOnMode (0) = Disable"); + Console.WriteLine("[Chat-Logger-GoldKingZ] Discord_EnableLoggingMessagesOnMode (1) = Text Only"); + Console.WriteLine("[Chat-Logger-GoldKingZ] Discord_EnableLoggingMessagesOnMode (2) = Text With + Name + Hyperlink To Steam Profile"); + Console.WriteLine("[Chat-Logger-GoldKingZ] Discord_EnableLoggingMessagesOnMode (3) = Text With + Name + Hyperlink To Steam Profile + Profile Picture"); + Console.WriteLine("[Chat-Logger-GoldKingZ] Discord_EnableLoggingMessagesOnMode (4) = Text With + Name + Hyperlink To Steam Profile + Profile Picture + Saparate Date And Time From Message"); + Console.WriteLine("[Chat-Logger-GoldKingZ] Discord_EnableLoggingMessagesOnMode (5) = Text With + Name + Hyperlink To Steam Profile + Profile Picture + Saparate Date And Time From Message + Server Ip In Footer"); + Console.WriteLine("|||||||||||||||||||||||||||||||||||||||||||||||| I N V A L I D ||||||||||||||||||||||||||||||||||||||||||||||||"); + } + } + } + public bool Discord_PrivateTeamMessagesOnly { get; set; } + public string Discord_IncludeFlagsMessagesOnly { get; set; } + public string Discord_ExcludeFlagsMessages { get; set; } + public string Discord_ExcludeMessageContains { get; set; } + public int Discord_ExcludeMessageContainsLessThanXLetters { get; set; } + public bool Discord_ExcludeMessageDuplicate { get; set; } + public string Discord_MessageFormat { get; set; } + public string Discord_DateFormat { get; set; } + public string Discord_TimeFormat { get; set; } + private string? _Discord_SideColor; + public string Discord_SideColor + { + get => _Discord_SideColor!; + set + { + _Discord_SideColor = value; + if (_Discord_SideColor.StartsWith("#")) + { + Discord_SideColor = _Discord_SideColor.Substring(1); + } + } + } + public string Discord_WebHookURL { get; set; } + public string Discord_UsersWithNoAvatarImage { get; set; } + public string Discord_FooterImage { get; set; } + public string empty2 { get; set; } + public string Information_For_You_Dont_Delete_it { get; set; } + + public ConfigData() + { + Text_EnableLoggingMessages = false; + Text_PrivateTeamMessagesOnly = false; + Text_IncludeFlagsMessagesOnly = ""; + Text_ExcludeFlagsMessages = "@css/exclude,#css/exclude"; + Text_ExcludeMessageContains = "!./"; + Text_ExcludeMessageContainsLessThanXLetters = 0; + Text_ExcludeMessageDuplicate = false; + Text_MessageFormat = "[{TIME}] [{STEAMID}] {TEAM} ({PLAYERNAME}) {MESSAGE}"; + Text_DateFormat = "MM-dd-yyyy"; + Text_TimeFormat = "HH:mm:ss"; + Text_AutoDeleteLogsMoreThanXdaysOld = 0; + empty = "-----------------------------------------------------------------------------------"; + Discord_EnableLoggingMessagesOnMode = 0; + Discord_PrivateTeamMessagesOnly = false; + Discord_IncludeFlagsMessagesOnly = ""; + Discord_ExcludeFlagsMessages = "@css/exclude,#css/exclude"; + Discord_ExcludeMessageContains = "!./"; + Discord_ExcludeMessageContainsLessThanXLetters = 0; + Discord_ExcludeMessageDuplicate = false; + Discord_MessageFormat = "[{TIME}] [{STEAMID}] {TEAM} ({PLAYERNAME}) {MESSAGE}"; + Discord_DateFormat = "MM-dd-yyyy"; + Discord_TimeFormat = "HH:mm:ss"; + Discord_SideColor = "00FFFF"; + Discord_WebHookURL = "https://discord.com/api/webhooks/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; + Discord_UsersWithNoAvatarImage = "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b5/b5bd56c1aa4644a474a2e4972be27ef9e82e517e_full.jpg"; + Discord_FooterImage = "https://github.com/oqyh/cs2-Chat-Logger-GoldKingZ/blob/main/Resources/serverip.png?raw=true"; + empty2 = "-----------------------------------------------------------------------------------"; + Information_For_You_Dont_Delete_it = " Vist [https://github.com/oqyh/cs2-Chat-Logger-GoldKingZ/tree/main?tab=readme-ov-file#-configuration-] To Understand All Above"; + } + } + } +} \ No newline at end of file diff --git a/Config/Globals.cs b/Config/Globals.cs new file mode 100644 index 0000000..7abeea2 --- /dev/null +++ b/Config/Globals.cs @@ -0,0 +1,7 @@ +namespace Chat_Logger_GoldKingZ; + +public class Globals +{ + public static Dictionary Client_Text1 = new Dictionary(); + public static Dictionary Client_Text2 = new Dictionary(); +} \ No newline at end of file diff --git a/Config/Helper.cs b/Config/Helper.cs new file mode 100644 index 0000000..64c87f3 --- /dev/null +++ b/Config/Helper.cs @@ -0,0 +1,425 @@ +using CounterStrikeSharp.API.Core; +using CounterStrikeSharp.API.Modules.Admin; +using CounterStrikeSharp.API; +using CounterStrikeSharp.API.Modules.Utils; +using Chat_Logger_GoldKingZ.Config; +using System.Text.RegularExpressions; +using System.Text; +using System.Drawing; + +namespace Chat_Logger_GoldKingZ; + +public class Helper +{ + public static readonly HttpClient _httpClient = new HttpClient(); + public static readonly HttpClient httpClient = new HttpClient(); + + public static void AdvancedPrintToChat(CCSPlayerController player, string message, params object[] args) + { + for (int i = 0; i < args.Length; i++) + { + message = message.Replace($"{{{i}}}", args[i].ToString()); + } + if (Regex.IsMatch(message, "{nextline}", RegexOptions.IgnoreCase)) + { + string[] parts = Regex.Split(message, "{nextline}", RegexOptions.IgnoreCase); + foreach (string part in parts) + { + string messages = part.Trim(); + player.PrintToChat(" " + messages); + } + }else + { + player.PrintToChat(message); + } + } + public static void AdvancedPrintToServer(string message, params object[] args) + { + for (int i = 0; i < args.Length; i++) + { + message = message.Replace($"{{{i}}}", args[i].ToString()); + } + if (Regex.IsMatch(message, "{nextline}", RegexOptions.IgnoreCase)) + { + string[] parts = Regex.Split(message, "{nextline}", RegexOptions.IgnoreCase); + foreach (string part in parts) + { + string messages = part.Trim(); + Server.PrintToChatAll(" " + messages); + } + }else + { + Server.PrintToChatAll(message); + } + } + + public static bool IsPlayerInGroupPermission(CCSPlayerController player, string groups) + { + var excludedGroups = groups.Split(','); + foreach (var group in excludedGroups) + { + if (group.StartsWith("#")) + { + if (AdminManager.PlayerInGroup(player, group)) + return true; + } + else if (group.StartsWith("@")) + { + if (AdminManager.PlayerHasPermissions(player, group)) + return true; + } + } + return false; + } + public static bool IsStringValid(string input) + { + if (!string.IsNullOrEmpty(input) && !input.Contains(" ") && input.Any(c => Configs.GetConfigData().Text_ExcludeMessageContains.Contains(c)) && !char.IsWhiteSpace(input.Last())) + { + return true; + } + return false; + } + public static int CountLetters(string input) + { + int count = 0; + + foreach (char c in input) + { + if (char.IsLetter(c)) + { + count++; + } + } + + return count; + } + public static List GetCounterTerroristController() + { + var playerList = Utilities.FindAllEntitiesByDesignerName("cs_player_controller").Where(p => p != null && p.IsValid && !p.IsHLTV && p.Connected == PlayerConnectedState.PlayerConnected && p.Team == CsTeam.CounterTerrorist).ToList(); + return playerList; + } + public static List GetTerroristController() + { + var playerList = Utilities.FindAllEntitiesByDesignerName("cs_player_controller").Where(p => p != null && p.IsValid && !p.IsHLTV && p.Connected == PlayerConnectedState.PlayerConnected && p.Team == CsTeam.Terrorist).ToList(); + return playerList; + } + public static List GetAllController() + { + var playerList = Utilities.FindAllEntitiesByDesignerName("cs_player_controller").Where(p => p != null && p.IsValid && !p.IsHLTV && p.Connected == PlayerConnectedState.PlayerConnected).ToList(); + return playerList; + } + public static int GetCounterTerroristCount() + { + return Utilities.GetPlayers().Count(p => p != null && p.IsValid && !p.IsHLTV && p.Connected == PlayerConnectedState.PlayerConnected && p.TeamNum == (byte)CsTeam.CounterTerrorist); + } + public static int GetTerroristCount() + { + return Utilities.GetPlayers().Count(p => p != null && p.IsValid && !p.IsHLTV && p.Connected == PlayerConnectedState.PlayerConnected && p.TeamNum == (byte)CsTeam.Terrorist); + } + public static int GetAllCount() + { + return Utilities.GetPlayers().Count(p => p != null && p.IsValid && !p.IsHLTV && p.Connected == PlayerConnectedState.PlayerConnected); + } + + public static string ReplaceMessages(string Message, string time, string date, string message, string PlayerName, string SteamId, string SteamId3, string SteamId32, string SteamId64, string IPaddress, string chatteam) + { + var replacedMessage = Message + .Replace("{TIME}", time) + .Replace("{DATE}", date) + .Replace("{MESSAGE}", message) + .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("{TEAM}", chatteam); + return replacedMessage; + } + public static void ClearVariables() + { + Globals.Client_Text1.Clear(); + Globals.Client_Text2.Clear(); + } + + public static 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); + + + } + catch + { + } + } + + public static async Task SendToDiscordWebhookNameLink(string webhookUrl, string message, string steamUserId, string STEAMNAME) + { + try + { + string profileLink = GetSteamProfileLink(steamUserId); + int colorss = int.Parse(Configs.GetConfigData().Discord_SideColor, 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); + + } + } + catch + { + } + } + public static async Task SendToDiscordWebhookNameLinkWithPicture(string webhookUrl, string message, string steamUserId, string STEAMNAME) + { + try + { + string profileLink = GetSteamProfileLink(steamUserId); + string profilePictureUrl = await GetProfilePictureAsync(steamUserId, Configs.GetConfigData().Discord_UsersWithNoAvatarImage); + int colorss = int.Parse(Configs.GetConfigData().Discord_SideColor, 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); + } + } + catch + { + + } + } + public static async Task SendToDiscordWebhookNameLinkWithPicture2(string webhookUrl, string message, string steamUserId, string STEAMNAME) + { + try + { + string profileLink = GetSteamProfileLink(steamUserId); + string profilePictureUrl = await GetProfilePictureAsync(steamUserId, Configs.GetConfigData().Discord_UsersWithNoAvatarImage); + int colorss = int.Parse(Configs.GetConfigData().Discord_SideColor, 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", + color = color.ToArgb() & 0xFFFFFF, + author = new + { + name = STEAMNAME, + url = profileLink, + icon_url = profilePictureUrl + }, + fields = new[] + { + new + { + name = "Date/Time", + value = DateTime.Now.ToString($"{Configs.GetConfigData().Discord_DateFormat} {Configs.GetConfigData().Discord_TimeFormat}"), + inline = false + }, + new + { + name = "Message", + value = message, + inline = false + } + } + }; + + 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); + } + } + catch + { + + } + } + public static async Task SendToDiscordWebhookNameLinkWithPicture3(string webhookUrl, string message, string steamUserId, string STEAMNAME, string ipadress) + { + try + { + string profileLink = GetSteamProfileLink(steamUserId); + string profilePictureUrl = await GetProfilePictureAsync(steamUserId, Configs.GetConfigData().Discord_UsersWithNoAvatarImage); + int colorss = int.Parse(Configs.GetConfigData().Discord_SideColor, System.Globalization.NumberStyles.HexNumber); + Color color = Color.FromArgb(colorss >> 16, (colorss >> 8) & 0xFF, colorss & 0xFF); + + var embed = new + { + type = "rich", + color = color.ToArgb() & 0xFFFFFF, + author = new + { + name = STEAMNAME, + url = profileLink, + icon_url = profilePictureUrl + }, + fields = new[] + { + new + { + name = "Date/Time", + value = DateTime.Now.ToString($"{Configs.GetConfigData().Discord_DateFormat} {Configs.GetConfigData().Discord_TimeFormat}"), + inline = false + }, + new + { + name = "Message", + value = message, + inline = false + } + }, + footer = new + { + text = $"Server Ip: {ipadress}", + icon_url = $"{Configs.GetConfigData().Discord_FooterImage}" + } + }; + + 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); + response.EnsureSuccessStatusCode(); + } + catch + { + + } + } + public static async Task GetProfilePictureAsync(string steamId64, string defaultImage) + { + 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("", startIndex); + + if (endIndex >= 0) + { + string profilePictureUrl = xmlResponse.Substring(startIndex, endIndex - startIndex); + return profilePictureUrl; + } + else + { + return defaultImage; + } + } + else + { + return null!; + } + } + catch + { + return null!; + } + } + public static string GetSteamProfileLink(string userId) + { + return $"https://steamcommunity.com/profiles/{userId}"; + } + public static async Task GetServerPublicIPAsync() + { + try + { + HttpResponseMessage response = await httpClient.GetAsync("https://api.ipify.org"); + response.EnsureSuccessStatusCode(); + string responseBody = await response.Content.ReadAsStringAsync(); + return responseBody.Trim(); + } + catch (Exception ex) + { + return "Error retrieving public IP: " + ex.Message; + } + } + public 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 + { + + } + } + catch + { + } + } + +} \ No newline at end of file