diff --git a/DeukBot4/APIHandlers/CatFactsApi.cs b/DeukBot4/APIHandlers/CatFactsApi.cs new file mode 100644 index 0000000..4b61223 --- /dev/null +++ b/DeukBot4/APIHandlers/CatFactsApi.cs @@ -0,0 +1,30 @@ +using System; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace DeukBot4.APIHandlers +{ + public static class CatFactsApi + { + private const string URL = "https://catfact.ninja/"; + + public static async Task GetRandomCatFact() + { + var client = new HttpClient {BaseAddress = new Uri(URL)}; + client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + var response = await client.GetAsync("facts?limit=1"); // Blocking call! + if (!response.IsSuccessStatusCode) + return null; + + var res = await response.Content.ReadAsStringAsync(); + var json = JObject.Parse(res); + var a = json["data"].AsEnumerable(); + return a.First()["fact"].Value(); + + } + } +} \ No newline at end of file diff --git a/DeukBot4/MessageHandlers/CommandHandler/Commands/GeneralCommands.cs b/DeukBot4/MessageHandlers/CommandHandler/Commands/GeneralCommands.cs index b6966e3..07582af 100644 --- a/DeukBot4/MessageHandlers/CommandHandler/Commands/GeneralCommands.cs +++ b/DeukBot4/MessageHandlers/CommandHandler/Commands/GeneralCommands.cs @@ -1,5 +1,6 @@ using System; using System.Threading.Tasks; +using DeukBot4.APIHandlers; using DeukBot4.MessageHandlers.CommandHandler.RequestStructure; using DeukBot4.MessageHandlers.Permissions; using DeukBot4.Utilities; @@ -69,5 +70,12 @@ namespace DeukBot4.MessageHandlers.CommandHandler { await request.SendMessageAsync(BotOpinions.GetOpinion(request)); } + + [Command("catfact", PermissionLevel.Everyone)] + [CommandHelp("Returns a random cat fact", "Returns a random cat fact, powered by https://catfact.ninja/")] + public async Task RandomCatFact(CommandRequest request) + { + await request.SendMessageAsync(await CatFactsApi.GetRandomCatFact()); + } } } \ No newline at end of file