geekbot/Geekbot.net/Commands/Randomness/Dad/DadJokes.cs

51 lines
1.7 KiB
C#
Raw Normal View History

2018-04-28 19:27:41 +02:00
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Discord.Commands;
using Geekbot.net.Lib.ErrorHandling;
2018-04-28 19:27:41 +02:00
using Newtonsoft.Json;
namespace Geekbot.net.Commands.Randomness.Dad
2018-04-28 19:27:41 +02:00
{
public class DadJokes : ModuleBase
{
private readonly IErrorHandler _errorHandler;
public DadJokes(IErrorHandler errorHandler)
{
_errorHandler = errorHandler;
}
[Command("dad", RunMode = RunMode.Async)]
[Summary("A random dad joke")]
public async Task Say()
{
try
{
using (var client = new HttpClient())
{
try
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
var response = await client.GetAsync("https://icanhazdadjoke.com/");
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<DadJokeResponseDto>(stringResponse);
2018-04-30 23:44:19 +02:00
await ReplyAsync(data.Joke);
2018-04-28 19:27:41 +02:00
}
catch (HttpRequestException)
{
await ReplyAsync("Api down...");
}
}
}
catch (Exception e)
{
_errorHandler.HandleCommandException(e, Context);
}
}
}
}