Exemplo n.º 1
0
        /// <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));
        }
Exemplo n.º 2
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));
        }
Exemplo n.º 3
0
        /// <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));
        }
Exemplo n.º 4
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));
        }
Exemplo n.º 5
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));
        }
Exemplo n.º 6
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));
        }