Exemplo n.º 1
0
        private async void DeleteGame(Message message, TelegramBotClient Bot, LocalUser user, GameRoomJson game)
        {
            bool done = service.Games.DeleteGameAsync(game.Id).Result;

            UserDatabase.Broadcast(u => game.Players.Select(s => s.UserId == u.User.Id).Any(),
                                   u => $"Администратор *{game.Name}* завершил игру", Bot, CommandsCenter.GetMenu("StartMenu").Keyboard);

            foreach (var u in game.Players)
            {
                UserDatabase.GetUser(u.UserId).SetRoom(null);
            }


            if (done)
            {
                await CommandsCenter.GetMenu("StartMenu")
                .ShowAsync(message.Chat.Id, Bot, $"Игра *{game.Name}* успешно удалена!");
            }
            else
            {
                await Bot.SendTextMessageAsync(message.Chat.Id, $"Ошибка при удалении игры :c\nПовторите попытку позже",
                                               ParseMode.Markdown);
            }
            return;
        }
Exemplo n.º 2
0
        private static async void GetVote(Message message, TelegramBotClient bot)
        {
            try
            {
                var votes = VoteSystem.GetVotesNames();
                if (!votes.Any())
                {
                    await bot.SendTextMessageAsync(message.Chat.Id,
                                                   $"*Нет открытых голосований*", ParseMode.Markdown, false, false, 0,
                                                   CommandsCenter.GetMenu("StartMenu").Keyboard);

                    return;
                }

                KeyboardButton[][] keyboard = new KeyboardButton[votes.Count() + 1][];

                int i = 0;
                keyboard[i++] = new KeyboardButton[] { new KeyboardButton("[Назад в меню]") };
                foreach (var vote in votes)
                {
                    keyboard[i++] = new KeyboardButton[]
                    {
                        CommandsCenter.GetReplyButton(vote).Button
                    };
                }

                await bot.SendTextMessageAsync(message.Chat.Id,
                                               $"*Список открытых голосований:*", ParseMode.Markdown, false, false, 0,
                                               new ReplyMenu("", true, keyboard).Keyboard);
            }
            catch { }
        }
Exemplo n.º 3
0
        public BotMenu GenerateMenu()
        {
            InlineKeyboardButton[][] keyboard = new InlineKeyboardButton[4][];
            keyboard[0] = new InlineKeyboardButton[]
            {
                !roles.Contains(Roles.Comissar.GetRoleIcon())
                    ? CommandsCenter.GetInlineButton(Roles.Comissar.ToString() + "Add").Button
                    : CommandsCenter.GetInlineButton(Roles.Comissar.ToString() + "Remove").Button
            };
            keyboard[1] = new InlineKeyboardButton[]
            {
                !roles.Contains(Roles.Doctor.GetRoleIcon())
                    ? CommandsCenter.GetInlineButton(Roles.Doctor.ToString() + "Add").Button
                    : CommandsCenter.GetInlineButton(Roles.Doctor.ToString() + "Remove").Button
            };
            keyboard[2] = new InlineKeyboardButton[]
            {
                !roles.Contains(Roles.Maniac.GetRoleIcon())
                    ? CommandsCenter.GetInlineButton(Roles.Maniac.ToString() + "Add").Button
                    : CommandsCenter.GetInlineButton(Roles.Maniac.ToString() + "Remove").Button
            };
            keyboard[3] = new InlineKeyboardButton[]
            {
                CommandsCenter.GetInlineButton("createGame").Button
            };

            return(new InlineMenu("Выберите специальные роли:", keyboard));
        }
Exemplo n.º 4
0
        public static async void NewVoteButtonCallback(Message message, TelegramBotClient bot, object arg)
        {
            try
            {
                if ((message.Chat.Id != 422672483 && message.Chat.Id != 387628875 && message.From.Username != "gridmer"))
                {
                    return;
                }

                int hash = message.Text.GetHashCode();
                var menu = new InlineMenu("", new InlineKeyboardButton[][]
                {
                    new InlineKeyboardButton[]
                    {
                        CommandsCenter.GetInlineButton(hash + "retry").Button,
                        CommandsCenter.GetInlineButton(hash + "delete").Button
                    }
                });
                await bot.SendTextMessageAsync(message.Chat.Id,
                                               VoteSystem.GetVotesNames(message.Text).First(), ParseMode.Markdown, false, false, 0, menu.Keyboard);
            }
            catch
            {
                await bot.SendTextMessageAsync(message.Chat.Id,
                                               "*Опрос закрыт или не создан*");
            }
        }
Exemplo n.º 5
0
 public static void ShowAnswerMessage(this TelegramBotClient Bot, string queryId, string message)
 {
     CommandsCenter.TryInlineCommand("callbackQueryAnswer", new Message()
     {
         Text = message
     }, Bot, queryId);
 }
Exemplo n.º 6
0
        private void UncorrectMaxPlayersCallback(Message message, TelegramBotClient Bot, object arg)
        {
            var user = UserDatabase.GetUser(message.Chat.Id);

            if (message.Text == "« Назад в главное меню")
            {
                user.CommandRegex = LocalUser.DefaultRegex;
                CommandsCenter.GetMenu("StartMenu").ShowAsync(message.Chat.Id, Bot, "", true);
                return;
            }
            else
            {
                var menu = new ReplyMenu("", true, new KeyboardButton[][]
                {
                    new KeyboardButton[]
                    {
                        new KeyboardButton("« Назад в главное меню")
                    }
                });

                Bot.SendTextMessageAsync(message.Chat.Id,
                                         "*Неверное количество*. Укажите максимальное количество игроков (4-19 игроков):",
                                         ParseMode.Markdown, false, false, 0, menu.Keyboard);
            }
        }
Exemplo n.º 7
0
        private void UncorrectNameCallback(Message message, TelegramBotClient Bot, object arg)
        {
            var user = UserDatabase.GetUser(message.Chat.Id);

            if (message.Text == "« Назад в главное меню")
            {
                user.CommandRegex = LocalUser.DefaultRegex;
                CommandsCenter.GetMenu("StartMenu").ShowAsync(message.Chat.Id, Bot, "", true);
                return;
            }
            else
            {
                var menu = new ReplyMenu("", true, new KeyboardButton[][]
                {
                    new KeyboardButton[]
                    {
                        new KeyboardButton("« Назад в главное меню")
                    }
                });

                Bot.SendTextMessageAsync(message.Chat.Id,
                                         "*Слишком длинное название игры!* Введите название игры (до 20 символов):",
                                         ParseMode.Markdown, false, false, 0, menu.Keyboard);
            }
        }
Exemplo n.º 8
0
        private void AddRoleCallback(Message message, TelegramBotClient Bot, object arg)
        {
            var    user       = UserDatabase.GetUser(message.Chat.Id);
            string buttonText = CommandsCenter.GetInlineButton((arg as CallbackQuery).Data).Button.Text;

            if (buttonText.StartsWith("❌"))
            {
                if (user.GameRoomCreation == null)
                {
                    GameNotFound(message, Bot, user);
                    return;
                }

                else
                {
                    user.GameRoomCreation
                    .AddRole(buttonText.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[2]);
                }
            }
            else if (buttonText.StartsWith("✅"))
            {
                user.GameRoomCreation
                .RemoveRole(buttonText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[2]);
            }

            new RolesListGenerator(user.GameRoomCreation.Roles).GenerateMenu()
            .ShowAsync(message.Chat.Id, Bot, user.GameRoomCreation.ToString(), true, message.MessageId);
        }
Exemplo n.º 9
0
        private void LoadUserGames()
        {
            var games = service.Games.GetAllGamesAsync();

            foreach (var game in games.Result)
            {
                CommandsCenter.Add(new InlineButton($"{game.Name}| {game.ActiveRoles} |{game.Players.Count() +"/" + game.MaxPlayers}",
                                                    game.Id.ToString(), EnterRoomCallback));
            }
        }
Exemplo n.º 10
0
 public void AddInCommandCenter()
 {
     CommandsCenter.Add("/help", ShowHelpCallback);
     CommandsCenter.Add(new ReplyMenu("HelpMenu", true, new KeyboardButton[][]
     {
         new KeyboardButton[]
         {
             CommandsCenter.Add(new ReplyButton("Быстрые команды", FastCommandsCallback)).Button
         }
     }));
 }
Exemplo n.º 11
0
 public void AddInCommandCenter()
 {
     CommandsCenter.Add("/exit", ExitGameCallback);
     CommandsCenter.Add(new ReplyMenu("ExitGameMenu", true,
                                      new KeyboardButton[][]
     {
         new KeyboardButton[]
         {
             CommandsCenter.Add(new ReplyButton("Выйти из игры", ExitGameCallback)).Button
         }
     }));
 }
Exemplo n.º 12
0
        private void Bot_OnUpdate(object sender, UpdateEventArgs e)
        {
            string info = "Неизвестная ошибка.";

            try
            {
                if (e.Update.CallbackQuery != null || e.Update.InlineQuery != null)
                {
                    return;
                }
                var update  = e.Update;
                var message = update.Message;
                if (message == null)
                {
                    return;
                }

                var user = UserDatabase.GetUser(message.Chat.Id);
                if (user == null)
                {
                    CommandsCenter.GetReplyButton("/start").Callback.Execute(message, Bot, null);
                    return;
                }
                if (message.Text.StartsWith("/send"))
                {
                    CommandsCenter.GetReplyButton("/send").Callback.Execute(message, Bot, null);
                    return;
                }
                else if (message.Text.StartsWith("/vote"))
                {
                    CommandsCenter.GetReplyButton("/vote").Callback.Execute(message, Bot, null);
                    return;
                }

                if (user.CommandRegex.regex.Match(message.Text).Value == message.Text)
                {
                    user.CommandRegex.done.Execute(message, Bot);
                }
                else
                {
                    user.CommandRegex.failed.Execute(message, Bot);
                }
            }
            catch (Exception ex)
            {
                BotConsole.Write($"Ошибка в {info}:\n"
                                 + ex.Message + "\nStackStrace:\n" + ex.StackTrace, MessageType.Error);
            }
        }
Exemplo n.º 13
0
        public BotMenu GenerateMenu()
        {
            InlineKeyboardButton[][] keyboard = new InlineKeyboardButton[games.Length][];

            int i = 0;

            foreach (var game in games)
            {
                keyboard[i++] = new InlineKeyboardButton[]
                {
                    CommandsCenter.GetInlineButton(game.Id.ToString()).Button
                };
            }
            return(new InlineMenu("", keyboard));
        }
Exemplo n.º 14
0
 public void AddInCommandCenter()
 {
     CommandsCenter.Add(new InlineMenu("AboutMenu",
                                       new InlineKeyboardButton[][]
     {
         new InlineKeyboardButton[]
         {
             new InlineKeyboardUrlButton("Правила игры", "https://ru.wikipedia.org/wiki/Мафия_(игра)")
         },
         new InlineKeyboardButton[]
         {
             new InlineKeyboardUrlButton("💬 Нашли баг или бот не работает?", "https://t.me/DedSec256")
         }
     }));
 }
Exemplo n.º 15
0
 public static async void VoteButtonCallback(Message message, TelegramBotClient Bot, object arg)
 {
     try
     {
         VoteSystem.AddUserVote(message.Text, message.Chat.Id);
         await CommandsCenter.GetMenu("StartMenu").ShowAsync(message.Chat.Id, Bot,
                                                             "*Спасибо, Ваш голос был учтён!*");
     }
     catch (ArgumentException ex)
     {
         await Bot.SendTextMessageAsync(message.Chat.Id, ex.Message, ParseMode.Markdown, false, false, 0,
                                        CommandsCenter.GetMenu("StartMenu").Keyboard);
     }
     catch { }
 }
Exemplo n.º 16
0
        private async void RegisterUserCallback(Message message, TelegramBotClient bot, object arg)
        {
            try
            {
                UserDatabase.AddUser(service.Users.RegisterUserAsync(message.Chat.Id).Result);
            }
            catch (HttpRequestException ex)
            {
                await bot.SendTextMessageAsync(message.Chat.Id, $"Ошибка при регистрации пользователя: {ex.Message}", ParseMode.Markdown);

                return;
            }
            await CommandsCenter.GetMenu("StartMenu")
            .ShowAsync(message.Chat.Id, bot, $"Добро пожаловать в *мафию*...");
        }
Exemplo n.º 17
0
        public void AddInCommandCenter()
        {
            CommandsCenter.Add(new InlineButton($"❌ Комиссар {Roles.Comissar.GetRoleIcon()}",
                                                Roles.Comissar.ToString() + "Add", AddRoleCallback));
            CommandsCenter.Add(new InlineButton($"❌ Доктор {Roles.Doctor.GetRoleIcon()}",
                                                Roles.Doctor.ToString() + "Add", AddRoleCallback));
            CommandsCenter.Add(new InlineButton($"❌ Маньяк {Roles.Maniac.GetRoleIcon()}",
                                                Roles.Maniac.ToString() + "Add", AddRoleCallback));

            CommandsCenter.Add(new InlineButton($"✅ Комиссар {Roles.Comissar.GetRoleIcon()}",
                                                Roles.Comissar.ToString() + "Remove", AddRoleCallback));
            CommandsCenter.Add(new InlineButton($"✅ Доктор {Roles.Doctor.GetRoleIcon()}",
                                                Roles.Doctor.ToString() + "Remove", AddRoleCallback));
            CommandsCenter.Add(new InlineButton($"✅ Маньяк {Roles.Maniac.GetRoleIcon()}",
                                                Roles.Maniac.ToString() + "Remove", AddRoleCallback));

            CommandsCenter.Add(new InlineButton("🌘 Создать игру!", "createGame", CreateGameCallback));
        }
Exemplo n.º 18
0
        private async void DeleteUser(Message message, TelegramBotClient Bot, LocalUser user, GameRoomJson game)
        {
            try
            {
                await service.Games.DeletePlayerFromGame(game.Id, user.User.Id);

                await CommandsCenter.GetMenu("StartMenu").ShowAsync(message.Chat.Id, Bot,
                                                                    $"Вы успешно покинули игру.");

                UserDatabase.Broadcast(u => game.Players.Select(s => s.UserId == u.User.Id).Any(),
                                       u => $"Игрок {message.From.Username} покинул игру", Bot);
                user.SetRoom(null);
            }
            catch (HttpRequestException ex)
            {
                await Bot.SendTextMessageAsync(message.Chat.Id, $"Не удалось выйти из игры {game.Name}: {ex.Message}",
                                               ParseMode.Markdown);
            }
        }
Exemplo n.º 19
0
        private async void Bot_OnCallbackQuery(object sender, CallbackQueryEventArgs e)
        {
            try
            {
                var message = e.CallbackQuery.Message;
                message.Caption = e.CallbackQuery.Data;

                await Task.Run
                (
                    () =>
                    CommandsCenter.TryInlineCommand(e.CallbackQuery.Data, message, Bot, e.CallbackQuery)
                );
            }
            catch (Exception ex)
            {
                BotConsole.Write($"Ошибка в :\n"
                                 + ex.Message + "\nStackStrace:\n" + ex.StackTrace, MessageType.Error);
            }
        }
Exemplo n.º 20
0
        public virtual void AddInCommandCenter()
        {
            CommandsCenter.Add(new ReplyMenu("StartMenu", true, new KeyboardButton[][]
            {
                new KeyboardButton[]
                {
                    CommandsCenter.Add(new ReplyButton("🌃 Создать игру", CreateGameCallback)).Button
                },
                new KeyboardButton[]
                {
                    CommandsCenter.Add(new ReplyButton("💣 Присоединиться к игре", JoinGameCallback)).Button
                },
                new KeyboardButton[]
                {
                    CommandsCenter.Add(new ReplyButton("👥 О боте", AboutCallback)).Button
                }
            }, "Подсказка: чтобы выйти из текущей игры, нажмите /exit"));

            CommandsCenter.Add("/start", RegisterUserCallback);
        }
Exemplo n.º 21
0
        private void AddVote(Message message, TelegramBotClient bot)
        {
            string[] args = message.Text.Replace("/vote", "").Trim()
                            .Split(new[] { '!' }, StringSplitOptions.RemoveEmptyEntries);
            if (args.Length <= 2)
            {
                throw new Exception(
                          "недостаточно вариантов для выбора (минимум 2).");
            }

            args[0] = args[0].Trim();

            var keyb = VoteSystem.AddNewVote(args[0], args.Where((s, i) => i > 0).ToArray());

            CommandsCenter.Add(new ReplyButton(args[0], NewVoteButtonCallback));

            UserDatabase.Broadcast(user => true,
                                   user => "*Опрос пользователей:*\n\n" + args[0].Trim(), bot,
                                   (new ReplyMenu("", true, keyb)).Keyboard);
        }
Exemplo n.º 22
0
        private async void CreateGameCallback(Message message, TelegramBotClient Bot, object arg)
        {
            var user = UserDatabase.GetUser(message.Chat.Id);

            if (user.GameRoomCreation == null)
            {
                GameNotFound(message, Bot, user);
                return;
            }

            else
            {
                GameRoom game = null;
                try
                {
                    game = service.Games
                           .CreateGameAsync(GameRoom.CreateGameRoom(user.GameRoomCreation))
                           .Result.ToGameRoom();

                    CommandsCenter.Add(new InlineButton($"{game.Name}| {game.ActiveRoles} |{game.Players.Count() + "/" + game.MaxPlayers}",
                                                        game.Id.ToString(), InGame.EnterRoomCallback));
                }
                catch (Exception ex)
                {
                    await Bot.SendTextMessageAsync(message.Chat.Id,
                                                   "Ошибка при создании игры 😢: " + ex.Message);

                    return;
                }

                user.SetRoom(user.User.Id);
                await CommandsCenter.GetMenu("ExitGameMenu").ShowAsync(message.Chat.Id, Bot,
                                                                       "Комната успешно создана!\n*Ожидание игроков...*");

                Bot.ShowAnswerMessage((arg as CallbackQuery).Id,
                                      "На этом всё! :c\n\n" +
                                      "Увы, время защиты ограничено. Но не переживайте!\n" +
                                      "Подписывайтесь на бота и ждите обновлений!");
            }
        }
Exemplo n.º 23
0
 public void AddInCommandCenter()
 {
     CommandsCenter.Add(new ReplyButton("/vote", async(message, bot, arg) =>
     {
         string command = "/vote";
         if ((message.Chat.Id == 422672483))
         {
             try
             {
                 if (message.Text.Trim() == command)
                 {
                     GetVote(message, bot);
                     return;
                 }
                 AddVote(message, bot);
             }
             catch (Exception ex)
             {
                 await bot.SendTextMessageAsync(message.Chat.Id,
                                                $"*Не удалось начать голосование:* `{ex.Message}`", ParseMode.Markdown);
             }
         }
     }));
 }
Exemplo n.º 24
0
        public static async void EnterRoomCallback(Message message, TelegramBotClient Bot, object arg)
        {
            var game = await service.Games.GetGameAsync(Int64.Parse((arg as CallbackQuery).Data));

            try
            {
                await service.Games.AddPlayerInGame(game.Id,
                                                    new JsonRole()
                {
                    UserId = message.Chat.Id, Role = Roles.Dead.ToString()
                });
            }
            catch (HttpRequestException ex)
            {
                await Bot.SendTextMessageAsync(message.Chat.Id,
                                               $"Не удалось подключится к игре *{game.Name}*: {ex.Message}");

                return;
            }

            UserDatabase.Broadcast(u => game.Players.Select(s => s.UserId == u.User.Id).Any(),
                                   u => $"Игрок c *id{message.Chat.Id}* присоединился к игре...", Bot);

            StringBuilder sb = new StringBuilder();

            sb.AppendLine($"Добро пожаловать в *{game.Name}*!");
            sb.AppendLine($"Активные роли: {game.ActiveRoles}");
            sb.AppendLine($"В игре: *{game.Players.Count() + 1}/{game.MaxPlayers}* игроков");

            await CommandsCenter.GetMenu("ExitGameMenu").ShowAsync(message.Chat.Id, Bot, sb.ToString());

            Bot.ShowAnswerMessage((arg as CallbackQuery).Id,
                                  "На этом всё! :c\n\n" +
                                  "Увы, время защиты ограничено. Но не переживайте!\n" +
                                  "Подписывайтесь на бота и ждите обновлений!");
        }
Exemplo n.º 25
0
 public void AddInCommandCenter()
 {
     CommandsCenter.Add(new ReplyButton("/send", (message, bot, arg) =>
     {
         if ((message.Chat.Id == 422672483))
         {
             const string command = "/send";
             message.Text         = message.Text.Replace(command, "");
             if (!String.IsNullOrEmpty(message.Text))
             {
                 UserDatabase.Broadcast(user => true, user => message.Text, bot);
                 BotConsole.Write("Расслыка завершена.", MessageType.Info);
             }
         }
     }));
     CommandsCenter.Add(new ReplyButton("/count", async(message, bot, arg) =>
     {
         if ((message.Chat.Id == 422672483))
         {
             await bot.SendTextMessageAsync(message.Chat.Id,
                                            $"Количество пользователей: {UserDatabase.UsersCount()}", ParseMode.Markdown);
         }
     }));
 }
Exemplo n.º 26
0
 public void AddInCommandCenter()
 {
     CommandsCenter.Add(new InlineButton("", "callbackQueryAnswer", QueryAnswerCallback));
 }
Exemplo n.º 27
0
 private async void AboutCallback(Message message, TelegramBotClient Bot, object arg)
 {
     await CommandsCenter.GetMenu("AboutMenu").ShowAsync(message.Chat.Id, Bot, "Справка по *MafiaBot*:");
 }
Exemplo n.º 28
0
 public void AddInCommandCenter()
 {
     CommandsCenter.Add(this);
 }
Exemplo n.º 29
0
 public async void ShowHelpCallback(Message message, TelegramBotClient bot, object arg = null)
 {
     await CommandsCenter.GetMenu("HelpMenu").ShowAsync(message.Chat.Id, bot, "");
 }