Esempio n. 1
0
        /// <summary>
        /// Replies with an embed message for a single cryptocurrency value.
        /// </summary>
        /// <param name="searchText">The text to be searched.</param>
        /// <param name="cryptoCurrenciesList">The collection of valid currency codes.</param>
        /// <param name="allowMultipleResults">Indicates wether the search result can return multiple results.</param>
        private async Task SendCryptoCurrencyValueAsync(string searchText, List <CryptoCodeResponse> cryptoCurrenciesList, bool allowMultipleResults = true, IDisposable typingState = null)
        {
            List <CryptoCodeResponse> cryptoCurrencyCodeResponses = CryptoService.FilterByText(cryptoCurrenciesList, searchText);

            if (allowMultipleResults && cryptoCurrencyCodeResponses.Count > 1)
            {
                string title       = $"Multiples resultados para {Format.Code(searchText)}";
                string description = $"La búsqueda retornó multiples resultados.";
                await SendCryptoCurrencyListAsync(cryptoCurrencyCodeResponses, true, title, description, typingState);
            }
            else if (cryptoCurrencyCodeResponses.Count == 1)
            {
                CryptoCodeResponse cryptoCurrencyCodeResponse = cryptoCurrencyCodeResponses.First();
                CryptoResponse     cryptoResponse             = await CryptoService.GetCryptoRateByCode(cryptoCurrencyCodeResponse.Code);
                await SendCryptoReply(cryptoResponse, cryptoCurrencyCodeResponse.Name);
            }
            else
            {
                string commandPrefix   = Configuration["commandPrefix"];
                string currencyCommand = GetType().GetMethod(nameof(GetCryptoRatesAsync)).GetCustomAttributes(true).OfType <CommandAttribute>().First().Text;
                await ReplyAsync($"El código {Format.Code(searchText)} no corresponde con ningún identificador válido. Para ver la lista de identificadores de criptomonedas disponibles, ejecutá {Format.Code($"{commandPrefix}{currencyCommand}")}.");
            }

            if (typingState != null)
            {
                typingState.Dispose();
            }
        }
Esempio n. 2
0
        public async Task <IActionResult> GetTrader([FromQuery] string market)
        {
            var trader         = _clusterClient.GetGrain <ITraderGrain>(market);
            var traderResponse = new CryptoResponse <TraderState>(await trader.GetTraderData());

            return(Ok(new { trader = traderResponse.Content, isSuccessful = true }));
        }
        /// <summary>
        /// Queries the API endpoint asynchronously and returns a <see cref="CryptoResponse"/> object.
        /// </summary>
        /// <returns>A task that contains a normalized <see cref="CryptoResponse"/> object.</returns>
        public async Task <CryptoResponse> GetCryptoCurrencyRate(string cryptoCurrencyCode)
        {
            string         endpoint       = $"{CryptoEndpoints.Crypto.GetDescription()}/{cryptoCurrencyCode.ToUpper()}";
            CryptoResponse cachedResponse = Cache.GetObject <CryptoResponse>(endpoint);

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

                if (response.IsSuccessful)
                {
                    CryptoResponse cryptoResponse = response.Data;
                    Cache.SaveObject(endpoint, cryptoResponse, Cache.GetCryptoExpiration());
                    return(cryptoResponse);
                }
                else
                {
                    OnError(response);
                    return(null);
                }
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Creates an <see cref="EmbedBuilder"/> object for a single crypto response.
        /// </summary>
        /// <param name="cryptoResponse">The crypto response object.</param>
        /// <param name="cryptoCurrencyName">A custom cryptocurrency name.</param>
        /// <param name="quantity">The cryptocurrency quantity.</param>
        /// <returns>An <see cref="EmbedBuilder"/> object ready to be built.</returns>
        public async Task <EmbedBuilder> CreateCryptoEmbedAsync(CryptoResponse cryptoResponse, string cryptoCurrencyName, decimal quantity = 1)
        {
            var   emojis         = Configuration.GetSection("customEmojis");
            Emoji cryptoEmoji    = new(emojis["cryptoCoin"]);
            Emoji argentinaEmoji = new(":flag_ar:");
            Emoji usaEmoji       = new(":flag_us:");
            Emoji dollarEmoji    = Emoji.Parse(":dollar:");
            Emoji moneyBagEmoji  = Emoji.Parse(":moneybag:");
            Emoji whatsappEmoji  = new(emojis["whatsapp"]);

            TimeZoneInfo localTimeZone  = GlobalConfiguration.GetLocalTimeZoneInfo();
            int          utcOffset      = localTimeZone.GetUtcOffset(DateTime.UtcNow).Hours;
            string       footerImageUrl = Configuration.GetSection("images").GetSection("clock")["32"];
            string       cryptoCode     = cryptoResponse.Code.Length > 10 ? $"{cryptoResponse.Code[..7]}..." : cryptoResponse.Code;
        /// <summary>
        /// Replies with an embed message containing the rate for the current cryptocurrency.
        /// </summary>
        /// <param name="response">The crypto response with the data.</param>
        /// <param name="cryptoCurrencyName">A custom cryptocurrency name.</param>
        protected async Task SendCryptoReply(CryptoResponse response, string cryptoCurrencyName = null)
        {
            if (response != null)
            {
                EmbedBuilder embed = await CryptoService.CreateCryptoEmbedAsync(response, cryptoCurrencyName);

                embed.AddCommandDeprecationNotice(Configuration);
                await ReplyAsync(embed : embed.Build());
            }
            else
            {
                await ReplyAsync(REQUEST_ERROR_MESSAGE);
            }
        }
Esempio n. 6
0
 public async Task GetChainlinkRatesAsync()
 {
     try
     {
         using (Context.Channel.EnterTypingState())
         {
             CryptoResponse result = await CryptoService.GetCryptoRateByCode("chainlink");
             await SendCryptoReply(result, "Chainlink");
         }
     }
     catch (Exception ex)
     {
         await SendErrorReply(ex);
     }
 }
        /// <summary>
        /// Replies with an embed message for a single cryptocurrency value.
        /// </summary>
        /// <param name="cryptoCurrenciesList">The collection of valid currency codes.</param>
        /// <param name="code">The code to be searched.</param>
        /// <param name="quantity">Crypto currency quantity.</param>
        private async Task SendCryptoResponseAsync(List <CryptoCodeResponse> cryptoCurrenciesList, string code, decimal quantity = 1)
        {
            CryptoCodeResponse cryptoCurrencyCode = cryptoCurrenciesList.FirstOrDefault(x => x.Code.Equals(code, StringComparison.OrdinalIgnoreCase));

            if (cryptoCurrencyCode != null)
            {
                CryptoResponse cryptoResponse = await CryptoService.GetCryptoRateByCode(cryptoCurrencyCode.Code);

                if (cryptoResponse != null)
                {
                    EmbedBuilder embed = await CryptoService.CreateCryptoEmbedAsync(cryptoResponse, cryptoCurrencyCode.Name, quantity);
                    await SendDeferredEmbedAsync(embed.Build(), new CalculatorComponentBuilder(cryptoCurrencyCode.Code, CalculatorTypes.Crypto, Configuration).Build());
                }
                else
                {
                    await SendDeferredApiErrorResponseAsync();
                }
            }
            else
            {
                await SendDeferredMessageAsync($"No hay resultados para la búsqueda. Asegurate de utilizar los resultados autocompletados.");
            }
        }
Esempio n. 8
0
        public async Task <IActionResult> GetOrders([FromQuery] OrderType orderType)
        {
            CryptoResponse <List <CryptoOrder> > ordersResponse = null;

            switch (orderType)
            {
            case OrderType.OpenOrders:
                ordersResponse = await _cryptoApi.GetOpenOrdersAsync();

                break;

            case OrderType.CompletedOrders:
                ordersResponse = await _cryptoApi.GetCompletedOrdersAsync();

                break;
            }

            if (ordersResponse != null && ordersResponse.IsSuccessful)
            {
                return(Ok(new { orders = ordersResponse.Content, isSuccessful = true }));
            }
            return(BadRequest(new { ordersResponse.ErrorMessage }));
        }
Esempio n. 9
0
        public CryptoResponse CreateCryptoResponse(CMCResponse CMCResponse)
        {
            CryptoResponse response = new CryptoResponse();

            if (CMCResponse != null)
            {
                response.successful = true;
                response.message    = $"Listing for {CMCResponse.Data.BTC.Name}";
                response.data       = new CryptoData()
                {
                    lastUpdated = CMCResponse.Data.BTC.Quote.EUR.LastUpdated,
                    name        = CMCResponse.Data.BTC.Name,
                    price       = CMCResponse.Data.BTC.Quote.EUR.Price,
                    raw         = CMCResponse,
                    symbol      = CMCResponse.Data.BTC.Symbol,
                };
            }
            else
            {
                response.successful = false;
                response.message    = "Could not get listing.";
            }
            return(response);
        }