Skip to content

Commit

Permalink
support for No Database, custom reason and more
Browse files Browse the repository at this point in the history
  • Loading branch information
1Mack committed Dec 4, 2023
1 parent 8b3d8be commit b5d41c2
Show file tree
Hide file tree
Showing 13 changed files with 257 additions and 179 deletions.
75 changes: 33 additions & 42 deletions CallAdmin.cs
Original file line number Diff line number Diff line change
@@ -1,27 +1,22 @@
using System.Text;
using System.Text.Json;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Modules.Commands;

namespace CallAdmin;

public interface IReportedPlayers
{
string SteamId { get; set; }
string Groups { get; set; }
string Timestamp { get; set; }
string EndDate { get; set; }

}

public class ReportedPlayersClass : IReportedPlayers
public class ReportedPlayersClass
{
public required string SteamId { get; set; }
public required string Groups { get; set; }
public required string Timestamp { get; set; }
public required string EndDate { get; set; }
// Outras propriedades e métodos...
}
public class CustomMessagePlayersClass
{
public required int Player { get; set; }
public int? Target { get; set; }
public required bool HandleMessage { get; set; }
}
[MinimumApiVersion(77)]
public partial class CallAdmin : BasePlugin, IPluginConfig<CallAdminConfig>
Expand All @@ -30,54 +25,50 @@ public partial class CallAdmin : BasePlugin, IPluginConfig<CallAdminConfig>
public override string ModuleName => "CallAdmin";
public override string ModuleDescription => "Report System with database support";
public override string ModuleAuthor => "1MaaaaaacK";
public override string ModuleVersion => "1.4";
public static int ConfigVersion => 3;
public override string ModuleVersion => "1.5";
public static int ConfigVersion => 4;

private string DatabaseConnectionString = string.Empty;

private DateTime[] commandCooldown = new DateTime[Server.MaxPlayers];
private List<ReportedPlayersClass> ReportedPlayers = new();


private List<IReportedPlayers> ReportedPlayers = new();
private List<CustomMessagePlayersClass> CustomMessagePlayers = new();

public override void Load(bool hotReload)
{

AddCommand($"css_{Config.Commands.ReportPrefix}", "Report a player", ReportCommand);
AddCommand($"css_{Config.Commands.ReportHandledPrefix}", "Handle Report", ReportHandledCommand);

BuildDatabaseConnectionString();
TestDatabaseConnection();
AddCommandListener("say", OnPlayerChat);
AddCommandListener("say_team", OnPlayerChat);
if (Config.Commands.ReportHandledEnabled)
{
BuildDatabaseConnectionString();
TestDatabaseConnection();
}

}
public async Task<string> SendMessageToDiscord(dynamic json, string? messageId = null)


private HookResult OnPlayerChat(CCSPlayerController? player, CommandInfo info)
{
if (player == null || !player.IsValid || player.IsBot) return HookResult.Continue;
var findPlayer = CustomMessagePlayers.Find(obj => obj.Player == (int)player.Index);

try
{
var httpClient = new HttpClient();
var content = new StringContent(json, Encoding.UTF8, "application/json");
if (findPlayer == null || !findPlayer.HandleMessage || findPlayer.Target == null ||
info.GetArg(1).StartsWith("!") || info.GetArg(1).StartsWith("/") || info.GetArg(1) == "rtv") return HookResult.Continue;

var result = string.IsNullOrEmpty(messageId) ? httpClient.PostAsync($"{Config.WebHookUrl}?wait=true", content).Result : httpClient.PatchAsync($"{Config.WebHookUrl}/messages/{messageId}", content).Result;
var findTarget = Utilities.GetPlayerFromIndex((int)findPlayer.Target);

if (!result.IsSuccessStatusCode)
{
Console.WriteLine(result);
return "There was an error sending the webhook";
}
_ = HandleSentToDiscordAsync(player, findTarget, info.ArgString.Replace("\"", ""));

var toJson = JsonSerializer.Deserialize<IWebHookSuccess>(await result.Content.ReadAsStringAsync());
return string.IsNullOrEmpty(toJson?.id) ? "Unable to get message ID" : toJson.id;
findPlayer.Target = null;
findPlayer.HandleMessage = false;

}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public class IWebHookSuccess
{
public required string id { get; set; }
return HookResult.Handled;
}


Expand Down
105 changes: 105 additions & 0 deletions Commands/Report.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Admin;
using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Cvars;
using CounterStrikeSharp.API.Modules.Menu;

namespace CallAdmin
{
public partial class CallAdmin
{
public void ReportCommand(CCSPlayerController? player, CommandInfo command)
{
if (player == null || !player.IsValid || player.IsBot) return;

if (!string.IsNullOrEmpty(Config.Commands.ReportPermission) && !AdminManager.PlayerHasPermissions(player, Config.Commands.ReportPermission.Split(";")))
{
command.ReplyToCommand($"{Config.Prefix} {Config.ChatMessages.MissingCommandPermission}");
return;
}

int playerIndex = (int)player.Index;

if (commandCooldown != null && DateTime.UtcNow >= commandCooldown[playerIndex].AddSeconds(Config.CooldownRefreshCommandSeconds))
{

commandCooldown[playerIndex] = DateTime.UtcNow;

ChatMenu reportMenu = new(Config.ChatMenuMessages.PlayersTitle);

foreach (var playerOnServer in Utilities.GetPlayers())
{
if (playerOnServer.IsBot || playerOnServer.Index == player.Index) continue;

reportMenu.AddMenuOption($"{playerOnServer.PlayerName} [{playerOnServer.Index}]", HandleMenu);
}

if (reportMenu.MenuOptions.Count == 0)
{
command.ReplyToCommand($"{Config.Prefix} {Config.ChatMessages.NoPlayersAvailable}");
return;
}
ChatMenus.OpenMenu(player, reportMenu);
return;
}

command.ReplyToCommand($"{Config.Prefix} {Config.ChatMessages.InCoolDown}");

}

private void HandleMenu(CCSPlayerController player, ChatMenuOption option)
{
var parts = option.Text.Split('[', ']');
var lastPart = parts[parts.Length - 2];
var numbersOnly = string.Join("", lastPart.Where(char.IsDigit));

var index = int.Parse(numbersOnly.Trim());
var reasons = Config.Reasons.Split(";");
var reasonMenu = new ChatMenu(Config.ChatMenuMessages.ReasonsTitle);
reasonMenu.MenuOptions.Clear();
foreach (var reason in reasons)
{
reasonMenu.AddMenuOption($"{reason.Replace("{CUSTOMREASON}", "")} [{index}{(reason.Contains("{CUSTOMREASON}") == true ? "-c" : "")}]", HandleMenu2Async);
}

ChatMenus.OpenMenu(player, reasonMenu);
}

private async void HandleMenu2Async(CCSPlayerController player, ChatMenuOption option)
{
var parts = option.Text.Split('[', ']');
var lastPart = parts[^2];

if (lastPart.Contains("-c"))
{

var findPlayer = CustomMessagePlayers.Find(obj => obj.Player == (int)player.Index);
if (findPlayer == null)
CustomMessagePlayers.Add(new CustomMessagePlayersClass
{
HandleMessage = true,
Player = (int)player.Index,
Target = int.Parse(lastPart.Replace("-c", "").Trim())

});
else
{
findPlayer.HandleMessage = true;
findPlayer.Target = int.Parse(lastPart.Replace("-c", "").Trim());
}
player.PrintToChat($"{Config.Prefix} {Config.ChatMessages.CustomReason}");
return;
}
else
{
var target = Utilities.GetPlayerFromIndex(int.Parse(lastPart.Replace("-c", "").Trim()));

await HandleSentToDiscordAsync(player, target, parts[0]);
}

}


}
}
63 changes: 63 additions & 0 deletions Commands/ReportHandled.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Admin;
using CounterStrikeSharp.API.Modules.Commands;

namespace CallAdmin
{
public partial class CallAdmin
{
[CommandHelper(minArgs: 1, usage: "[identifier]", whoCanExecute: CommandUsage.CLIENT_ONLY)]
public async void ReportHandledCommand(CCSPlayerController? player, CommandInfo command)
{
if (player == null || !player.IsValid || player.IsBot || !Config.Commands.ReportHandledEnabled) return;



if (!string.IsNullOrEmpty(Config.Commands.ReportHandledPermission) && !AdminManager.PlayerHasPermissions(player, Config.Commands.ReportHandledPermission.Split(";").Select(space => space.Trim()).ToArray()))
{
command.ReplyToCommand($"{Config.Prefix} {Config.ChatMessages.MissingCommandPermission}");
return;
}

int playerIndex = (int)player.Index;

if (commandCooldown != null && DateTime.UtcNow >= commandCooldown[playerIndex].AddSeconds(Config.CooldownRefreshCommandSeconds))
{

commandCooldown[playerIndex] = DateTime.UtcNow;

string identifier = command.ArgString.Split(" ")[0].Trim();

var query = await GetReportDatabase(identifier);

if (query == null)
{
command.ReplyToCommand($"{Config.Prefix} {Config.ChatMessages.ReportNotFound}");
return;
}

string result = await SendMessageToDiscord(Payload(query.victim_name, query.victim_steamid, query.suspect_name,
query.suspect_steamid, query.host_name, query.host_ip, query.reason, identifier, Config.EmbedMessages.Content, player.PlayerName, player.SteamID.ToString()), query.message_id);

if (!result.All(char.IsDigit))
{
player.PrintToChat($"{Config.Prefix} {Config.ChatMessages.WebhookError}");
Console.WriteLine(result);
return;
}

bool executeResult = await UpdateReportDatabase(identifier, player.PlayerName, player.SteamID.ToString());

if (!executeResult)
player.PrintToChat($"{Config.Prefix} {Config.ChatMessages.MarkedAsHandledButNotInDatabase}");

player.PrintToChat($"{Config.Prefix} {Config.ChatMessages.ReportMarkedAsHandled}");

return;
}

command.ReplyToCommand($"{Config.Prefix} {Config.ChatMessages.InCoolDown}");

}
}
}
34 changes: 19 additions & 15 deletions Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public void OnConfigParsed(CallAdminConfig config)
{
if (config.Version != ConfigVersion) throw new Exception($"You have a wrong config version. Delete it and restart the server to get the right version ({ConfigVersion})!");

if (string.IsNullOrEmpty(config.Database.Host) || string.IsNullOrEmpty(config.Database.Name) || string.IsNullOrEmpty(config.Database.User))
if (config.Commands.ReportHandledEnabled && (string.IsNullOrEmpty(config.Database.Host) || string.IsNullOrEmpty(config.Database.Name) || string.IsNullOrEmpty(config.Database.User)))
{
throw new Exception($"You need to setup Database credentials in config!");
}
Expand Down Expand Up @@ -43,7 +43,7 @@ public void OnConfigParsed(CallAdminConfig config)
Config = config;

}
private string ChatTags(CallAdminConfig config, string input)
private static string ChatTags(CallAdminConfig config, string input)
{
Dictionary<string, dynamic> tags = new()
{
Expand Down Expand Up @@ -81,18 +81,18 @@ private string ChatTags(CallAdminConfig config, string input)
}
public class CallAdminConfig : BasePluginConfig
{
public override int Version { get; set; } = 3;
public override int Version { get; set; } = 4;

[JsonPropertyName("Prefix")]
public string Prefix { get; set; } = "{DEFAULT}[{GREEN}CallAdmin{DEFAULT}]";
[JsonPropertyName("ServerIpWithPort")]
public string ServerIpWithPort { get; set; } = "111.222.333.444:56789";
public string ServerIpWithPort { get; set; } = "";
[JsonPropertyName("CooldownRefreshCommandSeconds")]
public int CooldownRefreshCommandSeconds { get; set; } = 60;
[JsonPropertyName("Reasons")]
public string Reasons { get; set; } = "Hack;Toxic;Camping";
public string Reasons { get; set; } = "Hack;Toxic;Camping;Your Custom Reason{CUSTOMREASON}";
[JsonPropertyName("WebHookUrl")]
public string WebHookUrl { get; set; } = "https://discord.com/api/webhooks/id/token";
public string WebHookUrl { get; set; } = "";
[JsonPropertyName("Database")]
public Database Database { get; set; } = new();
[JsonPropertyName("Commands")]
Expand All @@ -101,6 +101,8 @@ public class CallAdminConfig : BasePluginConfig
public ChatMessages ChatMessages { get; set; } = new();
[JsonPropertyName("EmbedMessages")]
public EmbedMessages EmbedMessages { get; set; } = new();
[JsonPropertyName("ChatMenuMessages")]
public ChatMenuMessages ChatMenuMessages { get; set; } = new();
}
public class Database
{
Expand All @@ -124,22 +126,15 @@ public class Commands

[JsonPropertyName("ReportPermission")]
public string ReportPermission { get; set; } = "";
[JsonPropertyName("ReportHandledEnabled")]
public bool ReportHandledEnabled { get; set; } = true;

[JsonPropertyName("ReportHandledPrefix")]
public string ReportHandledPrefix { get; set; } = "report_handled";

[JsonPropertyName("ReportHandledPermission")]
public string ReportHandledPermission { get; set; } = "@css/generic;@css/ban";

}
public class CommandsPrefix
{
[JsonPropertyName("Report")]
public string Report { get; set; } = "report";

[JsonPropertyName("ReportHandled")]
public string ReportHandled { get; set; } = "report_handled";

}
public class ChatMessages
{
Expand Down Expand Up @@ -169,6 +164,8 @@ public class ChatMessages

[JsonPropertyName("ReportMarkedAsHandled")]
public string ReportMarkedAsHandled { get; set; } = "{DEFAULT}This report has been marked as handled!";
[JsonPropertyName("CustomReason")]
public string CustomReason { get; set; } = "{DEFAULT}Type the reason for the report";
}
public class EmbedMessages
{
Expand Down Expand Up @@ -204,4 +201,11 @@ public class EmbedMessages
[JsonPropertyName("Content")]
public string Content { get; set; } = "You can write anything here or leave it blank. Ping a member like this: <@MemberId> or a role: <@&RoleID>";
}
public class ChatMenuMessages
{
[JsonPropertyName("ReasonsTitle")]
public string ReasonsTitle { get; set; } = "[REPORT] Choose a Reason";
[JsonPropertyName("PlayersTitle")]
public string PlayersTitle { get; set; } = "[REPORT] Choose a Player";
}
}
3 changes: 2 additions & 1 deletion Database.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ private void BuildDatabaseConnectionString()
Password = Config.Database.Password,
Database = Config.Database.Name,
Port = (uint)Config.Database.Port,
ConvertZeroDateTime = true
ConvertZeroDateTime = true,
SslMode = MySqlSslMode.Preferred
};

DatabaseConnectionString = builder.ConnectionString;
Expand Down

0 comments on commit b5d41c2

Please sign in to comment.