DeukBot4/DeukBot4/APIHandlers/CatFactsApi.cs

30 lines
955 B
C#

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