using System.Collections.Concurrent; using System.Text.Json; using SkyBot.Helpers; using SkyBot.Models; using Valour.Sdk.Models; using Valour.Shared.Models; namespace SkyBot.Commands { public class Happy : ICommand { public string Name => "happy"; public string[] Aliases => Array.Empty(); public string Description => "Express happiness with a random gif."; public string Section => "RP"; public string Usage => "happy [@user]"; private static readonly HttpClient _http = new() { DefaultRequestHeaders = { { "User-Agent", "SkyBot/1.0 (https://skyjoshua.xyz, https://valour.gg)" } } }; public async Task Execute(CommandContext ctx) { ConcurrentDictionary channelCache = ctx.ChannelCache; long channelId = ctx.ChannelId; if (!channelCache.TryGetValue(channelId, out var channel)) return; await channel.SendIsTyping(); string json; try { json = await _http.GetStringAsync("https://nekos.best/api/v2/happy"); } catch { await MessageHelper.ReplyAsync(ctx, channel, "Could not fetch a happy gif. Try again later."); return; } using var doc = JsonDocument.Parse(json); var results = doc.RootElement.GetProperty("results"); string gifUrl = results[0].GetProperty("url").GetString()!; byte[] gifBytes; try { gifBytes = await _http.GetByteArrayAsync(gifUrl); } catch { await MessageHelper.ReplyAsync(ctx, channel, "Could not download the happy gif. Try again later."); return; } int width = 0, height = 0; if (gifBytes.Length >= 10) { width = gifBytes[6] | (gifBytes[7] << 8); height = gifBytes[8] | (gifBytes[9] << 8); } string cdnUrl; try { using var form = new MultipartFormDataContent(); using var fileContent = new ByteArrayContent(gifBytes); fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/gif"); form.Add(fileContent, "file", "happy.gif"); var uploadResult = await ctx.Planet.Node.PostMultipartDataWithResponse("upload/image", form); if (!uploadResult.Success) { await MessageHelper.ReplyAsync(ctx, channel, "Could not upload the happy gif. Try again later."); return; } cdnUrl = uploadResult.Data!; } catch { await MessageHelper.ReplyAsync(ctx, channel, "Could not upload the happy gif. Try again later."); return; } string? target = null; if (ctx.Message.ReplyToId is not null) { var replied = await ctx.Message.FetchReplyMessageAsync(); if (replied is not null) { var author = await replied.FetchAuthorAsync(); if (author is not null) target = author.Name; } } if (target is null && ctx.Args.Length > 0) target = string.Join(" ", ctx.Args); string sender = ctx.Member.Nickname ?? ctx.Member.User?.Name ?? "Unknown"; string text = target is not null ? $"{sender} is happy with {target}!" : $"{sender} is happy!"; var attachment = new MessageAttachment(MessageAttachmentType.Image) { Location = cdnUrl, MimeType = "image/gif", FileName = "happy.gif", Width = width, Height = height }; await MessageHelper.ReplyAsync(ctx, channel, text, [attachment]); } } }