geekbot/Geekbot.net/Commands/Integrations/UbranDictionary/UrbanDictionary.cs

66 lines
2.7 KiB
C#
Raw Normal View History

using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Geekbot.net.Lib.ErrorHandling;
2018-05-17 22:06:58 +02:00
using Geekbot.net.Lib.Extensions;
using Newtonsoft.Json;
namespace Geekbot.net.Commands.Integrations.UbranDictionary
{
public class UrbanDictionary : ModuleBase
{
private readonly IErrorHandler _errorHandler;
2017-12-29 01:53:50 +01:00
public UrbanDictionary(IErrorHandler errorHandler)
{
_errorHandler = errorHandler;
}
2017-12-29 01:53:50 +01:00
[Command("urban", RunMode = RunMode.Async)]
[Summary("Lookup something on urban dictionary")]
2018-04-30 23:44:19 +02:00
public async Task UrbanDefine([Remainder] [Summary("word")] string word)
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://api.urbandictionary.com");
var response = await client.GetAsync($"/v0/define?term={word}");
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
var definitions = JsonConvert.DeserializeObject<UrbanResponseDto>(stringResponse);
2018-04-30 23:44:19 +02:00
if (definitions.List.Count == 0)
{
await ReplyAsync("That word hasn't been defined...");
return;
}
2017-12-29 01:53:50 +01:00
2018-04-30 23:44:19 +02:00
var definition = definitions.List.First(e => !string.IsNullOrWhiteSpace(e.Example));
2017-12-29 01:53:50 +01:00
var eb = new EmbedBuilder();
2017-12-29 01:53:50 +01:00
eb.WithAuthor(new EmbedAuthorBuilder
{
2018-04-30 23:44:19 +02:00
Name = definition.Word,
Url = definition.Permalink
});
2017-12-29 01:53:50 +01:00
eb.WithColor(new Color(239, 255, 0));
if (!string.IsNullOrEmpty(definition.Definition)) eb.Description = definition.Definition.Substring(0, 1800);
2018-05-01 00:19:03 +02:00
if (!string.IsNullOrEmpty(definition.Example)) eb.AddField("Example", definition.Example ?? "(no example given...)");
if (!string.IsNullOrEmpty(definition.ThumbsUp)) eb.AddInlineField("Upvotes", definition.ThumbsUp);
if (!string.IsNullOrEmpty(definition.ThumbsDown)) eb.AddInlineField("Downvotes", definition.ThumbsDown);
if (definitions.Tags?.Length > 0) eb.AddField("Tags", string.Join(", ", definitions.Tags));
2017-11-16 17:33:07 +01:00
await ReplyAsync("", false, eb.Build());
}
}
catch (Exception e)
{
await _errorHandler.HandleCommandException(e, Context);
}
}
}
}