Skip to content

Commit

Permalink
Handle HttpRequestException in /random cat & /random dog
Browse files Browse the repository at this point in the history
  • Loading branch information
FloatingMilkshake committed Oct 10, 2024
1 parent 2d214bd commit 8ac12f7
Showing 1 changed file with 31 additions and 3 deletions.
34 changes: 31 additions & 3 deletions Commands/RandomCommands.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
namespace MechanicalMilkshake.Commands;
using System.Net;

namespace MechanicalMilkshake.Commands;

public partial class RandomCommands : ApplicationCommandModule
{
Expand Down Expand Up @@ -38,7 +40,20 @@ public static async Task RandomFact(InteractionContext ctx)
public static async Task RandomCat(InteractionContext ctx)
{
await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);
var data = await Program.HttpClient.GetStringAsync("https://api.thecatapi.com/v1/images/search");
string data;
try
{
data = await Program.HttpClient.GetStringAsync("https://api.thecatapi.com/v1/images/search");
}
catch (HttpRequestException ex)
{
if (ex.StatusCode is HttpStatusCode.TooManyRequests)
await ctx.FollowUpAsync(new DiscordFollowupMessageBuilder().WithContent("You're going too fast! Try again in a few seconds."));
else
await ctx.FollowUpAsync(new DiscordFollowupMessageBuilder().WithContent($"Something went wrong! The Cat API returned status code {ex.StatusCode}. Try again in a bit, or contact a bot owner if this persists."));

return;
}
var pattern = CatApiUrlPattern();
var cat = pattern.Match(data);

Expand All @@ -49,7 +64,20 @@ public static async Task RandomCat(InteractionContext ctx)
public static async Task RandomDog(InteractionContext ctx)
{
await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);
var data = await Program.HttpClient.GetStringAsync("https://dog.ceo/api/breeds/image/random");
string data;
try
{
data = await Program.HttpClient.GetStringAsync("https://dog.ceo/api/breeds/image/random");
}
catch (HttpRequestException ex)
{
if (ex.StatusCode is HttpStatusCode.TooManyRequests)
await ctx.FollowUpAsync(new DiscordFollowupMessageBuilder().WithContent("You're going too fast! Try again in a few seconds."));
else
await ctx.FollowUpAsync(new DiscordFollowupMessageBuilder().WithContent($"Something went wrong! The Dog API returned status code {ex.StatusCode}. Try again in a bit, or contact a bot owner if this persists."));

return;
}
var pattern = DogApiUrlPattern();
var dogMatch = pattern.Match(data);

Expand Down

0 comments on commit 8ac12f7

Please sign in to comment.