Example #1
0
 /// <summary>
 /// Creates an ApiCalls object and instantiates the available API objects.
 /// </summary>
 /// <param name="configuration">An <see cref="IConfiguration"/> object to access application settings.</param>
 /// <param name="logger">The log4net logger.</param>
 public ApiCalls(IConfiguration configuration, ILog logger)
 {
     Logger   = logger;
     Cache    = new ResponseCache(configuration);
     DolarBot = new DolarBotApiService(configuration, Cache, LogError);
     Cuttly   = new CuttlyApiService(configuration);
     Topgg    = new TopggApiService(configuration, logger);
 }
        /// <summary>
        /// Creates an <see cref="EmbedBuilder"/> object for a <see cref="VzlaResponse"/>.
        /// </summary>
        /// <param name="vzlaResponse">The Venezuela response.</param>
        /// <param name="amount">The amount to rate against.</param>
        /// <returns>An <see cref="EmbedBuilder"/> object ready to be built.</returns>
        public async Task <EmbedBuilder> CreateVzlaEmbedAsync(VzlaResponse vzlaResponse, decimal amount = 1)
        {
            var   emojis        = Configuration.GetSection("customEmojis");
            Emoji currencyEmoji = GetEmoji(vzlaResponse.Type);
            Emoji bankEmoji     = new(":bank:");
            Emoji moneyEmoji    = new(":money_with_wings:");
            Emoji whatsappEmoji = new(emojis["whatsapp"]);
            Emoji amountEmoji   = Emoji.Parse(":moneybag:");

            string       blankSpace    = GlobalConfiguration.Constants.BLANK_SPACE;
            TimeZoneInfo localTimeZone = GlobalConfiguration.GetLocalTimeZoneInfo();
            int          utcOffset     = localTimeZone.GetUtcOffset(DateTime.UtcNow).Hours;

            string thumbnailUrl   = Configuration.GetSection("images").GetSection("venezuela")["64"];
            string footerImageUrl = Configuration.GetSection("images").GetSection("clock")["32"];
            string currencyCode   = vzlaResponse.Type switch
            {
                VenezuelaEndpoints.Dollar => "USD",
                VenezuelaEndpoints.Euro => "EUR",
                _ => throw new NotImplementedException(),
            };

            decimal?bancosValue       = decimal.TryParse(vzlaResponse?.Bancos, NumberStyles.Any, DolarBotApiService.GetApiCulture(), out decimal b) ? b * amount : null;
            decimal?paraleloValue     = decimal.TryParse(vzlaResponse?.Paralelo, NumberStyles.Any, DolarBotApiService.GetApiCulture(), out decimal p) ? p * amount : null;
            string  bancosValueText   = bancosValue.HasValue ? Format.Bold($"B$ {bancosValue.Value.ToString("N2", GlobalConfiguration.GetLocalCultureInfo())}") : "No informado";
            string  paraleloValueText = paraleloValue.HasValue ? Format.Bold($"B$ {paraleloValue.Value.ToString("N2", GlobalConfiguration.GetLocalCultureInfo())}") : "No informado";

            string title       = $"{GetName(vzlaResponse.Type).Capitalize()} Venezuela";
            string description = new StringBuilder()
                                 .AppendLine($"Cotizaciones disponibles del {Format.Bold(GetName(vzlaResponse.Type))} expresadas en {Format.Bold("bolívares venezolanos")}.")
                                 .AppendLineBreak()
                                 .AppendLine($"{bankEmoji} {Format.Bold("Bancos")}: {Format.Italics("Promedio de las cotizaciones bancarias")}.")
                                 .Append($"{moneyEmoji} {Format.Bold("Paralelo")}: {Format.Italics($"Cotización del {GetName(vzlaResponse.Type).ToLower()} paralelo")}.")
                                 .ToString();
            string lastUpdated = vzlaResponse.Fecha.ToString(vzlaResponse.Fecha.Date == TimeZoneInfo.ConvertTime(DateTime.UtcNow, localTimeZone).Date ? "HH:mm" : "dd/MM/yyyy - HH:mm");

            string amountField = Format.Bold($"{amountEmoji} {blankSpace} {amount} {currencyCode}").AppendLineBreak();
            string shareText   = $"*{title}*{Environment.NewLine}{Environment.NewLine}*{amount} {currencyCode}*{Environment.NewLine}Bancos: \t\tB$ *{bancosValue.GetValueOrDefault().ToString("N2", GlobalConfiguration.GetLocalCultureInfo())}*{Environment.NewLine}Paralelo: \t\tB$ *{paraleloValue.GetValueOrDefault().ToString("N2", GlobalConfiguration.GetLocalCultureInfo())}*{Environment.NewLine}Hora: \t\t{lastUpdated} (UTC {utcOffset})";

            EmbedBuilder embed = new EmbedBuilder().WithColor(GlobalConfiguration.Colors.Venezuela)
                                 .WithTitle(title)
                                 .WithDescription(description.ToString().AppendLineBreak())
                                 .WithThumbnailUrl(thumbnailUrl)
                                 .WithFooter(new EmbedFooterBuilder()
            {
                Text    = $"Ultima actualización: {lastUpdated} (UTC {utcOffset})",
                IconUrl = footerImageUrl
            })
                                 .AddField("Monto", amountField)
                                 .AddInlineField($"{bankEmoji} Bancos", $"{currencyEmoji} {blankSpace} {bancosValueText} {blankSpace}")
                                 .AddInlineField($"{moneyEmoji} Paralelo", $"{currencyEmoji} {blankSpace} {paraleloValueText} {blankSpace}".AppendLineBreak());

            await embed.AddFieldWhatsAppShare(whatsappEmoji, shareText, Api.Cuttly.ShortenUrl);

            return(embed.AddPlayStoreLink(Configuration));
        }
 public async Task HandleCalculatorModalInput(string cryptoCode, CryptoCalculatorModal calculatorModal)
 {
     await DeferAsync().ContinueWith(async(task) =>
     {
         bool isNumeric = decimal.TryParse(calculatorModal.Value.Replace(",", "."), NumberStyles.Any, DolarBotApiService.GetApiCulture(), out decimal quantity);
         if (!isNumeric || quantity <= 0)
         {
             quantity = 1;
         }
         List <CryptoCodeResponse> cryptoCurrenciesList = await CryptoService.GetCryptoCodeList();
         await SendCryptoResponseAsync(cryptoCurrenciesList, cryptoCode, quantity);
     });
 }
        public async Task HandleCalculatorModalInput(string currencyCode, VzlaCalculatorModal calculatorModal)
        {
            await DeferAsync().ContinueWith(async(task) =>
            {
                try
                {
                    bool isNumeric = decimal.TryParse(calculatorModal.Value.Replace(",", "."), NumberStyles.Any, DolarBotApiService.GetApiCulture(), out decimal amount);
                    if (!isNumeric || amount <= 0)
                    {
                        amount = 1;
                    }

                    Currencies currency = Enum.Parse <Currencies>(currencyCode);
                    VzlaResponse result = currency switch
                    {
                        Currencies.Dolar => await VzlaService.GetDollarRates(),
                        Currencies.Euro => await VzlaService.GetEuroRates(),
                        _ => throw new NotImplementedException(),
                    };
                    if (result != null)
                    {
                        EmbedBuilder embed = await VzlaService.CreateVzlaEmbedAsync(result, amount);
                        await SendDeferredEmbedAsync(embed.Build());
                    }
                    else
                    {
                        await SendDeferredApiErrorResponseAsync();
                    }
                }
                catch (Exception ex)
                {
                    await SendDeferredErrorResponseAsync(ex);
                }
            });
        }
Example #5
0
        /// <summary>
        /// Creates an <see cref="EmbedBuilder"/> object for a single dollar response specifying a custom description, title and thumbnail URL.
        /// </summary>
        /// <param name="historicalRatesResponse">The historical rates response to show.</param>
        /// <param name="historicalRatesParam">The parameter type for historical rates.</param>
        /// <returns>An <see cref="EmbedBuilder"/> object ready to be built.</returns>
        public EmbedBuilder CreateHistoricalRatesEmbed(HistoricalRatesResponse historicalRatesResponse, HistoricalRatesParamEndpoints historicalRatesParam)
        {
            var          emojis           = Configuration.GetSection("customEmojis");
            Emoji        upEmoji          = new(emojis["arrowUpRed"]);
            Emoji        downEmoji        = new(emojis["arrowDownGreen"]);
            Emoji        neutralEmoji     = new(emojis["neutral"]);
            TimeZoneInfo localTimeZone    = GlobalConfiguration.GetLocalTimeZoneInfo();
            int          utcOffset        = localTimeZone.GetUtcOffset(DateTime.UtcNow).Hours;
            string       blankSpace       = GlobalConfiguration.Constants.BLANK_SPACE;
            string       chartImageUrl    = Configuration.GetSection("images").GetSection("chart")["64"];
            string       footerImageUrl   = Configuration.GetSection("images").GetSection("clock")["32"];
            string       embedTitle       = GetTitle(historicalRatesParam);
            string       embedDescription = GetDescription(historicalRatesParam);
            Color        embedColor       = GetColor(historicalRatesParam);
            string       lastUpdated      = historicalRatesResponse.Fecha.ToString(historicalRatesResponse.Fecha.Date == TimeZoneInfo.ConvertTime(DateTime.UtcNow, localTimeZone).Date ? "HH:mm" : "dd/MM/yyyy - HH:mm");

            StringBuilder sbField      = new();
            var           monthlyRates = historicalRatesResponse.Meses.OrderBy(x => Convert.ToInt32(x.Anio)).ThenBy(x => Convert.ToInt32(x.Mes));

            for (int i = 0; i < monthlyRates.Count(); i++)
            {
                HistoricalMonthlyRate month = monthlyRates.ElementAt(i);
                string monthName            = GlobalConfiguration.GetLocalCultureInfo().DateTimeFormat.GetMonthName(Convert.ToInt32(month.Mes)).Capitalize();
                bool   monthRateIsNumeric   = decimal.TryParse(month.Valor, NumberStyles.Any, DolarBotApiService.GetApiCulture(), out decimal monthRate);
                string monthRateText        = monthRateIsNumeric ? monthRate.ToString("N2", GlobalConfiguration.GetLocalCultureInfo()) : "?";

                Emoji fieldEmoji = neutralEmoji;
                if (i > 0)
                {
                    HistoricalMonthlyRate previousMonth = monthlyRates.ElementAt(i - 1);
                    bool previousMonthRateIsNumeric     = decimal.TryParse(previousMonth.Valor, NumberStyles.Any, DolarBotApiService.GetApiCulture(), out decimal previousMonthRate);
                    if (monthRateIsNumeric && previousMonthRateIsNumeric)
                    {
                        if (monthRate >= previousMonthRate)
                        {
                            fieldEmoji = monthRate > previousMonthRate ? upEmoji : neutralEmoji;
                        }
                        else
                        {
                            fieldEmoji = downEmoji;
                        }
                    }
                }

                string fieldText = $"{fieldEmoji} {blankSpace} {Format.Bold($"$ {monthRate}")} - {Format.Code($"{monthName} {month.Anio}")} {blankSpace}";
                sbField = sbField.AppendLine(fieldText);
            }

            HistoricalMonthlyRate firstMonth = monthlyRates.First();
            HistoricalMonthlyRate lastMonth  = monthlyRates.Last();
            string firstMonthName            = GlobalConfiguration.GetLocalCultureInfo().DateTimeFormat.GetMonthName(Convert.ToInt32(firstMonth.Mes)).Capitalize();
            string lastMonthName             = GlobalConfiguration.GetLocalCultureInfo().DateTimeFormat.GetMonthName(Convert.ToInt32(lastMonth.Mes)).Capitalize();
            string fieldTitle = $"{firstMonthName} {firstMonth.Anio} - {lastMonthName} {lastMonth.Anio}";

            EmbedBuilder embed = new EmbedBuilder().WithColor(embedColor)
                                 .WithTitle(embedTitle)
                                 .WithDescription(embedDescription.AppendLineBreak())
                                 .WithThumbnailUrl(chartImageUrl)
                                 .WithFooter($"Ultima actualización: {lastUpdated} (UTC {utcOffset})", footerImageUrl)
                                 .AddField(fieldTitle, sbField.AppendLineBreak().ToString());

            return(embed.AddPlayStoreLink(Configuration));
        }
        /// <summary>
        /// Creates an <see cref="EmbedBuilder"/> object for a <see cref="MetalResponse"/>.
        /// </summary>
        /// <param name="metalResponse">The metal response.</param>
        /// <returns>An <see cref="EmbedBuilder"/> object ready to be built.</returns>
        public async Task <EmbedBuilder> CreateMetalEmbedAsync(MetalResponse metalResponse)
        {
            var   emojis        = Configuration.GetSection("customEmojis");
            Emoji metalEmoji    = GetEmoji(metalResponse.Type);
            Emoji whatsappEmoji = new(emojis["whatsapp"]);

            TimeZoneInfo localTimeZone = GlobalConfiguration.GetLocalTimeZoneInfo();
            int          utcOffset     = localTimeZone.GetUtcOffset(DateTime.UtcNow).Hours;

            string  thumbnailUrl   = GetThumbnailUrl(metalResponse.Type);
            string  footerImageUrl = Configuration.GetSection("images").GetSection("clock")["32"];
            decimal value          = decimal.TryParse(metalResponse?.Valor, NumberStyles.Any, DolarBotApiService.GetApiCulture(), out decimal valor) ? valor : 0;
            string  valueText      = value > 0 ? Format.Bold($"US$ {valor.ToString("N2", GlobalConfiguration.GetLocalCultureInfo())} / {metalResponse.Unidad.ToLower()}") : "No informado";
            string  title          = $"Cotización {(metalResponse.Type != MetalEndpoints.Silver ? "del" : "de la")} {GetName(metalResponse.Type).Capitalize()}";
            string  description    = $"Valor internacional {(metalResponse.Type != MetalEndpoints.Silver ? "del" : "de la")} {Format.Bold(GetName(metalResponse.Type).ToLower())} expresado en {Format.Bold("dólares")} por {Format.Bold(metalResponse.Unidad.ToLower())}.";
            string  lastUpdated    = metalResponse.Fecha.ToString(metalResponse.Fecha.Date == TimeZoneInfo.ConvertTime(DateTime.UtcNow, localTimeZone).Date ? "HH:mm" : "dd/MM/yyyy - HH:mm");
            string  shareText      = $"*{title}*{Environment.NewLine}{Environment.NewLine}US$ *{value.ToString("N2", GlobalConfiguration.GetLocalCultureInfo())} / {metalResponse.Unidad.ToLower()}*{Environment.NewLine}Hora: {lastUpdated} (UTC {utcOffset})";

            EmbedBuilder embed = new EmbedBuilder().WithColor(GetColor(metalResponse.Type))
                                 .WithTitle(title)
                                 .WithDescription(description.AppendLineBreak())
                                 .WithThumbnailUrl(thumbnailUrl)
                                 .WithFooter(new EmbedFooterBuilder()
            {
                Text    = $"Ultima actualización: {lastUpdated} (UTC {utcOffset})",
                IconUrl = footerImageUrl
            })
                                 .AddField($"Valor", $"{metalEmoji} {GlobalConfiguration.Constants.BLANK_SPACE} {valueText}".AppendLineBreak());

            await embed.AddFieldWhatsAppShare(whatsappEmoji, shareText, Api.Cuttly.ShortenUrl);

            return(embed.AddPlayStoreLink(Configuration));
        }
Example #7
0
        /// <summary>
        /// Creates an <see cref="EmbedBuilder"/> object for a <see cref="CountryRiskResponse"/>.
        /// </summary>
        /// <param name="riesgoPaisResponse">The Riesgo Pais response.</param>
        /// <returns>An <see cref="EmbedBuilder"/> object ready to be built.</returns>
        public async Task <EmbedBuilder> CreateCountryRiskEmbedAsync(CountryRiskResponse riesgoPaisResponse)
        {
            var    emojis         = Configuration.GetSection("customEmojis");
            Emoji  chartEmoji     = new("\uD83D\uDCC8");
            Emoji  whatsappEmoji  = new(emojis["whatsapp"]);
            string riskImageUrl   = Configuration.GetSection("images").GetSection("risk")["64"];
            string footerImageUrl = Configuration.GetSection("images").GetSection("clock")["32"];

            TimeZoneInfo localTimeZone = GlobalConfiguration.GetLocalTimeZoneInfo();
            int          utcOffset     = localTimeZone.GetUtcOffset(DateTime.UtcNow).Hours;
            string       lastUpdated   = riesgoPaisResponse.Fecha.ToString(riesgoPaisResponse.Fecha.Date == TimeZoneInfo.ConvertTime(DateTime.UtcNow, localTimeZone).Date ? "HH:mm" : "dd/MM/yyyy - HH:mm");
            bool         isNumber      = double.TryParse(riesgoPaisResponse?.Valor, NumberStyles.Any, DolarBotApiService.GetApiCulture(), out double valor);
            string       value;

            if (isNumber)
            {
                int convertedValue = (int)Math.Round(valor, MidpointRounding.AwayFromZero);
                value = convertedValue.ToString("n0", GlobalConfiguration.GetLocalCultureInfo());
            }
            else
            {
                value = "No informado";
            }

            string       shareText = $"*Riesgo país*{Environment.NewLine}{Environment.NewLine}{(isNumber ? $"*{value}* puntos" : value)}{Environment.NewLine}Hora: {lastUpdated}";
            EmbedBuilder embed     = new EmbedBuilder().WithColor(GlobalConfiguration.Colors.Main)
                                     .WithTitle("Riesgo País")
                                     .WithDescription($"Valor del {Format.Bold("riesgo país")} de la República Argentina.".AppendLineBreak())
                                     .WithThumbnailUrl(riskImageUrl)
                                     .WithFooter(new EmbedFooterBuilder()
            {
                Text    = $"Ultima actualización: {lastUpdated} (UTC {utcOffset})",
                IconUrl = footerImageUrl
            })
                                     .AddInlineField($"Valor", $"{Format.Bold($"{chartEmoji} {GlobalConfiguration.Constants.BLANK_SPACE} {value}")} puntos".AppendLineBreak());

            await embed.AddFieldWhatsAppShare(whatsappEmoji, shareText, Api.Cuttly.ShortenUrl);

            return(embed.AddPlayStoreLink(Configuration));
        }
Example #8
0
        /// <summary>
        /// Creates an <see cref="EmbedBuilder"/> object for a <see cref="BcraResponse"/>.
        /// </summary>
        /// <param name="bcraResponse">The BCRA response.</param>
        /// <returns>An <see cref="EmbedBuilder"/> object ready to be built.</returns>
        public async Task <EmbedBuilder> CreateCirculatingMoneyEmbedAsync(BcraResponse bcraResponse)
        {
            var    emojis = Configuration.GetSection("customEmojis");
            Emoji  circulatingMoneyEmoji = new(":money_with_wings:");
            Emoji  whatsappEmoji         = new(emojis["whatsapp"]);
            string reservesImageUrl      = Configuration.GetSection("images").GetSection("money")["64"];
            string footerImageUrl        = Configuration.GetSection("images").GetSection("clock")["32"];

            TimeZoneInfo localTimeZone = GlobalConfiguration.GetLocalTimeZoneInfo();
            int          utcOffset     = localTimeZone.GetUtcOffset(DateTime.UtcNow).Hours;
            string       lastUpdated   = bcraResponse.Fecha.ToString(bcraResponse.Fecha.Date == TimeZoneInfo.ConvertTime(DateTime.UtcNow, localTimeZone).Date ? "HH:mm" : "dd/MM/yyyy - HH:mm");
            bool         isNumber      = double.TryParse(bcraResponse?.Valor, NumberStyles.Any, DolarBotApiService.GetApiCulture(), out double valor);
            string       text;
            string       value;

            if (isNumber)
            {
                long convertedValue = (long)Math.Round(valor, MidpointRounding.AwayFromZero);
                value = convertedValue.ToString("n2", GlobalConfiguration.GetLocalCultureInfo());
                text  = $"{Format.Bold($"{circulatingMoneyEmoji} {GlobalConfiguration.Constants.BLANK_SPACE} $ {value}")}";
            }
            else
            {
                value = "No informado";
                text  = $"{Format.Bold($"{circulatingMoneyEmoji} {GlobalConfiguration.Constants.BLANK_SPACE} {value}")}";
            }

            string       shareText = $"*Pesos en circulación*{Environment.NewLine}{Environment.NewLine}{(isNumber ? $"$ *{value}*" : value)}{Environment.NewLine}Hora: {lastUpdated} (UTC {utcOffset})";
            EmbedBuilder embed     = new EmbedBuilder().WithColor(GlobalConfiguration.Colors.Main)
                                     .WithTitle("Pesos en circulación")
                                     .WithDescription($"Cantidad total aproximada de {Format.Bold("pesos argentinos")} en circulación.".AppendLineBreak())
                                     .WithThumbnailUrl(reservesImageUrl)
                                     .WithFooter(new EmbedFooterBuilder()
            {
                Text    = $"Ultima actualización: {lastUpdated} (UTC {utcOffset})",
                IconUrl = footerImageUrl
            })
                                     .AddInlineField($"Valor", text);

            await embed.AddFieldWhatsAppShare(whatsappEmoji, shareText, Api.Cuttly.ShortenUrl);

            return(embed.AddPlayStoreLink(Configuration));
        }
Example #9
0
        /// <summary>
        /// Creates an <see cref="EmbedBuilder"/> object for a <see cref="WorldCurrencyResponse"/>.
        /// </summary>
        /// <param name="worldCurrencyResponse">The world currency response.</param>
        /// <param name="currencyName">The currency name.</param>
        /// <param name="amount">The amount to rate against.</param>
        /// <returns>An <see cref="EmbedBuilder"/> object ready to be built.</returns>
        public async Task <EmbedBuilder> CreateWorldCurrencyEmbedAsync(WorldCurrencyResponse worldCurrencyResponse, string currencyName, decimal amount = 1)
        {
            var    emojis           = Configuration.GetSection("customEmojis");
            Emoji  currencyEmoji    = Emoji.Parse(":flag_ar:");
            Emoji  whatsappEmoji    = new(emojis["whatsapp"]);
            Emoji  amountEmoji      = Emoji.Parse(":moneybag:");
            string currencyImageUrl = Configuration.GetSection("images").GetSection("coins")["64"];
            string footerImageUrl   = Configuration.GetSection("images").GetSection("clock")["32"];

            string       blankSpace    = GlobalConfiguration.Constants.BLANK_SPACE;
            TimeZoneInfo localTimeZone = GlobalConfiguration.GetLocalTimeZoneInfo();
            int          utcOffset     = localTimeZone.GetUtcOffset(DateTime.UtcNow).Hours;
            string       lastUpdated   = worldCurrencyResponse.Fecha.ToString(worldCurrencyResponse.Fecha.Date == TimeZoneInfo.ConvertTime(DateTime.UtcNow, localTimeZone).Date ? "HH:mm" : "dd/MM/yyyy - HH:mm");
            string       amountField   = Format.Bold($"{amountEmoji} {blankSpace} {amount} {worldCurrencyResponse.Code}");

            decimal?valuePrice = decimal.TryParse(worldCurrencyResponse?.Valor, NumberStyles.Any, DolarBotApiService.GetApiCulture(), out decimal v) ? v * amount : null;
            string  value      = valuePrice.HasValue ? valuePrice.Value.ToString("N2", GlobalConfiguration.GetLocalCultureInfo()) : "?";

            string       shareText = $"*{currencyName} ({worldCurrencyResponse.Code})*{Environment.NewLine}{Environment.NewLine}*{amount} {worldCurrencyResponse.Code}*{Environment.NewLine}Valor: \t$ *{value}*{Environment.NewLine}Hora: \t{lastUpdated} (UTC {utcOffset})";
            EmbedBuilder embed     = new EmbedBuilder().WithColor(GlobalConfiguration.Colors.Currency)
                                     .WithTitle($"{currencyName} ({worldCurrencyResponse.Code})")
                                     .WithDescription($"Cotización de {Format.Bold($"{currencyName} ({worldCurrencyResponse.Code})")} expresada en {Format.Bold("pesos argentinos")}.".AppendLineBreak())
                                     .WithThumbnailUrl(currencyImageUrl)
                                     .WithFooter(new EmbedFooterBuilder()
            {
                Text    = $"Ultima actualización: {lastUpdated} (UTC {utcOffset})",
                IconUrl = footerImageUrl
            })
                                     .AddInlineField("Monto", amountField)
                                     .AddInlineField($"Valor", $"{Format.Bold($"{currencyEmoji} ${blankSpace} {value.AppendLineBreak()}")}");

            await embed.AddFieldWhatsAppShare(whatsappEmoji, shareText, Api.Cuttly.ShortenUrl);

            return(embed.AddPlayStoreLink(Configuration));
        }
Example #10
0
        /// <summary>
        /// Creates a collection of <see cref="EmbedBuilder"/> objects representing historical values.
        /// </summary>
        /// <param name="historicalCurrencyValues">A collection of <see cref="WorldCurrencyResponse"/> objects.</param>
        /// <param name="currencyName">The currency name.</param>
        /// <returns>A list of embeds ready to be built.</returns>
        public List <EmbedBuilder> CreateHistoricalValuesEmbedsAsync(List <WorldCurrencyResponse> historicalCurrencyValues, string currencyName, DateTime?startDate, DateTime?endDate)
        {
            var    emojis        = Configuration.GetSection("customEmojis");
            Emoji  upEmoji       = new(emojis["arrowUpRed"]);
            Emoji  downEmoji     = new(emojis["arrowDownGreen"]);
            Emoji  neutralEmoji  = new(emojis["neutral"]);
            Emoji  calendarEmoji = new(":calendar_spiral:");
            string chartImageUrl = Configuration.GetSection("images").GetSection("chart")["64"];

            int pageCount  = 0;
            int totalPages = (int)Math.Ceiling(Convert.ToDecimal(historicalCurrencyValues.Count) / HISTORICAL_DATES_PER_PAGE);
            List <IEnumerable <WorldCurrencyResponse> > historicalCurrencyValuesPages = historicalCurrencyValues.ChunkBy(HISTORICAL_DATES_PER_PAGE);

            if (!startDate.HasValue)
            {
                startDate = historicalCurrencyValues.First().Fecha.Date;
            }
            if (!endDate.HasValue || endDate.Value.Date > DateTime.Now.Date)
            {
                endDate = DateTime.Now.Date;
            }
            bool isSingleDate = startDate.Value.Date == endDate.Value.Date;

            List <EmbedBuilder> embeds = new();

            for (int i = 0; i < historicalCurrencyValuesPages.Count; i++)
            {
                IEnumerable <WorldCurrencyResponse> page = historicalCurrencyValuesPages.ElementAt(i);

                StringBuilder sbField = new();
                for (int j = 0; j < page.Count(); j++)
                {
                    WorldCurrencyResponse currencyValue = page.ElementAt(j);
                    bool rateIsNumeric = decimal.TryParse(currencyValue.Valor, NumberStyles.Any, DolarBotApiService.GetApiCulture(), out decimal currencyRate);

                    Emoji fieldEmoji = isSingleDate ? calendarEmoji : neutralEmoji;
                    if (i > 0 || j > 0)
                    {
                        WorldCurrencyResponse previousCurrencyValue = j > 0 ? page.ElementAt(j - 1) : historicalCurrencyValuesPages.ElementAt(i - 1).Last();
                        bool previousValueIsNumeric = decimal.TryParse(previousCurrencyValue.Valor, NumberStyles.Any, DolarBotApiService.GetApiCulture(), out decimal previousRate);
                        if (rateIsNumeric && previousValueIsNumeric)
                        {
                            if (currencyRate >= previousRate)
                            {
                                fieldEmoji = currencyRate > previousRate ? upEmoji : neutralEmoji;
                            }
                            else
                            {
                                fieldEmoji = downEmoji;
                            }
                        }
                    }
                    string fieldText = $"{fieldEmoji} {Format.Code(currencyValue.Fecha.ToString("dd/MM/yyyy"))}: {Format.Bold($"$ {currencyRate}")}";
                    sbField = sbField.AppendLine(fieldText);
                }

                string       worldCurrencyCode = historicalCurrencyValues.First().Code;
                string       embedTitle        = isSingleDate ? "Cotización por fecha" : "Cotizaciones por Fecha";
                string       embedDescription  = $"{(isSingleDate ? "Cotización oficial" : "Cotizaciones oficiales")} de {Format.Bold($"{currencyName} ({worldCurrencyCode})")} {(isSingleDate ? $"para el día {Format.Code(startDate.Value.Date.ToString("dd/MM/yyyy"))}" : $"entre el {Format.Code(startDate.Value.Date.ToString("dd/MM/yyyy"))} y el {Format.Code(endDate.Value.Date.ToString("dd/MM/yyyy"))}")}, expresada en {Format.Bold("pesos argentinos")}.".AppendLineBreak();
                EmbedBuilder embed             = new EmbedBuilder().WithColor(GlobalConfiguration.Colors.Currency)
                                                 .WithTitle($"{currencyName} ({worldCurrencyCode})")
                                                 .WithDescription(embedDescription)
                                                 .WithThumbnailUrl(chartImageUrl)
                                                 .WithFooter($"Página {++pageCount} de {totalPages}")
                                                 .AddField(embedTitle, sbField.AppendLineBreak().ToString());
                embeds.Add(embed);
            }

            return(embeds);
        }
Example #11
0
 public async Task HandleCalculatorModalInput(string currencyCode, FiatCurrencyCalculatorModal calculatorModal)
 {
     await DeferAsync().ContinueWith(async(task) =>
     {
         try
         {
             bool isNumeric = decimal.TryParse(calculatorModal.Value.Replace(",", "."), NumberStyles.Any, DolarBotApiService.GetApiCulture(), out decimal amount);
             if (!isNumeric || amount <= 0)
             {
                 amount = 1;
             }
             List <WorldCurrencyCodeResponse> currenciesList = await FiatCurrencyService.GetWorldCurrenciesList();
             WorldCurrencyCodeResponse worldCurrencyCode     = currenciesList.FirstOrDefault(x => x.Code.Equals(currencyCode, StringComparison.OrdinalIgnoreCase));
             if (worldCurrencyCode != null)
             {
                 WorldCurrencyResponse currencyResponse = await FiatCurrencyService.GetCurrencyValue(currencyCode);
                 EmbedBuilder embed = await FiatCurrencyService.CreateWorldCurrencyEmbedAsync(currencyResponse, worldCurrencyCode.Name, amount);
                 await SendDeferredEmbedAsync(embed.Build());
             }
         }
         catch (Exception ex)
         {
             await SendDeferredErrorResponseAsync(ex);
         }
     });
 }