From 1bae33f9f831fc29a0b2e763e37956b5ebb660ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Gabriel?= Date: Tue, 18 Jun 2024 02:28:17 -0300 Subject: [PATCH] Enhance birthday messages, and application log --- src/Commands/CommandBirthday.cs | 26 ++++++----- src/Data/Servers.cs | 3 +- src/Data/Users.cs | 20 ++++---- src/Entities/Server.cs | 5 ++ src/Entities/User.cs | 13 +++++- src/KWIJisho-doc.xml | 53 +++++++++++++++------ src/KWiJishoBot.cs | 6 ++- src/Models/Birthday.cs | 12 ++--- src/Scheduling/BirthdayJob.cs | 6 ++- src/Scheduling/NoticeJob.cs | 12 +++++ src/Utils/KWiJishoLog.cs | 81 ++++++++++++++++++++++++++------- src/Utils/KWiJishoLogs.cs | 22 +++++++++ 12 files changed, 195 insertions(+), 64 deletions(-) create mode 100644 src/Scheduling/NoticeJob.cs create mode 100644 src/Utils/KWiJishoLogs.cs diff --git a/src/Commands/CommandBirthday.cs b/src/Commands/CommandBirthday.cs index b60bd10..20bfceb 100644 --- a/src/Commands/CommandBirthday.cs +++ b/src/Commands/CommandBirthday.cs @@ -1,5 +1,6 @@ using DSharpPlus.Entities; using KWiJisho.Config; +using KWiJisho.Utils; using System; using System.Collections.Generic; using System.IO; @@ -44,8 +45,6 @@ internal static async Task ExecuteNextBirthdayAsync(DiscordChannel discordChanne internal static async Task SendBirthdayMessage(DiscordChannel discordChannel, DiscordGuild discordGuild, bool sendOnlyIfTodayBirthday = false) { - string notFoundBirthdayUser = "Eu sinto muito.. :( eu não consegui encontrar nesse servidor o próximo usuário da lista a fazer aniversário."; - // Getting closest birthday from user present in the server and its member info var user = Models.Birthday.GetNextUserToMakeBirthday(discordGuild); @@ -53,7 +52,7 @@ internal static async Task SendBirthdayMessage(DiscordChannel discordChannel, Di if (user is null) { // Sends the message. - await discordChannel.SendMessageAsync(notFoundBirthdayUser); + await SendMessageBirthdayUserNotFound(discordChannel); // Return to the method. return; } @@ -64,8 +63,8 @@ internal static async Task SendBirthdayMessage(DiscordChannel discordChannel, Di // If the user is null, send a message to the Discord channel indicating inability to find the next user in the birthday list. if (discordMember is null) { - // Sends the message. - await discordChannel.SendMessageAsync(notFoundBirthdayUser); + // Sends the message that birthday user wasn't found. + await SendMessageBirthdayUserNotFound(discordChannel); // Return to the method. return; } @@ -75,7 +74,11 @@ internal static async Task SendBirthdayMessage(DiscordChannel discordChannel, Di var upcomingDate = Models.Birthday.GetBirthdayUpcomingDate(daysRemaining); // Return method if flagged to show only if user's birthday is today, and the birthday is not today. - if (sendOnlyIfTodayBirthday && upcomingDate is not Models.Birthday.BirthdayUpcomingDate.Today) return; + if (sendOnlyIfTodayBirthday && upcomingDate is not Models.Birthday.BirthdayUpcomingDate.Today) + { + await KWiJishoLogs.DefaultLog.AddInfoAsync(KWiJishoLog.Module.Birthday, $@"Birthday message wasn't sent because today is not birthday of ""{discordMember.Username}""."); + return; + } // Generates birthday message according how many days are remaining for its birthday. var message = await Models.Birthday.GenerateBirthdayMessage(user); @@ -89,10 +92,10 @@ internal static async Task SendBirthdayMessage(DiscordChannel discordChannel, Di { Color = ConfigJson.DefaultColor.DiscordColor, Title = "ANIVERSARIANTE", - Description = $@"O próximo aniversariante é.. {discordMember.Username}!! {message}", + Description = $@"O próximo aniversariante é.. {user.Nickname}!! {message}", Footer = new DiscordEmbedBuilder.EmbedFooter { - Text = $"Aniversariante: {discordMember.Username} • Aniversário: {user.Birthday:dd/MM/yyyy}" + Text = $"Aniversariante: {user.FirstName} • Aniversário: {user.Birthday:dd/MM/yyyy}" } } .WithThumbnail($"attachment://{fileName}") @@ -116,10 +119,6 @@ internal static async Task ExecuteBirthdayListAsync(DiscordChannel discordChanne // Getting list of users and their birthday var users = Models.Birthday.GetBirthdayList(); - // Getting image name and image's full path. - var fileName = $"500x281-talking.gif"; - var imagePath = Path.GetFullPath($"Resources/Images/{fileName}"); - // Initializing discord embed builder var discordEmbedBuilder = new DiscordEmbedBuilder { @@ -159,5 +158,8 @@ internal static async Task ExecuteBirthdayListAsync(DiscordChannel discordChanne // Sending the builded embed message await discordChannel.SendMessageAsync(discordEmbedBuilder); } + + private static async Task SendMessageBirthdayUserNotFound(DiscordChannel discordChannel) => + await discordChannel.SendMessageAsync("Eu sinto muito.. :( eu não consegui encontrar nesse servidor o próximo usuário da lista a fazer aniversário."); } } diff --git a/src/Data/Servers.cs b/src/Data/Servers.cs index 32cfb9b..6954af0 100644 --- a/src/Data/Servers.cs +++ b/src/Data/Servers.cs @@ -17,7 +17,8 @@ internal class Servers { GuildId = 737541664318554143, GeneralChannelId = 737541664775602269, - WelcomeChannelId = 737541664775602269 + WelcomeChannelId = 737541664775602269, + LogChannelId = 1252137920995790919 }; } } diff --git a/src/Data/Users.cs b/src/Data/Users.cs index 6baabb8..d3dc072 100644 --- a/src/Data/Users.cs +++ b/src/Data/Users.cs @@ -14,15 +14,17 @@ internal static class DiscordUsers /// internal static List Users => [ - new(748963722088677376, new DateTime(2002, 06, 14), "Dark"), // eita_tami - new(256137979335016448, new DateTime(2001, 08, 15), "Orlando"), // fellippeo - new(221419309333741569, new DateTime(2001, 03, 30), "Biel"), // gabstend - new(301152393821814794, new DateTime(2001, 05, 09), "Luiz"), // galo_lpc - new(421101332326383618, new DateTime(2004, 09, 05), "Lívia"), // haruna1686 - new(331920695359569922, new DateTime(2000, 11, 08), "Posca"), // p0sc4t - new(207556639719555072, new DateTime(2002, 11, 24), "Vini"), // monambike - new(737573340851470348, new DateTime(2003, 03, 21), "Betty"), // darksidevision - new(737535848102363259, KWiJisho.Created.Date, "KWiJisho") // KWiJisho Bot + new(748963722088677376, new DateTime(2002, 06, 14), "Felipe", "Dark", "tamizinho"), // eita_tami + new(256137979335016448, new DateTime(2001, 08, 15), "Fellippe", "Orlando", "orlandinho"), // fellippeo + new(221419309333741569, new DateTime(2001, 03, 30), "Gabriel", "Biel", "bielzinho"), // gabstend + new(301152393821814794, new DateTime(2001, 05, 09), "Luiz", "Luizão", "louiszon"), // galo_lpc + new(421101332326383618, new DateTime(2004, 09, 05), "Lívia", "Haru", "haruzinha"), // haruna1686 + new(331920695359569922, new DateTime(2000, 11, 08), "Filipe", "Posca", "posquete"), // p0sc4t + new(207556639719555072, new DateTime(2002, 11, 24), "Vinícius", "Vini", "vinicin"), // monambike + new(737573340851470348, new DateTime(2003, 03, 21), "Elizabeth", "Betty", "bettyzinha"), // darksidevision + new(352948739029336074, new DateTime(2002, 10, 29), "Matheus", "Mello", "mellinho"), // mello4906 + new(352948739029336074, new DateTime(2002, 10, 29), "Maria", "Mari", "freirezika"), // freirezoka + new(737535848102363259, KWiJisho.Created.Date, "KWiJisho", "KWiJisho", "KWiJisho") // KWiJisho Bot ]; } } diff --git a/src/Entities/Server.cs b/src/Entities/Server.cs index 229d428..74a6612 100644 --- a/src/Entities/Server.cs +++ b/src/Entities/Server.cs @@ -26,5 +26,10 @@ internal class Server() /// Server birthday role Id. /// internal ulong BirthdayRoleId { get; init; } + + /// + /// Server log channel Id. + /// + internal ulong LogChannelId { get; init; } } } diff --git a/src/Entities/User.cs b/src/Entities/User.cs index 9305ed6..c58db51 100644 --- a/src/Entities/User.cs +++ b/src/Entities/User.cs @@ -6,7 +6,7 @@ namespace KWiJisho.Entities /// /// Represents a Discord user along with their identifier and additional information. /// - internal class User(ulong id, DateTime born, string identifier) + internal class User(ulong id, DateTime born, string firstName, string nickname, string nicknameVariation) { /// /// The unique identifier of the user. @@ -18,10 +18,19 @@ internal class User(ulong id, DateTime born, string identifier) /// internal DateTime Born => born; + /// + /// The user real first name. + /// + internal string FirstName => firstName; + + /// + /// The custom identifier or nickname associated with the user. + /// + internal string Nickname => nickname; /// /// The custom identifier or nickname associated with the user. /// - internal string Identifier => identifier; + internal string NicknameVariation => nicknameVariation; /// /// Gets or sets the user's birthday (if applicable). diff --git a/src/KWIJisho-doc.xml b/src/KWIJisho-doc.xml index cc6b5f0..81deb2f 100644 --- a/src/KWIJisho-doc.xml +++ b/src/KWIJisho-doc.xml @@ -1145,12 +1145,17 @@ Server birthday role Id. + + + Server log channel Id. + + Represents a Discord user along with their identifier and additional information. - + Represents a Discord user along with their identifier and additional information. @@ -1165,7 +1170,17 @@ The date when the user was born. - + + + The user real first name. + + + + + The custom identifier or nickname associated with the user. + + + The custom identifier or nickname associated with the user. @@ -1355,7 +1370,7 @@ Method responsible for generating a birthday message. - The user that to get the generated birthday message. + The user that to get the generated birthday message. A containing the generated birthday message. Thrown if the upcoming birthday date is not yet implemented on this current method. @@ -1602,9 +1617,14 @@ Provides methods for handling the application log for important tasks. - + + + Provides methods for handling the application log for important tasks. + + + - The log file path. + The log file name. @@ -1637,48 +1657,53 @@ Indicated a fatal level log. - + Adds a debug log entry with the specified message. The debug log message. - + Adds a info log entry with the specified message. The info log message. - + Adds a warning log entry with the specified message. The warning log message. - + Adds a error log entry with the specified message. The error log message. - + Adds a fatal log entry with the specified message. The fatal log message. - + Adds a formatted log entry to the log file. The type of log entry. The log message to be added. - + + + Adds a line to the log file or send to discord log channel with the specified content. + + The entry to be added to the log. + + - Adds a line to the log file with the specified content. + Gets or sets the instance for handling bot log. - The line to be added to the log file. diff --git a/src/KWiJishoBot.cs b/src/KWiJishoBot.cs index 638c18b..74024ae 100644 --- a/src/KWiJishoBot.cs +++ b/src/KWiJishoBot.cs @@ -5,8 +5,7 @@ using KWiJisho.Config; using KWiJisho.Data; using KWiJisho.Scheduling; -using System; -using System.Collections.Generic; +using KWiJisho.Utils; using System.Threading.Tasks; namespace KWiJisho @@ -97,6 +96,9 @@ internal async Task RunAsync() // Creating all schedulers for application jobs. await Scheduler.CreateAllSchedulers(DiscordClient); + // Instantiating all application logs. + KWiJishoLogs.InstantiateAllLogs(DiscordClient); + // Connecting the bot into the Discord. await DiscordClient.ConnectAsync(); diff --git a/src/Models/Birthday.cs b/src/Models/Birthday.cs index 8b75d59..fb1d58f 100644 --- a/src/Models/Birthday.cs +++ b/src/Models/Birthday.cs @@ -61,20 +61,20 @@ internal static List GetBirthdayList() /// /// Method responsible for generating a birthday message. /// - /// The user that to get the generated birthday message. + /// The user that to get the generated birthday message. /// A containing the generated birthday message. /// Thrown if the upcoming birthday date is not yet implemented on this /// current method. - internal static async Task GenerateBirthdayMessage(User discordUser) + internal static async Task GenerateBirthdayMessage(User user) { // Getting days remaining for registered user birthday. - var daysRemaning = GetBirthdayDaysRemaining(discordUser); + var daysRemaning = GetBirthdayDaysRemaining(user); var upcomingBirthdayDate = GetBirthdayUpcomingDate(daysRemaning); return upcomingBirthdayDate switch { - BirthdayUpcomingDate.Today => $"Hoje é seu aniversário!! 🥳🎉 {"PARABÉNSS!!!!".ToDiscordBold()} Feliz Aniversário 🎂❤️ {Environment.NewLine + Environment.NewLine} { await ChatGPT.GetKWiJishoPromptAsync($"dê uma mensagem de aniversário especial")} {Environment.NewLine + Environment.NewLine} Gente vem cá! <@&{Servers.Tramontina.BirthdayRoleId}>, {discordUser.Identifier} fez aniversário!", - BirthdayUpcomingDate.Tomorrow => $"{"Amanhá".ToDiscordBold()} já é o aniversário. 🥳🎉", - BirthdayUpcomingDate.InSomeDays => $"Faltam apenas {(daysRemaning + " dias").ToDiscordBold()} para o aniversário!! 👀 Tô ansiosa!!", + BirthdayUpcomingDate.Today => $"Hoje é seu aniversário!! 🥳🎉 {"PARABÉNSS!!!!".ToDiscordBold()} Feliz Aniversário {user.NicknameVariation} 🎂❤️ {Environment.NewLine + Environment.NewLine} { await ChatGPT.GetKWiJishoPromptAsync($"dê uma mensagem de aniversário especial para {user.Nickname}")} {Environment.NewLine + Environment.NewLine} Gente vem cá! <@&{Servers.Tramontina.BirthdayRoleId}>, {user.FirstName} fez aniversário hoje!", + BirthdayUpcomingDate.Tomorrow => $"{"Amanhã".ToDiscordBold()} já é o seu aniversário {user.Nickname}! 🥳🎉 Mal posso esperar!!", + BirthdayUpcomingDate.InSomeDays => $"Faltam apenas {(daysRemaning + " dias").ToDiscordBold()} pra {user.Nickname} fazer aniversário!! 👀 Tô ansiosa!!", _ => throw new NotImplementedException() }; } diff --git a/src/Scheduling/BirthdayJob.cs b/src/Scheduling/BirthdayJob.cs index 1b3887b..e520dbc 100644 --- a/src/Scheduling/BirthdayJob.cs +++ b/src/Scheduling/BirthdayJob.cs @@ -2,6 +2,7 @@ using KWiJisho.Commands; using KWiJisho.Data; using KWiJisho.Models; +using KWiJisho.Utils; using Quartz; using System.Threading.Tasks; @@ -21,10 +22,11 @@ internal class BirthdayJob : IJob /// A representing the asynchronous execution of the job. public async Task Execute(IJobExecutionContext context) { + await KWiJishoLogs.DefaultLog.AddInfoAsync(KWiJishoLog.Module.Birthday, "Executing birthday job."); var dataMap = context.MergedJobDataMap; - _client = (DiscordClient)dataMap.Get("DiscordClient"); - + _client = (DiscordClient) dataMap.Get("DiscordClient"); await GiveBirthdayMessage(); + await KWiJishoLogs.DefaultLog.AddInfoAsync(KWiJishoLog.Module.Birthday, "Finished birthday job."); } /// diff --git a/src/Scheduling/NoticeJob.cs b/src/Scheduling/NoticeJob.cs new file mode 100644 index 0000000..07ff4ed --- /dev/null +++ b/src/Scheduling/NoticeJob.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace KWiJisho.Scheduling +{ + internal class NoticeJob + { + } +} diff --git a/src/Utils/KWiJishoLog.cs b/src/Utils/KWiJishoLog.cs index 716cc3d..2e39ca0 100644 --- a/src/Utils/KWiJishoLog.cs +++ b/src/Utils/KWiJishoLog.cs @@ -1,17 +1,26 @@ -using System; +using DSharpPlus; +using KWiJisho.Data; +using System; using System.IO; +using System.Threading.Tasks; namespace KWiJisho.Utils { /// /// Provides methods for handling the application log for important tasks. /// - internal static class KWiJishoLog + internal class KWiJishoLog(DiscordClient? client) { + public required bool WriteFile { get; init; } + + public required bool SendToDiscord { get; init; } + + private readonly DiscordClient? _client = client; + /// - /// The log file path. + /// The log file name. /// - private static string Path => "KWiJishoLog.txt"; + private const string FileName = "KWiJishoLog.txt"; /// /// Represents options for the application log type. @@ -44,55 +53,95 @@ internal enum LogType Fatal } + internal enum Module + { + Basic, + Birthday, + Info, + KWiGpt, + Nasa, + Notice, + ThemeTramontina + } + /// /// Adds a debug log entry with the specified message. /// /// The debug log message. - internal static void AddDebug(string message) => Add(LogType.Debug, message); + internal async Task AddDebugAsync(Module module, string message) => await AddCustomLogAsync(LogType.Debug, module, message); /// /// Adds a info log entry with the specified message. /// /// The info log message. - internal static void AddInfo(string message) => Add(LogType.Info, message); + internal async Task AddInfoAsync(Module module, string message) => await AddCustomLogAsync(LogType.Info, module, message); /// /// Adds a warning log entry with the specified message. /// /// The warning log message. - internal static void AddWarning(string message) => Add(LogType.Warning, message); + internal async Task AddWarningAsync(Module module, string message) => await AddCustomLogAsync(LogType.Warning, module, message); /// /// Adds a error log entry with the specified message. /// /// The error log message. - internal static void AddError(string message) => Add(LogType.Error, message); + internal async Task AddErrorAsync(Module module, string message) => await AddCustomLogAsync(LogType.Error, module, message); /// /// Adds a fatal log entry with the specified message. /// /// The fatal log message. - internal static void AddFatal(string message) => Add(LogType.Fatal, message); + internal async Task AddFatalAsync(Module module, string message) => await AddCustomLogAsync(LogType.Fatal, module, message); /// /// Adds a formatted log entry to the log file. /// /// The type of log entry. /// The log message to be added. - private static void Add(LogType logType, string message) - => AddLineToFile($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] {logType.ToString().ToUpper()} {message}"); + private async Task AddCustomLogAsync(LogType logType, Module module, string message) + => await AddEntryAsync($"[{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss.fff}] [{module}] {logType.ToString().ToUpper()} {message}"); /// - /// Adds a line to the log file with the specified content. + /// Adds a line to the log file or send to discord log channel with the specified content. /// - /// The line to be added to the log file. - internal static void AddLineToFile(string line) + /// The entry to be added to the log. + internal async Task AddEntryAsync(string entry) + { + // Writing entry to log file. + var taskWriteToFile = WriteEntryToFileAsync(entry); + + // Sending entry to discord log channel. + var taskSendToDiscord = SendEntryToDiscordAsync(entry); + + // Running all tasks assynchronously. + await Task.WhenAll(taskWriteToFile, taskSendToDiscord); + } + + internal async Task WriteEntryToFileAsync(string entry) { + if (!WriteFile) return; + // Opens the log file at the specified path for appending a new text. - using StreamWriter writer = File.AppendText(Path); + using StreamWriter writer = File.AppendText(FileName); // Writing the line on the log file. - writer.WriteLine(line); + await writer.WriteLineAsync(entry); + } + + internal async Task SendEntryToDiscordAsync(string entry) + { + if (!SendToDiscord) return; + + var server = Servers.Personal; + + var serverGuild = await _client.GetGuildAsync(server.GuildId); + + // Getting channel by id. + var discordChannel = serverGuild.GetChannel(server.LogChannelId); + + // Sending the birthday message. + await discordChannel.SendMessageAsync(entry); } } } diff --git a/src/Utils/KWiJishoLogs.cs b/src/Utils/KWiJishoLogs.cs new file mode 100644 index 0000000..561e8e4 --- /dev/null +++ b/src/Utils/KWiJishoLogs.cs @@ -0,0 +1,22 @@ +using DSharpPlus; + +namespace KWiJisho.Utils +{ + internal static class KWiJishoLogs + { + /// + /// Gets or sets the instance for handling bot log. + /// + internal static KWiJishoLog DefaultLog { get; set; } = null!; + + public static void InstantiateAllLogs(DiscordClient discordClient) + { + // Defining default discord log instance. + DefaultLog = new KWiJishoLog(discordClient) + { + SendToDiscord = true, + WriteFile = true + }; + } + } +}