Esempio n. 1
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());
            }
        }
Esempio n. 2
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;
        }
Esempio n. 3
0
 public async void HandleCoinAsync(string sendAnyway)
 {
     TraceError.Info("HandleCoinAsync called from Worker");
     await new CoinModule().GenerateAndSendWorkerAsync(_bot, new List <string>()
     {
         sendAnyway
     });
 }
Esempio n. 4
0
        private async Task SendComicsAsync(Subscription subscriptionType)
        {
            using (var 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)subscriptionType
                               select c.ChatId
                               ).Distinct();

                MessageToSend message = (subscriptionType == Subscription.Oglaf) ? GetOglafPicture() : GetXKCDPicture();

                foreach (var client in clients)
                {
                    var lastPostedKey = (from cli in db.Clients
                                         join sub in db.Subscriptions on cli.Subscription equals sub.Id
                                         where cli.ChatId == client && sub.SubsctiptionType == (int)subscriptionType
                                         orderby sub.Id descending
                                         select new
                    {
                        LTK = sub.LastPostedKey,
                        SUBID = sub.Id
                    }
                                         ).First();

                    if (message.Title.Equals(lastPostedKey.LTK))
                    {
                        continue;
                    }

                    DatabaseInteractions.Subscription subToUpdate = db.Subscriptions.Where(x => x.Id == lastPostedKey.SUBID).First();
                    string newHash = message.Title;
                    subToUpdate.LastPostedKey = newHash;
                    db.Update(subToUpdate);
                    //db.Subscriptions.Where(x => x.Id == lastPostedKey.SUBID).First().LastPostedKey = message.Title.GetHashCode().ToString();

                    try
                    {
                        await _bot.SendTextMessageAsync(client, message.Title.ToUpper());

                        await _bot.SendTextMessageAsync(client, message.SubTitle);

                        await _bot.SendPhotoAsync(client, new InputOnlineFile(message.Image));
                    }
                    catch (ChatNotFoundException e)
                    {
                        TraceError.Info(e.Message);
                        var clientsRecords = db.Clients.Where(c => c.ChatId == client).ToList();
                        TraceError.Info("Client Recs to remove: " + string.Join(",", clientsRecords.Select(c => c.ChatId)));
                        var subscriptionsToRemove = db.Subscriptions.Where(x => clientsRecords.Select(o => o.Subscription).Contains(x.Id));
                        TraceError.Info("Subscription Recs to remove: " + string.Join(",", subscriptionsToRemove.Select(s => s.SubsctiptionType.ToString())));
                        db.Subscriptions.RemoveRange(subscriptionsToRemove);
                        db.Clients.RemoveRange(clientsRecords);
                    }
                }
                await db.SaveChangesAsync();
            }
        }
Esempio 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());
 }
Esempio 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());
 }
Esempio 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());
 }
Esempio n. 8
0
        public async Task GenerateAndSendAsync(TelegramBotClient bot, Update update)
        {
            TraceError.Info($"In Balance module");
            double totalAmount    = 0;
            double BTCtotalAmount = 0;
            double ALTtotalAmount = 0;

            try
            {
                using (BotDBContext db = new BotDBContext())
                {
                    TraceError.Info($"DB initiated");
                    var balances = db.Balances.Where(o => o.Client == (int)update.Message.From.Id);

                    StringBuilder sb = new StringBuilder();
                    foreach (var b in balances)
                    {
                        sb.Append(b.Symbol + ',');
                    }
                    sb.Remove(sb.Length - 1, 1);

                    var prices = GetPrices(sb.ToString());

                    foreach (var item in balances)
                    {
                        prices.TryGetValue(item.Symbol, out double price);
                        totalAmount += ((double)item.Shares * price);
                        if (item.Symbol == "BTC")
                        {
                            BTCtotalAmount += ((double)item.Shares * price);
                        }
                        if (item.Symbol != "BTC")
                        {
                            ALTtotalAmount += ((double)item.Shares * price);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                TraceError.Info("EXception thrown ");
                TraceError.Info("DB ERROR: " + e.Message);
            }
            string msg = $"BTC: ${Math.Round(BTCtotalAmount, 2)}{Environment.NewLine}ALT: ${Math.Round(ALTtotalAmount, 2)}{Environment.NewLine}TOTAL: ${Math.Round(totalAmount, 2)}";
            await bot.SendTextMessageAsync(update.Message.From.Id, msg, parseMode : ParseMode.Html);
        }
Esempio n. 9
0
 /// <summary>
 /// Get the bot and set the hook
 /// </summary>
 public static TelegramBotClient Get()
 {
     if (_bot != null)
     {
         return(_bot);
     }
     if (Config.Environment == "Development")
     {
         _bot = new TelegramBotClient(Config.BotApiKey);
         _bot.SetWebhookAsync(Config.WebHookUrl);
         _bot.SendTextMessageAsync(182328439, "Local Bot started!");
     }
     else if (Config.Environment == "Production" || Config.Environment == "Release")
     {
         _bot = new TelegramBotClient(Config.BotApiKey);
         _bot.SetWebhookAsync(Config.WebHookUrl);
         _bot.SendTextMessageAsync(182328439, "Remote Bot started!!!");
         TraceError.Info("Bot started");
     }
     return(_bot);
 }
Esempio n. 10
0
        static async Task Run()
        {
            var TelegramBotClient = new TelegramBotClient(Config.BotApiKey);

            var offset = 0;

            TraceError.Info("Inside NoHookLoop");
            while (true)
            {
                var updates = await TelegramBotClient.GetUpdatesAsync(offset);

                foreach (var update in updates)
                {
                    TraceError.Info("Update from NoHookLoop");
                    await Task.Run(() => new MessageHandler().Handle(update));

                    offset = update.Id + 1;
                }

                await Task.Delay(1000);
            }
        }
Esempio n. 11
0
        public async Task UpdateSubscriptions(Update update)
        {
            Subscription subscriptionType = Subscription.NoSubscription;

            if (update.CallbackQuery.Data.Equals("/subs=Oglaf"))
            {
                subscriptionType = Subscription.Oglaf;
            }
            if (update.CallbackQuery.Data.Equals("/subs=Xkcd"))
            {
                subscriptionType = Subscription.XKCD;
            }
            if (update.CallbackQuery.Data.Equals("/subs=CoinCM"))
            {
                subscriptionType = Subscription.CoinCapMarket;
            }
            if (update.CallbackQuery.Data.Equals("/subs=ErrL"))
            {
                subscriptionType = Subscription.ErrorMessageLog;
            }

            var userId = update.CallbackQuery.From.Id;

            TraceError.Info("In callback");

            using (BotDBContext db = new BotDBContext())
            {
                try
                {
                    TraceError.Info("DB Init");
                    var exists = (from c in db.Clients
                                  join sub in db.Subscriptions on c.Subscription equals sub.Id
                                  where c.ChatId == userId &&
                                  sub.SubsctiptionType == (int)subscriptionType
                                  select c.Id
                                  ).Count();



                    if (exists == 0)
                    {
                        var subscription = new DatabaseInteractions.Subscription {
                            SubsctiptionType = (int)subscriptionType
                        };
                        db.Subscriptions.Add(subscription);
                        db.SaveChanges();
                        var client = new DatabaseInteractions.Client {
                            ChatId = userId, Subscription = subscription.Id
                        };
                        db.Clients.Add(client);
                        db.SaveChanges();

                        await _bot.SendTextMessageAsync(userId, $"You've subscribed to { subscriptionType.ToString() }!");
                    }
                    else
                    {
                        var clients = db.Clients.Where(x => x.ChatId == userId &&
                                                       db.Subscriptions.Any(y => y.Id == x.Subscription && y.SubsctiptionType == (int)subscriptionType));
                        foreach (var item in clients)
                        {
                            db.Clients.Remove(item);
                            var sub = db.Subscriptions.Where(x => x.Id == item.Subscription).FirstOrDefault();
                            db.Subscriptions.Remove(sub);
                        }
                        db.SaveChanges();
                        await _bot.SendTextMessageAsync(userId, $"Unsubscribed from { subscriptionType.ToString() }!");
                    }
                }
                catch (Exception e)
                {
                    TraceError.Info(e.Message);
                }
            }
        }
Esempio n. 12
0
 public async void SendErrorMessageToBot(string errormsg)
 {
     TraceError.Info("HandleErrorMsg called from Worker");
     await new ErrorMsgModule().SendErrorMessage(_bot, errormsg);
 }
Esempio n. 13
0
 public async void HandleComicAsync()
 {
     TraceError.Info("HandleComicAsync called from Worker");
     await new ComicModule().SendComicsAsync();
 }