Beispiel #1
0
        public async Task MainAsync()
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("authentication.json", false, false);

            Configuration = builder.Build();

            _client = new DiscordSocketClient(new DiscordSocketConfig()
            {
                LogLevel            = LogSeverity.Info,
                DefaultRetryMode    = RetryMode.AlwaysRetry,
                AlwaysDownloadUsers = true
            });
            _client.Log += Log;

            string token = Configuration["auth:token"];

            BotUsername = Configuration["auth:BotUsername"];

            await _client.LoginAsync(TokenType.Bot, token);

            await _client.StartAsync();

            adminBot = new AdminBot();
            _client.MessageReceived    += MessageReceived;
            _client.GuildMemberUpdated += GuildMemberUpdated;

            _client.GuildAvailable += GuildAvailable;

            await Task.Delay(-1);
        }
Beispiel #2
0
 internal PublishingTask(PublishBot publishBot, PostingManager postingManager, AdminBot adminBot)
 {
     this.posts       = postingManager;
     this.publishBot  = publishBot;
     this.adminBot    = adminBot;
     this.publishTask = this.periodicPublishingTask(new TimeSpan(0, 0, 0, IntervalCheckPublishSeconds, 0), this.cancelTaskSource.Token);
 }
Beispiel #3
0
        public static void CallbackQuery(CallbackQueryEventArgs e, ITelegramBotClient bot)
        {
            string message = e.CallbackQuery.Data;
            var    chatId  = e.CallbackQuery.From.Id;

            int id = 0;

            int.TryParse(message.Substring(6), out id);

            AdminBot.adminLog(message);

            Participant participant;

            using (MobileContext db = new MobileContext())
            {
                try
                {
                    var booking      = db.Bookings.Single(c => c.Id == id);
                    var bookingsWeek = db.Bookings.Remove(booking);
                    db.SaveChanges();
                } catch (InvalidOperationException ex)
                {
                    _ = bot.SendTextMessageAsync(chatId, "Бронь уже удалена").Result;
                    return;
                }

                participant = db.Participants.Single(c => c.Alias == e.CallbackQuery.From.Username);
            }

            using (FileStream fs = FormSchedule.FormScheduleImage(participant))
            {
                Message mes = bot.SendPhotoAsync(chatId: chatId, photo: new InputOnlineFile(fs, "schedule.png"), caption: "Бронь отменена.").Result;
            }
        }
Beispiel #4
0
 internal VoteAndFlagTask(PostingManager postingManager, PublishBot publishBot, DRaumStatistics statistics, AdminBot adminBot)
 {
     this.statistics      = statistics;
     this.adminBot        = adminBot;
     this.publishBot      = publishBot;
     this.posts           = postingManager;
     this.voteAndFlagTask = this.periodicVoteAndFlagTask(new TimeSpan(0, 0, intervalVoteAndFlagCountMinutes, 0, 0), this.cancelTaskSource.Token);
 }
Beispiel #5
0
 internal StatisticCollectionTask(AuthorManager authors, DRaumStatistics statistics, PostingManager posts, AdminBot adminBot)
 {
     this.authors    = authors;
     this.posts      = posts;
     this.statistics = statistics;
     this.adminBot   = adminBot;
     this.statisticCollectionTask = this.periodicStatisticCollectionTask(new TimeSpan(0, 0, intervalStatisticCollectionMinutes, 0, 0), this.cancelTaskSource.Token);
 }
 public AccountController(
     UserManager <ApplicationUser> userManager,
     SignInManager <ApplicationUser> signInManager,
     IEmailSender emailSender,
     ILogger <AccountController> logger,
     AdminBot adminBot)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _emailSender   = emailSender;
     _logger        = logger;
     _adminBot      = adminBot;
 }
Beispiel #7
0
        public static void Book(Message message, ITelegramBotClient bot, Participant participant)
        {
            var chatId      = message.Chat.Id;
            var messageId   = message.MessageId;
            var selectedDay = participant.SelectedDate;


            //парсинг времени и запись брони в бд если всё ок.
            string[] splitted = message.Text.Split(" ");
            DateTime startTime;
            DateTime endTime;

            try
            {
                if (splitted[0].Length == 4)
                {
                    splitted[0] = "0" + splitted[0];
                }
                if (splitted[1].Length == 4)
                {
                    splitted[1] = "0" + splitted[1];
                }

                startTime = DateTime.ParseExact(splitted[0], "HH:mm", CultureInfo.InvariantCulture);
                endTime   = DateTime.ParseExact(splitted[1], "HH:mm", CultureInfo.InvariantCulture);
            }
            catch (Exception ex)
            {
                Message mes = bot.SendTextMessageAsync(message.Chat.Id, "Введите время начала и завершения в формате \"HH:MM HH:MM\". Например 12:20 14:20", replyToMessageId: message.MessageId).Result;
                AdminBot.adminLog("Exception " + ex.Message);
                return;
            }

            DateTime startDateTime = new DateTime(selectedDay.Year, selectedDay.Month, selectedDay.Day, startTime.Hour, startTime.Minute, 0);
            DateTime endDateTime   = new DateTime(selectedDay.Year, selectedDay.Month, selectedDay.Day, endTime.Hour, endTime.Minute, 0);

            //на случай случайного ввода в неверном порядке
            if (startDateTime > endDateTime)
            {
                DateTime temp = startDateTime;
                startDateTime = endDateTime;
                endDateTime   = temp;
            }

            if (startDateTime.Hour < 7)
            {
                Message mes = bot.SendTextMessageAsync(message.Chat.Id, "Время начала раньше 7 утра. (Время работы спорткомплекса: с 7:00 до 23:00)", replyToMessageId: message.MessageId).Result;
                AdminBot.adminLog("Время начала раньше 7 утра.");
                return;
            }
            if (startDateTime.Hour >= 22 && startDateTime.Minute >= 30)
            {
                Message mes = bot.SendTextMessageAsync(message.Chat.Id, "Время начала позже 22:30. (Время работы спорткомплекса: с 7:00 до 23:00)", replyToMessageId: message.MessageId).Result;
                AdminBot.adminLog("Время начала позже 22:30.");
                return;
            }
            if (endDateTime.Hour < 7)
            {
                Message mes = bot.SendTextMessageAsync(message.Chat.Id, "Время завершения раньше 7 утра. (Время работы спорткомплекса: с 7:00 до 23:00)", replyToMessageId: message.MessageId).Result;
                AdminBot.adminLog("Время завершения раньше 7 утра.");
                return;
            }
            if (endDateTime.Hour >= 22 && endDateTime.Minute > 30)
            {
                Message mes = bot.SendTextMessageAsync(message.Chat.Id, "Время завершения позже 22:30. (Время работы спорткомплекса: с 7:00 до 23:00)\n\nПо просьбе руководства спорткомплекса музкомната освобождается за пол часа до закрытия ск.", replyToMessageId: message.MessageId).Result;
                AdminBot.adminLog("Время завершения позже 22:30.");
                return;
            }

            //Нужно получить доступное время для бронирования
            double freetime = BookCommand.maxHoursToBook(participant.Status);

            using (MobileContext db = new MobileContext())
            {
                var bookings = db.Bookings.Where(c => (c.Participant == participant) && (c.TimeEnd.Year == selectedDay.Year) && (c.TimeEnd.Month == selectedDay.Month) && (c.TimeEnd.Day == selectedDay.Day)).ToList();
                foreach (var booking in bookings)
                {
                    freetime -= (booking.TimeEnd.Subtract(booking.TimeStart).TotalHours);
                }

                if (startDateTime.Subtract(endDateTime).TotalHours >= freetime)
                {
                    _ = bot.SendTextMessageAsync(chatId, $"Недостаточно доступного времени для бронирования.\n\nВведите время начала и завершения брони. Например \"12:20 14:20\"", replyToMessageId: messageId).Result;
                    AdminBot.adminLog("Недостаточно доступного времени для бронирования.");
                    return;
                }

                //TODO выяснить почему если убрать запрос к таблице Participants, то в таблице Bookings все ссылки на Participants будут null
                var parts = db.Participants.ToList();

                var allBookingsInDay = db.Bookings.Where(c => (c.TimeEnd.Year == startDateTime.Year) && (c.TimeEnd.Month == startDateTime.Month) && (c.TimeEnd.Day == startDateTime.Day)).ToList();
                foreach (var booking in allBookingsInDay)
                {
                    //В принципе, этот иф можно использовать внутри where при выборке броней
                    if ((startDateTime >= booking.TimeStart && startDateTime < booking.TimeEnd) ||
                        (endDateTime > booking.TimeStart && endDateTime <= booking.TimeEnd) ||
                        (booking.TimeStart > startDateTime && booking.TimeStart < endDateTime))
                    {
                        _ = bot.SendTextMessageAsync(message.Chat.Id, $"Выбранное время занято бронью @{booking.Participant.Alias}\n\nВведите время начала и завершения в формате \"HH:MM HH:MM\". Например 12:20 14:20", replyToMessageId: message.MessageId).Result;
                        AdminBot.adminLog($"Выбранное время занято бронью @{booking.Participant.Alias}");
                        return;
                    }
                }

                //Изза того что контекст бд закрывается, то ломается состояние participant. найти почему так либо не закрывать контекст
                participant = db.Participants.Single(c => c.Alias == message.From.Username);
                Booking newEntry = new Booking(participant, startDateTime, endDateTime);
                db.Bookings.Add(newEntry);
                db.SaveChanges();

                using (FileStream fs = FormSchedule.FormScheduleImage(participant))
                {
                    Message mes = bot.SendPhotoAsync(chatId: chatId, photo: new InputOnlineFile(fs, "schedule.png"), caption: "Бронь установлена.", replyToMessageId: messageId).Result;
                }
            }
        }
 public TableController(UserManager <ApplicationUser> userManager, AdminBot adminBot)
 {
     _adminBot    = adminBot;
     _userManager = userManager;
     _tableModel  = new TableModel();
 }
Beispiel #9
0
        public async Task <IActionResult> Post([FromBody] Update update)
        {
            OkResult = this.Ok();

            if (update.CallbackQuery == null && update.InlineQuery == null)
            {
                BotCore = new ProductAddBot(update);
                Result  = await BotCore.Response();
            }

            if (update.InlineQuery != null)
            {
                InlineFind find = new InlineFind(update.InlineQuery);
                await find.Response();

                return(Ok());
            }


            if (update != null && update.CallbackQuery != null && update.CallbackQuery.Data != null && update.InlineQuery == null)
            {
                ModuleName = JsonConvert.DeserializeObject <BotCommand>(update.CallbackQuery.Data).M;
            }

            if (update.InlineQuery == null)
            {
                if (Result == null && ModuleName != null && ModuleName == ReportsBot.ModuleName || Result == null && ModuleName == null)
                {
                    BotCore = new ReportsBot(update);
                    Result  = await BotCore.Response();
                }

                if (Result == null && ModuleName != null && ModuleName == MoreSettingsBot.ModuleName || Result == null && ModuleName == null)
                {
                    BotCore = new MoreSettingsBot(update);
                    Result  = await BotCore.Response();
                }

                if (Result == null && ModuleName != null && ModuleName == HelpDeskProccessingBot.ModuleName || Result == null && ModuleName == null && update.InlineQuery == null)
                {
                    BotCore = new HelpDeskProccessingBot(update);
                    Result  = await BotCore.Response();
                }

                if (Result == null && ModuleName != null && ModuleName == NotificationBot.ModuleName || Result == null && ModuleName == null)
                {
                    BotCore = new NotificationBot(update);
                    Result  = await BotCore.Response();
                }

                if (Result == null && ModuleName != null && ModuleName == OrderProccesingBot.ModuleName || Result == null && ModuleName == null)
                {
                    BotCore = new OrderProccesingBot(update);
                    Result  = await BotCore.Response();
                }

                if (Result == null && ModuleName != null && ModuleName == CategoryBot.ModuleName || Result == null && ModuleName == null)
                {
                    BotCore = new CategoryBot(update);
                    Result  = await BotCore.Response();
                }

                if (Result == null && ModuleName != null && ModuleName == ProductBot.ModuleName || Result == null && ModuleName == null)
                {
                    BotCore = new ProductBot(update);
                    Result  = await BotCore.Response();
                }

                if (Result == null && ModuleName != null && ModuleName == BasketBot.ModuleName || Result == null && ModuleName == null)
                {
                    BotCore = new BasketBot(update);
                    Result  = await BotCore.Response();
                }

                if (Result == null && ModuleName != null && ModuleName == AddressBot.ModuleName || Result == null && ModuleName == null ||
                    Result == null && update.Message != null && update.Message.Location != null)
                {
                    BotCore = new AddressBot(update);
                    Result  = await BotCore.Response();
                }

                if (Result == null && ModuleName != null && ModuleName == OrderBot.ModuleName || Result == null && ModuleName == null ||
                    Result == null && update.PreCheckoutQuery != null)
                {
                    BotCore = new OrderBot(update);
                    Result  = await BotCore.Response();
                }

                if (Result == null && ModuleName != null && ModuleName == OperatorBot.ModuleName || Result == null && ModuleName == null ||
                    Result == null && update.PreCheckoutQuery != null)
                {
                    BotCore = new OperatorBot(update);
                    Result  = await BotCore.Response();
                }

                if (update.Message != null && Result == null)
                {
                    BotCore = new FollowerBot(update);
                    Result  = await BotCore.Response();
                }

                if (Result == null && ModuleName != null && ModuleName == OrderPositionBot.ModuleName || Result == null && ModuleName == null)
                {
                    BotCore = new OrderPositionBot(update);
                    Result  = await BotCore.Response();
                }

                if (Result == null && ModuleName != null && ModuleName == AdminBot.ModuleName || Result == null && ModuleName == null)
                {
                    BotCore = new AdminBot(update);
                    Result  = await BotCore.Response();
                }

                if (Result == null && ModuleName != null && ModuleName == ProductEditBot.ModuleName || Result == null && ModuleName == null)
                {
                    BotCore = new ProductEditBot(update);
                    Result  = await BotCore.Response();
                }

                if (Result == null && ModuleName != null && ModuleName == CategoryEditBot.ModuleName || Result == null && ModuleName == null)
                {
                    BotCore = new CategoryEditBot(update);
                    Result  = await BotCore.Response();
                }

                if (Result == null && ModuleName != null && ModuleName == MainMenuBot.ModuleName || Result == null && ModuleName == null)
                {
                    BotCore = new MainMenuBot(update);
                    Result  = await BotCore.Response();
                }


                if (Result == null && ModuleName != null && ModuleName == HelpDeskBot.ModuleName || Result == null && ModuleName == null)
                {
                    BotCore = new HelpDeskBot(update);
                    Result  = await BotCore.Response();
                }
            }

            //делаем так что бы наше приложние всегда отвечало телеграму ОК.
            //В противном случаем телеграм так и будет слать нам это сообщения в ожиданиее ответа ОК
            if (Result == null || Result != null)
            {
                Result = Ok();
            }

            if (update.Message != null && update.Message.Chat != null)
            {
                try
                {
                    BusinessLayer.FollowerFunction.InsertFollower(Convert.ToInt32(update.Message.Chat.Id),
                                                                  update.Message.Chat.FirstName, update.Message.Chat.LastName, update.Message.Chat.Username);
                }

                catch
                {
                }
            }

            if (update.CallbackQuery != null && update.CallbackQuery.Message != null && update.CallbackQuery.Message.Chat != null)
            {
                try
                {
                    BusinessLayer.FollowerFunction.InsertFollower(Convert.ToInt32(update.CallbackQuery.Message.Chat.Id),
                                                                  update.CallbackQuery.Message.Chat.FirstName, update.CallbackQuery.Message.Chat.LastName, update.CallbackQuery.Message.Chat.Username);
                }
                catch
                {
                }
            }

            AddUpdateMsgToDb(update);

            return(Result);
        }
Beispiel #10
0
        public async Task <IActionResult> Post([FromBody] Update update)
        {
            OkResult       = this.Ok();
            NotFoundResult = this.NotFound();

            if (update != null && update.CallbackQuery != null && update.CallbackQuery.Data != null)
            {
                ModuleName = JsonConvert.DeserializeObject <Bot.BotCommand>(update.CallbackQuery.Data).M;
            }

            if (Result == null && ModuleName != null && ModuleName == HelpDeskProccessingBot.ModuleName || Result == null && ModuleName == null)
            {
                HelpDeskProccessingBot = new HelpDeskProccessingBot(update);
                Result = await HelpDeskProccessingBot.Response();
            }

            if (Result == null && ModuleName != null && ModuleName == OrderProccesingBot.ModuleName || Result == null && ModuleName == null)
            {
                OrderProccesingBot = new OrderProccesingBot(update);
                Result             = await OrderProccesingBot.Response();
            }

            if (Result == null && ModuleName != null && ModuleName == CategoryBot.ModuleName || Result == null && ModuleName == null)
            {
                Category = new CategoryBot(update);
                Result   = await Category.Response();
            }

            if (Result == null && ModuleName != null && ModuleName == ProductBot.ModuleName || Result == null && ModuleName == null)
            {
                Product = new ProductBot(update);
                Result  = await Product.Response();
            }

            if (Result == null && ModuleName != null && ModuleName == BasketBot.ModuleName || Result == null && ModuleName == null)
            {
                Basket = new BasketBot(update);
                Result = await Basket.Response();
            }

            if (Result == null && ModuleName != null && ModuleName == AddressBot.ModuleName || Result == null && ModuleName == null)
            {
                Address = new AddressBot(update);
                Result  = await Address.Response();
            }

            if (Result == null && ModuleName != null && ModuleName == OrderBot.ModuleName || Result == null && ModuleName == null)
            {
                OrderBot = new OrderBot(update);
                Result   = await OrderBot.Response();
            }

            if (update.Message != null && Result == null)
            {
                FollowerBot = new FollowerBot(update);
                Result      = await FollowerBot.Response();
            }

            if (Result == null && ModuleName != null && ModuleName == OrderPositionBot.ModuleName || Result == null && ModuleName == null)
            {
                PositionBot = new OrderPositionBot(update);
                Result      = await PositionBot.Response();
            }

            if (Result == null && ModuleName != null && ModuleName == AdminBot.ModuleName || Result == null && ModuleName == null)
            {
                AdminBot = new AdminBot(update);
                Result   = await AdminBot.Response();
            }

            if (Result == null && ModuleName != null && ModuleName == ProductEditBot.ModuleName || Result == null && ModuleName == null)
            {
                ProductEditBot = new ProductEditBot(update);
                Result         = await ProductEditBot.Response();
            }

            if (Result == null && ModuleName != null && ModuleName == CategoryEditBot.ModuleName || Result == null && ModuleName == null)
            {
                CategoryEditBot = new CategoryEditBot(update);
                Result          = await CategoryEditBot.Response();
            }

            if (Result == null && ModuleName != null && ModuleName == MainMenuBot.ModuleName || Result == null && ModuleName == null)
            {
                MainMenuBot = new MainMenuBot(update);
                Result      = await MainMenuBot.Response();
            }

            if (Result == null && ModuleName == null)
            {
                ImportCSVBot = new ImportCSVBot(update);
                Result       = await ImportCSVBot.Response();
            }

            if (Result == null && ModuleName != null && ModuleName == HelpDeskBot.ModuleName || Result == null && ModuleName == null)
            {
                HelpDeskBot = new HelpDeskBot(update);
                Result      = await HelpDeskBot.Response();
            }

            await AddUpdateMsgToDb(update);

            if (update.Message != null)
            {
                await  UpdateFollowerInfo(update.Message.Chat);
            }

            if (update.CallbackQuery != null && update.CallbackQuery.Message != null)
            {
                await UpdateFollowerInfo(update.CallbackQuery.Message.Chat);
            }


            if (Result == null || Result != null)
            {
                Result = Ok();
            }


            return(Result);
        }