Skip to content

Commit

Permalink
Make basic birthday job and schedule work
Browse files Browse the repository at this point in the history
  • Loading branch information
monambike committed Jun 17, 2024
1 parent e6593c9 commit 835e512
Show file tree
Hide file tree
Showing 8 changed files with 92 additions and 30 deletions.
23 changes: 18 additions & 5 deletions src/Commands/CommandBirthday.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,17 @@ internal static class CommandBirthday
/// <param name="discordChannel">The Discord channel where the message will be sent.</param>
/// <param name="discordGuild">The Discord guild containing the users.</param>
internal static async Task ExecuteNextBirthdayAsync(DiscordChannel discordChannel, DiscordGuild discordGuild)
{
await SendBirthdayMessage(discordChannel, discordGuild);
}

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);

// If the user is null, send a message to the Discord channel indicating inability to find the next user in the birthday list.
if (user is null)
{
Expand All @@ -69,8 +74,11 @@ internal static async Task ExecuteNextBirthdayAsync(DiscordChannel discordChanne
var daysRemaining = Models.Birthday.GetBirthdayDaysRemaining(user);
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;

// Generates birthday message according how many days are remaining for its birthday.
var message = Models.Birthday.GenerateBirthdayMessage(user);
var message = await Models.Birthday.GenerateBirthdayMessage(user);

// Gets the image name and image's full path.
var fileName = $"500x500-happybirthday-{upcomingDate.ToString().ToLower()}.png";
Expand All @@ -80,10 +88,15 @@ internal static async Task ExecuteNextBirthdayAsync(DiscordChannel discordChanne
var discordEmbedBuilder = new DiscordEmbedBuilder
{
Color = ConfigJson.DefaultColor.DiscordColor,
Title = "PRÓXIMO ANIVERSARIANTE",
Description = $@"O próximo aniversariante é.. {discordMember.Username}!! {message}"
Title = "ANIVERSARIANTE",
Description = $@"O próximo aniversariante é.. {discordMember.Username}!! {message}",
Footer = new DiscordEmbedBuilder.EmbedFooter
{
Text = $"Aniversariante: {discordMember.Username} • Aniversário: {user.Birthday:dd/MM/yyyy}"
}
}
.WithImageUrl($"attachment://{imagePath}").Build();
.WithThumbnail($"attachment://{fileName}")
.WithImageUrl(discordMember.AvatarUrl).Build();

using var fileStream = new FileStream(imagePath, FileMode.Open);
// Attachs file and embed to the message and sending it to the discord channel.
Expand Down
5 changes: 4 additions & 1 deletion src/Data/Servers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@ internal class Servers
public static Server Tramontina = new()
{
GuildId = 692588978959941653,
GeneralChannelId = 692588978959941656,
WelcomeChannelId = 842222447410544650,
NewsChannelId = 1203090940701446214
NewsChannelId = 1203090940701446214,
BirthdayRoleId = 1252121891284582521
};

public static Server Personal = new()
{
GuildId = 737541664318554143,
GeneralChannelId = 737541664775602269,
WelcomeChannelId = 737541664775602269
};
}
Expand Down
10 changes: 10 additions & 0 deletions src/Entities/Server.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ internal class Server()
/// </summary>
internal required ulong GuildId { get; init; }

/// <summary>
/// Server general channeld Id.
/// </summary>
internal ulong GeneralChannelId { get; init; }

/// <summary>
/// Server welcome channeld Id.
/// </summary>
Expand All @@ -16,5 +21,10 @@ internal class Server()
/// Server news channel Id.
/// </summary>
internal ulong NewsChannelId { get; init; }

/// <summary>
/// Server birthday role Id.
/// </summary>
internal ulong BirthdayRoleId { get; init; }
}
}
25 changes: 12 additions & 13 deletions src/KWIJisho-doc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion src/KWiJishoBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using DSharpPlus.SlashCommands;
using KWiJisho.Config;
using KWiJisho.Data;
using KWiJisho.Scheduling;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
Expand Down Expand Up @@ -77,7 +78,7 @@ internal async Task RunAsync()
// Defining bot prefix commands settings.
var commandsNextConfiguration = new CommandsNextConfiguration
{
StringPrefixes = new string[] { ConfigJson.Prefix },
StringPrefixes = [ConfigJson.Prefix],
EnableDms = false,
EnableMentionPrefix = true,
EnableDefaultHelp = false
Expand All @@ -93,6 +94,9 @@ internal async Task RunAsync()
RegisterSlashCommands();
RegisterSlashCommandsPermissions();

// Creating all schedulers for application jobs.
await Scheduler.CreateAllSchedulers(DiscordClient);

// Connecting the bot into the Discord.
await DiscordClient.ConnectAsync();

Expand Down
7 changes: 5 additions & 2 deletions src/Models/Birthday.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
using DSharpPlus.Entities;
using KWiJisho.APIs;
using KWiJisho.Data;
using KWiJisho.Entities;
using KWiJisho.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace KWiJisho.Models
{
Expand Down Expand Up @@ -62,14 +65,14 @@ internal static List<User> GetBirthdayList()
/// <returns>A <see cref="string"/> containing the generated birthday message.</returns>
/// <exception cref="NotImplementedException">Thrown if the upcoming birthday date is not yet implemented on this
/// current method.</exception>
internal static string GenerateBirthdayMessage(User discordUser)
internal static async Task<string> GenerateBirthdayMessage(User discordUser)
{
// Getting days remaining for registered user birthday.
var daysRemaning = GetBirthdayDaysRemaining(discordUser);
var upcomingBirthdayDate = GetBirthdayUpcomingDate(daysRemaning);
return upcomingBirthdayDate switch
{
BirthdayUpcomingDate.Today => $"Hoje é seu aniversário!! 🥳🎉 {"PARABÉNSS!!!!".ToDiscordBold()} Feliz Aniversário 🎂",
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!!",
_ => throw new NotImplementedException()
Expand Down
33 changes: 28 additions & 5 deletions src/Scheduling/BirthdayJob.cs
Original file line number Diff line number Diff line change
@@ -1,25 +1,48 @@
using Quartz;
using Quartz.Impl;
using DSharpPlus;
using KWiJisho.Commands;
using KWiJisho.Data;
using KWiJisho.Models;
using Quartz;
using System.Threading.Tasks;

namespace KWiJisho.Scheduling
{
[DisallowConcurrentExecution]
/// <summary>
/// Represents a Quartz.NET job that executes a birthday message task.
/// </summary>
internal class BirthdayJob : IJob
{
/// <summary>
private DiscordClient? _client;

/// Executes the birthday message task as part of the Quartz.NET job.
/// </summary>
/// <param name="context">The execution context provided by Quartz.NET.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous execution of the job.</returns>
public Task Execute(IJobExecutionContext context) => GiveBirthdayMessage();
public async Task Execute(IJobExecutionContext context)
{
var dataMap = context.MergedJobDataMap;
_client = (DiscordClient)dataMap.Get("DiscordClient");

await GiveBirthdayMessage();
}

/// <summary>
/// Sends a birthday message as an asynchronous task.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous execution of the birthday message task.</returns>
private static async Task GiveBirthdayMessage() => await Task.Run(() => "");
private async Task GiveBirthdayMessage()
{
var server = Servers.Personal;

// Getting guild by id.
var serverGuild = await _client.GetGuildAsync(server.GuildId);

// Getting channel by id.
var discordChannel = serverGuild.GetChannel(server.GeneralChannelId);

// Sending the birthday message.
await CommandBirthday.SendBirthdayMessage(discordChannel, serverGuild, true);
}
}
}
13 changes: 10 additions & 3 deletions src/Scheduling/Scheduler.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Quartz;
using DSharpPlus;
using Quartz;
using Quartz.Impl;
using System.Threading.Tasks;

Expand All @@ -9,11 +10,16 @@ namespace KWiJisho.Scheduling
/// </summary>
internal class Scheduler
{
internal static async Task CreateAllSchedulers(DiscordClient discordClient)
{
await CreateBirthdayScheduler(discordClient);
}

/// <summary>
/// Creates a birthday scheduler as part of the Quartz.NET library.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous creation of the birthday scheduler.</returns>
internal static async Task CreateBirthdayScheduler()
internal static async Task CreateBirthdayScheduler(DiscordClient discordClient)
{
// Creating and starting a scheduler.
var scheduler = await StdSchedulerFactory.GetDefaultScheduler();
Expand All @@ -24,8 +30,9 @@ internal static async Task CreateBirthdayScheduler()

// Creating a trigger that will fire everyday at 12pm.
var trigger = TriggerBuilder.Create()
.UsingJobData(new JobDataMap { { "DiscordClient", discordClient } })
.WithIdentity("BirthdayCheck", "KWiJisho")
.WithDailyTimeIntervalSchedule(period => period.StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(12, 0)).OnEveryDay())
.WithDailyTimeIntervalSchedule(period => period.StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(2, 52)).WithIntervalInHours(24))
.Build();

// Scheduling the job with the trigger.
Expand Down

0 comments on commit 835e512

Please sign in to comment.