Ejemplo 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));
        }
        /// <summary>
        /// Queries the API endpoint asynchronously and returns a <see cref="MetalResponse"/> object.
        /// </summary>
        /// <returns>A task that contains a normalized <see cref="MetalResponse"/> object.</returns>
        public async Task <MetalResponse> GetMetalRate(MetalEndpoints metal)
        {
            MetalResponse cachedResponse = Cache.GetObject <MetalResponse>(metal);

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

                if (response.IsSuccessful)
                {
                    MetalResponse metalResponse = response.Data;
                    metalResponse.Type = metal;
                    Cache.SaveObject(metal, metalResponse);

                    return(metalResponse);
                }
                else
                {
                    OnError(response);
                    return(null);
                }
            }
        }
Ejemplo n.º 3
0
        public async Task GetSilverPriceAsync()
        {
            try
            {
                using (Context.Channel.EnterTypingState())
                {
                    MetalResponse result = await MetalService.GetSilverPrice();

                    if (result != null)
                    {
                        EmbedBuilder embed = await MetalService.CreateMetalEmbedAsync(result);

                        embed.AddCommandDeprecationNotice(Configuration);
                        await ReplyAsync(embed : embed.Build());
                    }
                    else
                    {
                        await ReplyAsync(REQUEST_ERROR_MESSAGE);
                    }
                }
            }
            catch (Exception ex)
            {
                await SendErrorReply(ex);
            }
        }
Ejemplo n.º 4
0
 public async Task GetCopperPriceAsync()
 {
     await DeferAsync().ContinueWith(async(task) =>
     {
         try
         {
             MetalResponse result = await MetalService.GetCopperPrice();
             if (result != null)
             {
                 EmbedBuilder embed = await MetalService.CreateMetalEmbedAsync(result);
                 await SendDeferredEmbedAsync(embed.Build());
             }
             else
             {
                 await SendDeferredApiErrorResponseAsync();
             }
         }
         catch (Exception ex)
         {
             await SendDeferredErrorResponseAsync(ex);
         }
     });
 }