/// <summary>
        /// Queries the API endpoint asynchronously and returns a <see cref="HistoricalRatesResponse"/> object.
        /// </summary>
        /// <returns>A task that contains a normalized <see cref="HistoricalRatesResponse"/> object.</returns>
        public async Task <HistoricalRatesResponse> GetHistoricalRates(HistoricalRatesParamEndpoints historicalRatesParam)
        {
            HistoricalRatesResponse cachedResponse = Cache.GetObject <HistoricalRatesResponse>(historicalRatesParam);

            if (cachedResponse != null)
            {
                return(cachedResponse);
            }
            else
            {
                string      endpoint = historicalRatesParam.GetDescription();
                RestRequest request  = new(endpoint);
                RestResponse <HistoricalRatesResponse> response = await Client.ExecuteGetAsync <HistoricalRatesResponse>(request);

                if (response.IsSuccessful)
                {
                    Cache.SaveObject(historicalRatesParam, response.Data);
                    return(response.Data);
                }
                else
                {
                    OnError(response);
                    return(null);
                }
            }
        }
Exemple #2
0
 public async Task GetEvolutionAsync(
     [Summary("cotización", "Indica el tipo de cotización a obtener")]
     HistoricalRatesChoices historicalRatesChoice
     )
 {
     await DeferAsync().ContinueWith(async(task) =>
     {
         try
         {
             HistoricalRatesParamEndpoints historicalRatesParam = Enum.Parse <HistoricalRatesParamEndpoints>(historicalRatesChoice.ToString());
             HistoricalRatesResponse result = await HistoricalRatesService.GetHistoricalRates(historicalRatesParam);
             if (result != null && result.Meses != null && result.Meses.Count > 0)
             {
                 EmbedBuilder embed = HistoricalRatesService.CreateHistoricalRatesEmbed(result, historicalRatesParam);
                 await SendDeferredEmbedAsync(embed.Build());
             }
             else
             {
                 await SendDeferredApiErrorResponseAsync();
             }
         }
         catch (Exception ex)
         {
             await SendDeferredErrorResponseAsync(ex);
         }
     });
 }
Exemple #3
0
        public async Task GetEvolucionAsync([Summary("Indica el tipo de cotización a obtener")] string cotizacion = null)
        {
            try
            {
                using (Context.Channel.EnterTypingState())
                {
                    if (cotizacion == null)
                    {
                        await ReplyAsync(GetEvolucionInvalidParamsMessage());
                    }
                    else
                    {
                        string userInput = Format.Sanitize(cotizacion).RemoveFormat(true);
                        if (!userInput.IsNumeric() && Enum.TryParse(userInput, true, out HistoricalRatesParamEndpoints historicalRateParam))
                        {
                            HistoricalRatesResponse result = await HistoricalRatesService.GetHistoricalRates(historicalRateParam);

                            if (result != null && result.Meses != null && result.Meses.Count > 0)
                            {
                                EmbedBuilder embed = HistoricalRatesService.CreateHistoricalRatesEmbed(result, historicalRateParam);
                                embed.AddCommandDeprecationNotice(Configuration);
                                await ReplyAsync(embed : embed.Build());
                            }
                            else
                            {
                                await ReplyAsync(REQUEST_ERROR_MESSAGE);
                            }
                        }
                        else
                        {
                            await ReplyAsync(GetEvolucionInvalidParamsMessage());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                await SendErrorReply(ex);
            }
        }
Exemple #4
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));
        }