Ejemplo n.º 1
0
        public async Task GenerateAndSendWorkerAsync(TelegramBotClient bot, IList <string> parameters)
        {
            var currenciesNumber = 5;

            bool.TryParse(parameters[0], out bool sendAnyway);
            var result = await GetPricesAsync(currenciesNumber);

            if ((!sendAnyway && !result.Item2) || string.IsNullOrEmpty(result.Item1))
            {
                return;
            }

            try
            {
                using (BotDBContext db = new BotDBContext())
                {
                    var clients = (from c in db.Clients
                                   join sub in db.Subscriptions on c.Subscription equals sub.Id
                                   where sub.SubsctiptionType == (int)Subscription.CoinCapMarket
                                   select c.ChatId
                                   ).Distinct();

                    foreach (var client in clients)
                    {
                        await bot.SendTextMessageAsync(client, result.Item1, parseMode : Telegram.Bot.Types.Enums.ParseMode.Html);
                    }
                }
            }
            catch (Exception e)
            {
                TraceError.Error(e);
            }
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> Post([FromBody] Update update)
        {
            TraceError.Info("Called Trace Error from api/command");

            if (update == null)
            {
                TraceError.Info($"Update is null");
            }
            if (update?.Message == null)
            {
                TraceError.Info($"Message is null");
            }
            if (update?.Message?.Text == null)
            {
                TraceError.Info($"Text is null");
            }
            TraceError.Info("Update text - " + update?.Message?.Text);

            try
            {
                if (update?.Message?.Text != null && update.Message.Text.StartsWith("/"))
                {
                    TraceError.Info("api/command called with: " + update?.Message?.Text);
                }
                await new MessageHandler().Handle(update);
                return(Ok());
            }
            catch (System.Exception e)
            {
                TraceError.Error(e, "Upper level Exception");
                return(Ok());
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Update handling
        /// </summary>
        ///
        public async Task Handle(Update update)
        {
            TraceError.Info($"inside message handler with {update?.Message?.Text}");
            if (update == null)
            {
                TraceError.Error("Update is null");
                return;
            }
            switch (update.Type)
            {
            case Telegram.Bot.Types.Enums.UpdateType.Message:
                await MessageUpdate(update);

                break;

            case Telegram.Bot.Types.Enums.UpdateType.CallbackQuery:
                await CallbackQuertUpdate(update);

                break;

            default:
                break;
            }
            return;
        }
Ejemplo n.º 4
0
        internal async Task BalanceAddAsync(TelegramBotClient bot, Update update)
        {
            var params1 = update.Message.Text.Split(' ');

            if (params1.Length != 3)
            {
                await bot.SendTextMessageAsync(update.Message.From.Id, "Incorrect parameters", parseMode : ParseMode.Html);

                return;
            }

            var symbol = params1[1].ToUpper();
            var parsed = double.TryParse(params1[2], out double value);
            var client = update.Message.From.Id;

            if (string.IsNullOrEmpty(symbol) && parsed)
            {
                await bot.SendTextMessageAsync(update.Message.From.Id, "Incorrect parameters", parseMode : ParseMode.Html);
            }

            string message;

            using (var db = new BotDBContext())
            {
                var result = db.Balances.SingleOrDefault(o => o.Client == client && o.Symbol == symbol);
                if (result != null)
                {
                    result.Shares = (decimal)value;
                    message       = symbol + " Record Updated!";
                }
                else
                {
                    var balance = new Balance()
                    {
                        Client = client,
                        Symbol = symbol,
                        Shares = (decimal)value
                    };
                    db.Balances.Add(balance);
                    message = symbol + " Record Added!";
                }
                db.SaveChanges();
            }

            try
            {
                await bot.SendTextMessageAsync(update.Message.From.Id, message);
            }
            catch (Exception e)
            {
                TraceError.Error(e);
            }
        }
Ejemplo n.º 5
0
 public OkResult SendErrorMessageToBot([FromQuery] string errormsg)
 {
     TraceError.Info("api/SendErrorMessageToBot");
     try
     {
         Task.Run(() => new WorkerHandler().SendErrorMessageToBot(errormsg));
     }
     catch (Exception e)
     {
         TraceError.Error(e, "Upper level Exception");
         return(Ok());
     }
     return(Ok());
 }
Ejemplo n.º 6
0
 public OkResult CoinUpdate([FromQuery] string sendAnyway = "false")
 {
     TraceError.Info("api/CoinUpdate called");
     try
     {
         Task.Run(() => new WorkerHandler().HandleCoinAsync(sendAnyway));
     }
     catch (Exception e)
     {
         TraceError.Error(e, "Upper level Exception");
         return(Ok());
     }
     return(Ok());
 }
Ejemplo n.º 7
0
 public OkResult ComicUpdate()
 {
     TraceError.Info("api/comicUpdate called");
     try
     {
         Task.Run(() => new WorkerHandler().HandleComicAsync());
     }
     catch (Exception e)
     {
         TraceError.Error(e, "Upper level Exception");
         return(Ok());
     }
     return(Ok());
 }
Ejemplo n.º 8
0
 public OkResult CUTest()
 {
     try
     {
         using (var db = new BotDBContext())
         {
             db.Subscriptions.Add(new DatabaseInteractions.Subscription()
             {
                 LastPostedKey = "", SubsctiptionType = 7
             });
             db.SaveChanges();
         }
     }
     catch (Exception e)
     {
         TraceError.Error(e, "Upper level Exception");
         return(Ok());
     }
     return(Ok());
 }
Ejemplo n.º 9
0
        private MessageToSend GetXKCDPicture()
        {
            WebClient webclient = new WebClient();

            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
            // Use SecurityProtocolType.Ssl3 if needed for compatibility reasons
            string html = "";

            try
            {
                html = webclient.DownloadString("https://xkcd.com/");
            }
            catch (Exception e)
            {
                TraceError.Error(e);
            }

            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml(html);

            List <HtmlNode> imageNodes = null;

            imageNodes = (from HtmlNode node in doc.DocumentNode.SelectNodes("//img")
                          where node.Name == "img" &&
                          !string.IsNullOrEmpty(node.Attributes["title"]?.Value) &&
                          node.Attributes["src"].Value.Contains("comics")
                          select node).ToList();

            var attrs = imageNodes[0]?.Attributes;

            return(new MessageToSend
            {
                Title = attrs["alt"]?.Value.Replace("&quot;", "\"").Replace("&#39;", "'"),
                SubTitle = attrs["title"]?.Value.Replace("&quot;", "\"").Replace("&#39;", "'"),
                Image = attrs["src"]?.Value.Substring(2)
            });
        }
Ejemplo n.º 10
0
        internal async Task BalanceRemoveAsync(TelegramBotClient bot, Update update)
        {
            var params1 = update.Message.Text.Split(' ');
            var client  = update.Message.From.Id;

            if (params1.Length != 2 && string.IsNullOrEmpty(params1[1]))
            {
                await bot.SendTextMessageAsync(update.Message.From.Id, "Incorrect parameters");

                return;
            }
            var symbol = params1[1].ToUpper();

            string message;

            using (var db = new BotDBContext())
            {
                var result = db.Balances.SingleOrDefault(o => o.Client == client && o.Symbol == symbol);
                if (result != null)
                {
                    db.Balances.Remove(result);
                    message = symbol + " Record Deleted!";
                }
                else
                {
                    message = symbol + " Record Not Found!";
                }
                db.SaveChanges();
            }

            try
            {
                await bot.SendTextMessageAsync(update.Message.From.Id, message);
            }
            catch (Exception e)
            {
                TraceError.Error(e);
            }
        }
Ejemplo n.º 11
0
        private async static Task <(string, bool)> GetPricesAsync(int currenciesNumber)
        {
            //HttpClient client = HttpClientProvider.GetClient();
            if (currenciesNumber > 50)
            {
                currenciesNumber = 50;
            }
            if (currenciesNumber < 0)
            {
                return("Incorrect number", true);
            }
            if (currenciesNumber == 0)
            {
                currenciesNumber = 5;
            }
            try
            {
                var URL = new UriBuilder("https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest");
                //var queryString = HttpUtility.ParseQueryString(string.Empty);
                //queryString["id"] = "1,2,3";

                //URL.Query = queryString.ToString();

                var client = new WebClient();
                client.Headers.Add("X-CMC_PRO_API_KEY", API_KEY);
                client.Headers.Add("Accepts", "application/json");
                var response = client.DownloadString(URL.ToString());

                response = response.Replace("USD", "CurrentPriceInfo");

                CoinmarketcapItemData result       = JsonConvert.DeserializeObject <CoinmarketcapItemData>(response);
                List <Currency>       currencyList = new List <Currency>();

                foreach (ItemData data in result.DataList)
                {
                    if (data.symbol.Contains("CurrentPriceInfo"))
                    {
                        continue;
                    }
                    Currency item = new Currency
                    {
                        Id               = data.id.ToString(),
                        Name             = data.name,
                        Symbol           = data.symbol,
                        Rank             = data.cmc_rank.ToString(),
                        Price            = data.quote.CurrentPriceInfo.price ?? 0d,
                        Volume24hUsd     = data.quote.CurrentPriceInfo.volume_24h ?? 0,
                        MarketCapUsd     = data.quote.CurrentPriceInfo.volume_24h ?? 0,
                        PercentChange1h  = data.quote.CurrentPriceInfo.percent_change_1h ?? 0,
                        PercentChange24h = data.quote.CurrentPriceInfo.percent_change_24h ?? 0,
                        PercentChange7d  = data.quote.CurrentPriceInfo.percent_change_7d ?? 0,
                        LastUpdated      = data.quote.CurrentPriceInfo.last_updated,
                        MarketCapConvert = data.quote.CurrentPriceInfo.market_cap ?? 0d,
                        ConvertCurrency  = "USD"
                    };

                    currencyList.Add(item);
                }

                //var response = await client.GetAsync("https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest");

                //if (response.IsSuccessStatusCode)
                //{
                //    var result = response.Content.ReadAsAsync<CoinPrice[]>().Result;
                //    StringBuilder sb = new StringBuilder();
                //    foreach (var item in result)
                //    {
                //        sb.Append($"{item.symbol.Bold()}: ${item.price_usd}, {item.percent_change_24h.Italic()}%{Environment.NewLine}");
                //    }

                //    if (currenciesNumber == 1)
                //    {
                //        return (sb.ToString(), true);
                //    }
                //    else
                //    {
                //        double.TryParse(result[0].percent_change_24h, out double BTCchange);
                //        double.TryParse(result[1].percent_change_24h, out double ETHchange);
                //        var change = (Math.Abs(BTCchange) >= 10 || Math.Abs(ETHchange) >= 10) ? true : false;
                //        return (sb.ToString(), change);
                //    }
                //}


                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < currenciesNumber; i++)
                {
                    sb.Append($"{currencyList[i].Symbol.Bold()}:  ${Math.Round(currencyList[i].Price, 2).ToString()},  {Math.Round(currencyList[i].PercentChange24h, 1).ToString().Italic()}%{Environment.NewLine}");
                }

                return(sb.ToString(), false);
            }
            catch (Exception e)
            {
                TraceError.Error(e);
                return("", false);
            }
        }