Vital new functionality

This commit is contained in:
Deukhoofd 2018-05-09 00:41:56 +02:00
parent 62439b4d14
commit 356baa51b8
No known key found for this signature in database
GPG Key ID: B4C087AC81641654
2 changed files with 38 additions and 0 deletions

View File

@ -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<string> 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<string>();
}
}
}

View File

@ -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());
}
}
}