Skip to content

Commit

Permalink
Merge pull request #9 from KevinDaGame/development
Browse files Browse the repository at this point in the history
Development
  • Loading branch information
KevinDaGame authored Feb 17, 2024
2 parents f30a0be + f330e4a commit fbcca4c
Show file tree
Hide file tree
Showing 8 changed files with 243 additions and 35 deletions.
17 changes: 10 additions & 7 deletions RemindoBot/Commands/UrbanDictionaryCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,10 @@ public async Task Handle(SocketSlashCommand command)
string word = command.Data.Options.First().Value.ToString() ??
throw new ArgumentNullException("word", "Word cannot be null");
UrbanDictionaryDefinition? definition;
int definitionCount;
try
{
definition = await _urbanDictionaryService.GetDefinitionOfWord(word);
definition = await _urbanDictionaryService.GetDefinitionOfWord(word, out definitionCount);
}
catch (FlurlHttpException)
{
Expand All @@ -51,15 +52,17 @@ public async Task Handle(SocketSlashCommand command)
.WithTitle(definition.Word)
.WithDescription(definition.Definition)
.WithUrl(definition.Permalink)
.WithFooter(definition.Author)
.WithFooter(
$"{definition.Author} - [1/{definitionCount}] - {definition.Thumbs_up} 👍 {definition.Thumbs_down} 👎")
.WithColor(Color.Blue)
.WithTimestamp(DateTime.Parse(definition.Written_on));
MessageComponent? viewButton = new ComponentBuilder()

MessageComponent buttons = new ComponentBuilder()
.WithButton("View on Urban Dictionary", style: ButtonStyle.Link, url: definition.Permalink)
.WithButton("Next definition", customId: $"urban-{word}-1")
.WithButton("Actual definition", customId: $"actual-{word}-0")
.Build();


await command.RespondAsync(embed: embed.Build(), components: viewButton);

await command.RespondAsync(embed: embed.Build(), components: buttons);
}
}
152 changes: 152 additions & 0 deletions RemindoBot/Handlers/UrbanButtonHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
using Discord;
using Discord.WebSocket;
using Flurl.Http;
using Microsoft.Extensions.Logging;
using RemindoBot.Services;

namespace RemindoBot.Handlers;

public class UrbanButtonHandler : IHandler
{
private readonly DiscordSocketClient _client;
private readonly ILogger<VoiceChatStatusHandler> _logger;
private readonly IUrbanDictionaryService _urbanDictionaryService;
private readonly IActualDictionaryService _actualDictionaryService;

public UrbanButtonHandler(DiscordSocketClient client, ILogger<VoiceChatStatusHandler> logger,
IUrbanDictionaryService urbanDictionaryService,
IActualDictionaryService actualDictionaryService)
{
_client = client;
_logger = logger;
_urbanDictionaryService = urbanDictionaryService;
_actualDictionaryService = actualDictionaryService;
}

public void RegisterHandlers()
{
_client.ButtonExecuted += HandleUrbanButton;
}

public async Task HandleUrbanButton(SocketMessageComponent component)
{
if (component.Data.CustomId.StartsWith("urban-"))
{
string word = component.Data.CustomId.Split("-")[1];
int number = int.Parse(component.Data.CustomId.Split("-")[^1]);

if (number < 0)
{
await component.RespondAsync("Invalid definition number");
return;
}

UrbanDictionaryDefinition definition;
int definitionCount;
try
{
var definitions = await _urbanDictionaryService.GetDefinitionsOfWord(word);
if (number >= definitions.Count)
{
await component.RespondAsync("no more definitions");
return;
}

definitionCount = definitions.Count;
definition = definitions[number];
}
catch (FlurlHttpException)
{
await component.RespondAsync("Failed to fetch definition");
return;
}

EmbedBuilder? embed = new EmbedBuilder()
.WithTitle(definition.Word)
.WithDescription(definition.Definition)
.WithUrl(definition.Permalink)
.WithFooter(
$"{definition.Author} - [{number + 1}/{definitionCount}] - {definition.Thumbs_up} 👍 {definition.Thumbs_down} 👎")
.WithColor(Color.Blue)
.WithTimestamp(DateTime.Parse(definition.Written_on));

ComponentBuilder buttonsBuilder = new ComponentBuilder()
.WithButton("View on Urban Dictionary", style: ButtonStyle.Link, url: definition.Permalink);

if (number > 0)
{
buttonsBuilder.WithButton("Previous definition", customId: $"urban-{word}-{number - 1}");
}

if (number < definitionCount - 1)
{
buttonsBuilder.WithButton("Next definition", customId: $"urban-{word}-{number + 1}");
}

buttonsBuilder.WithButton("Actual definition", style: ButtonStyle.Success, customId: $"actual-{word}-0");

await component.Message.ModifyAsync(properties =>
{
properties.Embed = embed.Build();
properties.Components = buttonsBuilder.Build();
});
await component.DeferAsync();
}

if (component.Data.CustomId.StartsWith("actual-"))
{
string word = component.Data.CustomId.Split("-")[1];
int number = int.Parse(component.Data.CustomId.Split("-")[^1]);
if (number < 0)
{
await component.RespondAsync("Invalid definition number");
return;
}

ActualDictionaryDefinition definition;
int definitionCount;
try
{
var definitions = await _actualDictionaryService.GetDefinitionsOfWord(word);
if (number >= definitions.Count)
{
await component.RespondAsync("no more definitions");
return;
}

definitionCount = definitions.Count;
definition = definitions[number];
}
catch (FlurlHttpException e)
{
await component.RespondAsync("No definition found");
_logger.LogError(e, "Failed to fetch definition");
return;
}

EmbedBuilder? embed = new EmbedBuilder()
.WithTitle(definition.Word)
.WithDescription(definition.Definition)
.WithFooter($"[{number + 1}/{definitionCount}]")
.WithColor(Color.Blue);

ComponentBuilder buttonsBuilder = new ComponentBuilder();
if (number > 0)
{
buttonsBuilder.WithButton("Previous definition", customId: $"actual-{word}-{number - 1}");
}

if (number < definitionCount - 1)
{
buttonsBuilder.WithButton("Next definition", customId: $"actual-{word}-{number + 1}");
}

await component.Message.ModifyAsync(properties =>
{
properties.Embed = embed.Build();
properties.Components = buttonsBuilder.Build();
});
await component.DeferAsync();
}
}
}
8 changes: 3 additions & 5 deletions RemindoBot/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public Task Client_Ready()
{
var handlerManager = _services.GetRequiredService<HandlerManager>();
var commandManager = _services.GetRequiredService<CommandManager>();

handlerManager.RegisterHandlers();
commandManager.RegisterCommands();
return Task.CompletedTask;
Expand All @@ -75,11 +75,9 @@ private static IServiceProvider CreateServices()
.AddTransient<ITimeParserService, TimeParserService>()
.AddTransient<IRemindoRepository, RemindoRepository>()
.AddTransient<IUrbanDictionaryService, UrbanDictionaryService>()
.AddTransient<IActualDictionaryService, ActualDictionaryService>()
.AddTransient<IRemindoService, RemindoService>()
.AddLogging(builder =>
{
builder.AddConsole();
})
.AddLogging(builder => { builder.AddConsole(); })
.AddDbContext<RemindoDbContext>(optionsBuilder =>
optionsBuilder.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)))
.BuildServiceProvider();
Expand Down
42 changes: 42 additions & 0 deletions RemindoBot/Services/ActualDictionaryService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using Flurl;
using Flurl.Http;

namespace RemindoBot.Services;

public class ActualDictionaryService : IActualDictionaryService
{
string baseURI = "https://api.dictionaryapi.dev/api/v2/entries/en/";

public async Task<List<ActualDictionaryDefinition>> GetDefinitionsOfWord(string word)
{
var result = await baseURI.AppendPathSegment(word).GetJsonAsync<ActualDictionaryResponse[]>();
return result.First().Meanings.Select(m => new ActualDictionaryDefinition
{
Word = result.First().Word,
Definition = m.Definitions.First().Definition
}).ToList();
}

public Task<ActualDictionaryDefinition?> GetDefinitionOfWord(string world, out int definitionCount)
{
List<ActualDictionaryDefinition> result = GetDefinitionsOfWord(world).Result;
definitionCount = result.Count;
return Task.FromResult(result.Count == 0 ? null : result.FirstOrDefault());
}
}

public class ActualDictionaryResponse
{
public string Word { get; set; }
public List<ActualDictionaryMeaning> Meanings { get; set; }
}

public class ActualDictionaryMeaning
{
public List<ActualDictionaryDefinitionR> Definitions { get; set; }
}

public class ActualDictionaryDefinitionR
{
public string Definition { get; set; }
}
14 changes: 14 additions & 0 deletions RemindoBot/Services/IActualDictionaryService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace RemindoBot.Services;

public interface IActualDictionaryService
{
public Task<List<ActualDictionaryDefinition>> GetDefinitionsOfWord(string word);
public Task<ActualDictionaryDefinition?> GetDefinitionOfWord(string world, out int definitionCount);
}

public class ActualDictionaryDefinition
{
public string Word { get; set; }
public string Definition { get; set; }
public string Example { get; set; }
}
2 changes: 1 addition & 1 deletion RemindoBot/Services/IUrbanDictionaryService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ namespace RemindoBot.Services;
public interface IUrbanDictionaryService
{
public Task<List<UrbanDictionaryDefinition>> GetDefinitionsOfWord(string word);
public Task<UrbanDictionaryDefinition?> GetDefinitionOfWord(string world);
public Task<UrbanDictionaryDefinition?> GetDefinitionOfWord(string world, out int definitionCount);
}
25 changes: 21 additions & 4 deletions RemindoBot/Services/UrbanDictionaryService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,27 @@ public async Task<List<UrbanDictionaryDefinition>> GetDefinitionsOfWord(string w
return result.List;
}

public async Task<UrbanDictionaryDefinition?> GetDefinitionOfWord(string world)
public Task<UrbanDictionaryDefinition?> GetDefinitionOfWord(string world, out int definitionCount)
{
List<UrbanDictionaryDefinition> result = await GetDefinitionsOfWord(world);

return result.Count == 0 ? null : result.FirstOrDefault();
List<UrbanDictionaryDefinition> result = GetDefinitionsOfWord(world).Result;
definitionCount = result.Count;
return Task.FromResult(result.Count == 0 ? null : result.FirstOrDefault());
}
}

public class UrbanDictionaryResponse
{
public List<UrbanDictionaryDefinition> List { get; set; }
}

public class UrbanDictionaryDefinition
{
public string Definition { get; set; }
public string Example { get; set; }
public string Permalink { get; set; }
public string Word { get; set; }
public int Thumbs_up { get; set; }
public int Thumbs_down { get; set; }
public string Author { get; set; }
public string Written_on { get; set; }
}
18 changes: 0 additions & 18 deletions RemindoBot/Services/UrbanUrbanDictionaryService.cs

This file was deleted.

0 comments on commit fbcca4c

Please sign in to comment.