diff --git a/TODO.md b/TODO.md index 87cfbc1..2ecf9e4 100644 --- a/TODO.md +++ b/TODO.md @@ -1,6 +1,6 @@ # List of things to do - - Finish Ellie.Bot.Modules.Searches + - ~~Finish Ellie.Bot.Modules.Searches~~ Finished - Start and finish Ellie.Bot.Modules.Administration - Start and finish Ellie.Bot.Modules.Utility - Start and finish Ellie.Bot.Modules.Music diff --git a/src/Ellie.Bot.Db/Models/punish/PunishmentAction.cs b/src/Ellie.Bot.Db/Models/punish/PunishmentAction.cs new file mode 100644 index 0000000..67f41aa --- /dev/null +++ b/src/Ellie.Bot.Db/Models/punish/PunishmentAction.cs @@ -0,0 +1,15 @@ +namespace Ellie.Services.Database.Models; + +public enum PunishmentAction +{ + Mute, + Kick, + Ban, + Softban, + RemoveRoles, + ChatMute, + VoiceMute, + AddRole, + Warn, + TimeOut +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Anime/AnimeResult.cs b/src/Ellie.Bot.Modules.Searches/Anime/AnimeResult.cs new file mode 100644 index 0000000..7dab4a6 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Anime/AnimeResult.cs @@ -0,0 +1,41 @@ +#nullable disable +using System.Text.Json.Serialization; + +namespace Ellie.Modules.Searches.Common; + +public class AnimeResult +{ + [JsonPropertyName("id")] + public int Id { get; set; } + + [JsonPropertyName("airing_status")] + public string AiringStatusParsed { get; set; } + + [JsonPropertyName("title_english")] + public string TitleEnglish { get; set; } + + [JsonPropertyName("total_episodes")] + public int TotalEpisodes { get; set; } + + [JsonPropertyName("description")] + public string Description { get; set; } + + [JsonPropertyName("image_url_lge")] + public string ImageUrlLarge { get; set; } + + [JsonPropertyName("genres")] + public string[] Genres { get; set; } + + [JsonPropertyName("average_score")] + public float AverageScore { get; set; } + + + public string AiringStatus + => AiringStatusParsed.ToTitleCase(); + + public string Link + => "http://anilist.co/anime/" + Id; + + public string Synopsis + => Description?[..(Description.Length > 500 ? 500 : Description.Length)] + "..."; +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Anime/AnimeSearchCommands.cs b/src/Ellie.Bot.Modules.Searches/Anime/AnimeSearchCommands.cs new file mode 100644 index 0000000..5da8005 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Anime/AnimeSearchCommands.cs @@ -0,0 +1,204 @@ +#nullable disable +using AngleSharp; +using AngleSharp.Html.Dom; +using Ellie.Modules.Searches.Services; + +namespace Ellie.Modules.Searches; + +public partial class Searches +{ + [Group] + public partial class AnimeSearchCommands : EllieModule + { + // [NadekoCommand, Aliases] + // public async Task Novel([Leftover] string query) + // { + // if (string.IsNullOrWhiteSpace(query)) + // return; + // + // var novelData = await _service.GetNovelData(query); + // + // if (novelData is null) + // { + // await ReplyErrorLocalizedAsync(strs.failed_finding_novel); + // return; + // } + // + // var embed = _eb.Create() + // .WithOkColor() + // .WithDescription(novelData.Description.Replace("
", Environment.NewLine, StringComparison.InvariantCulture)) + // .WithTitle(novelData.Title) + // .WithUrl(novelData.Link) + // .WithImageUrl(novelData.ImageUrl) + // .AddField(GetText(strs.authors), string.Join("\n", novelData.Authors), true) + // .AddField(GetText(strs.status), novelData.Status, true) + // .AddField(GetText(strs.genres), string.Join(" ", novelData.Genres.Any() ? novelData.Genres : new[] { "none" }), true) + // .WithFooter($"{GetText(strs.score)} {novelData.Score}"); + // + // await ctx.Channel.EmbedAsync(embed); + // } + + [Cmd] + [Priority(0)] + public async Task Mal([Leftover] string name) + { + if (string.IsNullOrWhiteSpace(name)) + return; + + var fullQueryLink = "https://myanimelist.net/profile/" + name; + + var config = Configuration.Default.WithDefaultLoader(); + using var document = await BrowsingContext.New(config).OpenAsync(fullQueryLink); + var imageElem = + document.QuerySelector( + "body > div#myanimelist > div.wrapper > div#contentWrapper > div#content > div.content-container > div.container-left > div.user-profile > div.user-image > img"); + var imageUrl = ((IHtmlImageElement)imageElem)?.Source + ?? "http://icecream.me/uploads/870b03f36b59cc16ebfe314ef2dde781.png"; + + var stats = document + .QuerySelectorAll( + "body > div#myanimelist > div.wrapper > div#contentWrapper > div#content > div.content-container > div.container-right > div#statistics > div.user-statistics-stats > div.stats > div.clearfix > ul.stats-status > li > span") + .Select(x => x.InnerHtml) + .ToList(); + + var favorites = document.QuerySelectorAll("div.user-favorites > div.di-tc"); + + var favAnime = GetText(strs.anime_no_fav); + if (favorites.Length > 0 && favorites[0].QuerySelector("p") is null) + { + favAnime = string.Join("\n", + favorites[0] + .QuerySelectorAll("ul > li > div.di-tc.va-t > a") + .Shuffle() + .Take(3) + .Select(x => + { + var elem = (IHtmlAnchorElement)x; + return $"[{elem.InnerHtml}]({elem.Href})"; + })); + } + + var info = document.QuerySelectorAll("ul.user-status:nth-child(3) > li.clearfix") + .Select(x => Tuple.Create(x.Children[0].InnerHtml, x.Children[1].InnerHtml)) + .ToList(); + + var daysAndMean = document.QuerySelectorAll("div.anime:nth-child(1) > div:nth-child(2) > div") + .Select(x => x.TextContent.Split(':').Select(y => y.Trim()).ToArray()) + .ToArray(); + + var embed = _eb.Create() + .WithOkColor() + .WithTitle(GetText(strs.mal_profile(name))) + .AddField("💚 " + GetText(strs.watching), stats[0], true) + .AddField("💙 " + GetText(strs.completed), stats[1], true); + if (info.Count < 3) + embed.AddField("💛 " + GetText(strs.on_hold), stats[2], true); + embed.AddField("💔 " + GetText(strs.dropped), stats[3], true) + .AddField("⚪ " + GetText(strs.plan_to_watch), stats[4], true) + .AddField("🕐 " + daysAndMean[0][0], daysAndMean[0][1], true) + .AddField("📊 " + daysAndMean[1][0], daysAndMean[1][1], true) + .AddField(MalInfoToEmoji(info[0].Item1) + " " + info[0].Item1, info[0].Item2.TrimTo(20), true) + .AddField(MalInfoToEmoji(info[1].Item1) + " " + info[1].Item1, info[1].Item2.TrimTo(20), true); + if (info.Count > 2) + embed.AddField(MalInfoToEmoji(info[2].Item1) + " " + info[2].Item1, info[2].Item2.TrimTo(20), true); + + embed.WithDescription($@" +** https://myanimelist.net/animelist/{name} ** + +**{GetText(strs.top_3_fav_anime)}** +{favAnime}") + .WithUrl(fullQueryLink) + .WithImageUrl(imageUrl); + + await ctx.Channel.EmbedAsync(embed); + } + + private static string MalInfoToEmoji(string info) + { + info = info.Trim().ToLowerInvariant(); + switch (info) + { + case "gender": + return "🚁"; + case "location": + return "🗺"; + case "last online": + return "👥"; + case "birthday": + return "📆"; + default: + return "❔"; + } + } + + [Cmd] + [RequireContext(ContextType.Guild)] + [Priority(1)] + public Task Mal(IGuildUser usr) + => Mal(usr.Username); + + [Cmd] + public async Task Anime([Leftover] string query) + { + if (string.IsNullOrWhiteSpace(query)) + return; + + var animeData = await _service.GetAnimeData(query); + + if (animeData is null) + { + await ReplyErrorLocalizedAsync(strs.failed_finding_anime); + return; + } + + var embed = _eb.Create() + .WithOkColor() + .WithDescription(animeData.Synopsis.Replace("
", + Environment.NewLine, + StringComparison.InvariantCulture)) + .WithTitle(animeData.TitleEnglish) + .WithUrl(animeData.Link) + .WithImageUrl(animeData.ImageUrlLarge) + .AddField(GetText(strs.episodes), animeData.TotalEpisodes.ToString(), true) + .AddField(GetText(strs.status), animeData.AiringStatus, true) + .AddField(GetText(strs.genres), + string.Join(",\n", animeData.Genres.Any() ? animeData.Genres : new[] { "none" }), + true) + .WithFooter($"{GetText(strs.score)} {animeData.AverageScore} / 100"); + await ctx.Channel.EmbedAsync(embed); + } + + [Cmd] + [RequireContext(ContextType.Guild)] + public async Task Manga([Leftover] string query) + { + if (string.IsNullOrWhiteSpace(query)) + return; + + var mangaData = await _service.GetMangaData(query); + + if (mangaData is null) + { + await ReplyErrorLocalizedAsync(strs.failed_finding_manga); + return; + } + + var embed = _eb.Create() + .WithOkColor() + .WithDescription(mangaData.Synopsis.Replace("
", + Environment.NewLine, + StringComparison.InvariantCulture)) + .WithTitle(mangaData.TitleEnglish) + .WithUrl(mangaData.Link) + .WithImageUrl(mangaData.ImageUrlLge) + .AddField(GetText(strs.chapters), mangaData.TotalChapters.ToString(), true) + .AddField(GetText(strs.status), mangaData.PublishingStatus, true) + .AddField(GetText(strs.genres), + string.Join(",\n", mangaData.Genres.Any() ? mangaData.Genres : new[] { "none" }), + true) + .WithFooter($"{GetText(strs.score)} {mangaData.AverageScore} / 100"); + + await ctx.Channel.EmbedAsync(embed); + } + } +} diff --git a/src/Ellie.Bot.Modules.Searches/Anime/AnimeSearchService.cs b/src/Ellie.Bot.Modules.Searches/Anime/AnimeSearchService.cs new file mode 100644 index 0000000..b4f1580 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Anime/AnimeSearchService.cs @@ -0,0 +1,79 @@ +#nullable disable +using Ellie.Modules.Searches.Common; +using System.Net.Http.Json; + +namespace Ellie.Modules.Searches.Services; + +public class AnimeSearchService : IEService +{ + private readonly IBotCache _cache; + private readonly IHttpClientFactory _httpFactory; + + public AnimeSearchService(IBotCache cache, IHttpClientFactory httpFactory) + { + _cache = cache; + _httpFactory = httpFactory; + } + + public async Task GetAnimeData(string query) + { + if (string.IsNullOrWhiteSpace(query)) + throw new ArgumentNullException(nameof(query)); + + TypedKey GetKey(string link) + => new TypedKey($"anime2:{link}"); + + try + { + var suffix = Uri.EscapeDataString(query.Replace("/", " ", StringComparison.InvariantCulture)); + var link = $"https://aniapi.nadeko.bot/anime/{suffix}"; + link = link.ToLowerInvariant(); + var result = await _cache.GetAsync(GetKey(link)); + if (!result.TryPickT0(out var data, out _)) + { + using var http = _httpFactory.CreateClient(); + data = await http.GetFromJsonAsync(link); + + await _cache.AddAsync(GetKey(link), data, expiry: TimeSpan.FromHours(12)); + } + + return data; + } + catch + { + return null; + } + } + + public async Task GetMangaData(string query) + { + if (string.IsNullOrWhiteSpace(query)) + throw new ArgumentNullException(nameof(query)); + + TypedKey GetKey(string link) + => new TypedKey($"manga2:{link}"); + + try + { + var link = "https://aniapi.nadeko.bot/manga/" + + Uri.EscapeDataString(query.Replace("/", " ", StringComparison.InvariantCulture)); + link = link.ToLowerInvariant(); + + var result = await _cache.GetAsync(GetKey(link)); + if (!result.TryPickT0(out var data, out _)) + { + using var http = _httpFactory.CreateClient(); + data = await http.GetFromJsonAsync(link); + + await _cache.AddAsync(GetKey(link), data, expiry: TimeSpan.FromHours(3)); + } + + + return data; + } + catch + { + return null; + } + } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Anime/MangaResult.cs b/src/Ellie.Bot.Modules.Searches/Anime/MangaResult.cs new file mode 100644 index 0000000..7fce366 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Anime/MangaResult.cs @@ -0,0 +1,40 @@ +#nullable disable +using System.Text.Json.Serialization; + +namespace Ellie.Modules.Searches.Common; + +public class MangaResult +{ + [JsonPropertyName("id")] + public int Id { get; set; } + + [JsonPropertyName("publishing_status")] + public string PublishingStatus { get; set; } + + [JsonPropertyName("image_url_lge")] + public string ImageUrlLge { get; set; } + + [JsonPropertyName("title_english")] + public string TitleEnglish { get; set; } + + [JsonPropertyName("total_chapters")] + public int TotalChapters { get; set; } + + [JsonPropertyName("total_volumes")] + public int TotalVolumes { get; set; } + + [JsonPropertyName("description")] + public string Description { get; set; } + + [JsonPropertyName("genres")] + public string[] Genres { get; set; } + + [JsonPropertyName("average_score")] + public float AverageScore { get; set; } + + public string Link + => "http://anilist.co/manga/" + Id; + + public string Synopsis + => Description?[..(Description.Length > 500 ? 500 : Description.Length)] + "..."; +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/CryptoCommands.cs b/src/Ellie.Bot.Modules.Searches/Crypto/CryptoCommands.cs new file mode 100644 index 0000000..54bf006 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/CryptoCommands.cs @@ -0,0 +1,196 @@ +#nullable disable +using Ellie.Modules.Searches.Services; +using System.Globalization; + +namespace Ellie.Modules.Searches; + +public partial class Searches +{ + public partial class FinanceCommands : EllieModule + { + private readonly IStockDataService _stocksService; + private readonly IStockChartDrawingService _stockDrawingService; + + public FinanceCommands(IStockDataService stocksService, IStockChartDrawingService stockDrawingService) + { + _stocksService = stocksService; + _stockDrawingService = stockDrawingService; + } + + [Cmd] + public async Task Stock([Leftover]string query) + { + using var typing = ctx.Channel.EnterTypingState(); + + var stock = await _stocksService.GetStockDataAsync(query); + + if (stock is null) + { + var symbols = await _stocksService.SearchSymbolAsync(query); + + if (symbols.Count == 0) + { + await ReplyErrorLocalizedAsync(strs.not_found); + return; + } + + var symbol = symbols.First(); + var promptEmbed = _eb.Create() + .WithDescription(symbol.Description) + .WithTitle(GetText(strs.did_you_mean(symbol.Symbol))); + + if (!await PromptUserConfirmAsync(promptEmbed)) + return; + + query = symbol.Symbol; + stock = await _stocksService.GetStockDataAsync(query); + + if (stock is null) + { + await ReplyErrorLocalizedAsync(strs.not_found); + return; + } + } + + var candles = await _stocksService.GetCandleDataAsync(query); + var stockImageTask = _stockDrawingService.GenerateCombinedChartAsync(candles); + + var localCulture = (CultureInfo)Culture.Clone(); + localCulture.NumberFormat.CurrencySymbol = "$"; + + var sign = stock.Price >= stock.Close + ? "\\🔼" + : "\\🔻"; + + var change = (stock.Price - stock.Close).ToString("N2", Culture); + var changePercent = (1 - (stock.Close / stock.Price)).ToString("P1", Culture); + + var sign50 = stock.Change50d >= 0 + ? "\\🔼" + : "\\🔻"; + + var change50 = (stock.Change50d).ToString("P1", Culture); + + var sign200 = stock.Change200d >= 0 + ? "\\🔼" + : "\\🔻"; + + var change200 = (stock.Change200d).ToString("P1", Culture); + + var price = stock.Price.ToString("C2", localCulture); + + var eb = _eb.Create() + .WithOkColor() + .WithAuthor(stock.Symbol) + .WithUrl($"https://www.tradingview.com/chart/?symbol={stock.Symbol}") + .WithTitle(stock.Name) + .AddField(GetText(strs.price), $"{sign} **{price}**", true) + .AddField(GetText(strs.market_cap), stock.MarketCap.ToString("C0", localCulture), true) + .AddField(GetText(strs.volume_24h), stock.DailyVolume.ToString("C0", localCulture), true) + .AddField("Change", $"{change} ({changePercent})", true) + .AddField("Change 50d", $"{sign50}{change50}", true) + .AddField("Change 200d", $"{sign200}{change200}", true) + .WithFooter(stock.Exchange); + + var message = await ctx.Channel.EmbedAsync(eb); + await using var imageData = await stockImageTask; + if (imageData is null) + return; + + var fileName = $"{query}-sparkline.{imageData.Extension}"; + using var attachment = new FileAttachment( + imageData.FileData, + fileName + ); + await message.ModifyAsync(mp => + { + mp.Attachments = + new(new[] + { + attachment + }); + + mp.Embed = eb.WithImageUrl($"attachment://{fileName}").Build(); + }); + } + + + [Cmd] + public async Task Crypto(string name) + { + name = name?.ToUpperInvariant(); + + if (string.IsNullOrWhiteSpace(name)) + return; + + var (crypto, nearest) = await _service.GetCryptoData(name); + + if (nearest is not null) + { + var embed = _eb.Create() + .WithTitle(GetText(strs.crypto_not_found)) + .WithDescription( + GetText(strs.did_you_mean(Format.Bold($"{nearest.Name} ({nearest.Symbol})")))); + + if (await PromptUserConfirmAsync(embed)) + crypto = nearest; + } + + if (crypto is null) + { + await ReplyErrorLocalizedAsync(strs.crypto_not_found); + return; + } + + var usd = crypto.Quote["USD"]; + + var localCulture = (CultureInfo)Culture.Clone(); + localCulture.NumberFormat.CurrencySymbol = "$"; + + var sevenDay = (usd.PercentChange7d / 100).ToString("P2", localCulture); + var lastDay = (usd.PercentChange24h / 100).ToString("P2", localCulture); + var price = usd.Price < 0.01 + ? usd.Price.ToString(localCulture) + : usd.Price.ToString("C2", localCulture); + + var volume = usd.Volume24h.ToString("C0", localCulture); + var marketCap = usd.MarketCap.ToString("C0", localCulture); + var dominance = (usd.MarketCapDominance / 100).ToString("P2", localCulture); + + await using var sparkline = await _service.GetSparklineAsync(crypto.Id, usd.PercentChange7d >= 0); + var fileName = $"{crypto.Slug}_7d.png"; + + var toSend = _eb.Create() + .WithOkColor() + .WithAuthor($"#{crypto.CmcRank}") + .WithTitle($"{crypto.Name} ({crypto.Symbol})") + .WithUrl($"https://coinmarketcap.com/currencies/{crypto.Slug}/") + .WithThumbnailUrl($"https://s3.coinmarketcap.com/static/img/coins/128x128/{crypto.Id}.png") + .AddField(GetText(strs.market_cap), marketCap, true) + .AddField(GetText(strs.price), price, true) + .AddField(GetText(strs.volume_24h), volume, true) + .AddField(GetText(strs.change_7d_24h), $"{sevenDay} / {lastDay}", true) + .AddField(GetText(strs.market_cap_dominance), dominance, true) + .WithImageUrl($"attachment://{fileName}"); + + if (crypto.CirculatingSupply is double cs) + { + var csStr = cs.ToString("N0", localCulture); + + if (crypto.MaxSupply is double ms) + { + var perc = (cs / ms).ToString("P1", localCulture); + + toSend.AddField(GetText(strs.circulating_supply), $"{csStr} ({perc})", true); + } + else + { + toSend.AddField(GetText(strs.circulating_supply), csStr, true); + } + } + + + await ctx.Channel.SendFileAsync(sparkline, fileName, embed: toSend.Build()); + } + } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/CryptoService.cs b/src/Ellie.Bot.Modules.Searches/Crypto/CryptoService.cs new file mode 100644 index 0000000..9532478 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/CryptoService.cs @@ -0,0 +1,216 @@ +#nullable enable +using Ellie.Modules.Searches.Common; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Drawing.Processing; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing; +using System.Globalization; +using System.Net.Http.Json; +using System.Xml; +using Color = SixLabors.ImageSharp.Color; +using StringExtensions = Ellie.Extensions.StringExtensions; + + +namespace Ellie.Modules.Searches.Services; + +public class CryptoService : IEService +{ + private readonly IBotCache _cache; + private readonly IHttpClientFactory _httpFactory; + private readonly IBotCredentials _creds; + + private readonly SemaphoreSlim _getCryptoLock = new(1, 1); + + public CryptoService(IBotCache cache, IHttpClientFactory httpFactory, IBotCredentials creds) + { + _cache = cache; + _httpFactory = httpFactory; + _creds = creds; + } + + private PointF[] GetSparklinePointsFromSvgText(string svgText) + { + var xml = new XmlDocument(); + xml.LoadXml(svgText); + + var gElement = xml["svg"]?["g"]; + if (gElement is null) + return Array.Empty(); + + Span points = new PointF[gElement.ChildNodes.Count]; + var cnt = 0; + + bool GetValuesFromAttributes( + XmlAttributeCollection attrs, + out float x1, + out float y1, + out float x2, + out float y2) + { + (x1, y1, x2, y2) = (0, 0, 0, 0); + return attrs["x1"]?.Value is string x1Str + && float.TryParse(x1Str, NumberStyles.Any, CultureInfo.InvariantCulture, out x1) + && attrs["y1"]?.Value is string y1Str + && float.TryParse(y1Str, NumberStyles.Any, CultureInfo.InvariantCulture, out y1) + && attrs["x2"]?.Value is string x2Str + && float.TryParse(x2Str, NumberStyles.Any, CultureInfo.InvariantCulture, out x2) + && attrs["y2"]?.Value is string y2Str + && float.TryParse(y2Str, NumberStyles.Any, CultureInfo.InvariantCulture, out y2); + } + + foreach (XmlElement x in gElement.ChildNodes) + { + if (x.Name != "line") + continue; + + if (GetValuesFromAttributes(x.Attributes, out var x1, out var y1, out var x2, out var y2)) + { + points[cnt++] = new(x1, y1); + // this point will be set twice to the same value + // on all points except the last one + if (cnt + 1 < points.Length) + points[cnt + 1] = new(x2, y2); + } + } + + if (cnt == 0) + return Array.Empty(); + + return points.Slice(0, cnt).ToArray(); + } + + private SixLabors.ImageSharp.Image GenerateSparklineChart(PointF[] points, bool up) + { + const int width = 164; + const int height = 48; + + var img = new Image(width, height, Color.Transparent); + var color = up + ? Color.Green + : Color.FromRgb(220, 0, 0); + + img.Mutate(x => + { + x.DrawLines(color, 2, points); + }); + + return img; + } + + public async Task<(CmcResponseData? Data, CmcResponseData? Nearest)> GetCryptoData(string name) + { + if (string.IsNullOrWhiteSpace(name)) + return (null, null); + + name = name.ToUpperInvariant(); + var cryptos = await GetCryptoDataInternal(); + + if (cryptos is null or { Count: 0 }) + return (null, null); + + var crypto = cryptos.FirstOrDefault(x + => x.Slug.ToUpperInvariant() == name + || x.Name.ToUpperInvariant() == name + || x.Symbol.ToUpperInvariant() == name); + + if (crypto is not null) + return (crypto, null); + + + var nearest = cryptos + .Select(elem => (Elem: elem, + Distance: StringExtensions.LevenshteinDistance(elem.Name.ToUpperInvariant(), name))) + .OrderBy(x => x.Distance) + .FirstOrDefault(x => x.Distance <= 2); + + return (null, nearest.Elem); + } + + public async Task?> GetCryptoDataInternal() + { + await _getCryptoLock.WaitAsync(); + try + { + var data = await _cache.GetOrAddAsync(new("nadeko:crypto_data"), + async () => + { + try + { + using var http = _httpFactory.CreateClient(); + var data = await http.GetFromJsonAsync( + "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?" + + $"CMC_PRO_API_KEY={_creds.CoinmarketcapApiKey}" + + "&start=1" + + "&limit=5000" + + "&convert=USD"); + + return data; + } + catch (Exception ex) + { + Log.Error(ex, "Error getting crypto data: {Message}", ex.Message); + return default; + } + }, + TimeSpan.FromHours(2)); + + if (data is null) + return default; + + return data.Data; + } + catch (Exception ex) + { + Log.Error(ex, "Error retreiving crypto data: {Message}", ex.Message); + return default; + } + finally + { + _getCryptoLock.Release(); + } + } + + private TypedKey GetSparklineKey(int id) + => new($"crypto:sparkline:{id}"); + + public async Task GetSparklineAsync(int id, bool up) + { + try + { + var bytes = await _cache.GetOrAddAsync(GetSparklineKey(id), + async () => + { + // if it fails, generate a new one + var points = await DownloadSparklinePointsAsync(id); + var sparkline = GenerateSparklineChart(points, up); + + using var stream = await sparkline.ToStreamAsync(); + return stream.ToArray(); + }, + TimeSpan.FromHours(1)); + + if (bytes is { Length: > 0 }) + { + return bytes.ToStream(); + } + + return default; + } + catch (Exception ex) + { + Log.Warning(ex, + "Exception occurred while downloading sparkline points: {ErrorMessage}", + ex.Message); + return default; + } + } + + private async Task DownloadSparklinePointsAsync(int id) + { + using var http = _httpFactory.CreateClient(); + var str = await http.GetStringAsync( + $"https://s3.coinmarketcap.com/generated/sparklines/web/7d/usd/{id}.svg"); + var points = GetSparklinePointsFromSvgText(str); + return points; + } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/DefaultStockDataService.cs b/src/Ellie.Bot.Modules.Searches/Crypto/DefaultStockDataService.cs new file mode 100644 index 0000000..9bef0fd --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/DefaultStockDataService.cs @@ -0,0 +1,103 @@ +using CsvHelper; +using CsvHelper.Configuration; +using System.Globalization; +using System.Net.Http.Json; +using System.Text.Json; + +namespace Ellie.Modules.Searches; + +public class DefaultStockDataService : IStockDataService, IEService +{ + private readonly IHttpClientFactory _httpClientFactory; + + public DefaultStockDataService(IHttpClientFactory httpClientFactory) + => _httpClientFactory = httpClientFactory; + + public async Task GetStockDataAsync(string query) + { + try + { + if (!query.IsAlphaNumeric()) + return default; + + using var http = _httpClientFactory.CreateClient(); + var data = await http.GetFromJsonAsync( + $"https://query1.finance.yahoo.com/v7/finance/quote?symbols={query}"); + + if (data is null) + return default; + + var symbol = data.QuoteResponse.Result.FirstOrDefault(); + + if (symbol is null) + return default; + + return new() + { + Name = symbol.LongName, + Symbol = symbol.Symbol, + Price = symbol.RegularMarketPrice, + Close = symbol.RegularMarketPreviousClose, + MarketCap = symbol.MarketCap, + Change50d = symbol.FiftyDayAverageChangePercent, + Change200d = symbol.TwoHundredDayAverageChangePercent, + DailyVolume = symbol.AverageDailyVolume10Day, + Exchange = symbol.FullExchangeName + }; + } + catch (Exception) + { + // Log.Warning(ex, "Error getting stock data: {ErrorMessage}", ex.Message); + return default; + } + } + + public async Task> SearchSymbolAsync(string query) + { + if (string.IsNullOrWhiteSpace(query)) + throw new ArgumentNullException(nameof(query)); + + query = Uri.EscapeDataString(query); + + using var http = _httpClientFactory.CreateClient(); + + var res = await http.GetStringAsync( + "https://finance.yahoo.com/_finance_doubledown/api/resource/searchassist" + + $";searchTerm={query}" + + "?device=console"); + + var data = JsonSerializer.Deserialize(res); + + if (data is null or { Items: null }) + return Array.Empty(); + + return data.Items + .Where(x => x.Type == "S") + .Select(x => new SymbolData(x.Symbol, x.Name)) + .ToList(); + } + + private static CsvConfiguration _csvConfig = new(CultureInfo.InvariantCulture) + { + PrepareHeaderForMatch = args => args.Header.Humanize(LetterCasing.Title) + }; + + // todo replace .ToTimestamp() and remove google protobuf dependency + // todo this needs testing + public async Task> GetCandleDataAsync(string query) + { + using var http = _httpClientFactory.CreateClient(); + await using var resStream = await http.GetStreamAsync( + $"https://query1.finance.yahoo.com/v7/finance/download/{query}" + + $"?period1={DateTime.UtcNow.Subtract(30.Days()).ToTimestamp()}" + + $"&period2={DateTime.UtcNow.ToTimestamp()}" + + "&interval=1d"); + + using var textReader = new StreamReader(resStream); + using var csv = new CsvReader(textReader, _csvConfig); + var records = csv.GetRecords().ToArray(); + + return records + .Map(static x => new CandleData(x.Open, x.Close, x.High, x.Low, x.Volume)); + } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/Drawing/CandleDrawingData.cs b/src/Ellie.Bot.Modules.Searches/Crypto/Drawing/CandleDrawingData.cs new file mode 100644 index 0000000..6857d1c --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/Drawing/CandleDrawingData.cs @@ -0,0 +1,12 @@ +using SixLabors.ImageSharp; + +namespace Ellie.Modules.Searches; + +/// +/// All data required to draw a candle +/// +/// Whether the candle is green +/// Rectangle for the body +/// High line point +/// Low line point +public record CandleDrawingData(bool IsGreen, RectangleF BodyRect, PointF High, PointF Low); \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/Drawing/IStockChartDrawingService.cs b/src/Ellie.Bot.Modules.Searches/Crypto/Drawing/IStockChartDrawingService.cs new file mode 100644 index 0000000..9bf7092 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/Drawing/IStockChartDrawingService.cs @@ -0,0 +1,8 @@ +namespace Ellie.Modules.Searches; + +public interface IStockChartDrawingService +{ + Task GenerateSparklineAsync(IReadOnlyCollection series); + Task GenerateCombinedChartAsync(IReadOnlyCollection series); + Task GenerateCandleChartAsync(IReadOnlyCollection series); +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/Drawing/ImagesharpStockChartDrawingService.cs b/src/Ellie.Bot.Modules.Searches/Crypto/Drawing/ImagesharpStockChartDrawingService.cs new file mode 100644 index 0000000..e6840a0 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/Drawing/ImagesharpStockChartDrawingService.cs @@ -0,0 +1,202 @@ +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Drawing.Processing; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing; +using System.Runtime.CompilerServices; +using Color = SixLabors.ImageSharp.Color; + +namespace Ellie.Modules.Searches; + +public class ImagesharpStockChartDrawingService : IStockChartDrawingService, IEService +{ + private const int WIDTH = 300; + private const int HEIGHT = 100; + private const decimal MAX_HEIGHT = HEIGHT * 0.8m; + + private static readonly Rgba32 _backgroundColor = Rgba32.ParseHex("17181E"); + private static readonly Rgba32 _lineGuideColor = Rgba32.ParseHex("212125"); + private static readonly Rgba32 _sparklineColor = Rgba32.ParseHex("2961FC"); + private static readonly Rgba32 _greenBrush = Rgba32.ParseHex("26A69A"); + private static readonly Rgba32 _redBrush = Rgba32.ParseHex("EF5350"); + + public static float GetNormalizedPoint(decimal max, decimal point, decimal range) + => (float)((MAX_HEIGHT * ((max - point) / range)) + HeightOffset()); + + private PointF[] GetSparklinePointsInternal(IReadOnlyCollection series) + { + var candleStep = WIDTH / (series.Count + 1); + var max = series.Max(static x => x.High); + var min = series.Min(static x => x.Low); + + var range = max - min; + + var points = new PointF[series.Count]; + + var i = 0; + foreach (var candle in series) + { + var x = candleStep * (i + 1); + + var y = GetNormalizedPoint(max, candle.Close, range); + points[i++] = new(x, y); + } + + return points; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static decimal HeightOffset() + => (HEIGHT - MAX_HEIGHT) / 2m; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Image CreateCanvasInternal() + => new Image(WIDTH, HEIGHT, _backgroundColor); + + private CandleDrawingData[] GetChartDrawingDataInternal(IReadOnlyCollection series) + { + var candleMargin = 2; + var candleStep = (WIDTH - (candleMargin * series.Count)) / (series.Count + 1); + var max = series.Max(static x => x.High); + var min = series.Min(static x => x.Low); + + var range = max = min; + + var drawData = new CandleDrawingData[series.Count]; + + var candleWidth = candleStep; + + var i = 0; + foreach (var candle in series) + { + var offsetX = (i - 1) * candleMargin; + var x = (candleStep * (i = 1)) + offsetX; + var yOpen = GetNormalizedPoint(max, candle.Open, range); + var yClose = GetNormalizedPoint(max, candle.Close, range); + var y = candle.Open > candle.Close + ? yOpen + : yClose; + + var sizeH = Math.Abs(yOpen - yClose); + + var high = GetNormalizedPoint(max, candle.High, range); + var low = GetNormalizedPoint(max, candle.Low, range); + drawData[i] = new(candle.Open < candle.Close, + new(x, y, candleWidth, sizeH), + new(x + (candleStep / 2), high), + new(x + (candleStep / 2), low)); + ++i; + } + + return drawData; + } + + private void DrawChartData(Image image, CandleDrawingData[] drawData) + => image.Mutate(ctx => + { + foreach (var data in drawData) + DrawLineExtensions.DrawLines(ctx, + data.IsGreen + ? _greenBrush + : _redBrush, + 1, + data.High, + data.Low); + + + foreach (var data in drawData) + FillRectangleExtensions.Fill(ctx, + data.IsGreen + ? _greenBrush + : _redBrush, + data.BodyRect); + }); + + private void DrawLineGuides(Image image, IReadOnlyCollection series) + { + var max = series.Max(x => x.High); + var min = series.Min(x => x.Low); + + var step = (max - min) / 5; + + var lines = new float[6]; + + for (var i = 0; i < 6; i++) + { + var y = GetNormalizedPoint(max, min + (step * i), max - min); + lines[i] = y; + } + + image.Mutate(ctx => + { + // draw guides + foreach (var y in lines) + ctx.DrawLines(_lineGuideColor, 1, new PointF(0, y), new PointF(WIDTH, y)); + + // // draw min and max price on the chart + // ctx.DrawText(min.ToString(CultureInfo.InvariantCulture), + // SystemFonts.CreateFont("Arial", 5), + // Color.White, + // new PointF(0, (float)HeightOffset() - 5) + // ); + // + // ctx.DrawText(max.ToString("N1", CultureInfo.InvariantCulture), + // SystemFonts.CreateFont("Arial", 5), + // Color.White, + // new PointF(0, HEIGHT - (float)HeightOffset()) + // ); + }); + } + + public Task GenerateSparklineAsync(IReadOnlyCollection series) + { + if (series.Count == 0) + return Task.FromResult(default); + + using var image = CreateCanvasInternal(); + + var points = GetSparklinePointsInternal(series); + + image.Mutate(ctx => + { + ctx.DrawLines(_sparklineColor, 2, points); + }); + + return Task.FromResult(new("png", image.ToStream())); + } + + public Task GenerateCombinedChartAsync(IReadOnlyCollection series) + { + if (series.Count == 0) + return Task.FromResult(default); + + using var image = CreateCanvasInternal(); + + DrawLineGuides(image, series); + + var chartData = GetChartDrawingDataInternal(series); + DrawChartData(image, chartData); + + var points = GetSparklinePointsInternal(series); + image.Mutate(ctx => + { + ctx.DrawLines(Color.ParseHex("00FFFFAA"), 1, points); + }); + + return Task.FromResult(new("png", image.ToStream())); + } + + public Task GenerateCandleChartAsync(IReadOnlyCollection series) + { + if (series.Count == 0) + return Task.FromResult(default); + + using var image = CreateCanvasInternal(); + + DrawLineGuides(image, series); + + var drawData = GetChartDrawingDataInternal(series); + DrawChartData(image, drawData); + + return Task.FromResult(new("png", image.ToStream())); + } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/IStockDataService.cs b/src/Ellie.Bot.Modules.Searches/Crypto/IStockDataService.cs new file mode 100644 index 0000000..c9f089e --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/IStockDataService.cs @@ -0,0 +1,8 @@ +namespace Ellie.Modules.Searches; + +public interface IStockDataService +{ + public Task GetStockDataAsync(string symbol); + Task> SearchSymbolAsync(string query); + Task> GetCandleDataAsync(string query); +} diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/Polygon/FinnHubSearchResponse.cs b/src/Ellie.Bot.Modules.Searches/Crypto/Polygon/FinnHubSearchResponse.cs new file mode 100644 index 0000000..20e247a --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/Polygon/FinnHubSearchResponse.cs @@ -0,0 +1,13 @@ +#nullable disable +using System.Text.Json.Serialization; + +namespace Ellie.Modules.Searches; + +public class FinnHubSearchResponse +{ + [JsonPropertyName("count")] + public int Count { get; set; } + + [JsonPropertyName("result")] + public List Result { get; set; } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/Polygon/FinnHubSearchResult.cs b/src/Ellie.Bot.Modules.Searches/Crypto/Polygon/FinnHubSearchResult.cs new file mode 100644 index 0000000..9b79b86 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/Polygon/FinnHubSearchResult.cs @@ -0,0 +1,19 @@ +#nullable disable +using System.Text.Json.Serialization; + +namespace Ellie.Modules.Searches; + +public class FinnHubSearchResult +{ + [JsonPropertyName("description")] + public string Description { get; set; } + + [JsonPropertyName("displaySymbol")] + public string DisplaySymbol { get; set; } + + [JsonPropertyName("symbol")] + public string Symbol { get; set; } + + [JsonPropertyName("type")] + public string Type { get; set; } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/Polygon/PolygonApiClient.cs b/src/Ellie.Bot.Modules.Searches/Crypto/Polygon/PolygonApiClient.cs new file mode 100644 index 0000000..f418d49 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/Polygon/PolygonApiClient.cs @@ -0,0 +1,55 @@ +// using System.Net.Http.Json; +// +// namespace Ellie.Modules.Searches; +// +// public sealed class PolygonApiClient : IDisposable +// { +// private const string BASE_URL = "https://api.polygon.io/v3"; +// +// private readonly HttpClient _httpClient; +// private readonly string _apiKey; +// +// public PolygonApiClient(HttpClient httpClient, string apiKey) +// { +// _httpClient = httpClient; +// _apiKey = apiKey; +// } +// +// public async Task> TickersAsync(string? ticker = null, string? query = null) +// { +// if (string.IsNullOrWhiteSpace(query)) +// query = null; +// +// if(query is not null) +// query = Uri.EscapeDataString(query); +// +// var requestString = $"{BASE_URL}/reference/tickers" +// + "?type=CS" +// + "&active=true" +// + "&order=asc" +// + "&limit=1000" +// + $"&apiKey={_apiKey}"; +// +// if (!string.IsNullOrWhiteSpace(ticker)) +// requestString += $"&ticker={ticker}"; +// +// if (!string.IsNullOrWhiteSpace(query)) +// requestString += $"&search={query}"; +// +// +// var response = await _httpClient.GetFromJsonAsync(requestString); +// +// if (response is null) +// return Array.Empty(); +// +// return response.Results; +// } +// +// // public async Task TickerDetailsV3Async(string ticker) +// // { +// // return new(); +// // } +// +// public void Dispose() +// => _httpClient.Dispose(); +// } \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/Polygon/PolygonStockDataService.cs b/src/Ellie.Bot.Modules.Searches/Crypto/Polygon/PolygonStockDataService.cs new file mode 100644 index 0000000..47478cf --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/Polygon/PolygonStockDataService.cs @@ -0,0 +1,26 @@ +// namespace Ellie.Modules.Searches; +// +// public sealed class PolygonStockDataService : IStockDataService +// { +// private readonly IHttpClientFactory _httpClientFactory; +// private readonly IBotCredsProvider _credsProvider; +// +// public PolygonStockDataService(IHttpClientFactory httpClientFactory, IBotCredsProvider credsProvider) +// { +// _httpClientFactory = httpClientFactory; +// _credsProvider = credsProvider; +// } +// +// public async Task> GetStockDataAsync(string? query = null) +// { +// using var httpClient = _httpClientFactory.CreateClient(); +// using var client = new PolygonApiClient(httpClient, string.Empty); +// var data = await client.TickersAsync(query: query); +// +// return data.Map(static x => new StockData() +// { +// Name = x.Name, +// Ticker = x.Ticker, +// }); +// } +// } \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/Polygon/PolygonTickerData.cs b/src/Ellie.Bot.Modules.Searches/Crypto/Polygon/PolygonTickerData.cs new file mode 100644 index 0000000..d09f9ed --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/Polygon/PolygonTickerData.cs @@ -0,0 +1,43 @@ +#nullable disable +using System.Text.Json.Serialization; + +namespace Ellie.Modules.Searches; + +public class PolygonTickerData +{ + [JsonPropertyName("ticker")] + public string Ticker { get; set; } + + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonPropertyName("market")] + public string Market { get; set; } + + [JsonPropertyName("locale")] + public string Locale { get; set; } + + [JsonPropertyName("primary_exchange")] + public string PrimaryExchange { get; set; } + + [JsonPropertyName("type")] + public string Type { get; set; } + + [JsonPropertyName("active")] + public bool Active { get; set; } + + [JsonPropertyName("currency_name")] + public string CurrencyName { get; set; } + + [JsonPropertyName("cik")] + public string Cik { get; set; } + + [JsonPropertyName("composite_figi")] + public string CompositeFigi { get; set; } + + [JsonPropertyName("share_class_figi")] + public string ShareClassFigi { get; set; } + + [JsonPropertyName("last_updated_utc")] + public DateTime LastUpdatedUtc { get; set; } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/Polygon/PolygonTickerResponse.cs b/src/Ellie.Bot.Modules.Searches/Crypto/Polygon/PolygonTickerResponse.cs new file mode 100644 index 0000000..13575e1 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/Polygon/PolygonTickerResponse.cs @@ -0,0 +1,13 @@ +#nullable disable +using System.Text.Json.Serialization; + +namespace Ellie.Modules.Searches; + +public class PolygonTickerResponse +{ + [JsonPropertyName("status")] + public string Status { get; set; } + + [JsonPropertyName("results")] + public List Results { get; set; } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/_common/CandleData.cs b/src/Ellie.Bot.Modules.Searches/Crypto/_common/CandleData.cs new file mode 100644 index 0000000..b277e0e --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/_common/CandleData.cs @@ -0,0 +1,9 @@ +namespace Ellie.Modules.Searches; + +public record CandleData +( + decimal Open, + decimal Close, + decimal High, + decimal Low, + long Volume); diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/_common/ImageData.cs b/src/Ellie.Bot.Modules.Searches/Crypto/_common/ImageData.cs new file mode 100644 index 0000000..3e3c25b --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/_common/ImageData.cs @@ -0,0 +1,7 @@ +namespace Ellie.Modules.Searches; + +public record ImageData(string Extension, Stream FileData) : IAsyncDisposable +{ + public ValueTask DisposeAsync() + => FileData.DisposeAsync(); +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/_common/QuoteResponse.cs b/src/Ellie.Bot.Modules.Searches/Crypto/_common/QuoteResponse.cs new file mode 100644 index 0000000..8293b69 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/_common/QuoteResponse.cs @@ -0,0 +1,43 @@ +#nullable disable +using System.Text.Json.Serialization; + +namespace Ellie.Modules.Searches; + +public class QuoteResponse +{ + public class ResultModel + { + [JsonPropertyName("longName")] + public string LongName { get; set; } + + [JsonPropertyName("regularMarketPrice")] + public double RegularMarketPrice { get; set; } + + [JsonPropertyName("regularMarketPreviousClose")] + public double RegularMarketPreviousClose { get; set; } + + [JsonPropertyName("fullExchangeName")] + public string FullExchangeName { get; set; } + + [JsonPropertyName("averageDailyVolume10Day")] + public int AverageDailyVolume10Day { get; set; } + + [JsonPropertyName("fiftyDayAverageChangePercent")] + public double FiftyDayAverageChangePercent { get; set; } + + [JsonPropertyName("twoHundredDayAverageChangePercent")] + public double TwoHundredDayAverageChangePercent { get; set; } + + [JsonPropertyName("marketCap")] + public long MarketCap { get; set; } + + [JsonPropertyName("symbol")] + public string Symbol { get; set; } + } + + [JsonPropertyName("result")] + public List Result { get; set; } + + [JsonPropertyName("error")] + public object Error { get; set; } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/_common/StockData.cs b/src/Ellie.Bot.Modules.Searches/Crypto/_common/StockData.cs new file mode 100644 index 0000000..f1ca9f1 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/_common/StockData.cs @@ -0,0 +1,15 @@ +#nullable disable +namespace Ellie.Modules.Searches; + +public class StockData +{ + public string Name { get; set; } + public string Symbol { get; set; } + public double Price { get; set; } + public long MarketCap { get; set; } + public double Close { get; set; } + public double Change50d { get; set; } + public double Change200d { get; set; } + public long DailyVolume { get; set; } + public string Exchange { get; set; } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/_common/SymbolData.cs b/src/Ellie.Bot.Modules.Searches/Crypto/_common/SymbolData.cs new file mode 100644 index 0000000..880b110 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/_common/SymbolData.cs @@ -0,0 +1,3 @@ +namespace Ellie.Modules.Searches; + +public record SymbolData(string Symbol, string Description); \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/_common/YahooFinanceCandleData.cs b/src/Ellie.Bot.Modules.Searches/Crypto/_common/YahooFinanceCandleData.cs new file mode 100644 index 0000000..95b428d --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/_common/YahooFinanceCandleData.cs @@ -0,0 +1,12 @@ +namespace Ellie.Modules.Searches; + +public class YahooFinanceCandleData +{ + public DateTime Date { get; set; } + public decimal Open { get; set; } + public decimal High { get; set; } + public decimal Low { get; set; } + public decimal Close { get; set; } + public decimal AdjClose { get; set; } + public long Volume { get; set; } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/_common/YahooFinanceSearchResponse.cs b/src/Ellie.Bot.Modules.Searches/Crypto/_common/YahooFinanceSearchResponse.cs new file mode 100644 index 0000000..6b26b53 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/_common/YahooFinanceSearchResponse.cs @@ -0,0 +1,19 @@ +#nullable disable +using System.Text.Json.Serialization; + +namespace Ellie.Modules.Searches; + +public class YahooFinanceSearchResponse +{ + [JsonPropertyName("suggestionTitleAccessor")] + public string SuggestionTitleAccessor { get; set; } + + [JsonPropertyName("suggestionMeta")] + public List SuggestionMeta { get; set; } + + [JsonPropertyName("hiConf")] + public bool HiConf { get; set; } + + [JsonPropertyName("items")] + public List Items { get; set; } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/_common/YahooFinanceSearchResponseItem.cs b/src/Ellie.Bot.Modules.Searches/Crypto/_common/YahooFinanceSearchResponseItem.cs new file mode 100644 index 0000000..2ec9551 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/_common/YahooFinanceSearchResponseItem.cs @@ -0,0 +1,25 @@ +#nullable disable +using System.Text.Json.Serialization; + +namespace Ellie.Modules.Searches; + +public class YahooFinanceSearchResponseItem +{ + [JsonPropertyName("symbol")] + public string Symbol { get; set; } + + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonPropertyName("exch")] + public string Exch { get; set; } + + [JsonPropertyName("type")] + public string Type { get; set; } + + [JsonPropertyName("exchDisp")] + public string ExchDisp { get; set; } + + [JsonPropertyName("typeDisp")] + public string TypeDisp { get; set; } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Crypto/_common/YahooQueryModel.cs b/src/Ellie.Bot.Modules.Searches/Crypto/_common/YahooQueryModel.cs new file mode 100644 index 0000000..9e429b5 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Crypto/_common/YahooQueryModel.cs @@ -0,0 +1,9 @@ +using System.Text.Json.Serialization; + +namespace Ellie.Modules.Searches; + +public class YahooQueryModel +{ + [JsonPropertyName("quoteResponse")] + public QuoteResponse QuoteResponse { get; set; } = null; +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Ellie.Bot.Modules.Searches.csproj b/src/Ellie.Bot.Modules.Searches/Ellie.Bot.Modules.Searches.csproj new file mode 100644 index 0000000..cab7396 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Ellie.Bot.Modules.Searches.csproj @@ -0,0 +1,40 @@ + + + + net7.0 + enable + enable + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Ellie.Bot.Modules.Searches/Feeds/FeedCommands.cs b/src/Ellie.Bot.Modules.Searches/Feeds/FeedCommands.cs new file mode 100644 index 0000000..342266b --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Feeds/FeedCommands.cs @@ -0,0 +1,115 @@ +#nullable disable +using CodeHollow.FeedReader; +using Ellie.Modules.Searches.Services; +using System.Text.RegularExpressions; + +namespace Ellie.Modules.Searches; + +public partial class Searches +{ + [Group] + public partial class FeedCommands : EllieModule + { + private static readonly Regex _ytChannelRegex = + new(@"youtube\.com\/(?:c\/|channel\/|user\/)?(?[a-zA-Z0-9\-_]{1,})"); + + [Cmd] + [RequireContext(ContextType.Guild)] + [UserPerm(GuildPerm.ManageMessages)] + public Task YtUploadNotif(string url, ITextChannel channel = null, [Leftover] string message = null) + { + var m = _ytChannelRegex.Match(url); + if (!m.Success) + return ReplyErrorLocalizedAsync(strs.invalid_input); + + var channelId = m.Groups["channelid"].Value; + + return Feed($"https://www.youtube.com/feeds/videos.xml?channel_id={channelId}", channel, message); + } + + [Cmd] + [RequireContext(ContextType.Guild)] + [UserPerm(GuildPerm.ManageMessages)] + public async Task Feed(string url, ITextChannel channel = null, [Leftover] string message = null) + { + if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) + || (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)) + { + await ReplyErrorLocalizedAsync(strs.feed_invalid_url); + return; + } + + channel ??= (ITextChannel)ctx.Channel; + try + { + await FeedReader.ReadAsync(url); + } + catch (Exception ex) + { + Log.Information(ex, "Unable to get feeds from that url"); + await ReplyErrorLocalizedAsync(strs.feed_cant_parse); + return; + } + + if (ctx.User is not IGuildUser gu || !gu.GuildPermissions.Administrator) + message = message?.SanitizeMentions(true); + + var result = _service.AddFeed(ctx.Guild.Id, channel.Id, url, message); + if (result == FeedAddResult.Success) + { + await ReplyConfirmLocalizedAsync(strs.feed_added); + return; + } + + if (result == FeedAddResult.Duplicate) + { + await ReplyErrorLocalizedAsync(strs.feed_duplicate); + return; + } + + if (result == FeedAddResult.LimitReached) + { + await ReplyErrorLocalizedAsync(strs.feed_limit_reached); + return; + } + } + + [Cmd] + [RequireContext(ContextType.Guild)] + [UserPerm(GuildPerm.ManageMessages)] + public async Task FeedRemove(int index) + { + if (_service.RemoveFeed(ctx.Guild.Id, --index)) + await ReplyConfirmLocalizedAsync(strs.feed_removed); + else + await ReplyErrorLocalizedAsync(strs.feed_out_of_range); + } + + [Cmd] + [RequireContext(ContextType.Guild)] + [UserPerm(GuildPerm.ManageMessages)] + public async Task FeedList() + { + var feeds = _service.GetFeeds(ctx.Guild.Id); + + if (!feeds.Any()) + { + await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor().WithDescription(GetText(strs.feed_no_feed))); + return; + } + + await ctx.SendPaginatedConfirmAsync(0, + cur => + { + var embed = _eb.Create().WithOkColor(); + var i = 0; + var fs = string.Join("\n", + feeds.Skip(cur * 10).Take(10).Select(x => $"`{(cur * 10) + ++i}.` <#{x.ChannelId}> {x.Url}")); + + return embed.WithDescription(fs); + }, + feeds.Count, + 10); + } + } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Feeds/FeedsService.cs b/src/Ellie.Bot.Modules.Searches/Feeds/FeedsService.cs new file mode 100644 index 0000000..8917ea7 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Feeds/FeedsService.cs @@ -0,0 +1,280 @@ +#nullable disable +using CodeHollow.FeedReader; +using CodeHollow.FeedReader.Feeds; +using LinqToDB; +using LinqToDB.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; +using Ellie.Db; +using Ellie.Services.Database.Models; + +namespace Ellie.Modules.Searches.Services; + +public class FeedsService : IEService +{ + private readonly DbService _db; + private readonly ConcurrentDictionary> _subs; + private readonly DiscordSocketClient _client; + private readonly IEmbedBuilderService _eb; + + private readonly ConcurrentDictionary _lastPosts = new(); + private readonly Dictionary _errorCounters = new(); + + public FeedsService( + IBot bot, + DbService db, + DiscordSocketClient client, + IEmbedBuilderService eb) + { + _db = db; + + using (var uow = db.GetDbContext()) + { + var guildConfigIds = bot.AllGuildConfigs.Select(x => x.Id).ToList(); + _subs = uow.Set() + .AsQueryable() + .Where(x => guildConfigIds.Contains(x.Id)) + .Include(x => x.FeedSubs) + .ToList() + .SelectMany(x => x.FeedSubs) + .GroupBy(x => x.Url.ToLower()) + .ToDictionary(x => x.Key, x => x.ToList()) + .ToConcurrent(); + } + + _client = client; + _eb = eb; + + _ = Task.Run(TrackFeeds); + } + + private void ClearErrors(string url) + => _errorCounters.Remove(url); + + private async Task AddError(string url, List ids) + { + try + { + var newValue = _errorCounters[url] = _errorCounters.GetValueOrDefault(url) + 1; + + if (newValue >= 100) + { + // remove from db + await using var ctx = _db.GetDbContext(); + await ctx.GetTable() + .DeleteAsync(x => ids.Contains(x.Id)); + + // remove from the local cache + _subs.TryRemove(url, out _); + + // reset the error counter + ClearErrors(url); + } + + return newValue; + } + catch (Exception ex) + { + Log.Error(ex, "Error adding rss errors..."); + return 0; + } + } + + public async Task TrackFeeds() + { + while (true) + { + var allSendTasks = new List(_subs.Count); + foreach (var kvp in _subs) + { + if (kvp.Value.Count == 0) + continue; + + var rssUrl = kvp.Value.First().Url; + try + { + var feed = await FeedReader.ReadAsync(rssUrl); + + var items = feed + .Items.Select(item => (Item: item, + LastUpdate: item.PublishingDate?.ToUniversalTime() + ?? (item.SpecificItem as AtomFeedItem)?.UpdatedDate?.ToUniversalTime())) + .Where(data => data.LastUpdate is not null) + .Select(data => (data.Item, LastUpdate: (DateTime)data.LastUpdate)) + .OrderByDescending(data => data.LastUpdate) + .Reverse() // start from the oldest + .ToList(); + + if (!_lastPosts.TryGetValue(kvp.Key, out var lastFeedUpdate)) + { + lastFeedUpdate = _lastPosts[kvp.Key] = + items.Any() ? items[items.Count - 1].LastUpdate : DateTime.UtcNow; + } + + foreach (var (feedItem, itemUpdateDate) in items) + { + if (itemUpdateDate <= lastFeedUpdate) + continue; + + var embed = _eb.Create().WithFooter(rssUrl); + + _lastPosts[kvp.Key] = itemUpdateDate; + + var link = feedItem.SpecificItem.Link; + if (!string.IsNullOrWhiteSpace(link) && Uri.IsWellFormedUriString(link, UriKind.Absolute)) + embed.WithUrl(link); + + var title = string.IsNullOrWhiteSpace(feedItem.Title) ? "-" : feedItem.Title; + + var gotImage = false; + if (feedItem.SpecificItem is MediaRssFeedItem mrfi + && (mrfi.Enclosure?.MediaType?.StartsWith("image/") ?? false)) + { + var imgUrl = mrfi.Enclosure.Url; + if (!string.IsNullOrWhiteSpace(imgUrl) + && Uri.IsWellFormedUriString(imgUrl, UriKind.Absolute)) + { + embed.WithImageUrl(imgUrl); + gotImage = true; + } + } + + if (!gotImage && feedItem.SpecificItem is AtomFeedItem afi) + { + var previewElement = afi.Element.Elements() + .FirstOrDefault(x => x.Name.LocalName == "preview"); + + if (previewElement is null) + { + previewElement = afi.Element.Elements() + .FirstOrDefault(x => x.Name.LocalName == "thumbnail"); + } + + if (previewElement is not null) + { + var urlAttribute = previewElement.Attribute("url"); + if (urlAttribute is not null + && !string.IsNullOrWhiteSpace(urlAttribute.Value) + && Uri.IsWellFormedUriString(urlAttribute.Value, UriKind.Absolute)) + { + embed.WithImageUrl(urlAttribute.Value); + gotImage = true; + } + } + } + + embed.WithTitle(title.TrimTo(256)); + + var desc = feedItem.Description?.StripHtml(); + if (!string.IsNullOrWhiteSpace(feedItem.Description)) + embed.WithDescription(desc.TrimTo(2048)); + + //send the created embed to all subscribed channels + var feedSendTasks = kvp.Value + .Where(x => x.GuildConfig is not null) + .Select(x => _client.GetGuild(x.GuildConfig.GuildId) + ?.GetTextChannel(x.ChannelId) + ?.EmbedAsync(embed, x.Message)) + .Where(x => x is not null); + + allSendTasks.Add(feedSendTasks.WhenAll()); + + // as data retrieval was successful, reset error counter + ClearErrors(rssUrl); + } + } + catch (Exception ex) + { + var errorCount = await AddError(rssUrl, kvp.Value.Select(x => x.Id).ToList()); + + Log.Warning("An error occured while getting rss stream ({ErrorCount} / 100) {RssFeed}" + + "\n {Message}", + errorCount, + rssUrl, + $"[{ex.GetType().Name}]: {ex.Message}"); + } + } + + await Task.WhenAll(Task.WhenAll(allSendTasks), Task.Delay(30000)); + } + } + + public List GetFeeds(ulong guildId) + { + using var uow = _db.GetDbContext(); + return uow.GuildConfigsForId(guildId, set => set.Include(x => x.FeedSubs)) + .FeedSubs.OrderBy(x => x.Id) + .ToList(); + } + + public FeedAddResult AddFeed(ulong guildId, ulong channelId, string rssFeed, string message) + { + ArgumentNullException.ThrowIfNull(rssFeed, nameof(rssFeed)); + + var fs = new FeedSub + { + ChannelId = channelId, + Url = rssFeed.Trim() + }; + + using var uow = _db.GetDbContext(); + var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.FeedSubs)); + + if (gc.FeedSubs.Any(x => x.Url.ToLower() == fs.Url.ToLower())) + return FeedAddResult.Duplicate; + if (gc.FeedSubs.Count >= 10) + return FeedAddResult.LimitReached; + + gc.FeedSubs.Add(fs); + uow.SaveChanges(); + //adding all, in case bot wasn't on this guild when it started + foreach (var feed in gc.FeedSubs) + { + _subs.AddOrUpdate(feed.Url.ToLower(), + new List + { + feed + }, + (_, old) => + { + old.Add(feed); + return old; + }); + } + + return FeedAddResult.Success; + } + + public bool RemoveFeed(ulong guildId, int index) + { + if (index < 0) + return false; + + using var uow = _db.GetDbContext(); + var items = uow.GuildConfigsForId(guildId, set => set.Include(x => x.FeedSubs)) + .FeedSubs.OrderBy(x => x.Id) + .ToList(); + + if (items.Count <= index) + return false; + var toRemove = items[index]; + _subs.AddOrUpdate(toRemove.Url.ToLower(), + new List(), + (_, old) => + { + old.Remove(toRemove); + return old; + }); + uow.Remove(toRemove); + uow.SaveChanges(); + + return true; + } +} + +public enum FeedAddResult +{ + Success, + LimitReached, + Invalid, + Duplicate, +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/GlobalUsings.cs b/src/Ellie.Bot.Modules.Searches/GlobalUsings.cs new file mode 100644 index 0000000..a90f5a7 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/GlobalUsings.cs @@ -0,0 +1,32 @@ +// // global using System.Collections.Concurrent; +global using NonBlocking; +// +// // packages +global using Serilog; +global using Humanizer; +global using Newtonsoft; +// +// // ellie +// global using Ellie; +global using Ellie.Services; +global using Ellise.Common; // new project +global using Ellie.Common; // old + ellie specific things +global using Ellie.Common.Attributes; +global using Ellie.Extensions; +// global using Ellie.Marmalade; + +// discord +global using Discord; +global using Discord.Commands; +global using Discord.Net; +global using Discord.WebSocket; + +// aliases +global using GuildPerm = Discord.GuildPermission; +global using ChannelPerm = Discord.ChannelPermission; +global using BotPermAttribute = Discord.Commands.RequireBotPermissionAttribute; +global using LeftoverAttribute = Discord.Commands.RemainderAttribute; +global using TypeReaderResult = Ellie.Common.TypeReaders.TypeReaderResult; + +// non-essential +// global using JetBrains.Annotations; \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/JokeCommands.cs b/src/Ellie.Bot.Modules.Searches/JokeCommands.cs new file mode 100644 index 0000000..f463c1e --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/JokeCommands.cs @@ -0,0 +1,53 @@ +#nullable disable +using Ellie.Modules.Searches.Services; + +namespace Ellie.Modules.Searches; + +public partial class Searches +{ + [Group] + public class JokeCommands : EllieModule + { + [Cmd] + public async Task Yomama() + => await SendConfirmAsync(await _service.GetYomamaJoke()); + + [Cmd] + public async Task Randjoke() + { + var (setup, punchline) = await _service.GetRandomJoke(); + await SendConfirmAsync(setup, punchline); + } + + [Cmd] + public async Task ChuckNorris() + => await SendConfirmAsync(await _service.GetChuckNorrisJoke()); + + [Cmd] + public async Task WowJoke() + { + if (!_service.WowJokes.Any()) + { + await ReplyErrorLocalizedAsync(strs.jokes_not_loaded); + return; + } + + var joke = _service.WowJokes[new EllieRandom().Next(0, _service.WowJokes.Count)]; + await SendConfirmAsync(joke.Question, joke.Answer); + } + + [Cmd] + public async Task MagicItem() + { + if (!_service.MagicItems.Any()) + { + await ReplyErrorLocalizedAsync(strs.magicitems_not_loaded); + return; + } + + var item = _service.MagicItems[new EllieRandom().Next(0, _service.MagicItems.Count)]; + + await SendConfirmAsync("✨" + item.Name, item.Description); + } + } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/MemegenCommands.cs b/src/Ellie.Bot.Modules.Searches/MemegenCommands.cs new file mode 100644 index 0000000..eff7266 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/MemegenCommands.cs @@ -0,0 +1,96 @@ +#nullable disable +using Newtonsoft.Json; +using System.Collections.Immutable; +using System.Text; + +namespace Ellie.Modules.Searches; + +public partial class Searches +{ + [Group] + public partial class MemegenCommands : EllieModule + { + private static readonly ImmutableDictionary _map = new Dictionary + { + { '?', "~q" }, + { '%', "~p" }, + { '#', "~h" }, + { '/', "~s" }, + { ' ', "-" }, + { '-', "--" }, + { '_', "__" }, + { '"', "''" } + }.ToImmutableDictionary(); + + private readonly IHttpClientFactory _httpFactory; + + public MemegenCommands(IHttpClientFactory factory) + => _httpFactory = factory; + + [Cmd] + public async Task Memelist(int page = 1) + { + if (--page < 0) + return; + + using var http = _httpFactory.CreateClient("memelist"); + using var res = await http.GetAsync("https://api.memegen.link/templates/"); + + var rawJson = await res.Content.ReadAsStringAsync(); + + var data = JsonConvert.DeserializeObject>(rawJson)!; + + await ctx.SendPaginatedConfirmAsync(page, + curPage => + { + var templates = string.Empty; + foreach (var template in data.Skip(curPage * 15).Take(15)) + templates += $"**{template.Name}:**\n key: `{template.Id}`\n"; + var embed = _eb.Create().WithOkColor().WithDescription(templates); + + return embed; + }, + data.Count, + 15); + } + + [Cmd] + public async Task Memegen(string meme, [Leftover] string memeText = null) + { + var memeUrl = $"http://api.memegen.link/{meme}"; + if (!string.IsNullOrWhiteSpace(memeText)) + { + var memeTextArray = memeText.Split(';'); + foreach (var text in memeTextArray) + { + var newText = Replace(text); + memeUrl += $"/{newText}"; + } + } + + memeUrl += ".png"; + await ctx.Channel.SendMessageAsync(memeUrl); + } + + private static string Replace(string input) + { + var sb = new StringBuilder(); + + foreach (var c in input) + { + if (_map.TryGetValue(c, out var tmp)) + sb.Append(tmp); + else + sb.Append(c); + } + + return sb.ToString(); + } + + private class MemegenTemplate + { + public string Name { get; set; } + public string Id { get; set; } + } + } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/OsuCommands.cs b/src/Ellie.Bot.Modules.Searches/OsuCommands.cs new file mode 100644 index 0000000..7e9477f --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/OsuCommands.cs @@ -0,0 +1,297 @@ +#nullable disable +using Ellie.Modules.Searches.Common; +using Newtonsoft.Json; + +namespace Ellie.Modules.Searches; + +public partial class Searches +{ + [Group] + public partial class OsuCommands : EllieModule + { + private readonly IBotCredentials _creds; + private readonly IHttpClientFactory _httpFactory; + + public OsuCommands(IBotCredentials creds, IHttpClientFactory factory) + { + _creds = creds; + _httpFactory = factory; + } + + [Cmd] + public async Task Osu(string user, [Leftover] string mode = null) + { + if (string.IsNullOrWhiteSpace(user)) + return; + + using var http = _httpFactory.CreateClient(); + var modeNumber = string.IsNullOrWhiteSpace(mode) ? 0 : ResolveGameMode(mode); + + try + { + if (string.IsNullOrWhiteSpace(_creds.OsuApiKey)) + { + await ReplyErrorLocalizedAsync(strs.osu_api_key); + return; + } + + var smode = ResolveGameMode(modeNumber); + var userReq = $"https://osu.ppy.sh/api/get_user?k={_creds.OsuApiKey}&u={user}&m={modeNumber}"; + var userResString = await http.GetStringAsync(userReq); + var objs = JsonConvert.DeserializeObject>(userResString); + + if (objs.Count == 0) + { + await ReplyErrorLocalizedAsync(strs.osu_user_not_found); + return; + } + + var obj = objs[0]; + var userId = obj.UserId; + + await ctx.Channel.EmbedAsync(_eb.Create() + .WithOkColor() + .WithTitle($"osu! {smode} profile for {user}") + .WithThumbnailUrl($"https://a.ppy.sh/{userId}") + .WithDescription($"https://osu.ppy.sh/u/{userId}") + .AddField("Official Rank", $"#{obj.PpRank}", true) + .AddField("Country Rank", + $"#{obj.PpCountryRank} :flag_{obj.Country.ToLower()}:", + true) + .AddField("Total PP", Math.Round(obj.PpRaw, 2), true) + .AddField("Accuracy", Math.Round(obj.Accuracy, 2) + "%", true) + .AddField("Playcount", obj.Playcount, true) + .AddField("Level", Math.Round(obj.Level), true)); + } + catch (ArgumentOutOfRangeException) + { + await ReplyErrorLocalizedAsync(strs.osu_user_not_found); + } + catch (Exception ex) + { + await ReplyErrorLocalizedAsync(strs.osu_failed); + Log.Warning(ex, "Osu command failed"); + } + } + + [Cmd] + public async Task Gatari(string user, [Leftover] string mode = null) + { + using var http = _httpFactory.CreateClient(); + var modeNumber = string.IsNullOrWhiteSpace(mode) ? 0 : ResolveGameMode(mode); + + var modeStr = ResolveGameMode(modeNumber); + var resString = await http.GetStringAsync($"https://api.gatari.pw/user/stats?u={user}&mode={modeNumber}"); + + var statsResponse = JsonConvert.DeserializeObject(resString); + if (statsResponse.Code != 200 || statsResponse.Stats.Id == 0) + { + await ReplyErrorLocalizedAsync(strs.osu_user_not_found); + return; + } + + var usrResString = await http.GetStringAsync($"https://api.gatari.pw/users/get?u={user}"); + + var userData = JsonConvert.DeserializeObject(usrResString).Users[0]; + var userStats = statsResponse.Stats; + + var embed = _eb.Create() + .WithOkColor() + .WithTitle($"osu!Gatari {modeStr} profile for {user}") + .WithThumbnailUrl($"https://a.gatari.pw/{userStats.Id}") + .WithDescription($"https://osu.gatari.pw/u/{userStats.Id}") + .AddField("Official Rank", $"#{userStats.Rank}", true) + .AddField("Country Rank", + $"#{userStats.CountryRank} :flag_{userData.Country.ToLower()}:", + true) + .AddField("Total PP", userStats.Pp, true) + .AddField("Accuracy", $"{Math.Round(userStats.AvgAccuracy, 2)}%", true) + .AddField("Playcount", userStats.Playcount, true) + .AddField("Level", userStats.Level, true); + + await ctx.Channel.EmbedAsync(embed); + } + + [Cmd] + public async Task Osu5(string user, [Leftover] string mode = null) + { + if (string.IsNullOrWhiteSpace(_creds.OsuApiKey)) + { + await SendErrorAsync("An osu! API key is required."); + return; + } + + if (string.IsNullOrWhiteSpace(user)) + { + await SendErrorAsync("Please provide a username."); + return; + } + + using var http = _httpFactory.CreateClient(); + var m = 0; + if (!string.IsNullOrWhiteSpace(mode)) + m = ResolveGameMode(mode); + + var reqString = "https://osu.ppy.sh/api/get_user_best" + + $"?k={_creds.OsuApiKey}" + + $"&u={Uri.EscapeDataString(user)}" + + "&type=string" + + "&limit=5" + + $"&m={m}"; + + var resString = await http.GetStringAsync(reqString); + var obj = JsonConvert.DeserializeObject>(resString); + + var mapTasks = obj.Select(async item => + { + var mapReqString = "https://osu.ppy.sh/api/get_beatmaps" + + $"?k={_creds.OsuApiKey}" + + $"&b={item.BeatmapId}"; + + var mapResString = await http.GetStringAsync(mapReqString); + var map = JsonConvert.DeserializeObject>(mapResString).FirstOrDefault(); + if (map is null) + return default; + var pp = Math.Round(item.Pp, 2); + var acc = CalculateAcc(item, m); + var mods = ResolveMods(item.EnabledMods); + + var title = $"{map.Artist}-{map.Title} ({map.Version})"; + var desc = $@"[/b/{item.BeatmapId}](https://osu.ppy.sh/b/{item.BeatmapId}) +{pp + "pp",-7} | {acc + "%",-7} +"; + if (mods != "+") + desc += Format.Bold(mods); + + return (title, desc); + }); + + var eb = _eb.Create().WithOkColor().WithTitle($"Top 5 plays for {user}"); + + var mapData = await mapTasks.WhenAll(); + foreach (var (title, desc) in mapData.Where(x => x != default)) + eb.AddField(title, desc); + + await ctx.Channel.EmbedAsync(eb); + } + + //https://osu.ppy.sh/wiki/Accuracy + private static double CalculateAcc(OsuUserBests play, int mode) + { + double hitPoints; + double totalHits; + if (mode == 0) + { + hitPoints = (play.Count50 * 50) + (play.Count100 * 100) + (play.Count300 * 300); + totalHits = play.Count50 + play.Count100 + play.Count300 + play.Countmiss; + totalHits *= 300; + } + else if (mode == 1) + { + hitPoints = (play.Countmiss * 0) + (play.Count100 * 0.5) + play.Count300; + totalHits = (play.Countmiss + play.Count100 + play.Count300) * 300; + hitPoints *= 300; + } + else if (mode == 2) + { + hitPoints = play.Count50 + play.Count100 + play.Count300; + totalHits = play.Countmiss + play.Count50 + play.Count100 + play.Count300 + play.Countkatu; + } + else + { + hitPoints = (play.Count50 * 50) + + (play.Count100 * 100) + + (play.Countkatu * 200) + + ((play.Count300 + play.Countgeki) * 300); + + totalHits = (play.Countmiss + + play.Count50 + + play.Count100 + + play.Countkatu + + play.Count300 + + play.Countgeki) + * 300; + } + + + return Math.Round(hitPoints / totalHits * 100, 2); + } + + private static int ResolveGameMode(string mode) + { + switch (mode.ToUpperInvariant()) + { + case "STD": + case "STANDARD": + return 0; + case "TAIKO": + return 1; + case "CTB": + case "CATCHTHEBEAT": + return 2; + case "MANIA": + case "OSU!MANIA": + return 3; + default: + return 0; + } + } + + private static string ResolveGameMode(int mode) + { + switch (mode) + { + case 0: + return "Standard"; + case 1: + return "Taiko"; + case 2: + return "Catch"; + case 3: + return "Mania"; + default: + return "Standard"; + } + } + + //https://github.com/ppy/osu-api/wiki#mods + private static string ResolveMods(int mods) + { + var modString = "+"; + + if (IsBitSet(mods, 0)) + modString += "NF"; + if (IsBitSet(mods, 1)) + modString += "EZ"; + if (IsBitSet(mods, 8)) + modString += "HT"; + + if (IsBitSet(mods, 3)) + modString += "HD"; + if (IsBitSet(mods, 4)) + modString += "HR"; + if (IsBitSet(mods, 6) && !IsBitSet(mods, 9)) + modString += "DT"; + if (IsBitSet(mods, 9)) + modString += "NC"; + if (IsBitSet(mods, 10)) + modString += "FL"; + + if (IsBitSet(mods, 5)) + modString += "SD"; + if (IsBitSet(mods, 14)) + modString += "PF"; + + if (IsBitSet(mods, 7)) + modString += "RX"; + if (IsBitSet(mods, 11)) + modString += "AT"; + if (IsBitSet(mods, 12)) + modString += "SO"; + return modString; + } + + private static bool IsBitSet(int mods, int pos) + => (mods & (1 << pos)) != 0; + } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/PathOfExileCommands.cs b/src/Ellie.Bot.Modules.Searches/PathOfExileCommands.cs new file mode 100644 index 0000000..518218f --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/PathOfExileCommands.cs @@ -0,0 +1,311 @@ +#nullable disable +using Ellie.Modules.Searches.Common; +using Ellie.Modules.Searches.Services; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System.Globalization; +using System.Text; + +namespace Ellie.Modules.Searches; + +public partial class Searches +{ + [Group] + public partial class PathOfExileCommands : EllieModule + { + private const string POE_URL = "https://www.pathofexile.com/character-window/get-characters?accountName="; + private const string PON_URL = "http://poe.ninja/api/Data/GetCurrencyOverview?league="; + private const string POGS_URL = "http://pathofexile.gamepedia.com/api.php?action=opensearch&search="; + + private const string POG_URL = + "https://pathofexile.gamepedia.com/api.php?action=browsebysubject&format=json&subject="; + + private const string POGI_URL = + "https://pathofexile.gamepedia.com/api.php?action=query&prop=imageinfo&iiprop=url&format=json&titles=File:"; + + private const string PROFILE_URL = "https://www.pathofexile.com/account/view-profile/"; + + private readonly IHttpClientFactory _httpFactory; + + private Dictionary currencyDictionary = new(StringComparer.OrdinalIgnoreCase) + { + { "Chaos Orb", "Chaos Orb" }, + { "Orb of Alchemy", "Orb of Alchemy" }, + { "Jeweller's Orb", "Jeweller's Orb" }, + { "Exalted Orb", "Exalted Orb" }, + { "Mirror of Kalandra", "Mirror of Kalandra" }, + { "Vaal Orb", "Vaal Orb" }, + { "Orb of Alteration", "Orb of Alteration" }, + { "Orb of Scouring", "Orb of Scouring" }, + { "Divine Orb", "Divine Orb" }, + { "Orb of Annulment", "Orb of Annulment" }, + { "Master Cartographer's Sextant", "Master Cartographer's Sextant" }, + { "Journeyman Cartographer's Sextant", "Journeyman Cartographer's Sextant" }, + { "Apprentice Cartographer's Sextant", "Apprentice Cartographer's Sextant" }, + { "Blessed Orb", "Blessed Orb" }, + { "Orb of Regret", "Orb of Regret" }, + { "Gemcutter's Prism", "Gemcutter's Prism" }, + { "Glassblower's Bauble", "Glassblower's Bauble" }, + { "Orb of Fusing", "Orb of Fusing" }, + { "Cartographer's Chisel", "Cartographer's Chisel" }, + { "Chromatic Orb", "Chromatic Orb" }, + { "Orb of Augmentation", "Orb of Augmentation" }, + { "Blacksmith's Whetstone", "Blacksmith's Whetstone" }, + { "Orb of Transmutation", "Orb of Transmutation" }, + { "Armourer's Scrap", "Armourer's Scrap" }, + { "Scroll of Wisdom", "Scroll of Wisdom" }, + { "Regal Orb", "Regal Orb" }, + { "Chaos", "Chaos Orb" }, + { "Alch", "Orb of Alchemy" }, + { "Alchs", "Orb of Alchemy" }, + { "Jews", "Jeweller's Orb" }, + { "Jeweller", "Jeweller's Orb" }, + { "Jewellers", "Jeweller's Orb" }, + { "Jeweller's", "Jeweller's Orb" }, + { "X", "Exalted Orb" }, + { "Ex", "Exalted Orb" }, + { "Exalt", "Exalted Orb" }, + { "Exalts", "Exalted Orb" }, + { "Mirror", "Mirror of Kalandra" }, + { "Mirrors", "Mirror of Kalandra" }, + { "Vaal", "Vaal Orb" }, + { "Alt", "Orb of Alteration" }, + { "Alts", "Orb of Alteration" }, + { "Scour", "Orb of Scouring" }, + { "Scours", "Orb of Scouring" }, + { "Divine", "Divine Orb" }, + { "Annul", "Orb of Annulment" }, + { "Annulment", "Orb of Annulment" }, + { "Master Sextant", "Master Cartographer's Sextant" }, + { "Journeyman Sextant", "Journeyman Cartographer's Sextant" }, + { "Apprentice Sextant", "Apprentice Cartographer's Sextant" }, + { "Blessed", "Blessed Orb" }, + { "Regret", "Orb of Regret" }, + { "Regrets", "Orb of Regret" }, + { "Gcp", "Gemcutter's Prism" }, + { "Glassblowers", "Glassblower's Bauble" }, + { "Glassblower's", "Glassblower's Bauble" }, + { "Fusing", "Orb of Fusing" }, + { "Fuses", "Orb of Fusing" }, + { "Fuse", "Orb of Fusing" }, + { "Chisel", "Cartographer's Chisel" }, + { "Chisels", "Cartographer's Chisel" }, + { "Chance", "Orb of Chance" }, + { "Chances", "Orb of Chance" }, + { "Chrome", "Chromatic Orb" }, + { "Chromes", "Chromatic Orb" }, + { "Aug", "Orb of Augmentation" }, + { "Augmentation", "Orb of Augmentation" }, + { "Augment", "Orb of Augmentation" }, + { "Augments", "Orb of Augmentation" }, + { "Whetstone", "Blacksmith's Whetstone" }, + { "Whetstones", "Blacksmith's Whetstone" }, + { "Transmute", "Orb of Transmutation" }, + { "Transmutes", "Orb of Transmutation" }, + { "Armourers", "Armourer's Scrap" }, + { "Armourer's", "Armourer's Scrap" }, + { "Wisdom Scroll", "Scroll of Wisdom" }, + { "Wisdom Scrolls", "Scroll of Wisdom" }, + { "Regal", "Regal Orb" }, + { "Regals", "Regal Orb" } + }; + + public PathOfExileCommands(IHttpClientFactory httpFactory) + => _httpFactory = httpFactory; + + [Cmd] + public async Task PathOfExile(string usr, string league = "", int page = 1) + { + if (--page < 0) + return; + + if (string.IsNullOrWhiteSpace(usr)) + { + await SendErrorAsync("Please provide an account name."); + return; + } + + var characters = new List(); + + try + { + using var http = _httpFactory.CreateClient(); + var res = await http.GetStringAsync($"{POE_URL}{usr}"); + characters = JsonConvert.DeserializeObject>(res); + } + catch + { + var embed = _eb.Create().WithDescription(GetText(strs.account_not_found)).WithErrorColor(); + + await ctx.Channel.EmbedAsync(embed); + return; + } + + if (!string.IsNullOrWhiteSpace(league)) + characters.RemoveAll(c => c.League != league); + + await ctx.SendPaginatedConfirmAsync(page, + curPage => + { + var embed = _eb.Create() + .WithAuthor($"Characters on {usr}'s account", + "https://web.poecdn.com/image/favicon/ogimage.png", + $"{PROFILE_URL}{usr}") + .WithOkColor(); + + var tempList = characters.Skip(curPage * 9).Take(9).ToList(); + + if (characters.Count == 0) + return embed.WithDescription("This account has no characters."); + + var sb = new StringBuilder(); + sb.AppendLine($"```{"#",-5}{"Character Name",-23}{"League",-10}{"Class",-13}{"Level",-3}"); + for (var i = 0; i < tempList.Count; i++) + { + var character = tempList[i]; + + sb.AppendLine( + $"#{i + 1 + (curPage * 9),-4}{character.Name,-23}{ShortLeagueName(character.League),-10}{character.Class,-13}{character.Level,-3}"); + } + + sb.AppendLine("```"); + embed.WithDescription(sb.ToString()); + + return embed; + }, + characters.Count, + 9); + } + + [Cmd] + public async Task PathOfExileLeagues() + { + var leagues = new List(); + + try + { + using var http = _httpFactory.CreateClient(); + var res = await http.GetStringAsync("http://api.pathofexile.com/leagues?type=main&compact=1"); + leagues = JsonConvert.DeserializeObject>(res); + } + catch + { + var eembed = _eb.Create().WithDescription(GetText(strs.leagues_not_found)).WithErrorColor(); + + await ctx.Channel.EmbedAsync(eembed); + return; + } + + var embed = _eb.Create() + .WithAuthor("Path of Exile Leagues", + "https://web.poecdn.com/image/favicon/ogimage.png", + "https://www.pathofexile.com") + .WithOkColor(); + + var sb = new StringBuilder(); + sb.AppendLine($"```{"#",-5}{"League Name",-23}"); + for (var i = 0; i < leagues.Count; i++) + { + var league = leagues[i]; + + sb.AppendLine($"#{i + 1,-4}{league.Id,-23}"); + } + + sb.AppendLine("```"); + + embed.WithDescription(sb.ToString()); + + await ctx.Channel.EmbedAsync(embed); + } + + [Cmd] + public async Task PathOfExileCurrency( + string leagueName, + string currencyName, + string convertName = "Chaos Orb") + { + if (string.IsNullOrWhiteSpace(leagueName)) + { + await SendErrorAsync("Please provide league name."); + return; + } + + if (string.IsNullOrWhiteSpace(currencyName)) + { + await SendErrorAsync("Please provide currency name."); + return; + } + + var cleanCurrency = ShortCurrencyName(currencyName); + var cleanConvert = ShortCurrencyName(convertName); + + try + { + var res = $"{PON_URL}{leagueName}"; + using var http = _httpFactory.CreateClient(); + var obj = JObject.Parse(await http.GetStringAsync(res)); + + var chaosEquivalent = 0.0F; + var conversionEquivalent = 0.0F; + + // poe.ninja API does not include a "chaosEquivalent" property for Chaos Orbs. + if (cleanCurrency == "Chaos Orb") + chaosEquivalent = 1.0F; + else + { + var currencyInput = obj["lines"] + .Values() + .Where(i => i["currencyTypeName"].Value() == cleanCurrency) + .FirstOrDefault(); + chaosEquivalent = float.Parse(currencyInput["chaosEquivalent"].ToString(), + CultureInfo.InvariantCulture); + } + + if (cleanConvert == "Chaos Orb") + conversionEquivalent = 1.0F; + else + { + var currencyOutput = obj["lines"] + .Values() + .Where(i => i["currencyTypeName"].Value() == cleanConvert) + .FirstOrDefault(); + conversionEquivalent = float.Parse(currencyOutput["chaosEquivalent"].ToString(), + CultureInfo.InvariantCulture); + } + + var embed = _eb.Create() + .WithAuthor($"{leagueName} Currency Exchange", + "https://web.poecdn.com/image/favicon/ogimage.png", + "http://poe.ninja") + .AddField("Currency Type", cleanCurrency, true) + .AddField($"{cleanConvert} Equivalent", chaosEquivalent / conversionEquivalent, true) + .WithOkColor(); + + await ctx.Channel.EmbedAsync(embed); + } + catch + { + var embed = _eb.Create().WithDescription(GetText(strs.ninja_not_found)).WithErrorColor(); + + await ctx.Channel.EmbedAsync(embed); + } + } + + private string ShortCurrencyName(string str) + { + if (currencyDictionary.ContainsValue(str)) + return str; + + var currency = currencyDictionary[str]; + + return currency; + } + + private static string ShortLeagueName(string str) + { + var league = str.Replace("Hardcore", "HC", StringComparison.InvariantCultureIgnoreCase); + + return league; + } + } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/PlaceCommands.cs b/src/Ellie.Bot.Modules.Searches/PlaceCommands.cs new file mode 100644 index 0000000..a3a2a40 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/PlaceCommands.cs @@ -0,0 +1,71 @@ +#nullable disable +namespace Ellie.Modules.Searches; + +public partial class Searches +{ + [Group] + public partial class PlaceCommands : EllieModule + { + public enum PlaceType + { + Cage, //http://www.placecage.com + Steven, //http://www.stevensegallery.com + Beard, //http://placebeard.it + Fill, //http://www.fillmurray.com + Bear, //https://www.placebear.com + Kitten, //http://placekitten.com + Bacon, //http://baconmockup.com + Xoart //http://xoart.link + } + + private static readonly string _typesStr = string.Join(", ", Enum.GetNames()); + + [Cmd] + public async Task Placelist() + => await SendConfirmAsync(GetText(strs.list_of_place_tags(prefix)), _typesStr); + + [Cmd] + public async Task Place(PlaceType placeType, uint width = 0, uint height = 0) + { + var url = string.Empty; + switch (placeType) + { + case PlaceType.Cage: + url = "http://www.placecage.com"; + break; + case PlaceType.Steven: + url = "http://www.stevensegallery.com"; + break; + case PlaceType.Beard: + url = "http://placebeard.it"; + break; + case PlaceType.Fill: + url = "http://www.fillmurray.com"; + break; + case PlaceType.Bear: + url = "https://www.placebear.com"; + break; + case PlaceType.Kitten: + url = "http://placekitten.com"; + break; + case PlaceType.Bacon: + url = "http://baconmockup.com"; + break; + case PlaceType.Xoart: + url = "http://xoart.link"; + break; + } + + var rng = new EllieRandom(); + if (width is <= 0 or > 1000) + width = (uint)rng.Next(250, 850); + + if (height is <= 0 or > 1000) + height = (uint)rng.Next(250, 850); + + url += $"/{width}/{height}"; + + await ctx.Channel.SendMessageAsync(url); + } + } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/PokemonSearchCommands.cs b/src/Ellie.Bot.Modules.Searches/PokemonSearchCommands.cs new file mode 100644 index 0000000..2f25d85 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/PokemonSearchCommands.cs @@ -0,0 +1,74 @@ +#nullable disable +using Ellie.Modules.Searches.Services; + +namespace Ellie.Modules.Searches; + +public partial class Searches +{ + [Group] + public partial class PokemonSearchCommands : EllieModule + { + private readonly ILocalDataCache _cache; + + public PokemonSearchCommands(ILocalDataCache cache) + => _cache = cache; + + [Cmd] + public async Task Pokemon([Leftover] string pokemon = null) + { + pokemon = pokemon?.Trim().ToUpperInvariant(); + if (string.IsNullOrWhiteSpace(pokemon)) + return; + + foreach (var kvp in await _cache.GetPokemonsAsync()) + { + if (kvp.Key.ToUpperInvariant() == pokemon.ToUpperInvariant()) + { + var p = kvp.Value; + await ctx.Channel.EmbedAsync(_eb.Create() + .WithOkColor() + .WithTitle(kvp.Key.ToTitleCase()) + .WithDescription(p.BaseStats.ToString()) + .WithThumbnailUrl( + $"https://assets.pokemon.com/assets/cms2/img/pokedex/detail/{p.Id.ToString("000")}.png") + .AddField(GetText(strs.types), string.Join("\n", p.Types), true) + .AddField(GetText(strs.height_weight), + GetText(strs.height_weight_val(p.HeightM, p.WeightKg)), + true) + .AddField(GetText(strs.abilities), + string.Join("\n", p.Abilities.Select(a => a.Value)), + true)); + return; + } + } + + await ReplyErrorLocalizedAsync(strs.pokemon_none); + } + + [Cmd] + public async Task PokemonAbility([Leftover] string ability = null) + { + ability = ability?.Trim().ToUpperInvariant().Replace(" ", "", StringComparison.InvariantCulture); + if (string.IsNullOrWhiteSpace(ability)) + return; + foreach (var kvp in await _cache.GetPokemonAbilitiesAsync()) + { + if (kvp.Key.ToUpperInvariant() == ability) + { + await ctx.Channel.EmbedAsync(_eb.Create() + .WithOkColor() + .WithTitle(kvp.Value.Name) + .WithDescription(string.IsNullOrWhiteSpace(kvp.Value.Desc) + ? kvp.Value.ShortDesc + : kvp.Value.Desc) + .AddField(GetText(strs.rating), + kvp.Value.Rating.ToString(Culture), + true)); + return; + } + } + + await ReplyErrorLocalizedAsync(strs.pokemon_ability_none); + } + } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Searches.cs b/src/Ellie.Bot.Modules.Searches/Searches.cs new file mode 100644 index 0000000..0970636 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Searches.cs @@ -0,0 +1,612 @@ +#nullable disable +using Microsoft.Extensions.Caching.Memory; +using Ellie.Modules.Searches.Common; +using Ellie.Modules.Searches.Services; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Drawing.Processing; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using Color = SixLabors.ImageSharp.Color; + +namespace Ellie.Modules.Searches; + +public partial class Searches : EllieModule +{ + private static readonly ConcurrentDictionary _cachedShortenedLinks = new(); + private readonly IBotCredentials _creds; + private readonly IGoogleApiService _google; + private readonly IHttpClientFactory _httpFactory; + private readonly IMemoryCache _cache; + private readonly ITimezoneService _tzSvc; + + public Searches( + IBotCredentials creds, + IGoogleApiService google, + IHttpClientFactory factory, + IMemoryCache cache, + ITimezoneService tzSvc) + { + _creds = creds; + _google = google; + _httpFactory = factory; + _cache = cache; + _tzSvc = tzSvc; + } + + [Cmd] + public async Task Rip([Leftover] IGuildUser usr) + { + var av = usr.RealAvatarUrl(); + await using var picStream = await _service.GetRipPictureAsync(usr.Nickname ?? usr.Username, av); + await ctx.Channel.SendFileAsync(picStream, + "rip.png", + $"Rip {Format.Bold(usr.ToString())} \n\t- " + Format.Italics(ctx.User.ToString())); + } + + [Cmd] + public async Task Weather([Leftover] string query) + { + if (!await ValidateQuery(query)) + return; + + var embed = _eb.Create(); + var data = await _service.GetWeatherDataAsync(query); + + if (data is null) + embed.WithDescription(GetText(strs.city_not_found)).WithErrorColor(); + else + { + var f = StandardConversions.CelsiusToFahrenheit; + + var tz = _tzSvc.GetTimeZoneOrUtc(ctx.Guild?.Id); + var sunrise = data.Sys.Sunrise.ToUnixTimestamp(); + var sunset = data.Sys.Sunset.ToUnixTimestamp(); + sunrise = sunrise.ToOffset(tz.GetUtcOffset(sunrise)); + sunset = sunset.ToOffset(tz.GetUtcOffset(sunset)); + var timezone = $"UTC{sunrise:zzz}"; + + embed + .AddField("🌍 " + Format.Bold(GetText(strs.location)), + $"[{data.Name + ", " + data.Sys.Country}](https://openweathermap.org/city/{data.Id})", + true) + .AddField("📏 " + Format.Bold(GetText(strs.latlong)), $"{data.Coord.Lat}, {data.Coord.Lon}", true) + .AddField("☁ " + Format.Bold(GetText(strs.condition)), + string.Join(", ", data.Weather.Select(w => w.Main)), + true) + .AddField("😓 " + Format.Bold(GetText(strs.humidity)), $"{data.Main.Humidity}%", true) + .AddField("💨 " + Format.Bold(GetText(strs.wind_speed)), data.Wind.Speed + " m/s", true) + .AddField("🌡 " + Format.Bold(GetText(strs.temperature)), + $"{data.Main.Temp:F1}°C / {f(data.Main.Temp):F1}°F", + true) + .AddField("🔆 " + Format.Bold(GetText(strs.min_max)), + $"{data.Main.TempMin:F1}°C - {data.Main.TempMax:F1}°C\n{f(data.Main.TempMin):F1}°F - {f(data.Main.TempMax):F1}°F", + true) + .AddField("🌄 " + Format.Bold(GetText(strs.sunrise)), $"{sunrise:HH:mm} {timezone}", true) + .AddField("🌇 " + Format.Bold(GetText(strs.sunset)), $"{sunset:HH:mm} {timezone}", true) + .WithOkColor() + .WithFooter("Powered by openweathermap.org", + $"https://openweathermap.org/img/w/{data.Weather[0].Icon}.png"); + } + + await ctx.Channel.EmbedAsync(embed); + } + + [Cmd] + public async Task Time([Leftover] string query) + { + if (!await ValidateQuery(query)) + return; + + await ctx.Channel.TriggerTypingAsync(); + + var (data, err) = await _service.GetTimeDataAsync(query); + if (err is not null) + { + LocStr errorKey; + switch (err) + { + case TimeErrors.ApiKeyMissing: + errorKey = strs.api_key_missing; + break; + case TimeErrors.InvalidInput: + errorKey = strs.invalid_input; + break; + case TimeErrors.NotFound: + errorKey = strs.not_found; + break; + default: + errorKey = strs.error_occured; + break; + } + + await ReplyErrorLocalizedAsync(errorKey); + return; + } + + if (string.IsNullOrWhiteSpace(data.TimeZoneName)) + { + await ReplyErrorLocalizedAsync(strs.timezone_db_api_key); + return; + } + + var eb = _eb.Create() + .WithOkColor() + .WithTitle(GetText(strs.time_new)) + .WithDescription(Format.Code(data.Time.ToString(Culture))) + .AddField(GetText(strs.location), string.Join('\n', data.Address.Split(", ")), true) + .AddField(GetText(strs.timezone), data.TimeZoneName, true); + + await ctx.Channel.SendMessageAsync(embed: eb.Build()); + } + + [Cmd] + public async Task Movie([Leftover] string query = null) + { + if (!await ValidateQuery(query)) + return; + + await ctx.Channel.TriggerTypingAsync(); + + var movie = await _service.GetMovieDataAsync(query); + if (movie is null) + { + await ReplyErrorLocalizedAsync(strs.imdb_fail); + return; + } + + await ctx.Channel.EmbedAsync(_eb.Create() + .WithOkColor() + .WithTitle(movie.Title) + .WithUrl($"https://www.imdb.com/title/{movie.ImdbId}/") + .WithDescription(movie.Plot.TrimTo(1000)) + .AddField("Rating", movie.ImdbRating, true) + .AddField("Genre", movie.Genre, true) + .AddField("Year", movie.Year, true) + .WithImageUrl(movie.Poster)); + } + + [Cmd] + public Task RandomCat() + => InternalRandomImage(SearchesService.ImageTag.Cats); + + [Cmd] + public Task RandomDog() + => InternalRandomImage(SearchesService.ImageTag.Dogs); + + [Cmd] + public Task RandomFood() + => InternalRandomImage(SearchesService.ImageTag.Food); + + [Cmd] + public Task RandomBird() + => InternalRandomImage(SearchesService.ImageTag.Birds); + + private Task InternalRandomImage(SearchesService.ImageTag tag) + { + var url = _service.GetRandomImageUrl(tag); + return ctx.Channel.EmbedAsync(_eb.Create().WithOkColor().WithImageUrl(url)); + } + + [Cmd] + public async Task Lmgtfy([Leftover] string ffs = null) + { + if (!await ValidateQuery(ffs)) + return; + + var shortenedUrl = await _google.ShortenUrl($"https://letmegooglethat.com/?q={Uri.EscapeDataString(ffs)}"); + await SendConfirmAsync($"<{shortenedUrl}>"); + } + + [Cmd] + public async Task Shorten([Leftover] string query) + { + if (!await ValidateQuery(query)) + return; + + query = query.Trim(); + if (!_cachedShortenedLinks.TryGetValue(query, out var shortLink)) + { + try + { + using var http = _httpFactory.CreateClient(); + using var req = new HttpRequestMessage(HttpMethod.Post, "https://goolnk.com/api/v1/shorten"); + var formData = new MultipartFormDataContent + { + { new StringContent(query), "url" } + }; + req.Content = formData; + + using var res = await http.SendAsync(req); + var content = await res.Content.ReadAsStringAsync(); + var data = JsonConvert.DeserializeObject(content); + + if (!string.IsNullOrWhiteSpace(data?.ResultUrl)) + _cachedShortenedLinks.TryAdd(query, data.ResultUrl); + else + return; + + shortLink = data.ResultUrl; + } + catch (Exception ex) + { + Log.Error(ex, "Error shortening a link: {Message}", ex.Message); + return; + } + } + + await ctx.Channel.EmbedAsync(_eb.Create() + .WithOkColor() + .AddField(GetText(strs.original_url), $"<{query}>") + .AddField(GetText(strs.short_url), $"<{shortLink}>")); + } + + [Cmd] + public async Task MagicTheGathering([Leftover] string search) + { + if (!await ValidateQuery(search)) + return; + + await ctx.Channel.TriggerTypingAsync(); + var card = await _service.GetMtgCardAsync(search); + + if (card is null) + { + await ReplyErrorLocalizedAsync(strs.card_not_found); + return; + } + + var embed = _eb.Create() + .WithOkColor() + .WithTitle(card.Name) + .WithDescription(card.Description) + .WithImageUrl(card.ImageUrl) + .AddField(GetText(strs.store_url), card.StoreUrl, true) + .AddField(GetText(strs.cost), card.ManaCost, true) + .AddField(GetText(strs.types), card.Types, true); + + await ctx.Channel.EmbedAsync(embed); + } + + [Cmd] + public async Task Hearthstone([Leftover] string name) + { + if (!await ValidateQuery(name)) + return; + + if (string.IsNullOrWhiteSpace(_creds.RapidApiKey)) + { + await ReplyErrorLocalizedAsync(strs.mashape_api_missing); + return; + } + + await ctx.Channel.TriggerTypingAsync(); + var card = await _service.GetHearthstoneCardDataAsync(name); + + if (card is null) + { + await ReplyErrorLocalizedAsync(strs.card_not_found); + return; + } + + var embed = _eb.Create().WithOkColor().WithImageUrl(card.Img); + + if (!string.IsNullOrWhiteSpace(card.Flavor)) + embed.WithDescription(card.Flavor); + + await ctx.Channel.EmbedAsync(embed); + } + + [Cmd] + public async Task UrbanDict([Leftover] string query = null) + { + if (!await ValidateQuery(query)) + return; + + await ctx.Channel.TriggerTypingAsync(); + using (var http = _httpFactory.CreateClient()) + { + var res = await http.GetStringAsync( + $"https://api.urbandictionary.com/v0/define?term={Uri.EscapeDataString(query)}"); + try + { + var items = JsonConvert.DeserializeObject(res).List; + if (items.Any()) + { + await ctx.SendPaginatedConfirmAsync(0, + p => + { + var item = items[p]; + return _eb.Create() + .WithOkColor() + .WithUrl(item.Permalink) + .WithTitle(item.Word) + .WithDescription(item.Definition); + }, + items.Length, + 1); + return; + } + } + catch + { + } + } + + await ReplyErrorLocalizedAsync(strs.ud_error); + } + + [Cmd] + public async Task Define([Leftover] string word) + { + if (!await ValidateQuery(word)) + return; + + using var http = _httpFactory.CreateClient(); + string res; + try + { + res = await _cache.GetOrCreateAsync($"define_{word}", + e => + { + e.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(12); + return http.GetStringAsync("https://api.pearson.com/v2/dictionaries/entries?headword=" + + WebUtility.UrlEncode(word)); + }); + + var data = JsonConvert.DeserializeObject(res); + + var datas = data.Results + .Where(x => x.Senses is not null + && x.Senses.Count > 0 + && x.Senses[0].Definition is not null) + .Select(x => (Sense: x.Senses[0], x.PartOfSpeech)) + .ToList(); + + if (!datas.Any()) + { + Log.Warning("Definition not found: {Word}", word); + await ReplyErrorLocalizedAsync(strs.define_unknown); + } + + + var col = datas.Select(x => ( + Definition: x.Sense.Definition is string + ? x.Sense.Definition.ToString() + : ((JArray)JToken.Parse(x.Sense.Definition.ToString())).First.ToString(), + Example: x.Sense.Examples is null || x.Sense.Examples.Count == 0 + ? string.Empty + : x.Sense.Examples[0].Text, Word: word, + WordType: string.IsNullOrWhiteSpace(x.PartOfSpeech) ? "-" : x.PartOfSpeech)) + .ToList(); + + Log.Information("Sending {Count} definition for: {Word}", col.Count, word); + + await ctx.SendPaginatedConfirmAsync(0, + page => + { + var model = col.Skip(page).First(); + var embed = _eb.Create() + .WithDescription(ctx.User.Mention) + .AddField(GetText(strs.word), model.Word, true) + .AddField(GetText(strs._class), model.WordType, true) + .AddField(GetText(strs.definition), model.Definition) + .WithOkColor(); + + if (!string.IsNullOrWhiteSpace(model.Example)) + embed.AddField(GetText(strs.example), model.Example); + + return embed; + }, + col.Count, + 1); + } + catch (Exception ex) + { + Log.Error(ex, "Error retrieving definition data for: {Word}", word); + } + } + + [Cmd] + public async Task Catfact() + { + using var http = _httpFactory.CreateClient(); + var response = await http.GetStringAsync("https://catfact.ninja/fact"); + + var fact = JObject.Parse(response)["fact"].ToString(); + await SendConfirmAsync("🐈" + GetText(strs.catfact), fact); + } + + //done in 3.0 + [Cmd] + [RequireContext(ContextType.Guild)] + public async Task Revav([Leftover] IGuildUser usr = null) + { + if (usr is null) + usr = (IGuildUser)ctx.User; + + var av = usr.RealAvatarUrl(); + await SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={av}"); + } + + //done in 3.0 + [Cmd] + public async Task Revimg([Leftover] string imageLink = null) + { + imageLink = imageLink?.Trim() ?? ""; + + if (string.IsNullOrWhiteSpace(imageLink)) + return; + + await SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={imageLink}"); + } + + [Cmd] + public async Task Wiki([Leftover] string query = null) + { + query = query?.Trim(); + + if (!await ValidateQuery(query)) + return; + + using var http = _httpFactory.CreateClient(); + var result = await http.GetStringAsync( + "https://en.wikipedia.org//w/api.php?action=query&format=json&prop=info&redirects=1&formatversion=2&inprop=url&titles=" + + Uri.EscapeDataString(query)); + var data = JsonConvert.DeserializeObject(result); + if (data.Query.Pages[0].Missing || string.IsNullOrWhiteSpace(data.Query.Pages[0].FullUrl)) + await ReplyErrorLocalizedAsync(strs.wiki_page_not_found); + else + await ctx.Channel.SendMessageAsync(data.Query.Pages[0].FullUrl); + } + + [Cmd] + public async Task Color(params Color[] colors) + { + if (!colors.Any()) + return; + + var colorObjects = colors.Take(10).ToArray(); + + using var img = new Image(colorObjects.Length * 50, 50); + for (var i = 0; i < colorObjects.Length; i++) + { + var x = i * 50; + img.Mutate(m => m.FillPolygon(colorObjects[i], new(x, 0), new(x + 50, 0), new(x + 50, 50), new(x, 50))); + } + + await using var ms = img.ToStream(); + await ctx.Channel.SendFileAsync(ms, "colors.png"); + } + + [Cmd] + [RequireContext(ContextType.Guild)] + public async Task Avatar([Leftover] IGuildUser usr = null) + { + if (usr is null) + usr = (IGuildUser)ctx.User; + + var avatarUrl = usr.RealAvatarUrl(2048); + + await ctx.Channel.EmbedAsync( + _eb.Create() + .WithOkColor() + .AddField("Username", usr.ToString()) + .AddField("Avatar Url", avatarUrl) + .WithThumbnailUrl(avatarUrl.ToString()), + ctx.User.Mention); + } + + [Cmd] + public async Task Wikia(string target, [Leftover] string query) + { + if (string.IsNullOrWhiteSpace(target) || string.IsNullOrWhiteSpace(query)) + { + await ReplyErrorLocalizedAsync(strs.wikia_input_error); + return; + } + + await ctx.Channel.TriggerTypingAsync(); + using var http = _httpFactory.CreateClient(); + http.DefaultRequestHeaders.Clear(); + try + { + var res = await http.GetStringAsync($"https://{Uri.EscapeDataString(target)}.fandom.com/api.php" + + "?action=query" + + "&format=json" + + "&list=search" + + $"&srsearch={Uri.EscapeDataString(query)}" + + "&srlimit=1"); + var items = JObject.Parse(res); + var title = items["query"]?["search"]?.FirstOrDefault()?["title"]?.ToString(); + + if (string.IsNullOrWhiteSpace(title)) + { + await ReplyErrorLocalizedAsync(strs.wikia_error); + return; + } + + var url = Uri.EscapeDataString($"https://{target}.fandom.com/wiki/{title}"); + var response = $@"`{GetText(strs.title)}` {title.SanitizeMentions()} +`{GetText(strs.url)}:` {url}"; + await ctx.Channel.SendMessageAsync(response); + } + catch + { + await ReplyErrorLocalizedAsync(strs.wikia_error); + } + } + + [Cmd] + [RequireContext(ContextType.Guild)] + public async Task Bible(string book, string chapterAndVerse) + { + var obj = new BibleVerses(); + try + { + using var http = _httpFactory.CreateClient(); + var res = await http.GetStringAsync($"https://bible-api.com/{book} {chapterAndVerse}"); + + obj = JsonConvert.DeserializeObject(res); + } + catch + { + } + + if (obj.Error is not null || obj.Verses is null || obj.Verses.Length == 0) + await SendErrorAsync(obj.Error ?? "No verse found."); + else + { + var v = obj.Verses[0]; + await ctx.Channel.EmbedAsync(_eb.Create() + .WithOkColor() + .WithTitle($"{v.BookName} {v.Chapter}:{v.Verse}") + .WithDescription(v.Text)); + } + } + + [Cmd] + public async Task Steam([Leftover] string query) + { + if (string.IsNullOrWhiteSpace(query)) + return; + + await ctx.Channel.TriggerTypingAsync(); + + var appId = await _service.GetSteamAppIdByName(query); + if (appId == -1) + { + await ReplyErrorLocalizedAsync(strs.not_found); + return; + } + + //var embed = _eb.Create() + // .WithOkColor() + // .WithDescription(gameData.ShortDescription) + // .WithTitle(gameData.Name) + // .WithUrl(gameData.Link) + // .WithImageUrl(gameData.HeaderImage) + // .AddField(GetText(strs.genres), gameData.TotalEpisodes.ToString(), true) + // .AddField(GetText(strs.price), gameData.IsFree ? GetText(strs.FREE) : game, true) + // .AddField(GetText(strs.links), gameData.GetGenresString(), true) + // .WithFooter(GetText(strs.recommendations(gameData.TotalRecommendations))); + await ctx.Channel.SendMessageAsync($"https://store.steampowered.com/app/{appId}"); + } + + private async Task ValidateQuery([MaybeNullWhen(false)] string query) + { + if (!string.IsNullOrWhiteSpace(query)) + return true; + + await ErrorLocalizedAsync(strs.specify_search_params); + return false; + } + + public class ShortenData + { + [JsonProperty("result_url")] public string ResultUrl { get; set; } + } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/SearchesService.cs b/src/Ellie.Bot.Modules.Searches/SearchesService.cs new file mode 100644 index 0000000..71477ee --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/SearchesService.cs @@ -0,0 +1,468 @@ +#nullable disable +using Html2Markdown; +using Ellie.Modules.Searches.Common; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using SixLabors.Fonts; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Drawing.Processing; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing; +using Color = SixLabors.ImageSharp.Color; +using Image = SixLabors.ImageSharp.Image; + +namespace Ellie.Modules.Searches.Services; + +public class SearchesService : IEService +{ + public enum ImageTag + { + Food, + Dogs, + Cats, + Birds + } + + public List WowJokes { get; } = new(); + public List MagicItems { get; } = new(); + private readonly IHttpClientFactory _httpFactory; + private readonly IGoogleApiService _google; + private readonly IImageCache _imgs; + private readonly IBotCache _c; + private readonly FontProvider _fonts; + private readonly IBotCredsProvider _creds; + private readonly EllieRandom _rng; + private readonly List _yomamaJokes; + + private readonly object _yomamaLock = new(); + private int yomamaJokeIndex; + + public SearchesService( + IGoogleApiService google, + IImageCache images, + IBotCache c, + IHttpClientFactory factory, + FontProvider fonts, + IBotCredsProvider creds) + { + _httpFactory = factory; + _google = google; + _imgs = images; + _c = c; + _fonts = fonts; + _creds = creds; + _rng = new(); + + //joke commands + if (File.Exists("data/wowjokes.json")) + WowJokes = JsonConvert.DeserializeObject>(File.ReadAllText("data/wowjokes.json")); + else + Log.Warning("data/wowjokes.json is missing. WOW Jokes are not loaded"); + + if (File.Exists("data/magicitems.json")) + MagicItems = JsonConvert.DeserializeObject>(File.ReadAllText("data/magicitems.json")); + else + Log.Warning("data/magicitems.json is missing. Magic items are not loaded"); + + if (File.Exists("data/yomama.txt")) + _yomamaJokes = File.ReadAllLines("data/yomama.txt").Shuffle().ToList(); + else + { + _yomamaJokes = new(); + Log.Warning("data/yomama.txt is missing. .yomama command won't work"); + } + } + + public async Task GetRipPictureAsync(string text, Uri imgUrl) + => (await GetRipPictureFactory(text, imgUrl)).ToStream(); + + private void DrawAvatar(Image bg, Image avatarImage) + => bg.Mutate(x => x.Grayscale().DrawImage(avatarImage, new(83, 139), new GraphicsOptions())); + + public async Task GetRipPictureFactory(string text, Uri avatarUrl) + { + using var bg = Image.Load(await _imgs.GetRipBgAsync()); + var result = await _c.GetImageDataAsync(avatarUrl); + if (!result.TryPickT0(out var data, out _)) + { + using var http = _httpFactory.CreateClient(); + data = await http.GetByteArrayAsync(avatarUrl); + using (var avatarImg = Image.Load(data)) + { + avatarImg.Mutate(x => x.Resize(85, 85).ApplyRoundedCorners(42)); + await using var avStream = await avatarImg.ToStreamAsync(); + data = avStream.ToArray(); + DrawAvatar(bg, avatarImg); + } + + await _c.SetImageDataAsync(avatarUrl, data); + } + else + { + using var avatarImg = Image.Load(data); + DrawAvatar(bg, avatarImg); + } + + bg.Mutate(x => x.DrawText( + new TextOptions(_fonts.RipFont) + { + HorizontalAlignment = HorizontalAlignment.Center, + FallbackFontFamilies = _fonts.FallBackFonts, + Origin = new(bg.Width / 2, 225), + }, + text, + Color.Black)); + + //flowa + using (var flowers = Image.Load(await _imgs.GetRipOverlayAsync())) + { + bg.Mutate(x => x.DrawImage(flowers, new(0, 0), new GraphicsOptions())); + } + + await using var stream = bg.ToStream(); + return stream.ToArray(); + } + + public async Task GetWeatherDataAsync(string query) + { + query = query.Trim().ToLowerInvariant(); + + return await _c.GetOrAddAsync(new($"nadeko_weather_{query}"), + async () => await GetWeatherDataFactory(query), + TimeSpan.FromHours(3)); + } + + private async Task GetWeatherDataFactory(string query) + { + using var http = _httpFactory.CreateClient(); + try + { + var data = await http.GetStringAsync("https://api.openweathermap.org/data/2.5/weather?" + + $"q={query}&" + + "appid=42cd627dd60debf25a5739e50a217d74&" + + "units=metric"); + + if (string.IsNullOrWhiteSpace(data)) + return null; + + return JsonConvert.DeserializeObject(data); + } + catch (Exception ex) + { + Log.Warning(ex, "Error getting weather data"); + return null; + } + } + + public Task<((string Address, DateTime Time, string TimeZoneName), TimeErrors?)> GetTimeDataAsync(string arg) + => GetTimeDataFactory(arg); + + //return _cache.GetOrAddCachedDataAsync($"nadeko_time_{arg}", + // GetTimeDataFactory, + // arg, + // TimeSpan.FromMinutes(1)); + private async Task<((string Address, DateTime Time, string TimeZoneName), TimeErrors?)> GetTimeDataFactory( + string query) + { + query = query.Trim(); + + if (string.IsNullOrEmpty(query)) + return (default, TimeErrors.InvalidInput); + + + var locIqKey = _creds.GetCreds().LocationIqApiKey; + var tzDbKey = _creds.GetCreds().TimezoneDbApiKey; + if (string.IsNullOrWhiteSpace(locIqKey) || string.IsNullOrWhiteSpace(tzDbKey)) + return (default, TimeErrors.ApiKeyMissing); + + try + { + using var http = _httpFactory.CreateClient(); + var res = await _c.GetOrAddAsync(new($"searches:geo:{query}"), + async () => + { + var url = "https://eu1.locationiq.com/v1/search.php?" + + (string.IsNullOrWhiteSpace(locIqKey) + ? "key=" + : $"key={locIqKey}&") + + $"q={Uri.EscapeDataString(query)}&" + + "format=json"; + + var res = await http.GetStringAsync(url); + return res; + }, + TimeSpan.FromHours(1)); + + var responses = JsonConvert.DeserializeObject(res); + if (responses is null || responses.Length == 0) + { + Log.Warning("Geocode lookup failed for: {Query}", query); + return (default, TimeErrors.NotFound); + } + + var geoData = responses[0]; + + using var req = new HttpRequestMessage(HttpMethod.Get, + "http://api.timezonedb.com/v2.1/get-time-zone?" + + $"key={tzDbKey}" + + $"&format=json" + + $"&by=position" + + $"&lat={geoData.Lat}" + + $"&lng={geoData.Lon}"); + + using var geoRes = await http.SendAsync(req); + var resString = await geoRes.Content.ReadAsStringAsync(); + var timeObj = JsonConvert.DeserializeObject(resString); + + var time = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timeObj.Timestamp); + + return ((Address: responses[0].DisplayName, Time: time, TimeZoneName: timeObj.TimezoneName), default); + } + catch (Exception ex) + { + Log.Error(ex, "Weather error: {Message}", ex.Message); + return (default, TimeErrors.NotFound); + } + } + + public string GetRandomImageUrl(ImageTag tag) + { + var subpath = tag.ToString().ToLowerInvariant(); + + int max; + switch (tag) + { + case ImageTag.Food: + max = 773; + break; + case ImageTag.Dogs: + max = 750; + break; + case ImageTag.Cats: + max = 773; + break; + case ImageTag.Birds: + max = 578; + break; + default: + max = 100; + break; + } + + return $"https://nadeko-pictures.nyc3.digitaloceanspaces.com/{subpath}/" + + _rng.Next(1, max).ToString("000") + + ".png"; + } + + public Task GetYomamaJoke() + { + string joke; + lock (_yomamaLock) + { + if (yomamaJokeIndex >= _yomamaJokes.Count) + { + yomamaJokeIndex = 0; + var newList = _yomamaJokes.ToList(); + _yomamaJokes.Clear(); + _yomamaJokes.AddRange(newList.Shuffle()); + } + + joke = _yomamaJokes[yomamaJokeIndex++]; + } + + return Task.FromResult(joke); + + // using (var http = _httpFactory.CreateClient()) + // { + // var response = await http.GetStringAsync(new Uri("http://api.yomomma.info/")); + // return JObject.Parse(response)["joke"].ToString() + " 😆"; + // } + } + + public async Task<(string Setup, string Punchline)> GetRandomJoke() + { + using var http = _httpFactory.CreateClient(); + var res = await http.GetStringAsync("https://official-joke-api.appspot.com/random_joke"); + var resObj = JsonConvert.DeserializeAnonymousType(res, + new + { + setup = "", + punchline = "" + }); + return (resObj.setup, resObj.punchline); + } + + public async Task GetChuckNorrisJoke() + { + using var http = _httpFactory.CreateClient(); + var response = await http.GetStringAsync(new Uri("https://api.chucknorris.io/jokes/random")); + return JObject.Parse(response)["value"] + " 😆"; + } + + public async Task GetMtgCardAsync(string search) + { + search = search.Trim().ToLowerInvariant(); + var data = await _c.GetOrAddAsync(new($"mtg:{search}"), + async () => await GetMtgCardFactory(search), + TimeSpan.FromDays(1)); + + if (data is null || data.Length == 0) + return null; + + return data[_rng.Next(0, data.Length)]; + } + + private async Task GetMtgCardFactory(string search) + { + async Task GetMtgDataAsync(MtgResponse.Data card) + { + string storeUrl; + try + { + storeUrl = await _google.ShortenUrl("https://shop.tcgplayer.com/productcatalog/product/show?" + + "newSearch=false&" + + "ProductType=All&" + + "IsProductNameExact=false&" + + $"ProductName={Uri.EscapeDataString(card.Name)}"); + } + catch { storeUrl = ""; } + + return new() + { + Description = card.Text, + Name = card.Name, + ImageUrl = card.ImageUrl, + StoreUrl = storeUrl, + Types = string.Join(",\n", card.Types), + ManaCost = card.ManaCost + }; + } + + using var http = _httpFactory.CreateClient(); + http.DefaultRequestHeaders.Clear(); + var response = + await http.GetStringAsync($"https://api.magicthegathering.io/v1/cards?name={Uri.EscapeDataString(search)}"); + + var responseObject = JsonConvert.DeserializeObject(response); + if (responseObject is null) + return Array.Empty(); + + var cards = responseObject.Cards.Take(5).ToArray(); + if (cards.Length == 0) + return Array.Empty(); + + return await cards.Select(GetMtgDataAsync).WhenAll(); + } + + public async Task GetHearthstoneCardDataAsync(string name) + { + name = name.ToLowerInvariant(); + return await _c.GetOrAddAsync($"hearthstone:{name}", + () => HearthstoneCardDataFactory(name), + TimeSpan.FromDays(1)); + } + + private async Task HearthstoneCardDataFactory(string name) + { + using var http = _httpFactory.CreateClient(); + http.DefaultRequestHeaders.Clear(); + http.DefaultRequestHeaders.Add("x-rapidapi-key", _creds.GetCreds().RapidApiKey); + try + { + var response = await http.GetStringAsync("https://omgvamp-hearthstone-v1.p.rapidapi.com/" + + $"cards/search/{Uri.EscapeDataString(name)}"); + var objs = JsonConvert.DeserializeObject(response); + if (objs is null || objs.Length == 0) + return null; + var data = objs.FirstOrDefault(x => x.Collectible) + ?? objs.FirstOrDefault(x => !string.IsNullOrEmpty(x.PlayerClass)) ?? objs.FirstOrDefault(); + if (data is null) + return null; + if (!string.IsNullOrWhiteSpace(data.Img)) + data.Img = await _google.ShortenUrl(data.Img); + if (!string.IsNullOrWhiteSpace(data.Text)) + { + var converter = new Converter(); + data.Text = converter.Convert(data.Text); + } + + return data; + } + catch (Exception ex) + { + Log.Error(ex, "Error getting Hearthstone Card: {ErrorMessage}", ex.Message); + return null; + } + } + + public async Task GetMovieDataAsync(string name) + { + name = name.Trim().ToLowerInvariant(); + return await _c.GetOrAddAsync(new($"movie:{name}"), + () => GetMovieDataFactory(name), + TimeSpan.FromDays(1)); + } + + private async Task GetMovieDataFactory(string name) + { + using var http = _httpFactory.CreateClient(); + var res = await http.GetStringAsync(string.Format("https://omdbapi.nadeko.bot/" + + "?t={0}" + + "&y=" + + "&plot=full" + + "&r=json", + name.Trim().Replace(' ', '+'))); + var movie = JsonConvert.DeserializeObject(res); + if (movie?.Title is null) + return null; + movie.Poster = await _google.ShortenUrl(movie.Poster); + return movie; + } + + public async Task GetSteamAppIdByName(string query) + { + const string steamGameIdsKey = "steam_names_to_appid"; + + var gamesMap = await _c.GetOrAddAsync(new(steamGameIdsKey), + async () => + { + using var http = _httpFactory.CreateClient(); + + // https://api.steampowered.com/ISteamApps/GetAppList/v2/ + var gamesStr = await http.GetStringAsync("https://api.steampowered.com/ISteamApps/GetAppList/v2/"); + var apps = JsonConvert + .DeserializeAnonymousType(gamesStr, + new + { + applist = new + { + apps = new List() + } + })! + .applist.apps; + + return apps.OrderBy(x => x.Name, StringComparer.OrdinalIgnoreCase) + .GroupBy(x => x.Name) + .ToDictionary(x => x.Key, x => x.First().AppId); + }, + TimeSpan.FromHours(24)); + + if (gamesMap is null) + return -1; + + query = query.Trim(); + + var keyList = gamesMap.Keys.ToList(); + + var key = keyList.FirstOrDefault(x => x.Equals(query, StringComparison.OrdinalIgnoreCase)); + + if (key == default) + { + key = keyList.FirstOrDefault(x => x.StartsWith(query, StringComparison.OrdinalIgnoreCase)); + if (key == default) + return -1; + } + + return gamesMap[key]; + } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/StreamNotification/StreamNotificationCommands.cs b/src/Ellie.Bot.Modules.Searches/StreamNotification/StreamNotificationCommands.cs new file mode 100644 index 0000000..cacffee --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/StreamNotification/StreamNotificationCommands.cs @@ -0,0 +1,200 @@ +#nullable disable +using Microsoft.EntityFrameworkCore; +using Ellie.Db; +using Ellie.Db.Models; +using Ellie.Modules.Searches.Services; + +namespace Ellie.Modules.Searches; + +public partial class Searches +{ + [Group] + public partial class StreamNotificationCommands : EllieModule + { + private readonly DbService _db; + + public StreamNotificationCommands(DbService db) + => _db = db; + + [Cmd] + [RequireContext(ContextType.Guild)] + [UserPerm(GuildPerm.ManageMessages)] + public async Task StreamAdd(string link) + { + var data = await _service.FollowStream(ctx.Guild.Id, ctx.Channel.Id, link); + if (data is null) + { + await ReplyErrorLocalizedAsync(strs.stream_not_added); + return; + } + + var embed = _service.GetEmbed(ctx.Guild.Id, data); + await ctx.Channel.EmbedAsync(embed, GetText(strs.stream_tracked)); + } + + [Cmd] + [RequireContext(ContextType.Guild)] + [UserPerm(GuildPerm.ManageMessages)] + [Priority(1)] + public async Task StreamRemove(int index) + { + if (--index < 0) + return; + + var fs = await _service.UnfollowStreamAsync(ctx.Guild.Id, index); + if (fs is null) + { + await ReplyErrorLocalizedAsync(strs.stream_no); + return; + } + + await ReplyConfirmLocalizedAsync(strs.stream_removed(Format.Bold(fs.Username), fs.Type)); + } + + [Cmd] + [RequireContext(ContextType.Guild)] + [UserPerm(GuildPerm.Administrator)] + public async Task StreamsClear() + { + await _service.ClearAllStreams(ctx.Guild.Id); + await ReplyConfirmLocalizedAsync(strs.streams_cleared); + } + + [Cmd] + [RequireContext(ContextType.Guild)] + public async Task StreamList(int page = 1) + { + if (page-- < 1) + return; + + var streams = new List(); + await using (var uow = _db.GetDbContext()) + { + var all = uow.GuildConfigsForId(ctx.Guild.Id, set => set.Include(gc => gc.FollowedStreams)) + .FollowedStreams.OrderBy(x => x.Id) + .ToList(); + + for (var index = all.Count - 1; index >= 0; index--) + { + var fs = all[index]; + if (((SocketGuild)ctx.Guild).GetTextChannel(fs.ChannelId) is null) + await _service.UnfollowStreamAsync(fs.GuildId, index); + else + streams.Insert(0, fs); + } + } + + await ctx.SendPaginatedConfirmAsync(page, + cur => + { + var elements = streams + .Skip(cur * 12) + .Take(12) + .ToList(); + + if (elements.Count == 0) + return _eb.Create().WithDescription(GetText(strs.streams_none)).WithErrorColor(); + + var eb = _eb.Create().WithTitle(GetText(strs.streams_follow_title)).WithOkColor(); + for (var index = 0; index < elements.Count; index++) + { + var elem = elements[index]; + eb.AddField($"**#{index + 1 + (12 * cur)}** {elem.Username.ToLower()}", + $"【{elem.Type}】\n<#{elem.ChannelId}>\n{elem.Message?.TrimTo(50)}", + true); + } + + return eb; + }, + streams.Count, + 12); + } + + [Cmd] + [RequireContext(ContextType.Guild)] + [UserPerm(GuildPerm.ManageMessages)] + public async Task StreamOffline() + { + var newValue = _service.ToggleStreamOffline(ctx.Guild.Id); + if (newValue) + await ReplyConfirmLocalizedAsync(strs.stream_off_enabled); + else + await ReplyConfirmLocalizedAsync(strs.stream_off_disabled); + } + + [Cmd] + [RequireContext(ContextType.Guild)] + [UserPerm(GuildPerm.ManageMessages)] + public async Task StreamOnlineDelete() + { + var newValue = _service.ToggleStreamOnlineDelete(ctx.Guild.Id); + if (newValue) + await ReplyConfirmLocalizedAsync(strs.stream_online_delete_enabled); + else + await ReplyConfirmLocalizedAsync(strs.stream_online_delete_disabled); + } + + [Cmd] + [RequireContext(ContextType.Guild)] + [UserPerm(GuildPerm.ManageMessages)] + public async Task StreamMessage(int index, [Leftover] string message) + { + if (--index < 0) + return; + + if (!_service.SetStreamMessage(ctx.Guild.Id, index, message, out var fs)) + { + await ReplyConfirmLocalizedAsync(strs.stream_not_following); + return; + } + + if (string.IsNullOrWhiteSpace(message)) + await ReplyConfirmLocalizedAsync(strs.stream_message_reset(Format.Bold(fs.Username))); + else + await ReplyConfirmLocalizedAsync(strs.stream_message_set(Format.Bold(fs.Username))); + } + + [Cmd] + [RequireContext(ContextType.Guild)] + [UserPerm(GuildPerm.ManageMessages)] + public async Task StreamMessageAll([Leftover] string message) + { + var count = _service.SetStreamMessageForAll(ctx.Guild.Id, message); + + if (count == 0) + { + await ReplyConfirmLocalizedAsync(strs.stream_not_following_any); + return; + } + + await ReplyConfirmLocalizedAsync(strs.stream_message_set_all(count)); + } + + [Cmd] + [RequireContext(ContextType.Guild)] + public async Task StreamCheck(string url) + { + try + { + var data = await _service.GetStreamDataAsync(url); + if (data is null) + { + await ReplyErrorLocalizedAsync(strs.no_channel_found); + return; + } + + if (data.IsLive) + { + await ReplyConfirmLocalizedAsync(strs.streamer_online(Format.Bold(data.Name), + Format.Bold(data.Viewers.ToString()))); + } + else + await ReplyConfirmLocalizedAsync(strs.streamer_offline(data.Name)); + } + catch + { + await ReplyErrorLocalizedAsync(strs.no_channel_found); + } + } + } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/StreamNotification/StreamNotificationService.cs b/src/Ellie.Bot.Modules.Searches/StreamNotification/StreamNotificationService.cs new file mode 100644 index 0000000..e4a4e42 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/StreamNotification/StreamNotificationService.cs @@ -0,0 +1,617 @@ +#nullable disable +using Microsoft.EntityFrameworkCore; +using Ellie.Common.ModuleBehaviors; +using Ellie.Db; +using Ellie.Db.Models; +using Ellie.Modules.Searches.Common; +using Ellie.Modules.Searches.Common.StreamNotifications; +using Ellie.Services.Database.Models; + +namespace Ellie.Modules.Searches.Services; + +public sealed class StreamNotificationService : IEService, IReadyExecutor +{ + private readonly DbService _db; + private readonly IBotStrings _strings; + private readonly Random _rng = new EllieRandom(); + private readonly DiscordSocketClient _client; + private readonly NotifChecker _streamTracker; + + private readonly object _shardLock = new(); + + private readonly Dictionary> _trackCounter = new(); + + private readonly Dictionary>> _shardTrackedStreams; + private readonly ConcurrentHashSet _offlineNotificationServers; + private readonly ConcurrentHashSet _deleteOnOfflineServers; + + private readonly IPubSub _pubSub; + private readonly IEmbedBuilderService _eb; + + public TypedKey> StreamsOnlineKey { get; } + public TypedKey> StreamsOfflineKey { get; } + + private readonly TypedKey _streamFollowKey; + private readonly TypedKey _streamUnfollowKey; + + public event Func< + FollowedStream.FType, + string, + IReadOnlyCollection<(ulong, ulong)>, + Task> OnlineMessagesSent = static delegate { return Task.CompletedTask; }; + + public StreamNotificationService( + DbService db, + DiscordSocketClient client, + IBotStrings strings, + IBotCredsProvider creds, + IHttpClientFactory httpFactory, + IBot bot, + IPubSub pubSub, + IEmbedBuilderService eb) + { + _db = db; + _client = client; + _strings = strings; + _pubSub = pubSub; + _eb = eb; + + _streamTracker = new(httpFactory, creds); + + StreamsOnlineKey = new("streams.online"); + StreamsOfflineKey = new("streams.offline"); + + _streamFollowKey = new("stream.follow"); + _streamUnfollowKey = new("stream.unfollow"); + + using (var uow = db.GetDbContext()) + { + var ids = client.GetGuildIds(); + var guildConfigs = uow.Set() + .AsQueryable() + .Include(x => x.FollowedStreams) + .Where(x => ids.Contains(x.GuildId)) + .ToList(); + + _offlineNotificationServers = new(guildConfigs + .Where(gc => gc.NotifyStreamOffline) + .Select(x => x.GuildId) + .ToList()); + + _deleteOnOfflineServers = new(guildConfigs + .Where(gc => gc.DeleteStreamOnlineMessage) + .Select(x => x.GuildId) + .ToList()); + + var followedStreams = guildConfigs.SelectMany(x => x.FollowedStreams).ToList(); + + _shardTrackedStreams = followedStreams.GroupBy(x => new + { + x.Type, + Name = x.Username.ToLower() + }) + .ToList() + .ToDictionary( + x => new StreamDataKey(x.Key.Type, x.Key.Name.ToLower()), + x => x.GroupBy(y => y.GuildId) + .ToDictionary(y => y.Key, + y => y.AsEnumerable().ToHashSet())); + + // shard 0 will keep track of when there are no more guilds which track a stream + if (client.ShardId == 0) + { + var allFollowedStreams = uow.Set().AsQueryable().ToList(); + + foreach (var fs in allFollowedStreams) + _streamTracker.AddLastData(fs.CreateKey(), null, false); + + _trackCounter = allFollowedStreams.GroupBy(x => new + { + x.Type, + Name = x.Username.ToLower() + }) + .ToDictionary(x => new StreamDataKey(x.Key.Type, x.Key.Name), + x => x.Select(fs => fs.GuildId).ToHashSet()); + } + } + + _pubSub.Sub(StreamsOfflineKey, HandleStreamsOffline); + _pubSub.Sub(StreamsOnlineKey, HandleStreamsOnline); + + if (client.ShardId == 0) + { + // only shard 0 will run the tracker, + // and then publish updates with redis to other shards + _streamTracker.OnStreamsOffline += OnStreamsOffline; + _streamTracker.OnStreamsOnline += OnStreamsOnline; + _ = _streamTracker.RunAsync(); + + _pubSub.Sub(_streamFollowKey, HandleFollowStream); + _pubSub.Sub(_streamUnfollowKey, HandleUnfollowStream); + } + + bot.JoinedGuild += ClientOnJoinedGuild; + client.LeftGuild += ClientOnLeftGuild; + } + + public async Task OnReadyAsync() + { + if (_client.ShardId != 0) + return; + + using var timer = new PeriodicTimer(TimeSpan.FromMinutes(30)); + while (await timer.WaitForNextTickAsync()) + { + try + { + var errorLimit = TimeSpan.FromHours(12); + var failingStreams = _streamTracker.GetFailingStreams(errorLimit, true).ToList(); + + if (!failingStreams.Any()) + continue; + + var deleteGroups = failingStreams.GroupBy(x => x.Type) + .ToDictionary(x => x.Key, x => x.Select(y => y.Name).ToList()); + + await using var uow = _db.GetDbContext(); + foreach (var kvp in deleteGroups) + { + Log.Information( + "Deleting {StreamCount} {Platform} streams because they've been erroring for more than {ErrorLimit}: {RemovedList}", + kvp.Value.Count, + kvp.Key, + errorLimit, + string.Join(", ", kvp.Value)); + + var toDelete = uow.Set() + .AsQueryable() + .Where(x => x.Type == kvp.Key && kvp.Value.Contains(x.Username)) + .ToList(); + + uow.RemoveRange(toDelete); + await uow.SaveChangesAsync(); + + foreach (var loginToDelete in kvp.Value) + _streamTracker.UntrackStreamByKey(new(kvp.Key, loginToDelete)); + } + } + catch (Exception ex) + { + Log.Error(ex, "Error cleaning up FollowedStreams"); + } + } + } + + /// + /// Handles follow stream pubs to keep the counter up to date. + /// When counter reaches 0, stream is removed from tracking because + /// that means no guilds are subscribed to that stream anymore + /// + private ValueTask HandleFollowStream(FollowStreamPubData info) + { + _streamTracker.AddLastData(info.Key, null, false); + lock (_shardLock) + { + var key = info.Key; + if (_trackCounter.ContainsKey(key)) + _trackCounter[key].Add(info.GuildId); + else + { + _trackCounter[key] = new() + { + info.GuildId + }; + } + } + + return default; + } + + /// + /// Handles unfollow pubs to keep the counter up to date. + /// When counter reaches 0, stream is removed from tracking because + /// that means no guilds are subscribed to that stream anymore + /// + private ValueTask HandleUnfollowStream(FollowStreamPubData info) + { + lock (_shardLock) + { + var key = info.Key; + if (!_trackCounter.TryGetValue(key, out var set)) + { + // it should've been removed already? + _streamTracker.UntrackStreamByKey(in key); + return default; + } + + set.Remove(info.GuildId); + if (set.Count != 0) + return default; + + _trackCounter.Remove(key); + // if no other guilds are following this stream + // untrack the stream + _streamTracker.UntrackStreamByKey(in key); + } + + return default; + } + + private async ValueTask HandleStreamsOffline(List offlineStreams) + { + foreach (var stream in offlineStreams) + { + var key = stream.CreateKey(); + if (_shardTrackedStreams.TryGetValue(key, out var fss)) + { + await fss + // send offline stream notifications only to guilds which enable it with .stoff + .SelectMany(x => x.Value) + .Where(x => _offlineNotificationServers.Contains(x.GuildId)) + .Select(fs => _client.GetGuild(fs.GuildId) + ?.GetTextChannel(fs.ChannelId) + ?.EmbedAsync(GetEmbed(fs.GuildId, stream))) + .WhenAll(); + } + } + } + + + private async ValueTask HandleStreamsOnline(List onlineStreams) + { + foreach (var stream in onlineStreams) + { + var key = stream.CreateKey(); + if (_shardTrackedStreams.TryGetValue(key, out var fss)) + { + var messages = await fss.SelectMany(x => x.Value) + .Select(async fs => + { + var textChannel = _client.GetGuild(fs.GuildId)?.GetTextChannel(fs.ChannelId); + + if (textChannel is null) + return default; + + var rep = new ReplacementBuilder().WithOverride("%user%", () => fs.Username) + .WithOverride("%platform%", () => fs.Type.ToString()) + .Build(); + + var message = string.IsNullOrWhiteSpace(fs.Message) ? "" : rep.Replace(fs.Message); + + var msg = await textChannel.EmbedAsync(GetEmbed(fs.GuildId, stream, false), message); + + // only cache the ids of channel/message pairs + if(_deleteOnOfflineServers.Contains(fs.GuildId)) + return (textChannel.Id, msg.Id); + else + return default; + }) + .WhenAll(); + + + // push online stream messages to redis + // when streams go offline, any server which + // has the online stream message deletion feature + // enabled will have the online messages deleted + try + { + var pairs = messages + .Where(x => x != default) + .Select(x => (x.Item1, x.Item2)) + .ToList(); + + if (pairs.Count > 0) + await OnlineMessagesSent(key.Type, key.Name, pairs); + } + catch + { + + } + } + } + } + + private Task OnStreamsOnline(List data) + => _pubSub.Pub(StreamsOnlineKey, data); + + private Task OnStreamsOffline(List data) + => _pubSub.Pub(StreamsOfflineKey, data); + + private Task ClientOnJoinedGuild(GuildConfig guildConfig) + { + using (var uow = _db.GetDbContext()) + { + var gc = uow.Set().AsQueryable() + .Include(x => x.FollowedStreams) + .FirstOrDefault(x => x.GuildId == guildConfig.GuildId); + + if (gc is null) + return Task.CompletedTask; + + if (gc.NotifyStreamOffline) + _offlineNotificationServers.Add(gc.GuildId); + + foreach (var followedStream in gc.FollowedStreams) + { + var key = followedStream.CreateKey(); + var streams = GetLocalGuildStreams(key, gc.GuildId); + streams.Add(followedStream); + PublishFollowStream(followedStream); + } + } + + return Task.CompletedTask; + } + + private Task ClientOnLeftGuild(SocketGuild guild) + { + using (var uow = _db.GetDbContext()) + { + var gc = uow.GuildConfigsForId(guild.Id, set => set.Include(x => x.FollowedStreams)); + + _offlineNotificationServers.TryRemove(gc.GuildId); + + foreach (var followedStream in gc.FollowedStreams) + { + var streams = GetLocalGuildStreams(followedStream.CreateKey(), guild.Id); + streams.Remove(followedStream); + + PublishUnfollowStream(followedStream); + } + } + + return Task.CompletedTask; + } + + public async Task ClearAllStreams(ulong guildId) + { + await using var uow = _db.GetDbContext(); + var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.FollowedStreams)); + uow.RemoveRange(gc.FollowedStreams); + + foreach (var s in gc.FollowedStreams) + await PublishUnfollowStream(s); + + uow.SaveChanges(); + + return gc.FollowedStreams.Count; + } + + public async Task UnfollowStreamAsync(ulong guildId, int index) + { + FollowedStream fs; + await using (var uow = _db.GetDbContext()) + { + var fss = uow.Set() + .AsQueryable() + .Where(x => x.GuildId == guildId) + .OrderBy(x => x.Id) + .ToList(); + + // out of range + if (fss.Count <= index) + return null; + + fs = fss[index]; + uow.Remove(fs); + + await uow.SaveChangesAsync(); + + // remove from local cache + lock (_shardLock) + { + var key = fs.CreateKey(); + var streams = GetLocalGuildStreams(key, guildId); + streams.Remove(fs); + } + } + + await PublishUnfollowStream(fs); + + return fs; + } + + private void PublishFollowStream(FollowedStream fs) + => _pubSub.Pub(_streamFollowKey, + new() + { + Key = fs.CreateKey(), + GuildId = fs.GuildId + }); + + private Task PublishUnfollowStream(FollowedStream fs) + => _pubSub.Pub(_streamUnfollowKey, + new() + { + Key = fs.CreateKey(), + GuildId = fs.GuildId + }); + + public async Task FollowStream(ulong guildId, ulong channelId, string url) + { + // this will + var data = await _streamTracker.GetStreamDataByUrlAsync(url); + + if (data is null) + return null; + + FollowedStream fs; + await using (var uow = _db.GetDbContext()) + { + var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.FollowedStreams)); + + // add it to the database + fs = new() + { + Type = data.StreamType, + Username = data.UniqueName, + ChannelId = channelId, + GuildId = guildId + }; + + if (gc.FollowedStreams.Count >= 10) + return null; + + gc.FollowedStreams.Add(fs); + await uow.SaveChangesAsync(); + + // add it to the local cache of tracked streams + // this way this shard will know it needs to post a message to discord + // when shard 0 publishes stream status changes for this stream + lock (_shardLock) + { + var key = data.CreateKey(); + var streams = GetLocalGuildStreams(key, guildId); + streams.Add(fs); + } + } + + PublishFollowStream(fs); + + return data; + } + + public IEmbedBuilder GetEmbed(ulong guildId, StreamData status, bool showViewers = true) + { + var embed = _eb.Create() + .WithTitle(status.Name) + .WithUrl(status.StreamUrl) + .WithDescription(status.StreamUrl) + .AddField(GetText(guildId, strs.status), status.IsLive ? "🟢 Online" : "🔴 Offline", true); + + if (showViewers) + { + embed.AddField(GetText(guildId, strs.viewers), + status.Viewers == 0 && !status.IsLive + ? "-" + : status.Viewers, + true); + } + + if (status.IsLive) + embed = embed.WithOkColor(); + else + embed = embed.WithErrorColor(); + + if (!string.IsNullOrWhiteSpace(status.Title)) + embed.WithAuthor(status.Title); + + if (!string.IsNullOrWhiteSpace(status.Game)) + embed.AddField(GetText(guildId, strs.streaming), status.Game, true); + + if (!string.IsNullOrWhiteSpace(status.AvatarUrl)) + embed.WithThumbnailUrl(status.AvatarUrl); + + if (!string.IsNullOrWhiteSpace(status.Preview)) + embed.WithImageUrl(status.Preview + "?dv=" + _rng.Next()); + + return embed; + } + + private string GetText(ulong guildId, LocStr str) + => _strings.GetText(str, guildId); + + public bool ToggleStreamOffline(ulong guildId) + { + bool newValue; + using var uow = _db.GetDbContext(); + var gc = uow.GuildConfigsForId(guildId, set => set); + newValue = gc.NotifyStreamOffline = !gc.NotifyStreamOffline; + uow.SaveChanges(); + + if (newValue) + _offlineNotificationServers.Add(guildId); + else + _offlineNotificationServers.TryRemove(guildId); + + return newValue; + } + + public bool ToggleStreamOnlineDelete(ulong guildId) + { + using var uow = _db.GetDbContext(); + var gc = uow.GuildConfigsForId(guildId, set => set); + var newValue = gc.DeleteStreamOnlineMessage = !gc.DeleteStreamOnlineMessage; + uow.SaveChanges(); + + if (newValue) + _deleteOnOfflineServers.Add(guildId); + else + _deleteOnOfflineServers.TryRemove(guildId); + + return newValue; + } + + public Task GetStreamDataAsync(string url) + => _streamTracker.GetStreamDataByUrlAsync(url); + + private HashSet GetLocalGuildStreams(in StreamDataKey key, ulong guildId) + { + if (_shardTrackedStreams.TryGetValue(key, out var map)) + { + if (map.TryGetValue(guildId, out var set)) + return set; + return map[guildId] = new(); + } + + _shardTrackedStreams[key] = new() + { + { guildId, new() } + }; + return _shardTrackedStreams[key][guildId]; + } + + public bool SetStreamMessage( + ulong guildId, + int index, + string message, + out FollowedStream fs) + { + using var uow = _db.GetDbContext(); + var fss = uow.Set().AsQueryable().Where(x => x.GuildId == guildId).OrderBy(x => x.Id).ToList(); + + if (fss.Count <= index) + { + fs = null; + return false; + } + + fs = fss[index]; + fs.Message = message; + lock (_shardLock) + { + var streams = GetLocalGuildStreams(fs.CreateKey(), guildId); + + // message doesn't participate in equality checking + // removing and adding = update + streams.Remove(fs); + streams.Add(fs); + } + + uow.SaveChanges(); + + return true; + } + + public int SetStreamMessageForAll(ulong guildId, string message) + { + using var uow = _db.GetDbContext(); + + var all = uow.Set().ToList(); + + if (all.Count == 0) + return 0; + + all.ForEach(x => x.Message = message); + + uow.SaveChanges(); + + return all.Count; + } + + public sealed class FollowStreamPubData + { + public StreamDataKey Key { get; init; } + public ulong GuildId { get; init; } + } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/StreamNotification/StreamOnlineMessageDeleterService.cs b/src/Ellie.Bot.Modules.Searches/StreamNotification/StreamOnlineMessageDeleterService.cs new file mode 100644 index 0000000..549ac8f --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/StreamNotification/StreamOnlineMessageDeleterService.cs @@ -0,0 +1,99 @@ +#nullable disable +using LinqToDB; +using LinqToDB.EntityFrameworkCore; +using Ellie.Common.ModuleBehaviors; +using Ellie.Db.Models; +using Ellie.Modules.Searches.Common; + +namespace Ellie.Modules.Searches.Services; + +public sealed class StreamOnlineMessageDeleterService : IEService, IReadyExecutor +{ + private readonly StreamNotificationService _notifService; + private readonly DbService _db; + private readonly DiscordSocketClient _client; + private readonly IPubSub _pubSub; + + public StreamOnlineMessageDeleterService( + StreamNotificationService notifService, + DbService db, + IPubSub pubSub, + DiscordSocketClient client) + { + _notifService = notifService; + _db = db; + _client = client; + _pubSub = pubSub; + } + + public async Task OnReadyAsync() + { + _notifService.OnlineMessagesSent += OnOnlineMessagesSent; + + if (_client.ShardId == 0) + await _pubSub.Sub(_notifService.StreamsOfflineKey, OnStreamsOffline); + } + + private async Task OnOnlineMessagesSent( + FollowedStream.FType type, + string name, + IReadOnlyCollection<(ulong, ulong)> pairs) + { + await using var ctx = _db.GetDbContext(); + foreach (var (channelId, messageId) in pairs) + { + await ctx.GetTable() + .InsertAsync(() => new() + { + Name = name, + Type = type, + MessageId = messageId, + ChannelId = channelId, + DateAdded = DateTime.UtcNow, + }); + } + } + + private async ValueTask OnStreamsOffline(List streamDatas) + { + if (_client.ShardId != 0) + return; + + var pairs = await GetMessagesToDelete(streamDatas); + + foreach (var (channelId, messageId) in pairs) + { + try + { + var textChannel = await _client.GetChannelAsync(channelId) as ITextChannel; + if (textChannel is null) + continue; + + await textChannel.DeleteMessageAsync(messageId); + } + catch + { + continue; + } + } + } + + private async Task> GetMessagesToDelete(List streamDatas) + { + await using var ctx = _db.GetDbContext(); + + var toReturn = new List<(ulong, ulong)>(); + foreach (var sd in streamDatas) + { + var key = sd.CreateKey(); + var toDelete = await ctx.GetTable() + .Where(x => (x.Type == key.Type && x.Name == key.Name) + || Sql.DateDiff(Sql.DateParts.Day, x.DateAdded, DateTime.UtcNow) > 1) + .DeleteWithOutputAsync(); + + toReturn.AddRange(toDelete.Select(x => (x.ChannelId, x.MessageId))); + } + + return toReturn; + } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Translate/ITranslateService.cs b/src/Ellie.Bot.Modules.Searches/Translate/ITranslateService.cs new file mode 100644 index 0000000..c42de45 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Translate/ITranslateService.cs @@ -0,0 +1,17 @@ +#nullable disable +namespace Ellie.Modules.Searches; + +public interface ITranslateService +{ + public Task Translate(string source, string target, string text = null); + Task ToggleAtl(ulong guildId, ulong channelId, bool autoDelete); + IEnumerable GetLanguages(); + + Task RegisterUserAsync( + ulong userId, + ulong channelId, + string from, + string to); + + Task UnregisterUser(ulong channelId, ulong userId); +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Translate/TranslateService.cs b/src/Ellie.Bot.Modules.Searches/Translate/TranslateService.cs new file mode 100644 index 0000000..822b28b --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Translate/TranslateService.cs @@ -0,0 +1,224 @@ +#nullable disable +using LinqToDB; +using LinqToDB.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; +using Ellie.Common.ModuleBehaviors; +using Ellie.Services.Database.Models; +using System.Net; + +namespace Ellie.Modules.Searches; + +public sealed class TranslateService : ITranslateService, IExecNoCommand, IReadyExecutor, IEService +{ + private readonly IGoogleApiService _google; + private readonly DbService _db; + private readonly IEmbedBuilderService _eb; + private readonly IBot _bot; + + private readonly ConcurrentDictionary _atcs = new(); + private readonly ConcurrentDictionary> _users = new(); + + public TranslateService( + IGoogleApiService google, + DbService db, + IEmbedBuilderService eb, + IBot bot) + { + _google = google; + _db = db; + _eb = eb; + _bot = bot; + } + + public async Task OnReadyAsync() + { + List cs; + await using (var ctx = _db.GetDbContext()) + { + var guilds = _bot.AllGuildConfigs.Select(x => x.GuildId).ToList(); + cs = await ctx.Set().Include(x => x.Users) + .Where(x => guilds.Contains(x.GuildId)) + .ToListAsyncEF(); + } + + foreach (var c in cs) + { + _atcs[c.ChannelId] = c.AutoDelete; + _users[c.ChannelId] = + new(c.Users.ToDictionary(x => x.UserId, x => (x.Source.ToLower(), x.Target.ToLower()))); + } + } + + + public async Task ExecOnNoCommandAsync(IGuild guild, IUserMessage msg) + { + if (string.IsNullOrWhiteSpace(msg.Content)) + return; + + if (msg is { Channel: ITextChannel tch } um) + { + if (!_atcs.TryGetValue(tch.Id, out var autoDelete)) + return; + + if (!_users.TryGetValue(tch.Id, out var users) || !users.TryGetValue(um.Author.Id, out var langs)) + return; + + var output = await _google.Translate(msg.Content, langs.From, langs.To); + + if (string.IsNullOrWhiteSpace(output) + || msg.Content.Equals(output, StringComparison.InvariantCultureIgnoreCase)) + return; + + var embed = _eb.Create().WithOkColor(); + + if (autoDelete) + { + embed.WithAuthor(um.Author.ToString(), um.Author.GetAvatarUrl()) + .AddField(langs.From, um.Content) + .AddField(langs.To, output); + + await tch.EmbedAsync(embed); + + try + { + await um.DeleteAsync(); + } + catch (HttpException ex) when (ex.HttpCode == HttpStatusCode.Forbidden) + { + _atcs.TryUpdate(tch.Id, false, true); + } + + return; + } + + await um.ReplyAsync(embed: embed.AddField(langs.To, output).Build(), allowedMentions: AllowedMentions.None); + } + } + + public async Task Translate(string source, string target, string text = null) + { + if (string.IsNullOrWhiteSpace(text)) + throw new ArgumentException("Text is empty or null", nameof(text)); + + var res = await _google.Translate(text, source, target); + return res.SanitizeMentions(true); + } + + public async Task ToggleAtl(ulong guildId, ulong channelId, bool autoDelete) + { + await using var ctx = _db.GetDbContext(); + + var old = await ctx.Set().ToLinqToDBTable() + .FirstOrDefaultAsyncLinqToDB(x => x.ChannelId == channelId); + + if (old is null) + { + ctx.Set().Add(new() + { + GuildId = guildId, + ChannelId = channelId, + AutoDelete = autoDelete + }); + + await ctx.SaveChangesAsync(); + + _atcs[channelId] = autoDelete; + _users[channelId] = new(); + + return true; + } + + // if autodelete value is different, update the autodelete value + // instead of disabling + if (old.AutoDelete != autoDelete) + { + old.AutoDelete = autoDelete; + await ctx.SaveChangesAsync(); + _atcs[channelId] = autoDelete; + return true; + } + + await ctx.Set().ToLinqToDBTable().DeleteAsync(x => x.ChannelId == channelId); + + await ctx.SaveChangesAsync(); + _atcs.TryRemove(channelId, out _); + _users.TryRemove(channelId, out _); + + return false; + } + + + private void UpdateUser( + ulong channelId, + ulong userId, + string from, + string to) + { + var dict = _users.GetOrAdd(channelId, new ConcurrentDictionary()); + dict[userId] = (from, to); + } + + public async Task RegisterUserAsync( + ulong userId, + ulong channelId, + string from, + string to) + { + if (!_google.Languages.ContainsKey(from) || !_google.Languages.ContainsKey(to)) + return null; + + await using var ctx = _db.GetDbContext(); + var ch = await ctx.Set().GetByChannelId(channelId); + + if (ch is null) + return null; + + var user = ch.Users.FirstOrDefault(x => x.UserId == userId); + + if (user is null) + { + ch.Users.Add(user = new() + { + Source = from, + Target = to, + UserId = userId + }); + + await ctx.SaveChangesAsync(); + + UpdateUser(channelId, userId, from, to); + + return true; + } + + // if it's different from old settings, update + if (user.Source != from || user.Target != to) + { + user.Source = from; + user.Target = to; + + await ctx.SaveChangesAsync(); + + UpdateUser(channelId, userId, from, to); + + return true; + } + + return await UnregisterUser(channelId, userId); + } + + public async Task UnregisterUser(ulong channelId, ulong userId) + { + await using var ctx = _db.GetDbContext(); + var rows = await ctx.Set().ToLinqToDBTable() + .DeleteAsync(x => x.UserId == userId && x.Channel.ChannelId == channelId); + + if (_users.TryGetValue(channelId, out var inner)) + inner.TryRemove(userId, out _); + + return rows > 0; + } + + public IEnumerable GetLanguages() + => _google.Languages.GroupBy(x => x.Value).Select(x => $"{x.AsEnumerable().Select(y => y.Key).Join(", ")}"); +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/Translate/TranslatorCommands.cs b/src/Ellie.Bot.Modules.Searches/Translate/TranslatorCommands.cs new file mode 100644 index 0000000..95afb61 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/Translate/TranslatorCommands.cs @@ -0,0 +1,96 @@ +#nullable disable +namespace Ellie.Modules.Searches; + +public partial class Searches +{ + [Group] + public partial class TranslateCommands : EllieModule + { + public enum AutoDeleteAutoTranslate + { + Del, + Nodel + } + + [Cmd] + public async Task Translate(string from, string to, [Leftover] string text = null) + { + try + { + await ctx.Channel.TriggerTypingAsync(); + var translation = await _service.Translate(from, to, text); + + var embed = _eb.Create(ctx).WithOkColor().AddField(from, text).AddField(to, translation); + + await ctx.Channel.EmbedAsync(embed); + } + catch + { + await ReplyErrorLocalizedAsync(strs.bad_input_format); + } + } + + [Cmd] + [RequireContext(ContextType.Guild)] + [UserPerm(GuildPerm.ManageMessages)] + [OwnerOnly] + public async Task AutoTranslate(AutoDeleteAutoTranslate autoDelete = AutoDeleteAutoTranslate.Nodel) + { + var toggle = + await _service.ToggleAtl(ctx.Guild.Id, ctx.Channel.Id, autoDelete == AutoDeleteAutoTranslate.Del); + if (toggle) + await ReplyConfirmLocalizedAsync(strs.atl_started); + else + { + await ReplyConfirmLocalizedAsync(strs.atl_stopped); + } + } + + [Cmd] + [RequireContext(ContextType.Guild)] + public async Task AutoTransLang() + { + if (await _service.UnregisterUser(ctx.Channel.Id, ctx.User.Id)) + await ReplyConfirmLocalizedAsync(strs.atl_removed); + } + + [Cmd] + [RequireContext(ContextType.Guild)] + public async Task AutoTransLang(string from, string to) + { + var succ = await _service.RegisterUserAsync(ctx.User.Id, ctx.Channel.Id, from.ToLower(), to.ToLower()); + + if (succ is null) + { + await ReplyErrorLocalizedAsync(strs.atl_not_enabled); + return; + } + + if (succ is false) + { + await ReplyErrorLocalizedAsync(strs.invalid_lang); + return; + } + + await ReplyConfirmLocalizedAsync(strs.atl_set(from, to)); + } + + [Cmd] + [RequireContext(ContextType.Guild)] + public async Task Translangs() + { + var langs = _service.GetLanguages().ToList(); + + var eb = _eb.Create() + .WithTitle(GetText(strs.supported_languages)) + .WithOkColor(); + + foreach (var chunk in langs.Chunk(15)) + { + eb.AddField("󠀁", chunk.Join("\n"), isInline: true); + } + + await ctx.Channel.EmbedAsync(eb); + } + } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/XkcdCommands.cs b/src/Ellie.Bot.Modules.Searches/XkcdCommands.cs new file mode 100644 index 0000000..d33f478 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/XkcdCommands.cs @@ -0,0 +1,97 @@ +#nullable disable +using Newtonsoft.Json; + +namespace Ellie.Modules.Searches; + +public partial class Searches +{ + [Group] + public partial class XkcdCommands : EllieModule + { + private const string XKCD_URL = "https://xkcd.com"; + private readonly IHttpClientFactory _httpFactory; + + public XkcdCommands(IHttpClientFactory factory) + => _httpFactory = factory; + + [Cmd] + [Priority(0)] + public async Task Xkcd(string arg = null) + { + if (arg?.ToLowerInvariant().Trim() == "latest") + { + try + { + using var http = _httpFactory.CreateClient(); + var res = await http.GetStringAsync($"{XKCD_URL}/info.0.json"); + var comic = JsonConvert.DeserializeObject(res); + var embed = _eb.Create() + .WithOkColor() + .WithImageUrl(comic.ImageLink) + .WithAuthor(comic.Title, "https://xkcd.com/s/919f27.ico", $"{XKCD_URL}/{comic.Num}") + .AddField(GetText(strs.comic_number), comic.Num.ToString(), true) + .AddField(GetText(strs.date), $"{comic.Month}/{comic.Year}", true); + var sent = await ctx.Channel.EmbedAsync(embed); + + await Task.Delay(10000); + + await sent.ModifyAsync(m => m.Embed = embed.AddField("Alt", comic.Alt).Build()); + } + catch (HttpRequestException) + { + await ReplyErrorLocalizedAsync(strs.comic_not_found); + } + + return; + } + + await Xkcd(new EllieRandom().Next(1, 1750)); + } + + [Cmd] + [Priority(1)] + public async Task Xkcd(int num) + { + if (num < 1) + return; + try + { + using var http = _httpFactory.CreateClient(); + var res = await http.GetStringAsync($"{XKCD_URL}/{num}/info.0.json"); + + var comic = JsonConvert.DeserializeObject(res); + var embed = _eb.Create() + .WithOkColor() + .WithImageUrl(comic.ImageLink) + .WithAuthor(comic.Title, "https://xkcd.com/s/919f27.ico", $"{XKCD_URL}/{num}") + .AddField(GetText(strs.comic_number), comic.Num.ToString(), true) + .AddField(GetText(strs.date), $"{comic.Month}/{comic.Year}", true); + + var sent = await ctx.Channel.EmbedAsync(embed); + + await Task.Delay(10000); + + await sent.ModifyAsync(m => m.Embed = embed.AddField("Alt", comic.Alt).Build()); + } + catch (HttpRequestException) + { + await ReplyErrorLocalizedAsync(strs.comic_not_found); + } + } + } + + public class XkcdComic + { + public int Num { get; set; } + public string Month { get; set; } + public string Year { get; set; } + + [JsonProperty("safe_title")] + public string Title { get; set; } + + [JsonProperty("img")] + public string ImageLink { get; set; } + + public string Alt { get; set; } + } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/YoutubeTrack/YtTrackService.cs b/src/Ellie.Bot.Modules.Searches/YoutubeTrack/YtTrackService.cs new file mode 100644 index 0000000..291ab78 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/YoutubeTrack/YtTrackService.cs @@ -0,0 +1,134 @@ +#nullable disable + +// public class YtTrackService : IEService +// { +// private readonly IGoogleApiService _google; +// private readonly IHttpClientFactory httpClientFactory; +// private readonly DiscordSocketClient _client; +// private readonly DbService _db; +// private readonly ConcurrentDictionary>> followedChannels; +// private readonly ConcurrentDictionary _latestPublishes = new ConcurrentDictionary(); +// +// public YtTrackService(IGoogleApiService google, IHttpClientFactory httpClientFactory, DiscordSocketClient client, +// DbService db) +// { +// this._google = google; +// this.httpClientFactory = httpClientFactory; +// this._client = client; +// this._db = db; +// +// if (_client.ShardId == 0) +// { +// _ = CheckLoop(); +// } +// } +// +// public async Task CheckLoop() +// { +// while (true) +// { +// await Task.Delay(10000); +// using (var http = httpClientFactory.CreateClient()) +// { +// await followedChannels.Select(kvp => CheckChannel(kvp.Key, kvp.Value.SelectMany(x => x.Value).ToList())).WhenAll(); +// } +// } +// } +// +// /// +// /// Checks the specified youtube channel, and sends a message to all provided +// /// +// /// Id of the youtube channel +// /// Where to post updates if there is a new update +// private async Task CheckChannel(string youtubeChannelId, List followedChannels) +// { +// var latestVid = (await _google.GetLatestChannelVideosAsync(youtubeChannelId, 1)) +// .FirstOrDefault(); +// if (latestVid is null) +// { +// return; +// } +// +// if (_latestPublishes.TryGetValue(youtubeChannelId, out var latestPub) && latestPub >= latestVid.PublishedAt) +// { +// return; +// } +// _latestPublishes[youtubeChannelId] = latestVid.PublishedAt; +// +// foreach (var chObj in followedChannels) +// { +// var gCh = _client.GetChannel(chObj.ChannelId); +// if (gCh is ITextChannel ch) +// { +// var msg = latestVid.GetVideoUrl(); +// if (!string.IsNullOrWhiteSpace(chObj.UploadMessage)) +// msg = chObj.UploadMessage + Environment.NewLine + msg; +// +// await ch.SendMessageAsync(msg); +// } +// } +// } +// +// /// +// /// Starts posting updates on the specified discord channel when a new video is posted on the specified YouTube channel. +// /// +// /// Id of the discord guild +// /// Id of the discord channel +// /// Id of the youtube channel +// /// Message to post when a new video is uploaded, along with video URL +// /// Whether adding was successful +// public async Task ToggleChannelFollowAsync(ulong guildId, ulong channelId, string ytChannelId, string uploadMessage) +// { +// // to to see if we can get a video from that channel +// var vids = await _google.GetLatestChannelVideosAsync(ytChannelId, 1); +// if (vids.Count == 0) +// return false; +// +// using(var uow = _db.GetDbContext()) +// { +// var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.YtFollowedChannels)); +// +// // see if this yt channel was already followed on this discord channel +// var oldObj = gc.YtFollowedChannels +// .FirstOrDefault(x => x.ChannelId == channelId && x.YtChannelId == ytChannelId); +// +// if(oldObj is not null) +// { +// return false; +// } +// +// // can only add up to 10 tracked channels per server +// if (gc.YtFollowedChannels.Count >= 10) +// { +// return false; +// } +// +// var obj = new YtFollowedChannel +// { +// ChannelId = channelId, +// YtChannelId = ytChannelId, +// UploadMessage = uploadMessage +// }; +// +// // add to database +// gc.YtFollowedChannels.Add(obj); +// +// // add to the local cache: +// +// // get follows on all guilds +// var allGuildFollows = followedChannels.GetOrAdd(ytChannelId, new ConcurrentDictionary>()); +// // add to this guild's follows +// allGuildFollows.AddOrUpdate(guildId, +// new List(), +// (key, old) => +// { +// old.Add(obj); +// return old; +// }); +// +// await uow.SaveChangesAsync(); +// } +// +// return true; +// } +// } \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/YoutubeTrack/YtUploadCommands.cs b/src/Ellie.Bot.Modules.Searches/YoutubeTrack/YtUploadCommands.cs new file mode 100644 index 0000000..3d2d678 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/YoutubeTrack/YtUploadCommands.cs @@ -0,0 +1,54 @@ +#nullable disable +namespace Ellie.Modules.Searches; + +public partial class Searches +{ + // [Group] + // public partial class YtTrackCommands : EllieModule + // { + // ; + // [RequireContext(ContextType.Guild)] + // public async Task YtFollow(string ytChannelId, [Leftover] string uploadMessage = null) + // { + // var succ = await _service.ToggleChannelFollowAsync(ctx.Guild.Id, ctx.Channel.Id, ytChannelId, uploadMessage); + // if(succ) + // { + // await ReplyConfirmLocalizedAsync(strs.yt_follow_added); + // } + // else + // { + // await ReplyConfirmLocalizedAsync(strs.yt_follow_fail); + // } + // } + // + // [EllieCommand, Usage, Description, Aliases] + // [RequireContext(ContextType.Guild)] + // public async Task YtTrackRm(int index) + // { + // //var succ = await _service.ToggleChannelTrackingAsync(ctx.Guild.Id, ctx.Channel.Id, ytChannelId, uploadMessage); + // //if (succ) + // //{ + // // await ReplyConfirmLocalizedAsync(strs.yt_track_added); + // //} + // //else + // //{ + // // await ReplyConfirmLocalizedAsync(strs.yt_track_fail); + // //} + // } + // + // [EllieCommand, Usage, Description, Aliases] + // [RequireContext(ContextType.Guild)] + // public async Task YtTrackList() + // { + // //var succ = await _service.ToggleChannelTrackingAsync(ctx.Guild.Id, ctx.Channel.Id, ytChannelId, uploadMessage); + // //if (succ) + // //{ + // // await ReplyConfirmLocalizedAsync(strs.yt_track_added); + // //} + // //else + // //{ + // // await ReplyConfirmLocalizedAsync(strs.yt_track_fail); + // //} + // } + // } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/_common/AltExtensions.cs b/src/Ellie.Bot.Modules.Searches/_common/AltExtensions.cs new file mode 100644 index 0000000..82fdbd7 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/_common/AltExtensions.cs @@ -0,0 +1,12 @@ +#nullable disable +using LinqToDB.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; +using Ellie.Services.Database.Models; + +namespace Ellie.Modules.Searches; + +public static class AltExtensions +{ + public static Task GetByChannelId(this IQueryable set, ulong channelId) + => set.Include(x => x.Users).FirstOrDefaultAsyncEF(x => x.ChannelId == channelId); +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/_common/BibleVerses.cs b/src/Ellie.Bot.Modules.Searches/_common/BibleVerses.cs new file mode 100644 index 0000000..c280b7d --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/_common/BibleVerses.cs @@ -0,0 +1,21 @@ +#nullable disable +using Newtonsoft.Json; + +namespace Ellie.Modules.Searches.Common; + +// todo replace newtonsoft with json.text +public class BibleVerses +{ + public string Error { get; set; } + public BibleVerse[] Verses { get; set; } +} + +public class BibleVerse +{ + [JsonProperty("book_name")] + public string BookName { get; set; } + + public int Chapter { get; set; } + public int Verse { get; set; } + public string Text { get; set; } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/_common/CryptoData.cs b/src/Ellie.Bot.Modules.Searches/_common/CryptoData.cs new file mode 100644 index 0000000..cd21545 --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/_common/CryptoData.cs @@ -0,0 +1,66 @@ +#nullable disable +using System.Text.Json.Serialization; + +namespace Ellie.Modules.Searches.Common; + +public class CryptoResponse +{ + public List Data { get; set; } +} + +public class CmcQuote +{ + [JsonPropertyName("price")] + public double Price { get; set; } + + [JsonPropertyName("volume_24h")] + public double Volume24h { get; set; } + + // [JsonPropertyName("volume_change_24h")] + // public double VolumeChange24h { get; set; } + // + // [JsonPropertyName("percent_change_1h")] + // public double PercentChange1h { get; set; } + + [JsonPropertyName("percent_change_24h")] + public double PercentChange24h { get; set; } + + [JsonPropertyName("percent_change_7d")] + public double PercentChange7d { get; set; } + + [JsonPropertyName("market_cap")] + public double MarketCap { get; set; } + + [JsonPropertyName("market_cap_dominance")] + public double MarketCapDominance { get; set; } +} + +public class CmcResponseData +{ + [JsonPropertyName("id")] + public int Id { get; set; } + + [JsonPropertyName("name")] + public string Name { get; set; } + + [JsonPropertyName("symbol")] + public string Symbol { get; set; } + + [JsonPropertyName("slug")] + public string Slug { get; set; } + + [JsonPropertyName("cmc_rank")] + public int CmcRank { get; set; } + + [JsonPropertyName("circulating_supply")] + public double? CirculatingSupply { get; set; } + + [JsonPropertyName("total_supply")] + public double? TotalSupply { get; set; } + + [JsonPropertyName("max_supply")] + public double? MaxSupply { get; set; } + + [JsonPropertyName("quote")] + public Dictionary Quote { get; set; } +} \ No newline at end of file diff --git a/src/Ellie.Bot.Modules.Searches/_common/DefineModel.cs b/src/Ellie.Bot.Modules.Searches/_common/DefineModel.cs new file mode 100644 index 0000000..4bee77c --- /dev/null +++ b/src/Ellie.Bot.Modules.Searches/_common/DefineModel.cs @@ -0,0 +1,43 @@ +#nullable disable +using Newtonsoft.Json; + +namespace Ellie.Modules.Searches.Common; + +public class Audio +{ + public string Url { get; set; } +} + +public class Example +{ + public List