/// <summary> /// Returns the title depending on the response type. /// </summary> /// <param name="dollarResponse">The dollar response.</param> /// <returns>The corresponding title.</returns> private string GetTitle(DolarResponse dollarResponse) { return(dollarResponse.Type switch { DollarType.Oficial => DOLAR_OFICIAL_TITLE, DollarType.Ahorro => DOLAR_AHORRO_TITLE, DollarType.Blue => DOLAR_BLUE_TITLE, DollarType.Bolsa => DOLAR_BOLSA_TITLE, DollarType.Promedio => DOLAR_PROMEDIO_TITLE, DollarType.ContadoConLiqui => DOLAR_CCL_TITLE, DollarType.Nacion => Banks.Nacion.GetDescription(), DollarType.BBVA => Banks.BBVA.GetDescription(), DollarType.Piano => Banks.Piano.GetDescription(), DollarType.Hipotecario => Banks.Hipotecario.GetDescription(), DollarType.Galicia => Banks.Galicia.GetDescription(), DollarType.Santander => Banks.Santander.GetDescription(), DollarType.Ciudad => Banks.Ciudad.GetDescription(), DollarType.Supervielle => Banks.Supervielle.GetDescription(), DollarType.Patagonia => Banks.Patagonia.GetDescription(), DollarType.Comafi => Banks.Comafi.GetDescription(), DollarType.BIND => Banks.BIND.GetDescription(), DollarType.Bancor => Banks.Bancor.GetDescription(), DollarType.Chaco => Banks.Chaco.GetDescription(), DollarType.Pampa => Banks.Pampa.GetDescription(), _ => throw new ArgumentException($"Unable to get title from '{dollarResponse.Type}'.") });
/// <summary> /// Creates an <see cref="EmbedBuilder"/> object for multiple dollar responses specifying a custom description and thumbnail URL. /// </summary> /// <param name="dollarResponses">The dollar responses to show.</param> /// <param name="description">The embed's description.</param> /// <param name="thumbnailUrl">The URL of the embed's thumbnail image.</param> /// <returns>An <see cref="EmbedBuilder"/> object ready to be built.</returns> private EmbedBuilder CreateDollarEmbed(DolarResponse[] dollarResponses, string description, string thumbnailUrl) { Emoji dollarEmoji = new Emoji("\uD83D\uDCB5"); Emoji clockEmoji = new Emoji("\u23F0"); TimeZoneInfo localTimeZone = GlobalConfiguration.GetLocalTimeZoneInfo(); EmbedBuilder embed = new EmbedBuilder().WithColor(mainEmbedColor) .WithTitle("Cotizaciones del Dólar") .WithDescription(description.AppendLineBreak()) .WithThumbnailUrl(thumbnailUrl) .WithFooter($"{clockEmoji} = Última actualización ({localTimeZone.StandardName})"); for (int i = 0; i < dollarResponses.Length; i++) { DolarResponse response = dollarResponses[i]; string blankSpace = GlobalConfiguration.Constants.BLANK_SPACE; string title = GetTitle(response); string lastUpdated = TimeZoneInfo.ConvertTimeFromUtc(response.Fecha, localTimeZone).ToString("dd/MM - HH:mm"); string buyPrice = decimal.TryParse(response?.Compra, NumberStyles.Any, Api.DolarArgentina.GetApiCulture(), out decimal compra) ? $"${compra:F}" : "?"; string sellPrice = decimal.TryParse(response?.Venta, NumberStyles.Any, Api.DolarArgentina.GetApiCulture(), out decimal venta) ? $"${venta:F}" : "?"; if (buyPrice != "?" || sellPrice != "?") { StringBuilder sbField = new StringBuilder() .AppendLine($"{dollarEmoji} {blankSpace} Compra: {Format.Bold(buyPrice)} {blankSpace}") .AppendLine($"{dollarEmoji} {blankSpace} Venta: {Format.Bold(sellPrice)} {blankSpace}") .AppendLine($"{clockEmoji} {blankSpace} {lastUpdated} {blankSpace} "); embed.AddInlineField(title, sbField.ToString().AppendLineBreak()); } } return(embed); }
public async Task GetDolarContadoConLiquiPriceAsync() { using (Context.Channel.EnterTypingState()) { DolarResponse result = await Api.DolarArgentina.GetDollarPrice(DollarType.ContadoConLiqui).ConfigureAwait(false); if (result != null) { EmbedBuilder embed = CreateDollarEmbed(result, $"Cotización del {Format.Bold("dólar contado con liquidación")}{Environment.NewLine} expresada en {Format.Bold("pesos argentinos")}."); await ReplyAsync(embed : embed.Build()).ConfigureAwait(false); } else { await ReplyAsync(REQUEST_ERROR_MESSAGE).ConfigureAwait(false); } } }
/// <summary> /// Creates an <see cref="EmbedBuilder"/> object for a single dollar response specifying a custom description, title and thumbnail URL. /// </summary> /// <param name="dollarResponse">>The dollar response to show.</param> /// <param name="description">The embed's description.</param> /// <param name="title">Optional. The embed's title.</param> /// <param name="thumbnailUrl">Optional. The embed's thumbnail URL.</param> /// <returns>An <see cref="EmbedBuilder"/> object ready to be built.</returns> private EmbedBuilder CreateDollarEmbed(DolarResponse dollarResponse, string description, string title = null, string thumbnailUrl = null) { Emoji dollarEmoji = new Emoji("\uD83D\uDCB5"); TimeZoneInfo localTimeZone = GlobalConfiguration.GetLocalTimeZoneInfo(); string dollarImageUrl = thumbnailUrl ?? Configuration.GetSection("images").GetSection("dollar")["64"]; string footerImageUrl = Configuration.GetSection("images").GetSection("clock")["32"]; string embedTitle = title ?? GetTitle(dollarResponse); string lastUpdated = TimeZoneInfo.ConvertTimeFromUtc(dollarResponse.Fecha, localTimeZone).ToString(dollarResponse.Fecha.Date == DateTime.UtcNow.Date ? "HH:mm" : "dd/MM/yyyy - HH:mm"); string buyPrice = decimal.TryParse(dollarResponse?.Compra, NumberStyles.Any, Api.DolarArgentina.GetApiCulture(), out decimal compra) ? $"${compra:F}" : null; string sellPrice = decimal.TryParse(dollarResponse?.Venta, NumberStyles.Any, Api.DolarArgentina.GetApiCulture(), out decimal venta) ? $"${venta:F}" : null; EmbedBuilder embed = new EmbedBuilder().WithColor(mainEmbedColor) .WithTitle(embedTitle) .WithDescription(description.AppendLineBreak()) .WithThumbnailUrl(dollarImageUrl) .WithFooter($"Ultima actualización: {lastUpdated} ({localTimeZone.StandardName})", footerImageUrl) .AddInlineField("Compra", Format.Bold($"{dollarEmoji} {GlobalConfiguration.Constants.BLANK_SPACE} {buyPrice}")) .AddInlineField("Venta", Format.Bold($"{dollarEmoji} {GlobalConfiguration.Constants.BLANK_SPACE} {sellPrice}".AppendLineBreak())); return(embed); }
/// <summary> /// Querys an API endpoint asynchronously and returs its result. /// </summary> /// <param name="type">The type of dollar (endpoint) to query.</param> /// <returns>A task that contains a normalized <see cref="DolarResponse"/> object.</returns> public async Task <DolarResponse> GetDollarPrice(DollarType type) { DolarResponse cachedResponse = cache.GetObject <DolarResponse>(type); if (cachedResponse != null) { return(cachedResponse); } else { string endpoint = type.GetDescription(); RestRequest request = new RestRequest(endpoint, DataFormat.Json); IRestResponse <DolarResponse> response = await client.ExecuteGetAsync <DolarResponse>(request).ConfigureAwait(false); if (response.IsSuccessful) { DolarResponse dolarResponse = response.Data; dolarResponse.Type = type; if (type == DollarType.Ahorro) { CultureInfo apiCulture = GetApiCulture(); decimal taxPercent = (decimal.Parse(configuration["dollarTaxPercent"]) / 100) + 1; if (decimal.TryParse(dolarResponse.Venta, NumberStyles.Any, apiCulture, out decimal venta)) { dolarResponse.Venta = Convert.ToDecimal(venta * taxPercent, apiCulture).ToString("F", apiCulture); } } cache.SaveObject(type, dolarResponse); return(response.Data); } else { OnError(response); return(null); } } }
public async Task GetDolarPriceAsync( [Summary("Indica la cotización del banco a mostrar. Los valores posibles son aquellos devueltos por el comando `$bancos`.")] string banco = null) { using (Context.Channel.EnterTypingState()) { if (banco != null) { if (Enum.TryParse(banco, true, out Banks bank)) { if (bank == Banks.Bancos) { //Show all private banks prices List <Banks> banks = Enum.GetValues(typeof(Banks)).Cast <Banks>().Where(b => b != Banks.Bancos).ToList(); Task <DolarResponse>[] tasks = new Task <DolarResponse> [banks.Count]; for (int i = 0; i < banks.Count; i++) { DollarType dollarType = GetBankInformation(banks[i], out string _); tasks[i] = Api.DolarArgentina.GetDollarPrice(dollarType); } DolarResponse[] responses = await Task.WhenAll(tasks).ConfigureAwait(false); if (responses.Any(r => r != null)) { string thumbnailUrl = Configuration.GetSection("images").GetSection("bank")["64"]; DolarResponse[] successfulResponses = responses.Where(r => r != null).ToArray(); EmbedBuilder embed = CreateDollarEmbed(successfulResponses, $"Cotizaciones de {Format.Bold("bancos")} expresados en {Format.Bold("pesos argentinos")}.", thumbnailUrl); if (responses.Length != successfulResponses.Length) { await ReplyAsync($"{Format.Bold("Atención")}: No se pudieron obtener algunas cotizaciones. Sólo se mostrarán aquellas que no presentan errores.").ConfigureAwait(false); } await ReplyAsync(embed : embed.Build()).ConfigureAwait(false); } else { await ReplyAsync(REQUEST_ERROR_MESSAGE).ConfigureAwait(false); } } else { //Show individual bank price DollarType dollarType = GetBankInformation(bank, out string thumbnailUrl); DolarResponse result = await Api.DolarArgentina.GetDollarPrice(dollarType).ConfigureAwait(false); if (result != null) { EmbedBuilder embed = CreateDollarEmbed(result, $"Cotización del {Format.Bold("dólar oficial")} del {Format.Bold(bank.GetDescription())} expresada en {Format.Bold("pesos argentinos")}.", null, thumbnailUrl); await ReplyAsync(embed : embed.Build()).ConfigureAwait(false); } else { await ReplyAsync(REQUEST_ERROR_MESSAGE).ConfigureAwait(false); } } } else { //Unknown parameter string commandPrefix = Configuration["commandPrefix"]; string bankCommand = GetType().GetMethod("GetBanks").GetCustomAttributes(true).OfType <CommandAttribute>().First().Text; await ReplyAsync($"Banco '{Format.Bold(banco)}' inexistente. Verifique los bancos disponibles con {Format.Code($"{commandPrefix}{bankCommand}")}.").ConfigureAwait(false); } } else { //Show all dollar types (not banks) DolarResponse[] responses = await Task.WhenAll(Api.DolarArgentina.GetDollarPrice(DollarType.Oficial), Api.DolarArgentina.GetDollarPrice(DollarType.Ahorro), Api.DolarArgentina.GetDollarPrice(DollarType.Blue), Api.DolarArgentina.GetDollarPrice(DollarType.Bolsa), Api.DolarArgentina.GetDollarPrice(DollarType.Promedio), Api.DolarArgentina.GetDollarPrice(DollarType.ContadoConLiqui)).ConfigureAwait(false); if (responses.Any(r => r != null)) { DolarResponse[] successfulResponses = responses.Where(r => r != null).ToArray(); EmbedBuilder embed = CreateDollarEmbed(successfulResponses); if (responses.Length != successfulResponses.Length) { await ReplyAsync($"{Format.Bold("Atención")}: No se pudieron obtener algunas cotizaciones. Sólo se mostrarán aquellas que no presentan errores.").ConfigureAwait(false); } await ReplyAsync(embed : embed.Build()).ConfigureAwait(false); } else { await ReplyAsync(REQUEST_ERROR_MESSAGE).ConfigureAwait(false); } } } }