Skip to content

Commit

Permalink
Update v2.0.9
Browse files Browse the repository at this point in the history
  • Loading branch information
NockyCZ committed Aug 28, 2024
1 parent 6085782 commit 2fc47ee
Show file tree
Hide file tree
Showing 16 changed files with 788 additions and 389 deletions.
46 changes: 40 additions & 6 deletions src/DiscordUtilities/API/Events.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,17 @@ public void TriggerEvent(IDiscordUtilitiesEvent @event)
{
DiscordUtilitiesEventHandlers?.Invoke(this, @event);
}

public void ExecuteCustomCommands(string server, List<string> Commands)
{
Server.NextFrame(() =>
{
DiscordUtilitiesAPI.Get()?.TriggerEvent(new ExecuteCustomCommands(server, Commands));
if (IsDebug)
Perform_SendConsoleMessage("New Event Triggered: 'ExecuteCustomCommands'", ConsoleColor.Cyan);
});
}

public void PlayerDataLoaded(CCSPlayerController player)
{
Server.NextFrame(() =>
Expand Down Expand Up @@ -63,12 +74,35 @@ public void BotLoaded()
public void Event_SlashCommand(SocketSlashCommand command)
{
var interactionId = int.Parse(GetRandomCode(6, true));
var optionsData = command.Data.Options.Select(option => new CommandOptionsData

List<CommandOptionsData> optionsData = new();
foreach (var option in command.Data.Options)
{
Name = option.Name.ToLower(),
Value = option.Value.ToString() ?? "",
Type = (SlashCommandOptionsType)option.Type
}).ToList();
string? value = "";
if (option.Type == ApplicationCommandOptionType.User)
{
var targetUser = (SocketUser)option.Value;
if (targetUser != null)
value = targetUser.Id.ToString();
}
else if (option.Type == ApplicationCommandOptionType.Role)
{
var targetRole = (SocketRole)option.Value;
if (targetRole != null)
value = targetRole.Id.ToString();
}
else
{
value = option.Value.ToString();
}

optionsData.Add(new CommandOptionsData
{
Name = option.Name.ToLower(),
Value = value != null ? value : "",
Type = (SlashCommandOptionsType)option.Type
});
}

ulong? guildId = command.GuildId != null ? command.GuildId.Value : null;

Expand Down Expand Up @@ -196,7 +230,7 @@ public void Event_ModalSubmited(SocketInteraction interaction)
ID = user != null ? user.Id : interaction.User.Id,
RolesIds = user != null ? user.Roles.Select(role => role.Id).ToList() : new(),
};

if (!savedInteractions.ContainsKey(interactionId))
savedInteractions.Add(interactionId, modalInteraction);

Expand Down
6 changes: 2 additions & 4 deletions src/DiscordUtilities/API/Players.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,7 @@ public void AddRolesToUser(ulong userId, List<string> rolesIds)
var socketUser = guild.GetUser(userId);
if (socketUser == null)
{
if (IsDebug)
Perform_SendConsoleMessage($"AddRolesToUser - User with ID '{userId}' was not found on the Discord server!", ConsoleColor.Cyan);
Perform_SendConsoleMessage($"AddRolesToUser - User with ID '{userId}' was not found on the Discord server!", ConsoleColor.Cyan);
return;
}

Expand Down Expand Up @@ -129,8 +128,7 @@ public void RemoveRolesFromUser(ulong userId, List<string> rolesIds)
var socketUser = guild.GetUser(userId);
if (socketUser == null)
{
if (IsDebug)
Perform_SendConsoleMessage($"'RemoveRolesFromUser' - User with ID '{userId}' was not found on the Discord server!", ConsoleColor.Cyan);
Perform_SendConsoleMessage($"'RemoveRolesFromUser' - User with ID '{userId}' was not found on the Discord server!", ConsoleColor.Cyan);
return;
}

Expand Down
54 changes: 42 additions & 12 deletions src/DiscordUtilities/Configs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public class DUConfig : BasePluginConfig
[JsonPropertyName("Server IP")] public string ServerIP { get; set; } = "0.0.0.0:00000";
[JsonPropertyName("Use Custom Variables")] public bool UseCustomVariables { get; set; } = true;
[JsonPropertyName("Date Format")] public string DateFormat { get; set; } = "yyyy-MM-dd HH:mm:ss";
[JsonPropertyName("Allow Timed Roles")] public bool TimedRoles { get; set; } = false;
[JsonPropertyName("Database Connection")] public Database Database { get; set; } = new Database();
[JsonPropertyName("BOT Status")] public BotStatus BotStatus { get; set; } = new BotStatus();
[JsonPropertyName("Link System")] public Link Link { get; set; } = new Link();
Expand Down Expand Up @@ -64,25 +65,54 @@ public class Database
public class Link
{
[JsonPropertyName("Enabled")] public bool Enabled { get; set; } = false;
[JsonPropertyName("Response Server")] public bool ResponseServer { get; set; } = true;
[JsonPropertyName("Response Server")] public bool ResponseServer { get; set; } = false;
[JsonPropertyName("Code Length")] public int CodeLength { get; set; } = 7;
[JsonPropertyName("Ingame Link Commands")] public string IngameLinkCommands { get; set; } = "link,discord";
[JsonPropertyName("Ingame Unlink Commands")] public string IngameUnlinkCommands { get; set; } = "unlink,logout";
[JsonPropertyName("Discord Link Command")] public string DiscordCommand { get; set; } = "link";
[JsonPropertyName("Discord Link Description")] public string DiscordDescription { get; set; } = "Link your Discord profile with your Steam Account";
[JsonPropertyName("Discord Link Option Description")] public string DiscordOptionDescription { get; set; } = "Insert your link code";
[JsonPropertyName("Discord Link Option Name")] public string DiscordOptionName { get; set; } = "code";
[JsonPropertyName("Link Ingame Permissions")] public string LinkPermissions { get; set; } = "@discord_utilities/linked";
[JsonPropertyName("Ingame Settings")] public LinkIngameSettings LinkIngameSettings { get; set; } = new();
[JsonPropertyName("Discord Settings")] public LinkDiscordSettings LinkDiscordSettings { get; set; } = new();
[JsonPropertyName("Link Embeds")] public LinkEmbed LinkEmbed { get; set; } = new();
}

public class LinkIngameSettings
{
[JsonPropertyName("Link Commands")] public List<string> LinkCommands { get; set; } = new() { "link", "discord" };
[JsonPropertyName("Unlink Commands")] public List<string> UnlinkCommands { get; set; } = new() { "unlink", "logout" };
[JsonPropertyName("Link Permissions")] public string Flag { get; set; } = "@du/linked";
[JsonPropertyName("Send Message to Player After Linking")] public bool SendLinkedMessageToPlayer { get; set; } = true;
[JsonPropertyName("Send Message to All After Linking")] public bool SendLinkedMessageToAll { get; set; } = true;
[JsonPropertyName("Profile Linked Sound Effect")] public string LinkedSound { get; set; } = "sounds/ui/xp_levelup.vsnd_c";
}

public class LinkDiscordSettings
{
[JsonPropertyName("Command Name")] public string Name { get; set; } = "link";
[JsonPropertyName("Command Description")] public string Description { get; set; } = "Link your Discord profile with your Steam Account";
[JsonPropertyName("Command Option Name")] public string OptionName { get; set; } = "code";
[JsonPropertyName("Command Option Description")] public string OptionDescription { get; set; } = "Insert your link code";
[JsonPropertyName("Send Embed to All After Linking (Channel ID)")] public string SendLinkedMessageToAll { get; set; } = "";
[JsonPropertyName("Link Role ID")] public string LinkRole { get; set; } = "";
[JsonPropertyName("Link Embed")] public LinkEmbed LinkEmbed { get; set; } = new LinkEmbed();
}

public class LinkEmbed
{
[JsonPropertyName("Success Embed")] public Success Success { get; set; } = new Success();
[JsonPropertyName("Failed Embed")] public Failed Failed { get; set; } = new Failed();
[JsonPropertyName("Already Linked Embed")] public AlreadyLinked AlreadyLinked { get; set; } = new AlreadyLinked();
[JsonPropertyName("Success Embed")] public Success Success { get; set; } = new();
[JsonPropertyName("Failed Embed")] public Failed Failed { get; set; } = new();
[JsonPropertyName("Already Linked Embed")] public AlreadyLinked AlreadyLinked { get; set; } = new();
[JsonPropertyName("User Linked (All) Embed")] public UserLinkedAll UserLinkedAll { get; set; } = new();
}

public class UserLinkedAll
{
[JsonPropertyName("Content")] public string Content { get; set; } = "";
[JsonPropertyName("Title")] public string Title { get; set; } = "";
[JsonPropertyName("Description")] public string Description { get; set; } = "> User **{DiscordUser.DisplayName}** (<@{DiscordUser.ID}>) has successfully linked his [Steam account](<https://steamcommunity.com/profiles/{STEAM}>)\n-# Do you also want to link your account? Type `/link` on any of our CS2 servers!";
[JsonPropertyName("Fields")] public string Fields { get; set; } = "";
[JsonPropertyName("Thumbnail")] public string Thumbnail { get; set; } = "";
[JsonPropertyName("Image")] public string Image { get; set; } = "";
[JsonPropertyName("HEX Color")] public string Color { get; set; } = "#ffff66";
[JsonPropertyName("Footer")] public string Footer { get; set; } = "";
[JsonPropertyName("Footer Timestamp")] public bool FooterTimestamp { get; set; } = false;
}

public class Success
{
[JsonPropertyName("Content")] public string Content { get; set; } = "";
Expand Down
74 changes: 64 additions & 10 deletions src/DiscordUtilities/DiscordUtilities.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
using CounterStrikeSharp.API;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Timers;
using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Modules.Cvars;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Microsoft.Extensions.DependencyInjection;
using CounterStrikeSharp.API.Core.Capabilities;
using System.Text;
using DiscordUtilitiesAPI.Events;
using System.Data.Common;

namespace DiscordUtilities
{
Expand All @@ -17,7 +17,7 @@ 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.8";
public override string ModuleVersion => "2.0.9";
public void OnConfigParsed(DUConfig config)
{
Config = config;
Expand Down Expand Up @@ -95,6 +95,9 @@ public override void Load(bool hotReload)
playerData.Clear();
AddTimer(3.0f, () =>
{
if (Config.TimedRoles)
CheckExpiredTimedRoles();
UpdateServerData();
serverData.MapName = mapName;
serverData.GameDirectory = Server.GameDirectory;
Expand Down Expand Up @@ -123,7 +126,7 @@ private async Task LoadDiscordBOT()
{
AlwaysDownloadUsers = true,
UseInteractionSnowflakeDate = false,
GatewayIntents = GatewayIntents.MessageContent | GatewayIntents.Guilds | GatewayIntents.GuildMessages | GatewayIntents.GuildMembers
GatewayIntents = GatewayIntents.MessageContent | GatewayIntents.Guilds | GatewayIntents.GuildMessages | GatewayIntents.GuildMembers | GatewayIntents.GuildScheduledEvents
});

BotCommands = new CommandService();
Expand Down Expand Up @@ -168,11 +171,13 @@ private async Task ReadyAsync()
BotClient.SlashCommandExecuted += SlashCommandHandler;
BotClient.MessageReceived += MessageReceivedHandler;
BotClient.InteractionCreated += InteractionCreatedHandler;
BotClient.GuildScheduledEventCreated += ScheduledEventCreated;
//BotClient.SentRequest += OnSentRequest;

var linkCommand = new SlashCommandBuilder()
.WithName(Config.Link.DiscordCommand.ToLower())
.WithDescription(Config.Link.DiscordDescription)
.AddOption(Config.Link.DiscordOptionName.ToLower(), ApplicationCommandOptionType.String, Config.Link.DiscordOptionDescription, isRequired: true);
.WithName(Config.Link.LinkDiscordSettings.Name.ToLower())
.WithDescription(Config.Link.LinkDiscordSettings.Description)
.AddOption(Config.Link.LinkDiscordSettings.OptionName.ToLower(), ApplicationCommandOptionType.String, Config.Link.LinkDiscordSettings.OptionDescription, isRequired: true);

try
{
Expand All @@ -197,6 +202,53 @@ 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)
{
Console.WriteLine($"Request sent: Method = {method}, Endpoint = {endpoint}, Duration = {duration}ms");
return Task.CompletedTask;
}*/

public async Task CreateScheduledEventAsync(string eventData)
{
var guild = BotClient!.GetGuild(ulong.Parse(ServerId));
if (guild == null)
return;

var guildEvent = await guild.CreateEventAsync($"Custom Event (DU)", DateTimeOffset.UtcNow.AddMinutes(1), GuildScheduledEventType.External, endTime: DateTimeOffset.UtcNow.AddMinutes(2), location: "Discord Utilities", description: eventData);
await guildEvent.DeleteAsync();
}

private async Task ScheduledEventCreated(SocketGuildEvent scheduledEvent)
{
if (scheduledEvent.Location.Equals("Discord Utilities"))
{
if (scheduledEvent.Name.Contains("Custom Event (DU)"))
{
var data = scheduledEvent.Description.Split(';');
var CustomId = data.FirstOrDefault();
if (CustomId == null)
return;

if (CustomId.Equals("addcode"))
{
var code = DecodeSecretString(data[1]);
if (!linkCodes.ContainsKey(code))
linkCodes.Add(code, data[2]);
}
else if (CustomId.Equals("removecode"))
{
var code = DecodeSecretString(data[1]);
if (linkCodes.ContainsKey(code))
linkCodes.Remove(code);
}
else if (CustomId.Equals("refreshlinkedplayers"))
{
await LoadLinkedPlayers();
}
}
}
return;
}

private Task InteractionCreatedHandler(SocketInteraction interaction)
{
Expand All @@ -215,6 +267,7 @@ private Task InteractionCreatedHandler(SocketInteraction interaction)
}
return Task.CompletedTask;
}

private Task MessageReceivedHandler(SocketMessage message)
{
if (message.Author.IsBot || message.Author.IsWebhook)
Expand All @@ -226,7 +279,7 @@ private Task MessageReceivedHandler(SocketMessage message)

private async Task SlashCommandHandler(SocketSlashCommand command)
{
if (command.CommandName == Config.Link.DiscordCommand.ToLower())
if (command.CommandName == Config.Link.LinkDiscordSettings.Name.ToLower())
await DiscordLink_CMD(command);
else
Event_SlashCommand(command);
Expand All @@ -242,6 +295,7 @@ public override void Unload(bool hotReload)
BotClient.SlashCommandExecuted -= SlashCommandHandler;
BotClient.MessageReceived -= MessageReceivedHandler;
BotClient.InteractionCreated -= InteractionCreatedHandler;
BotClient.GuildScheduledEventCreated -= ScheduledEventCreated;
}
}

Expand Down Expand Up @@ -281,4 +335,4 @@ public static void Perform_SendConsoleMessage(string text, ConsoleColor color)
Console.ResetColor();
}
}
}
}
2 changes: 1 addition & 1 deletion src/DiscordUtilities/Functions/Actions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ private async Task LoadPlayerData(string steamid, ulong discordID)
return;
}

await PerformLinkRole(discordID.ToString());
await PerformLinkRole(user, guild.GetRole(ulong.Parse(Config.Link.LinkDiscordSettings.LinkRole)));
LoadPlayerDiscordData(ulong.Parse(steamid), discordID);

Server.NextFrame(() =>
Expand Down
Loading

0 comments on commit 2fc47ee

Please sign in to comment.