Skip to content

Commit

Permalink
v2.1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
NockyCZ committed Oct 9, 2024
1 parent bb073e5 commit 54f7d27
Show file tree
Hide file tree
Showing 7 changed files with 138 additions and 50 deletions.
112 changes: 76 additions & 36 deletions src/DiscordUtilities/DiscordUtilities.cs
Original file line number Diff line number Diff line change
@@ -1,33 +1,29 @@
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Timers;
using CounterStrikeSharp.API.Core.Attributes;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Microsoft.Extensions.DependencyInjection;
using CounterStrikeSharp.API.Core.Capabilities;
using DiscordUtilitiesAPI.Events;
using System.Data.Common;

namespace DiscordUtilities
{
[MinimumApiVersion(202)]
public partial class DiscordUtilities : BasePlugin, IPluginConfig<DUConfig>
{
public override string ModuleName => "Discord Utilities";
public override string ModuleAuthor => "Nocky (SourceFactory.eu)";
public override string ModuleVersion => "2.0.9";
public override string ModuleVersion => "2.1.0";
public void OnConfigParsed(DUConfig config)
{
Config = config;
}
public override void OnAllPluginsLoaded(bool hotReload)
{
_ = LoadVersions();
_ = LoadDiscordBOT();
if (!string.IsNullOrEmpty(Config.Database.Password) && !string.IsNullOrEmpty(Config.Database.Host) && !string.IsNullOrEmpty(Config.Database.DatabaseName) && !string.IsNullOrEmpty(Config.Database.User))
{
_ = LoadDiscordBOT();
databaseData = new DatabaseConnection
{
Server = Config.Database.Host,
Expand All @@ -37,30 +33,31 @@ public override void OnAllPluginsLoaded(bool hotReload)
Password = Config.Database.Password,
};
_ = CreateDatabaseConnection();
}
else
{
Perform_SendConsoleMessage($"You need to setup Database credentials in config", ConsoleColor.Red);
throw new Exception("Database connection information is missing!");
}

if (string.IsNullOrEmpty(Config.ServerID))
{
Perform_SendConsoleMessage($"Invalid Discord Server ID!", ConsoleColor.Red);
throw new Exception("Invalid Discord Server ID");
}

int counter = 0;
while (!IsBotConnected)
{
counter++;
if (counter > 5)
if (string.IsNullOrEmpty(Config.ServerID) || !ulong.TryParse(Config.ServerID, out _))
{
Perform_SendConsoleMessage($"Discord BOT failed to connect!", ConsoleColor.Red);
throw new Exception("Discord BOT failed to connect");
Perform_SendConsoleMessage("Invalid Discord Server ID!", ConsoleColor.Red);
}
Perform_SendConsoleMessage($"Loading Discord BOT...", ConsoleColor.DarkYellow);
Thread.Sleep(3000);
else
{
int counter = 0;
while (!IsBotConnected)
{
counter++;
if (counter > 5)
{
Perform_SendConsoleMessage("Discord BOT failed to connect!", ConsoleColor.Red);
break;
}
else
Perform_SendConsoleMessage("Loading Discord BOT...", ConsoleColor.DarkYellow);
Thread.Sleep(3000);
}
}
}
else
{
Perform_SendConsoleMessage("You need to setup Database credentials in config", ConsoleColor.Red);
}
}
public override void Load(bool hotReload)
Expand All @@ -72,6 +69,7 @@ public override void Load(bool hotReload)
if (Config.UseCustomVariables)
LoadCustomConditions();

_ = LoadVersions();
_ = LoadMapImages();
IsDbConnected = false;
IsBotConnected = false;
Expand All @@ -93,7 +91,7 @@ public override void Load(bool hotReload)
mapStarted = true;
Server.ExecuteCommand("sv_hibernate_when_empty false");
playerData.Clear();
AddTimer(3.0f, () =>
AddTimer(4.0f, () =>
{
if (Config.TimedRoles)
CheckExpiredTimedRoles();
Expand Down Expand Up @@ -162,17 +160,16 @@ private async Task ReadyAsync()
Perform_SendConsoleMessage($"Guild with id '{ServerId}' was not found!", ConsoleColor.Red);
}

string ActivityFormat = ReplaceServerDataVariables(Config.BotStatus.ActivityFormat);
//await BotClient!.SetGameAsync(ActivityFormat, null, (ActivityType)Config.BotStatus.ActivityType);

var ActivityFormat = ReplaceServerDataVariables(Config.BotStatus.ActivityFormat);
await BotClient!.SetActivityAsync(new Game(ActivityFormat, (ActivityType)Config.BotStatus.ActivityType, ActivityProperties.None));
await BotClient.SetStatusAsync((UserStatus)Config.BotStatus.Status);

BotClient.SlashCommandExecuted += SlashCommandHandler;
BotClient.MessageReceived += MessageReceivedHandler;
BotClient.InteractionCreated += InteractionCreatedHandler;
BotClient.GuildScheduledEventCreated += ScheduledEventCreated;
//BotClient.SentRequest += OnSentRequest;
BotClient.GuildMemberUpdated += GuildMemberUpdated;
BotClient.UserLeft += GuildMemberLeft;

var linkCommand = new SlashCommandBuilder()
.WithName(Config.Link.LinkDiscordSettings.Name.ToLower())
Expand Down Expand Up @@ -202,11 +199,54 @@ private async Task ReadyAsync()
throw new Exception($"An error occurred while updating Link Slash Commands: {ex.Message}");
}
}
/*private Task OnSentRequest(string method, string endpoint, double duration)

private async Task GuildMemberLeft(SocketGuild guild, SocketUser user)
{
Console.WriteLine($"Request sent: Method = {method}, Endpoint = {endpoint}, Duration = {duration}ms");
return Task.CompletedTask;
}*/
if (Config.Link.Enabled && Config.Link.ResponseServer)
{
if (linkedPlayers.ContainsValue(user.Id))
{
var steamId = linkedPlayers.FirstOrDefault(x => x.Value == user.Id).Key;
if (linkedPlayers.ContainsKey(steamId))
{
await RemovePlayerData(steamId.ToString());
await CreateScheduledEventAsync("refreshlinkedplayers");
}
}
}
}

private async Task GuildMemberUpdated(Cacheable<SocketGuildUser, ulong> before, SocketGuildUser after)
{
if (!linkedPlayers.ContainsValue(after.Id))
return;

var beforeGuildUser = await before.GetOrDownloadAsync();

var beforeRoles = beforeGuildUser.Roles.Select(r => r.Id).ToList();
var afterRoles = after.Roles.Select(r => r.Id).ToList();

var addedRoles = afterRoles
.Except(beforeRoles)
.Select(role => role.ToString())
.ToList();

var removedRoles = beforeRoles
.Except(afterRoles)
.Select(role => role.ToString())
.ToList();

Server.NextFrame(() =>
{
var user = GetUserDataByUserID(after.Id);
if (user == null)
return;
DiscordUtilitiesAPI.Get()?.TriggerEvent(new LinkedUserRolesUpdated(user, addedRoles, removedRoles));
if (IsDebug)
Perform_SendConsoleMessage("New Event Triggered: 'LinkedUserRolesUpdated'", ConsoleColor.Cyan);
});
}

public async Task CreateScheduledEventAsync(string eventData)
{
Expand Down
11 changes: 8 additions & 3 deletions src/DiscordUtilities/Functions/Commands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using CounterStrikeSharp.API.Modules.Commands;
using Discord;
using DiscordUtilitiesAPI.Events;
using DiscordUtilitiesAPI.Helpers;

namespace DiscordUtilities
{
Expand Down Expand Up @@ -56,17 +57,21 @@ public void GetPlayerData_CMD(CCSPlayerController player, CommandInfo info)
{
cmdOverrides.Append("None");
}
var userId = linkedPlayers.ContainsKey(target.AuthorizedSteamID!.SteamId64) ? linkedPlayers[target.AuthorizedSteamID!.SteamId64].ToString() : "Not Found";
var user = GetUserDataByUserID(ulong.Parse(userId));

UserData? user = null;
if (linkedPlayers.TryGetValue(target.AuthorizedSteamID!.SteamId64, out var userId))
user = GetUserDataByUserID(userId);

info.ReplyToCommand("========================================");
info.ReplyToCommand("Discord Utilities • Player Data");
info.ReplyToCommand(" ");
info.ReplyToCommand($"• Player: {target.PlayerName}");
info.ReplyToCommand($"• Linked: {linkedPlayers.ContainsKey(target.AuthorizedSteamID!.SteamId64)}");
if (user != null)
{
info.ReplyToCommand($"• Discord User: {user.DisplayName}");
info.ReplyToCommand($"• Discord User ID: {userId}");
info.ReplyToCommand($"• Discord User ID: {userId}");
}
info.ReplyToCommand($"• Flags: {flags}");
info.ReplyToCommand($"• Command Overrides: {cmdOverrides}");
info.ReplyToCommand($"• Immunity: {immunity}");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ public record SlashCommandExecuted(CommandData Command, UserData User) : IDiscor
public record InteractionCreated(InteractionData Interaction, UserData User) : IDiscordUtilitiesEvent;
public record ModalSubmited(ModalData ModalData, UserData User) : IDiscordUtilitiesEvent;
public record LinkedUserDataLoaded(UserData User, CCSPlayerController player) : IDiscordUtilitiesEvent;
public record LinkedUserRolesUpdated(UserData User, List<string>? addedRoles, List<string>? removedRoles) : IDiscordUtilitiesEvent;
public record PlayerDataLoaded(CCSPlayerController player) : IDiscordUtilitiesEvent;
public record BotLoaded() : IDiscordUtilitiesEvent;
public record ServerDataLoaded() : IDiscordUtilitiesEvent;
Expand Down
2 changes: 1 addition & 1 deletion src/Modules/ManageRolesAndPermissions/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ namespace ManageRolesAndPermissions;
public class Config : BasePluginConfig
{
[JsonPropertyName("Remove Roles On Permission Loss")] public bool removeRolesOnPermissionLoss { get; set; } = false;
[JsonPropertyName("Remove Permissions On Role Loss")] public bool removePermissionsOnRoleLoss { get; set; } = false;
[JsonPropertyName("Role To Permission")]
public Dictionary<string, RoleGroupData> RoleToPermission { get; set; } = new Dictionary<string, RoleGroupData>()
{
Expand All @@ -23,7 +24,6 @@ public class Config : BasePluginConfig
command_overrides = { { "css_slay", true } }
}
};

[JsonPropertyName("Permission To Role")]
public Dictionary<string, string> PermissionToRole { get; set; } = new Dictionary<string, string>()
{
Expand Down
45 changes: 42 additions & 3 deletions src/Modules/ManageRolesAndPermissions/ManageRolesAndPermissions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@

using System.Text;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Capabilities;
using CounterStrikeSharp.API.Modules.Admin;
Expand Down Expand Up @@ -44,14 +45,52 @@ private void DiscordUtilitiesEventHandler(object? _, IDiscordUtilitiesEvent @eve
{
switch (@event)
{
case LinkedUserDataLoaded linkedUser:
OnLinkedUserDataLoaded(linkedUser.User, linkedUser.player);
case LinkedUserDataLoaded data:
OnLinkedUserDataLoaded(data.User, data.player);
break;
case LinkedUserRolesUpdated data:
OnLinkedUserRolesUpdated(data.User, data.removedRoles);
break;
default:
break;
}
}

private void OnLinkedUserRolesUpdated(UserData user, List<string>? removedRoles)
{
if (!Config.removePermissionsOnRoleLoss || removedRoles == null || removedRoles.Count == 0)
return;

var steamId = DiscordUtilities!.GetLinkedPlayers().FirstOrDefault(x => x.Value == user.ID).Key;
var player = Utilities.GetPlayerFromSteamId(steamId);

if (player == null || !player.IsValid)
return;

var permsToRemoveByRole = new List<string>();
foreach (var role in removedRoles)
{
if (Config.RoleToPermission.ContainsKey(role))
permsToRemoveByRole.Add(role);
}

if (permsToRemoveByRole.Count == 0)
return;

foreach (var role in permsToRemoveByRole)
{
if (Config.RoleToPermission.TryGetValue(role, out var data))
{
AdminManager.RemovePlayerPermissions(player, data.flags.ToArray());
foreach (var cmdOverride in data.command_overrides)
{
AdminManager.SetPlayerCommandOverride(player, cmdOverride.Key, !cmdOverride.Value);
}
}
}
AdminManager.SetPlayerImmunity(player, 0);
}

private void OnLinkedUserDataLoaded(UserData user, CCSPlayerController player)
{
if (Config.RoleToPermission.Count > 0)
Expand All @@ -61,7 +100,7 @@ private void OnLinkedUserDataLoaded(UserData user, CCSPlayerController player)

user.RolesIds.ForEach(roleID =>
{
if (Config.RoleToPermission.TryGetValue(roleID.ToString(), out RoleGroupData? roleGroupData))
if (Config.RoleToPermission.TryGetValue(roleID.ToString(), out var roleGroupData))
{
if (roleGroupData != null)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Modules/Report/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ public class Config : BasePluginConfig
{
[JsonPropertyName("Report Commands")] public string ReportCommands { get; set; } = "report,calladmin";
[JsonPropertyName("Reports List Commands")] public string ReportsListCommands { get; set; } = "reports,reportslist";
[JsonPropertyName("Blocked Words In Reason")] public string BlockedReason { get; set; } = "idiot,test,rtv,nominate,ws";
[JsonPropertyName("Blocked Words In Reason")] public string BlockedReason { get; set; } = "idiot,test,rtv,nominate";
[JsonPropertyName("Allow Ingame Reports List")] public bool ReportsListMenu { get; set; } = true;
[JsonPropertyName("Allow Self Report")] public bool SelfReport { get; set; } = false;
[JsonPropertyName("Report Expiration")] public int ReportExpiration { get; set; } = 120;
Expand Down
15 changes: 9 additions & 6 deletions src/Modules/Report/Report.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,14 +115,17 @@ private HookResult OnPlayerSay(CCSPlayerController? player, CommandInfo info)
}

var blockedReasons = Config.BlockedReason.Trim().ToLower().Split(",").ToList();
var reasonsList = reason.ToLower().Split(" ").ToList();
foreach (var x in reasonsList)
if (blockedReasons.Count > 0)
{
if (blockedReasons.Contains(x))
var reasonsList = reason.ToLower().Split(" ").ToList();
foreach (var x in reasonsList)
{
player.PrintToChat($"{Localizer["Chat.Prefix"]} {Localizer["Chat.ReportBlockedReason", x]}");
performReport.Remove(player);
return HookResult.Handled;
if (blockedReasons.Contains(x))
{
player.PrintToChat($"{Localizer["Chat.Prefix"]} {Localizer["Chat.ReportBlockedReason", x]}");
performReport.Remove(player);
return HookResult.Handled;
}
}
}
SendReport(player, performReport[player], reason);
Expand Down

0 comments on commit 54f7d27

Please sign in to comment.