Tigran пре 4 година
родитељ
комит
3b02e83867
35 измењених фајлова са 313 додато и 405 уклоњено
  1. 1 1
      MafiaTelegramBot.sln.DotSettings.user
  2. 1 0
      MafiaTelegramBot/Controllers/RoomController.cs
  3. 10 0
      MafiaTelegramBot/Game/GameRoom.cs
  4. 7 7
      MafiaTelegramBot/Models/Commands/Command.cs
  5. 3 14
      MafiaTelegramBot/Models/Commands/ConnectGameCommand.cs
  6. 3 13
      MafiaTelegramBot/Models/Commands/CreateGameCommand.cs
  7. 2 4
      MafiaTelegramBot/Models/Commands/CustomMessageHandlers/ChangeNicknameCommand.cs
  8. 7 16
      MafiaTelegramBot/Models/Commands/CustomMessageHandlers/CreateRoomCommand.cs
  9. 5 24
      MafiaTelegramBot/Models/Commands/CustomMessageHandlers/EnterPrivateRoomCommand.cs
  10. 6 13
      MafiaTelegramBot/Models/Commands/LeaveCommand.cs
  11. 2 6
      MafiaTelegramBot/Models/Commands/LookPlayersListCommand.cs
  12. 3 16
      MafiaTelegramBot/Models/Commands/RoomSettingsCommand.cs
  13. 2 15
      MafiaTelegramBot/Models/Commands/ShowProfileCommand.cs
  14. 9 32
      MafiaTelegramBot/Models/Commands/StartCommand.cs
  15. 3 8
      MafiaTelegramBot/Models/Inlines/ChangeNameQuery.cs
  16. 3 10
      MafiaTelegramBot/Models/Inlines/ConnectToPrivateRoomQuery.cs
  17. 3 23
      MafiaTelegramBot/Models/Inlines/ConnectToPublicRoomQuery.cs
  18. 4 25
      MafiaTelegramBot/Models/Inlines/ConnectToSelectedRoomQuery.cs
  19. 4 23
      MafiaTelegramBot/Models/Inlines/DecreaseRoomMaxCapacity.cs
  20. 4 24
      MafiaTelegramBot/Models/Inlines/IncreaseRoomMaxCapacityQuery.cs
  21. 6 12
      MafiaTelegramBot/Models/Inlines/MakeExtendedGameQuery.cs
  22. 4 17
      MafiaTelegramBot/Models/Inlines/MakePrivateRoomQuery.cs
  23. 4 17
      MafiaTelegramBot/Models/Inlines/MakePublicRoomQuery.cs
  24. 6 12
      MafiaTelegramBot/Models/Inlines/MakeStandartGameQuery.cs
  25. 2 5
      MafiaTelegramBot/Models/Inlines/MyRolesQuery.cs
  26. 10 3
      MafiaTelegramBot/Models/Inlines/Query.cs
  27. 3 9
      MafiaTelegramBot/Models/Inlines/SettingsQuery.cs
  28. 1 5
      MafiaTelegramBot/Models/Inlines/SettingsRoomQuery.cs
  29. 2 5
      MafiaTelegramBot/Models/Inlines/ShopQuery.cs
  30. 9 2
      MafiaTelegramBot/Models/Replies/Reply.cs
  31. 20 2
      MafiaTelegramBot/Models/UpdateModel.cs
  32. 72 0
      MafiaTelegramBot/Resources/Keyboards.cs
  33. 40 31
      MafiaTelegramBot/Resources/strings.Designer.cs
  34. 14 11
      MafiaTelegramBot/Resources/strings.resx
  35. 38 0
      MafiaTelegramBot/Utilities.cs

+ 1 - 1
MafiaTelegramBot.sln.DotSettings.user

@@ -2,7 +2,7 @@
 	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=MafiaTelegramBot_002Fappsettings/@EntryIndexedValue">True</s:Boolean>
 	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=MafiaTelegramBot_002FResources_002Fcallback/@EntryIndexedValue">False</s:Boolean>
 	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=MafiaTelegramBot_002FResources_002Fkeyboard/@EntryIndexedValue">True</s:Boolean>
-	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=MafiaTelegramBot_002FResources_002Fstrings/@EntryIndexedValue">False</s:Boolean>
+	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=MafiaTelegramBot_002FResources_002Fstrings/@EntryIndexedValue">True</s:Boolean>
 	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=MafiaTelegramBot_002Fstrings/@EntryIndexedValue">True</s:Boolean>
 	
 	<s:Boolean x:Key="/Default/ResxEditorPersonal/Initialized/@EntryValue">True</s:Boolean>

+ 1 - 0
MafiaTelegramBot/Controllers/RoomController.cs

@@ -36,6 +36,7 @@ namespace MafiaTelegramBot.Controllers
                 if (OpenedGames[roomKey].IsFilled()) return ResultCode.RoomIsFilled;
                 if (!await player.SetRoomKey(roomKey)) return ResultCode.UserAlreadyInGame;
                 OpenedGames[roomKey].Players.Add(player.Id, player);
+                await OpenedGames[roomKey].NotifyUserConnect(player);
                 return ResultCode.CodeOk;
             });
         }

+ 10 - 0
MafiaTelegramBot/Game/GameRoom.cs

@@ -1,6 +1,8 @@
 using System.Collections.Generic;
+using System.Linq;
 using System.Threading.Tasks;
 using MafiaTelegramBot.DataBase;
+using MafiaTelegramBot.Models;
 using MafiaTelegramBot.Resources;
 
 namespace MafiaTelegramBot.Game
@@ -35,5 +37,13 @@ namespace MafiaTelegramBot.Game
         {
             return Players.Count == MaxPlayers;
         }
+
+        public async Task NotifyUserConnect(User user)
+        {
+            foreach (var player in Players.Values.Where(player => user.Id != player.Id))
+            {
+                await Bot.SendWithMarkdown2(player.ChatId, $"{strings.entry_another_user} _*{user.NickName}*_");
+            }
+        }
     }
 }

+ 7 - 7
MafiaTelegramBot/Models/Commands/Command.cs

@@ -1,3 +1,4 @@
+#nullable enable
 using System.Collections.Generic;
 using System.Threading.Tasks;
 using MafiaTelegramBot.Models.Commands.CustomMessageHandlers;
@@ -8,7 +9,7 @@ namespace MafiaTelegramBot.Models.Commands
 {
     public abstract class Command : UpdateModel
     {
-        private static Dictionary<string, Command> _customHandlers = new()
+        private static readonly Dictionary<string, Command> CustomHandlers = new()
         {
             {"UsersThatChangesNickname", new ChangeNicknameCommand()},
             {"UsersThatCreatesRoom", new CreateRoomCommand()},
@@ -17,19 +18,18 @@ namespace MafiaTelegramBot.Models.Commands
         public static async Task<Message> Update(Update update)
         {
             var chatId = update.Message.Chat.Id;
+            var userId = update.Message.From.Id;
             await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
             var commands = Bot.Commands;
             var message = update.Message.Text;
             var command = FirstOrDefault(commands, message);
-            if (command != null) return await command.Execute(update);
-            var userId = update.Message.From.Id;
-            
+            if(command != null) return await ((Command?) command.Clone(chatId, userId))!.Execute(update);
             if (Bot.UsersThatChangesNickname.Remove(userId))
-                return await _customHandlers["UsersThatChangesNickname"].Execute(update);
+                return await ((Command?) CustomHandlers["UsersThatChangesNickname"].Clone(chatId, userId))!.Execute(update);
             if (Bot.UsersThatCreatesRoom.ContainsKey(userId))
-                return await _customHandlers["UsersThatCreatesRoom"].Execute(update);
+                return await ((Command?) CustomHandlers["UsersThatCreatesRoom"].Clone(chatId, userId))!.Execute(update);
             if (Bot.UserThatEntersPrivateCode.Remove(userId))
-                return await _customHandlers["UserThatEntersPrivateCode"].Execute(update);
+                return await ((Command?) CustomHandlers["UserThatEntersPrivateCode"].Clone(chatId, userId))!.Execute(update);
             return await Bot.SendWithMarkdown2(chatId, $"{strings.command_not_found} _*\\({message}\\)*_");
         }
     }

+ 3 - 14
MafiaTelegramBot/Models/Commands/ConnectGameCommand.cs

@@ -2,8 +2,6 @@ using System.Threading.Tasks;
 using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
-using Telegram.Bot.Types.ReplyMarkups;
 
 namespace MafiaTelegramBot.Models.Commands
 {
@@ -13,19 +11,10 @@ namespace MafiaTelegramBot.Models.Commands
 
         public override async Task<Message> Execute(Update update)
         {
-            var chatId = update.Message.Chat.Id;
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
-            var userId = update.Message.From.Id;
-            
-            var user = await UserDao.GetUserById(userId);
+            var user = await UserDao.GetUserById(UserId);
             if (user.GetRoomKey() != "")
-                return await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{await user.GetRoomName()}*_");
-            var inlineKeyboard = new InlineKeyboardMarkup(new[]
-            {
-                new[] {InlineKeyboardButton.WithCallbackData(strings.connect_to_public_room, $"{callback.connect_to_public_room}|{userId}")},
-                new[] {InlineKeyboardButton.WithCallbackData(strings.connect_to_private_room, $"{callback.connect_to_private_room}|{userId}")}
-            });
-            return await Bot.SendWithMarkdown2(chatId, strings.choose_type_room, inlineKeyboard);
+                return await Bot.SendWithMarkdown2(ChatId, strings.user_already_in_game);
+            return await Bot.SendWithMarkdown2(ChatId, strings.choose_type_room, Keyboards.ConnectToRoomKeyboard(UserId));
         }
     }
 }

+ 3 - 13
MafiaTelegramBot/Models/Commands/CreateGameCommand.cs

@@ -2,8 +2,6 @@ using System.Threading.Tasks;
 using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
-using Telegram.Bot.Types.ReplyMarkups;
 
 namespace MafiaTelegramBot.Models.Commands
 {
@@ -12,18 +10,10 @@ namespace MafiaTelegramBot.Models.Commands
         protected override string Name => keyboard.create_game;
         public override async Task<Message> Execute(Update update)
         {
-            var chatId = update.Message.Chat.Id;
-            var userId = update.Message.From.Id;
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
-            var user = await UserDao.GetUserById(userId);
+            var user = await UserDao.GetUserById(UserId);
             if (user.GetRoomKey() != "")
-                return await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{await user.GetRoomName()}*_");
-            var inlineKeyboard = new InlineKeyboardMarkup(new[]
-            {
-                new[] {InlineKeyboardButton.WithCallbackData(strings.make_public_room, $"{callback.make_public_room}|{userId}")},
-                new[] {InlineKeyboardButton.WithCallbackData(strings.make_private_room, $"{callback.make_private_room}|{userId}")}
-            });
-            return await Bot.SendWithMarkdown2(chatId, strings.settings_room, inlineKeyboard);
+                return await Bot.SendWithMarkdown2(ChatId, strings.user_already_in_game);
+            return await Bot.SendWithMarkdown2(ChatId, strings.settings_room, Keyboards.MakeRoomKeyboard(UserId));
         }
     }
 }

+ 2 - 4
MafiaTelegramBot/Models/Commands/CustomMessageHandlers/ChangeNicknameCommand.cs

@@ -9,12 +9,10 @@ namespace MafiaTelegramBot.Models.Commands.CustomMessageHandlers
         protected override string Name => "ChangeNicknameCommand";
         public override async Task<Message> Execute(Update update)
         {
-            var userId = update.Message.From.Id;
-            var chatId = update.Message.Chat.Id;
             var newNickname = update.Message.Text;
-            var user = await UserDao.GetUserById(userId);
+            var user = await UserDao.GetUserById(UserId);
             await user.UpdateName(newNickname);
-            return await Bot.SendWithMarkdown2(chatId, $"{strings.name_updated} _*{newNickname}*_");
+            return await Bot.SendWithMarkdown2(ChatId, $"{strings.name_updated} _*{newNickname}*_");
         }
     }
 }

+ 7 - 16
MafiaTelegramBot/Models/Commands/CustomMessageHandlers/CreateRoomCommand.cs

@@ -12,27 +12,18 @@ namespace MafiaTelegramBot.Models.Commands.CustomMessageHandlers
         protected override string Name => "CreateRoomCommand";
         public override async Task<Message> Execute(Update update)
         {
-            var userId = update.Message.From.Id;
-            var chatId = update.Message.Chat.Id;
-            var param = Bot.UsersThatCreatesRoom[userId];
-            Bot.UsersThatCreatesRoom.Remove(userId);
-            var user = await UserDao.GetUserById(userId);
+            var param = Bot.UsersThatCreatesRoom[UserId];
+            Bot.UsersThatCreatesRoom.Remove(UserId);
+            var user = await UserDao.GetUserById(UserId);
             var roomName = update.Message.Text;
             var resultCode = param[0] == "public"
                 ? await RoomController.CreateNewGame(user, roomName, param[1] == callback.extended)
                 : await RoomController.CreateNewGame(user, roomName, param[1] == callback.extended, RoomEncrypter.Encrypt(roomName));
-            var result = resultCode switch
-            {
-                ResultCode.CodeOk => await Bot.SendWithMarkdown2(chatId, $"{strings.room_with_name} _*{roomName}*_ {strings.was_created}", Keyboards.OwnerGameMenu),
-                ResultCode.UserAlreadyInGame => await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{await user.GetRoomName()}*_"),
-                ResultCode.GameAlreadyExists => await Bot.SendWithMarkdown2(chatId, $"{strings.room} _*{roomName}*_ {strings.already_exists}"),
-                _ => await Bot.SendWithMarkdown2(chatId, strings.unexpected_error)
-            };
+            var result = resultCode == ResultCode.CodeOk
+                ? await Bot.SendWithMarkdown2(ChatId, $"{strings.room_with_name} _*{roomName}*_ {strings.was_created}", Keyboards.OwnerGameMenu)
+                : await Utilities.GetResultCodeMessage(resultCode, ChatId);
             if (resultCode == ResultCode.CodeOk && param[0] == "private")
-            {
-                await Bot.SendWithMarkdown2(chatId,
-                    $"{strings.secret_key_is} _*{roomName}*_: ```{RoomEncrypter.NameToCode(roomName)}```");
-            }
+                await Bot.SendWithMarkdown2(ChatId, $"{strings.secret_key_is} _*{roomName}*_: ```{RoomEncrypter.NameToCode(roomName)}```");
             return result;
         }
     }

+ 5 - 24
MafiaTelegramBot/Models/Commands/CustomMessageHandlers/EnterPrivateRoomCommand.cs

@@ -1,4 +1,3 @@
-using System.Linq;
 using System.Threading.Tasks;
 using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.DataBase;
@@ -12,31 +11,13 @@ namespace MafiaTelegramBot.Models.Commands.CustomMessageHandlers
         protected override string Name => "EnterPrivateRoomCommand";
         public override async Task<Message> Execute(Update update)
         {
-            var userId = update.Message.From.Id;
-            var chatId = update.Message.Chat.Id;
-            var user = await UserDao.GetUserById(userId);
+            var user = await UserDao.GetUserById(UserId);
             var roomKey = update.Message.Text;
             var resultCode = await RoomController.ConnectToGame(user, roomKey);
-            switch (resultCode)
-            {
-                case ResultCode.CodeOk:
-                {
-                    var users = await RoomController.GetPlayers(roomKey);
-                    foreach (var player in users.Where(player => userId != player.Id))
-                    {
-                        await Bot.SendWithMarkdown2(player.ChatId, $"{strings.entry_another_user} _*{user.NickName}*_");
-                    }
-                    return await Bot.SendWithMarkdown2(chatId, strings.successful_entry_into_room, Keyboards.PlayerGameMenu);
-                }
-                case ResultCode.RoomIsFilled:
-                    return await Bot.SendWithMarkdown2(chatId, strings.room_is_filled);
-                case ResultCode.UserAlreadyInGame:
-                    return await Bot.SendWithMarkdown2(chatId, strings.user_already_in_game);
-                case ResultCode.RoomDoesNotExist:
-                    return await Bot.SendWithMarkdown2(chatId, strings.room_does_not_exists);
-                default:
-                    return await Bot.SendWithMarkdown2(chatId, strings.unexpected_error);
-            }
+            var result = resultCode == ResultCode.CodeOk
+                ? Bot.SendWithMarkdown2(ChatId, strings.successful_entry_into_room, Keyboards.PlayerGameMenu)
+                : Utilities.GetResultCodeMessage(resultCode, ChatId);
+            return await result;
         }
     }
 }

+ 6 - 13
MafiaTelegramBot/Models/Commands/LeaveCommand.cs

@@ -3,28 +3,21 @@ using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
 
 namespace MafiaTelegramBot.Models.Commands
 {
     public class LeaveCommand : Command
     {
         protected override string Name => keyboard.leave;
+
         public override async Task<Message> Execute(Update update)
         {
-            var chatId = update.Message.Chat.Id;
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
-
-            var userId = update.Message.From.Id;
-            var user = await UserDao.GetUserById(userId);
+            var user = await UserDao.GetUserById(UserId);
             var roomName = await user.GetRoomName();
-            var result = await RoomController.LeaveFromGame(user);
-            return result switch
-            {
-                ResultCode.CodeOk => await Bot.SendWithMarkdown2(chatId, $"{strings.leave_from_game} _*{roomName}*_", Keyboards.MainMenu),
-                ResultCode.UserNotInGame => await Bot.SendWithMarkdown2(chatId, strings.not_in_game),
-                _ => await Bot.SendWithMarkdown2(chatId, strings.unexpected_error)
-            };
+            var resultCode = await RoomController.LeaveFromGame(user);
+            return resultCode == ResultCode.CodeOk
+                ? await Bot.SendWithMarkdown2(ChatId, $"{strings.leave_from_game} _*{roomName}*_", Keyboards.MainMenu)
+                : await Utilities.GetResultCodeMessage(resultCode, ChatId);
         }
     }
 }

+ 2 - 6
MafiaTelegramBot/Models/Commands/LookPlayersListCommand.cs

@@ -4,7 +4,6 @@ using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
 
 namespace MafiaTelegramBot.Models.Commands
 {
@@ -14,17 +13,14 @@ namespace MafiaTelegramBot.Models.Commands
         
         public override async Task<Message> Execute(Update update)
         {
-            var chatId = update.Message.Chat.Id;
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
-            var userId = update.Message.From.Id;
-            var user = await UserDao.GetUserById(userId);
+            var user = await UserDao.GetUserById(UserId);
             var roomKey = user.GetRoomKey();
             var users = await RoomController.GetPlayers(roomKey);
             var list = users.Count > 1
                 ? users.Where(player => !player.Equals(user))
                     .Aggregate(strings.users_list, (current, player) => current + $"\n \n@{player.Username}\n{player.NickName}")
                 : strings.users_list_empty;
-            return await Bot.SendWithMarkdown2(chatId, list);
+            return await Bot.SendWithMarkdown2(ChatId, list);
         }
     }
 }

+ 3 - 16
MafiaTelegramBot/Models/Commands/RoomSettingsCommand.cs

@@ -3,33 +3,20 @@ using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.ReplyMarkups;
 
 namespace MafiaTelegramBot.Models.Commands
 {
-    public class RoomSettingsCommand:Command
+    public class RoomSettingsCommand : Command
     {
         protected override string Name => keyboard.room_settings;
         public override async Task<Message> Execute(Update update)
         {
-            var chatId = update.Message.Chat.Id;
-            var userId = update.Message.From.Id;
-
-            var user = await UserDao.GetUserById(userId);
+            var user = await UserDao.GetUserById(UserId);
             var roomKey = user.GetRoomKey();
             var room = await RoomController.GetRoom(roomKey);
             var roomMaxCapacity = room.MaxPlayers;
-            
             var message = $"{strings.max_capacity_message}: {roomMaxCapacity}";
-            
-            var inlineKeyboard = new InlineKeyboardMarkup(new[]
-            {
-                new[] {InlineKeyboardButton.WithCallbackData(strings.decrease_number_of_players, $"{callback.decrease_number_of_players}|{userId}"),
-                    InlineKeyboardButton.WithCallbackData(strings.increase_number_of_players, $"{callback.increase_number_of_players}|{userId}")}
-            });
-
-            var reply = await Bot.SendWithMarkdown2(chatId, message, inlineKeyboard);
-            return reply;
+            return await Bot.SendWithMarkdown2(ChatId, message, Keyboards.IncreaseDecreaseKeyboard(UserId));
         }
     }
 }

+ 2 - 15
MafiaTelegramBot/Models/Commands/ShowProfileCommand.cs

@@ -3,8 +3,6 @@ using System.Threading.Tasks;
 using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
-using Telegram.Bot.Types.ReplyMarkups;
 
 namespace MafiaTelegramBot.Models.Commands
 {
@@ -14,25 +12,14 @@ namespace MafiaTelegramBot.Models.Commands
 
         public override async Task<Message> Execute(Update update)
         {
-            var chatId = update.Message.Chat.Id;
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
-            var userId = update.Message.From.Id;
-            var user = await UserDao.GetUserById(userId);
+            var user = await UserDao.GetUserById(UserId);
             var winRate = user.Games < 1 ? 0.0 : Convert.ToDouble(user.Wins) / Convert.ToDouble(user.Games);
             var message =
                 $"__*{strings.statistics_for} _{user.NickName}_*__\n" +
                 $"{strings.games_count} {user.Games}\n" +
                 $"{strings.wins_count} {user.Wins}\n" +
                 $"{strings.winrate} {winRate}%\n";
-            var inlineKeyboard = new InlineKeyboardMarkup(new[]
-            {
-                new[] {
-                    InlineKeyboardButton.WithCallbackData(strings.shop, $"{callback.shop}|{userId}"),
-                    InlineKeyboardButton.WithCallbackData(strings.my_roles, $"{callback.my_roles}|{userId}")
-                },
-                new[] {InlineKeyboardButton.WithCallbackData(strings.settings, $"{callback.settings_profile}|{userId}")}
-            });
-            return await Bot.SendWithMarkdown2(chatId, message, inlineKeyboard);
+            return await Bot.SendWithMarkdown2(ChatId, message, Keyboards.ProfileKeyboard(UserId));
         }
     }
 }

+ 9 - 32
MafiaTelegramBot/Models/Commands/StartCommand.cs

@@ -2,7 +2,6 @@ using System.Threading.Tasks;
 using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
 
 namespace MafiaTelegramBot.Models.Commands
 {
@@ -12,44 +11,22 @@ namespace MafiaTelegramBot.Models.Commands
 
         public override async Task<Message> Execute(Update update)
         {
-            var chatId = update.Message.Chat.Id;
-            var userId = update.Message.From.Id;
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
-            if (await UserDao.UserExists(userId))
+            if (await UserDao.UserExists(UserId))
             {
-                var player = await UserDao.GetUserById(userId);
+                var player = await UserDao.GetUserById(UserId);
                 if (player.GetRoomKey() != "")
-                    return await Bot.SendWithMarkdown2(chatId, $"{strings.prefer_leave_from_room} {await player.GetRoomName()}");
-                return await Bot.SendWithMarkdown2(chatId, strings.start_message, Keyboards.MainMenu);
+                    return await Bot.SendWithMarkdown2(ChatId, $"{strings.prefer_leave_from_room} {await player.GetRoomName()}");
+                return await Bot.SendWithMarkdown2(ChatId, strings.start_message, Keyboards.MainMenu);
             } 
-            var username = await EscapeSpecific(update.Message.From.Username);
-            var firstName = await EscapeSpecific(update.Message.From.FirstName);
-            var lastName = await EscapeSpecific(update.Message.From.LastName);
+            var username = await Utilities.EscapeSpecific(update.Message.From.Username);
+            var firstName = await Utilities.EscapeSpecific(update.Message.From.FirstName);
+            var lastName = await Utilities.EscapeSpecific(update.Message.From.LastName);
             var user = new DataBase.User
             {
-                Id = userId, ChatId = chatId, Username = username, NickName =  $"{firstName} {lastName}"
+                Id = UserId, ChatId = ChatId, Username = username, NickName =  $"{firstName} {lastName}"
             };
             await UserDao.Update(user);
-            return await Bot.SendWithMarkdown2(chatId, strings.start_message, Keyboards.MainMenu);
-        }
-
-        private static async Task<string> EscapeSpecific(string src)
-        {
-            var result = src != null
-                ? await Task.Run(()=> src
-                    .Replace(".", "\\.")
-                    .Replace("`", "\\`")
-                    .Replace("@", "\\@")
-                    .Replace("#", "\\#")
-                    .Replace("!", "\\!")
-                    .Replace("*", "\\*")
-                    .Replace("_", "\\_")
-                    .Replace("'", "\\'")
-                    .Replace("~", "\\~")
-                    .Replace("[", "\\[")
-                )
-                :"";
-            return result;
+            return await Bot.SendWithMarkdown2(ChatId, strings.start_message, Keyboards.MainMenu);
         }
     }
 }

+ 3 - 8
MafiaTelegramBot/Models/Inlines/ChangeNameQuery.cs

@@ -1,7 +1,6 @@
 using System.Threading.Tasks;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
 
 namespace MafiaTelegramBot.Models.Inlines
 {
@@ -11,13 +10,9 @@ namespace MafiaTelegramBot.Models.Inlines
 
         public override async Task<Message> Execute(Update update)
         {
-            await DeletePreviousMessage(update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId);
-            var chatId = update.CallbackQuery.Message.Chat.Id;
-            var data = update.CallbackQuery.Data;
-            var userId = long.Parse(data.Split('|')[1]);
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
-            Bot.UsersThatChangesNickname.Add(userId);
-            return await Bot.SendWithMarkdown2(chatId, strings.enter_your_name);
+            await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
+            Bot.UsersThatChangesNickname.Add(UserId);
+            return await Bot.SendWithMarkdown2(ChatId, strings.enter_your_name);
         }
     }
 }

+ 3 - 10
MafiaTelegramBot/Models/Inlines/ConnectToPrivateRoomQuery.cs

@@ -1,7 +1,6 @@
 using System.Threading.Tasks;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
 
 namespace MafiaTelegramBot.Models.Inlines
 {
@@ -10,15 +9,9 @@ namespace MafiaTelegramBot.Models.Inlines
         protected override string Name => callback.connect_to_private_room;
         public override async Task<Message> Execute(Update update)
         {
-            await DeletePreviousMessage(update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId);
-            var chatId = update.CallbackQuery.Message.Chat.Id;
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
-            var data = update.CallbackQuery.Data;
-            var param = data.Split('|');
-            var userId = long.Parse(param[1]);
-            
-            Bot.UserThatEntersPrivateCode.Add(userId);
-            return await Bot.SendWithMarkdown2(chatId, strings.enter_private_code);
+            await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
+            Bot.UserThatEntersPrivateCode.Add(UserId);
+            return await Bot.SendWithMarkdown2(ChatId, strings.enter_private_code);
         }
     }
 }

+ 3 - 23
MafiaTelegramBot/Models/Inlines/ConnectToPublicRoomQuery.cs

@@ -1,10 +1,7 @@
 using System.Threading.Tasks;
 using MafiaTelegramBot.Controllers;
-using MafiaTelegramBot.Game;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
-using Telegram.Bot.Types.ReplyMarkups;
 
 namespace MafiaTelegramBot.Models.Inlines
 {
@@ -13,27 +10,10 @@ namespace MafiaTelegramBot.Models.Inlines
         protected override string Name => callback.connect_to_public_room;
         public override async Task<Message> Execute(Update update)
         {
-            await DeletePreviousMessage(update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId);
-            var chatId = update.CallbackQuery.Message.Chat.Id;
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
-            var data = update.CallbackQuery.Data;
-            var param = data.Split('|');
-            var userId = long.Parse(param[1]);
+            await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
             var rooms = await RoomController.GetPublicRooms();
-            if (rooms.Count == 0) return await Bot.SendWithMarkdown2(chatId, strings.public_rooms_are_not_exist);
-            var inlineButtons = new InlineKeyboardButton[rooms.Count];
-            for (var i = 0; i < rooms.Count && i < Constants.MAX_SHOWING_ROOMS; ++i) // buttons
-            {
-                inlineButtons[i] = new InlineKeyboardButton
-                {
-                    Text =
-                        $"{rooms[i].RoomName} ({rooms[i].Players.Values.Count.ToString()}/{rooms[i].MaxPlayers.ToString()})",
-                    CallbackData = $"{callback.connect_to_selected_room}|{userId}|{RoomEncrypter.FullToShort(rooms[i].RoomName)}"
-                };
-            }
-
-            var inlineKeyboard = new InlineKeyboardMarkup(inlineButtons);
-            return await Bot.SendWithMarkdown2(chatId, strings.rooms, inlineKeyboard);
+            if (rooms.Count == 0) return await Bot.SendWithMarkdown2(ChatId, strings.public_rooms_are_not_exist);
+            return await Bot.SendWithMarkdown2(ChatId, strings.rooms, Keyboards.RoomsKeyboard(rooms, UserId));
         }
     }
 }

+ 4 - 25
MafiaTelegramBot/Models/Inlines/ConnectToSelectedRoomQuery.cs

@@ -1,11 +1,9 @@
-using System.Linq;
 using System.Threading.Tasks;
 using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.Game;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
 
 namespace MafiaTelegramBot.Models.Inlines
 {
@@ -14,34 +12,15 @@ namespace MafiaTelegramBot.Models.Inlines
         protected override string Name => callback.connect_to_selected_room;
         public override async Task<Message> Execute(Update update)
         {
-            await DeletePreviousMessage(update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId);
-            var chatId = update.CallbackQuery.Message.Chat.Id;
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
+            await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
             var data = update.CallbackQuery.Data;
             var param = data.Split('|');
-            var userId = long.Parse(param[1]);
             var shortName = param[2];
             var roomName = RoomEncrypter.ShortToFull(shortName);
-            var user = await UserDao.GetUserById(userId);
+            var user = await UserDao.GetUserById(UserId);
             var resultCode = await RoomController.ConnectToGame(user, roomName);
-            switch (resultCode)
-            {
-                case ResultCode.CodeOk:
-                {
-                    var users = await RoomController.GetPlayers(roomName);
-                    foreach (var player in users.Where(player => userId != player.Id))
-                    {
-                        await Bot.SendWithMarkdown2(player.ChatId, $"{strings.entry_another_user} _*{user.NickName}*_");
-                    }
-                    return await Bot.SendWithMarkdown2(chatId, strings.successful_entry_into_room, Keyboards.PlayerGameMenu);
-                }
-                case ResultCode.RoomIsFilled:
-                    return await Bot.SendWithMarkdown2(chatId, strings.room_is_filled);
-                case ResultCode.UserAlreadyInGame:
-                    return await Bot.SendWithMarkdown2(chatId, strings.user_already_in_game);
-                default:
-                    return await Bot.SendWithMarkdown2(chatId, strings.unexpected_error);
-            }
+            if (resultCode != ResultCode.CodeOk) return await Utilities.GetResultCodeMessage(resultCode, ChatId);
+            return await Bot.SendWithMarkdown2(ChatId, strings.successful_entry_into_room, Keyboards.PlayerGameMenu);
         }
     }
 }

+ 4 - 23
MafiaTelegramBot/Models/Inlines/DecreaseRoomMaxCapacity.cs

@@ -3,7 +3,6 @@ using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.ReplyMarkups;
 
 namespace MafiaTelegramBot.Models.Inlines
 {
@@ -13,30 +12,12 @@ namespace MafiaTelegramBot.Models.Inlines
         public override async Task<Message> Execute(Update update)
         {
             var messageId = update.CallbackQuery.Message.MessageId;
-            var chatId = update.CallbackQuery.Message.Chat.Id;
-
-            var data = update.CallbackQuery.Data;
-            var userId = long.Parse(data.Split('|')[1]);
-
-            var user = await UserDao.GetUserById(userId);
+            var user = await UserDao.GetUserById(UserId);
             var roomKey = user.GetRoomKey();
             var room = await RoomController.GetRoom(roomKey);
-            var roomMaxCapacity = room.MaxPlayers;
-            
-            if (roomMaxCapacity > Constants.PLAYER_LIMITS_MIN)
-            {
-                roomMaxCapacity = --room.MaxPlayers;
-            }
-            
-            var message = $"{strings.max_capacity_message}: {roomMaxCapacity}";
-            
-            var inlineKeyboard = new InlineKeyboardMarkup(new[]
-            {
-                new[] {InlineKeyboardButton.WithCallbackData(strings.decrease_number_of_players, $"{callback.decrease_number_of_players}|{userId}"),
-                    InlineKeyboardButton.WithCallbackData(strings.increase_number_of_players, $"{callback.increase_number_of_players}|{userId}")}
-            });
-            
-            return await Bot.Get().EditMessageTextAsync(chatId, messageId, message, replyMarkup:inlineKeyboard);
+            if (room.MaxPlayers > Constants.PLAYER_LIMITS_MIN) --room.MaxPlayers;
+            var message = $"{strings.max_capacity_message}: {room.MaxPlayers}";
+            return await Bot.Get().EditMessageTextAsync(ChatId, messageId, message, replyMarkup:Keyboards.IncreaseDecreaseKeyboard(UserId));
         }
     }
 }

+ 4 - 24
MafiaTelegramBot/Models/Inlines/IncreaseRoomMaxCapacityQuery.cs

@@ -3,7 +3,6 @@ using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.ReplyMarkups;
 
 namespace MafiaTelegramBot.Models.Inlines
 {
@@ -14,31 +13,12 @@ namespace MafiaTelegramBot.Models.Inlines
         public override async Task<Message> Execute(Update update)
         {
             var messageId = update.CallbackQuery.Message.MessageId;
-            var chatId = update.CallbackQuery.Message.Chat.Id;
-
-            var data = update.CallbackQuery.Data;
-            var userId = long.Parse(data.Split('|')[1]);
-
-            var user = await UserDao.GetUserById(userId);
+            var user = await UserDao.GetUserById(UserId);
             var roomKey = user.GetRoomKey();
             var room = await RoomController.GetRoom(roomKey);
-            var roomMaxCapacity = room.MaxPlayers;
-
-
-            if (roomMaxCapacity < Constants.PLAYER_LIMITS_MAX)
-            {
-                roomMaxCapacity = ++room.MaxPlayers;
-            }
-            
-            var message = $"{strings.max_capacity_message}: {roomMaxCapacity}";
-            
-            var inlineKeyboard = new InlineKeyboardMarkup(new[]
-            {
-                new[] {InlineKeyboardButton.WithCallbackData(strings.decrease_number_of_players, $"{callback.decrease_number_of_players}|{userId}"),
-                    InlineKeyboardButton.WithCallbackData(strings.increase_number_of_players, $"{callback.increase_number_of_players}|{userId}")}
-            });
-            
-            return await Bot.Get().EditMessageTextAsync(chatId, messageId, message, replyMarkup:inlineKeyboard);
+            if (room.MaxPlayers < Constants.PLAYER_LIMITS_MAX) ++room.MaxPlayers;
+            var message = $"{strings.max_capacity_message}: {room.MaxPlayers}";
+            return await Bot.Get().EditMessageTextAsync(ChatId, messageId, message, replyMarkup:Keyboards.IncreaseDecreaseKeyboard(UserId));
         }
     }
 }

+ 6 - 12
MafiaTelegramBot/Models/Inlines/MakeExtendedGameQuery.cs

@@ -2,7 +2,6 @@ using System.Threading.Tasks;
 using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
 
 namespace MafiaTelegramBot.Models.Inlines
 {
@@ -11,20 +10,15 @@ namespace MafiaTelegramBot.Models.Inlines
         protected override string Name => callback.extended;
         public override async Task<Message> Execute(Update update)
         {
-            await DeletePreviousMessage(update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId);
-            var chatId = update.CallbackQuery.Message.Chat.Id;
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
+            await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
             var data = update.CallbackQuery.Data;
             var param = data.Split('|');
-            var userId = long.Parse(param[1]);
-            var user = await UserDao.GetUserById(userId);
+            var user = await UserDao.GetUserById(UserId);
             if (user.GetRoomKey() != "")
-                return await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{await user.GetRoomName()}*_");
-            if (Bot.UsersThatCreatesRoom.TryAdd(userId, new[] {param[2], Name}))
-            {
-                Bot.UsersThatCreatesRoom[userId] = new[] {param[2], Name};
-            }
-            return await Bot.SendWithMarkdown2(chatId, strings.enter_room_name);
+                return await Bot.SendWithMarkdown2(ChatId, strings.user_already_in_game);
+            if (Bot.UsersThatCreatesRoom.TryAdd(UserId, new[] {param[2], Name}))
+                Bot.UsersThatCreatesRoom[UserId] = new[] {param[2], Name};
+            return await Bot.SendWithMarkdown2(ChatId, strings.enter_room_name);
         }
     }
 }

+ 4 - 17
MafiaTelegramBot/Models/Inlines/MakePrivateRoomQuery.cs

@@ -2,8 +2,6 @@ using System.Threading.Tasks;
 using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
-using Telegram.Bot.Types.ReplyMarkups;
 
 namespace MafiaTelegramBot.Models.Inlines
 {
@@ -12,22 +10,11 @@ namespace MafiaTelegramBot.Models.Inlines
         protected override string Name => callback.make_private_room;
         public override async Task<Message> Execute(Update update)
         {
-            await DeletePreviousMessage(update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId);
-            var chatId = update.CallbackQuery.Message.Chat.Id;
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
-            var data = update.CallbackQuery.Data;
-            var userId = long.Parse(data.Split('|')[1]);
-            var user = await UserDao.GetUserById(userId);
+            await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
+            var user = await UserDao.GetUserById(UserId);
             if (user.GetRoomKey() != "")
-                return await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{await user.GetRoomName()}*_");
-            var inlineKeyboard = new InlineKeyboardMarkup(new[]
-            {
-                new[] {
-                    InlineKeyboardButton.WithCallbackData(strings.standart, $"{callback.standart}|{userId}|private"),
-                    InlineKeyboardButton.WithCallbackData(strings.extended, $"{callback.extended}|{userId}|private")
-                }
-            });
-            return await Bot.SendWithMarkdown2(chatId, strings.choose_game_type, inlineKeyboard);
+                return await Bot.SendWithMarkdown2(ChatId, strings.user_already_in_game);
+            return await Bot.SendWithMarkdown2(ChatId, strings.choose_game_type, Keyboards.StandartExtendedKeyboard(UserId, "private"));
         }
     }
 }

+ 4 - 17
MafiaTelegramBot/Models/Inlines/MakePublicRoomQuery.cs

@@ -2,8 +2,6 @@ using System.Threading.Tasks;
 using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
-using Telegram.Bot.Types.ReplyMarkups;
 
 namespace MafiaTelegramBot.Models.Inlines
 {
@@ -12,22 +10,11 @@ namespace MafiaTelegramBot.Models.Inlines
         protected override string Name => callback.make_public_room;
         public override async Task<Message> Execute(Update update)
         { 
-            await DeletePreviousMessage(update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId);
-            var chatId = update.CallbackQuery.Message.Chat.Id;
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
-            var data = update.CallbackQuery.Data;
-            var userId = long.Parse(data.Split('|')[1]);
-            var user = await UserDao.GetUserById(userId);
+            await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
+            var user = await UserDao.GetUserById(UserId);
             if (user.GetRoomKey() != "")
-                return await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{await user.GetRoomName()}*_");
-            var inlineKeyboard = new InlineKeyboardMarkup(new[]
-            {
-                new[] {
-                    InlineKeyboardButton.WithCallbackData(strings.standart, $"{callback.standart}|{userId}|public"),
-                    InlineKeyboardButton.WithCallbackData(strings.extended, $"{callback.extended}|{userId}|public")
-                }
-            });
-            return await Bot.SendWithMarkdown2(chatId, strings.choose_game_type, inlineKeyboard);
+                return await Bot.SendWithMarkdown2(ChatId, strings.user_already_in_game);
+            return await Bot.SendWithMarkdown2(ChatId, strings.choose_game_type, Keyboards.StandartExtendedKeyboard(UserId, "public"));
         }
     }
 }

+ 6 - 12
MafiaTelegramBot/Models/Inlines/MakeStandartGameQuery.cs

@@ -2,7 +2,6 @@ using System.Threading.Tasks;
 using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
 
 namespace MafiaTelegramBot.Models.Inlines
 {
@@ -11,20 +10,15 @@ namespace MafiaTelegramBot.Models.Inlines
         protected override string Name => callback.standart;
         public override async Task<Message> Execute(Update update)
         {
-            await DeletePreviousMessage(update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId);
-            var chatId = update.CallbackQuery.Message.Chat.Id;
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
+            await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
             var data = update.CallbackQuery.Data;
             var param = data.Split('|');
-            var userId = long.Parse(param[1]);
-            var user = await UserDao.GetUserById(userId);
+            var user = await UserDao.GetUserById(UserId);
             if (user.GetRoomKey() != "")
-                return await Bot.SendWithMarkdown2(chatId, $"{strings.user_already_playing} _*{await user.GetRoomName()}*_");
-            if (Bot.UsersThatCreatesRoom.TryAdd(userId, new[] {param[2], Name}))
-            {
-                Bot.UsersThatCreatesRoom[userId] = new[] {param[2], Name};
-            }
-            return await Bot.SendWithMarkdown2(chatId, strings.enter_room_name);
+                return await Bot.SendWithMarkdown2(ChatId, strings.user_already_in_game);
+            if (Bot.UsersThatCreatesRoom.TryAdd(UserId, new[] {param[2], Name}))
+                Bot.UsersThatCreatesRoom[UserId] = new[] {param[2], Name};
+            return await Bot.SendWithMarkdown2(ChatId, strings.enter_room_name);
         }
     }
 }

+ 2 - 5
MafiaTelegramBot/Models/Inlines/MyRolesQuery.cs

@@ -1,7 +1,6 @@
 using System.Threading.Tasks;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
 
 namespace MafiaTelegramBot.Models.Inlines
 {
@@ -11,10 +10,8 @@ namespace MafiaTelegramBot.Models.Inlines
 
         public override async Task<Message> Execute(Update update)
         {
-            await DeletePreviousMessage(update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId);
-            var chatId = update.CallbackQuery.Message.Chat.Id;
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
-            return await Bot.SendWithMarkdown2(chatId, strings.my_roles);
+            await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
+            return await Bot.SendWithMarkdown2(ChatId, strings.my_roles);
         }
     }
 }

+ 10 - 3
MafiaTelegramBot/Models/Inlines/Query.cs

@@ -1,5 +1,7 @@
+#nullable enable
 using System.Threading.Tasks;
 using Telegram.Bot.Types;
+using Telegram.Bot.Types.Enums;
 
 namespace MafiaTelegramBot.Models.Inlines
 {
@@ -9,12 +11,17 @@ namespace MafiaTelegramBot.Models.Inlines
         {
             return command == Name;
         }
-        public static Task Update(Update update)
+        public static async Task<Message> Update(Update update)
         {
+            var chatId = update.CallbackQuery.Message.Chat.Id;
+            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
             var data = update.CallbackQuery.Data;
-            var command = data.Split('|')[0];
+            var userId = long.Parse(data.Split('|')[1]);
+            var query = data.Split('|')[0];
             var queries = Bot.Queries;
-            return FirstOrDefault(queries, command).Execute(update);
+            var command = FirstOrDefault(queries, query);
+            if(command != null) return await ((Query?) command.Clone(chatId, userId))!.Execute(update);
+            return await Bot.SendWithMarkdown2(chatId, $"{strings.command_not_found} _*\\({data}\\)*_");
         }
     }
 }

+ 3 - 9
MafiaTelegramBot/Models/Inlines/SettingsQuery.cs

@@ -2,8 +2,6 @@ using System.Threading.Tasks;
 using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
-using Telegram.Bot.Types.ReplyMarkups;
 
 namespace MafiaTelegramBot.Models.Inlines
 {
@@ -13,13 +11,9 @@ namespace MafiaTelegramBot.Models.Inlines
 
         public override async Task<Message> Execute(Update update)
         {
-            await DeletePreviousMessage(update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId);
-            var chatId = update.CallbackQuery.Message.Chat.Id;
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
-            var userId = update.CallbackQuery.From.Id;
-            var user = await UserDao.GetUserById(userId);
-            var inlineKeyboard = new InlineKeyboardMarkup(InlineKeyboardButton.WithCallbackData(strings.change_name, $"{callback.change_name}|{userId}"));
-            return await Bot.SendWithMarkdown2(chatId, $"{strings.your_name} {user.NickName}", inlineKeyboard);
+            await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
+            var user = await UserDao.GetUserById(UserId);
+            return await Bot.SendWithMarkdown2(ChatId, $"{strings.your_name} {user.NickName}", Keyboards.ChangeNameKeyboard(UserId));
         }
     }
 }

+ 1 - 5
MafiaTelegramBot/Models/Inlines/SettingsRoomQuery.cs

@@ -1,7 +1,6 @@
 using System.Threading.Tasks;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
 
 namespace MafiaTelegramBot.Models.Inlines
 {
@@ -10,10 +9,7 @@ namespace MafiaTelegramBot.Models.Inlines
         protected override string Name => callback.settings_room;
         public override async Task<Message> Execute(Update update)
         {
-            var chatId = update.CallbackQuery.Message.Chat.Id;
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
-            return await Bot.SendWithMarkdown2(chatId, strings.settings_room);
+            return await Bot.SendWithMarkdown2(ChatId, strings.settings_room);
         }
-
     }
 }

+ 2 - 5
MafiaTelegramBot/Models/Inlines/ShopQuery.cs

@@ -1,7 +1,6 @@
 using System.Threading.Tasks;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
 
 namespace MafiaTelegramBot.Models.Inlines
 {
@@ -11,10 +10,8 @@ namespace MafiaTelegramBot.Models.Inlines
 
         public override async Task<Message> Execute(Update update)
         {
-            await DeletePreviousMessage(update.CallbackQuery.Message.Chat.Id, update.CallbackQuery.Message.MessageId);
-            var chatId = update.CallbackQuery.Message.Chat.Id;
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
-            return await Bot.SendWithMarkdown2(chatId, strings.shop);
+            await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
+            return await Bot.SendWithMarkdown2(ChatId, strings.shop);
         }
     }
 }

+ 9 - 2
MafiaTelegramBot/Models/Replies/Reply.cs

@@ -1,15 +1,22 @@
+#nullable enable
 using System.Threading.Tasks;
 using Telegram.Bot.Types;
+using Telegram.Bot.Types.Enums;
 
 namespace MafiaTelegramBot.Models.Replies
 {
     public abstract class Reply : UpdateModel
     {
-        public static Task Update(Update update)
+        public static async Task<Message> Update(Update update)
         {
             var commands = Bot.Replies;
             var message = update.Message.ReplyToMessage.Text;
-            return FirstOrDefault(commands, message).Execute(update);
+            var userId = update.Message.From.Id;
+            var chatId = update.Message.Chat.Id;
+            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
+            var command = FirstOrDefault(commands, message);
+            if(command != null) return await ((Reply?) command.Clone(chatId, userId))!.Execute(update);
+            return await Bot.SendWithMarkdown2(chatId, $"{strings.command_not_found} _*\\({message}\\)*_");
         }
     }
 }

+ 20 - 2
MafiaTelegramBot/Models/UpdateModel.cs

@@ -1,3 +1,5 @@
+#nullable enable
+using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Threading.Tasks;
@@ -5,9 +7,11 @@ using Telegram.Bot.Types;
 
 namespace MafiaTelegramBot.Models
 {
-    public abstract class UpdateModel
+    public abstract class UpdateModel : ICloneable
     {
         protected abstract string Name { get; }
+        protected long ChatId { get; set; }
+        protected long UserId { get; set; }
 
         public abstract Task<Message> Execute(Update update);
 
@@ -16,7 +20,7 @@ namespace MafiaTelegramBot.Models
             return command.Contains(Name);
         }
 
-        protected static UpdateModel FirstOrDefault(IReadOnlyList<UpdateModel> list, string data)
+        protected static UpdateModel? FirstOrDefault(IReadOnlyList<UpdateModel> list, string data)
         {
             return (from item in list
                 where item.Contains(data)
@@ -27,5 +31,19 @@ namespace MafiaTelegramBot.Models
         {
             await Bot.Get().DeleteMessageAsync(chatId, messageId);
         }
+
+        public object? Clone(long chatId, long userId)
+        {
+            var clone = (UpdateModel?) MemberwiseClone();
+            if(clone == null) return clone;
+            clone.ChatId = chatId;
+            clone.UserId = userId;
+            return clone;
+        }
+
+        public object Clone()
+        {
+            return MemberwiseClone();
+        }
     }
 }

+ 72 - 0
MafiaTelegramBot/Resources/Keyboards.cs

@@ -1,3 +1,5 @@
+using System.Collections.Generic;
+using MafiaTelegramBot.Game;
 using Telegram.Bot.Types.ReplyMarkups;
 
 namespace MafiaTelegramBot.Resources
@@ -25,5 +27,75 @@ namespace MafiaTelegramBot.Resources
                 new KeyboardButton[] {keyboard.leave}
             }, true
         );
+
+        public static InlineKeyboardMarkup ConnectToRoomKeyboard(long userId)
+        {
+            return new(new[]
+            {
+                new[] {InlineKeyboardButton.WithCallbackData(strings.connect_to_public_room, $"{callback.connect_to_public_room}|{userId}")},
+                new[] {InlineKeyboardButton.WithCallbackData(strings.connect_to_private_room, $"{callback.connect_to_private_room}|{userId}")}
+            });
+        }
+
+        public static InlineKeyboardMarkup MakeRoomKeyboard(long userId)
+        {
+            return new(new[]
+            {
+                new[] {InlineKeyboardButton.WithCallbackData(strings.make_public_room, $"{callback.make_public_room}|{userId}")},
+                new[] {InlineKeyboardButton.WithCallbackData(strings.make_private_room, $"{callback.make_private_room}|{userId}")}
+            });
+        }
+
+        public static InlineKeyboardMarkup IncreaseDecreaseKeyboard(long userId)
+        {
+            return new (new[]
+            {
+                new[] {InlineKeyboardButton.WithCallbackData(strings.decrease_number_of_players, $"{callback.decrease_number_of_players}|{userId}"),
+                    InlineKeyboardButton.WithCallbackData(strings.increase_number_of_players, $"{callback.increase_number_of_players}|{userId}")}
+            });
+        }
+
+        public static InlineKeyboardMarkup ProfileKeyboard(long userId)
+        {
+            return new (new[]
+            {
+                new[] {
+                    InlineKeyboardButton.WithCallbackData(strings.shop, $"{callback.shop}|{userId}"),
+                    InlineKeyboardButton.WithCallbackData(strings.my_roles, $"{callback.my_roles}|{userId}")
+                },
+                new[] {InlineKeyboardButton.WithCallbackData(strings.settings, $"{callback.settings_profile}|{userId}")}
+            });
+        }
+
+        public static InlineKeyboardMarkup StandartExtendedKeyboard(long userId, string type)
+        {
+            return new (new[]
+            {
+                new[] {
+                    InlineKeyboardButton.WithCallbackData(strings.standart, $"{callback.standart}|{userId}|{type}"),
+                    InlineKeyboardButton.WithCallbackData(strings.extended, $"{callback.extended}|{userId}|{type}")
+                }
+            });
+        }
+
+        public static InlineKeyboardMarkup ChangeNameKeyboard(long userId)
+        {
+            return new(InlineKeyboardButton.WithCallbackData(strings.change_name, $"{callback.change_name}|{userId}"));
+        }
+
+        public static InlineKeyboardMarkup RoomsKeyboard(List<GameRoom> rooms, long userId)
+        {
+            var inlineButtons = new InlineKeyboardButton[rooms.Count];
+            for (var i = 0; i < rooms.Count && i < Constants.MAX_SHOWING_ROOMS; ++i) // buttons
+            {
+                inlineButtons[i] = new InlineKeyboardButton
+                {
+                    Text =
+                        $"{rooms[i].RoomName} ({rooms[i].Players.Values.Count.ToString()}/{rooms[i].MaxPlayers.ToString()})",
+                    CallbackData = $"{callback.connect_to_selected_room}|{userId}|{RoomEncrypter.FullToShort(rooms[i].RoomName)}"
+                };
+            }
+            return new InlineKeyboardMarkup(inlineButtons);
+        }
     }
 }

+ 40 - 31
MafiaTelegramBot/Resources/strings.Designer.cs

@@ -60,15 +60,6 @@ namespace MafiaTelegramBot {
             }
         }
         
-        /// <summary>
-        ///   Looks up a localized string similar to уже существует.
-        /// </summary>
-        internal static string already_exists {
-            get {
-                return ResourceManager.GetString("already_exists", resourceCulture);
-            }
-        }
-        
         /// <summary>
         ///   Looks up a localized string similar to Сменить имя.
         /// </summary>
@@ -177,6 +168,24 @@ namespace MafiaTelegramBot {
             }
         }
         
+        /// <summary>
+        ///   Looks up a localized string similar to Комната с таким именем уже существует.
+        /// </summary>
+        internal static string game_already_exists {
+            get {
+                return ResourceManager.GetString("game_already_exists", resourceCulture);
+            }
+        }
+        
+        /// <summary>
+        ///   Looks up a localized string similar to Игра уже запущена.
+        /// </summary>
+        internal static string game_already_running {
+            get {
+                return ResourceManager.GetString("game_already_running", resourceCulture);
+            }
+        }
+        
         /// <summary>
         ///   Looks up a localized string similar to Число игр:.
         /// </summary>
@@ -258,15 +267,6 @@ namespace MafiaTelegramBot {
             }
         }
         
-        /// <summary>
-        ///   Looks up a localized string similar to Вы не находитесь сейчас в игре!.
-        /// </summary>
-        internal static string not_in_game {
-            get {
-                return ResourceManager.GetString("not_in_game", resourceCulture);
-            }
-        }
-        
         /// <summary>
         ///   Looks up a localized string similar to Сначала покиньте комнату.
         /// </summary>
@@ -285,15 +285,6 @@ namespace MafiaTelegramBot {
             }
         }
         
-        /// <summary>
-        ///   Looks up a localized string similar to Комната.
-        /// </summary>
-        internal static string room {
-            get {
-                return ResourceManager.GetString("room", resourceCulture);
-            }
-        }
-        
         /// <summary>
         ///   Looks up a localized string similar to Комната не существует.
         /// </summary>
@@ -402,6 +393,24 @@ namespace MafiaTelegramBot {
             }
         }
         
+        /// <summary>
+        ///   Looks up a localized string similar to Недостаточно игроков для старта игры.
+        /// </summary>
+        internal static string too_few_players {
+            get {
+                return ResourceManager.GetString("too_few_players", resourceCulture);
+            }
+        }
+        
+        /// <summary>
+        ///   Looks up a localized string similar to Количество игроков превышает максимальное.
+        /// </summary>
+        internal static string too_many_players {
+            get {
+                return ResourceManager.GetString("too_many_players", resourceCulture);
+            }
+        }
+        
         /// <summary>
         ///   Looks up a localized string similar to Произошла неожиданная ошибка... Попробуйте ещё раз..
         /// </summary>
@@ -412,7 +421,7 @@ namespace MafiaTelegramBot {
         }
         
         /// <summary>
-        ///   Looks up a localized string similar to Вы уже в этой комнате.
+        ///   Looks up a localized string similar to Вы уже находитесь в игре.
         /// </summary>
         internal static string user_already_in_game {
             get {
@@ -421,11 +430,11 @@ namespace MafiaTelegramBot {
         }
         
         /// <summary>
-        ///   Looks up a localized string similar to Вы уже находитесь в игре.
+        ///   Looks up a localized string similar to Вы не находитесь сейчас в игре.
         /// </summary>
-        internal static string user_already_playing {
+        internal static string user_not_in_game {
             get {
-                return ResourceManager.GetString("user_already_playing", resourceCulture);
+                return ResourceManager.GetString("user_not_in_game", resourceCulture);
             }
         }
         

+ 14 - 11
MafiaTelegramBot/Resources/strings.resx

@@ -84,20 +84,14 @@
     <data name="unexpected_error" xml:space="preserve">
         <value>Произошла неожиданная ошибка... Попробуйте ещё раз.</value>
     </data>
-    <data name="room" xml:space="preserve">
-        <value>Комната</value>
-    </data>
-    <data name="already_exists" xml:space="preserve">
-        <value>уже существует</value>
-    </data>
-    <data name="user_already_playing" xml:space="preserve">
-        <value>Вы уже находитесь в игре</value>
+    <data name="game_already_exists" xml:space="preserve">
+        <value>Комната с таким именем уже существует</value>
     </data>
     <data name="leave_from_game" xml:space="preserve">
         <value>Вы покинули игру</value>
     </data>
-    <data name="not_in_game" xml:space="preserve">
-        <value>Вы не находитесь сейчас в игре!</value>
+    <data name="user_not_in_game" xml:space="preserve">
+        <value>Вы не находитесь сейчас в игре</value>
     </data>
     <data name="standart" xml:space="preserve">
         <value>Стандартный</value>
@@ -124,7 +118,7 @@
         <value>Комната заполнена</value>
     </data>
     <data name="user_already_in_game" xml:space="preserve">
-        <value>Вы уже в этой комнате</value>
+        <value>Вы уже находитесь в игре</value>
     </data>
     <data name="successful_entry_into_room" xml:space="preserve">
         <value>Вы были добавлены в комнату</value>
@@ -159,4 +153,13 @@
     <data name="rooms" xml:space="preserve">
         <value>Комнаты</value>
     </data>
+    <data name="too_many_players" xml:space="preserve">
+        <value>Количество игроков превышает максимальное</value>
+    </data>
+    <data name="too_few_players" xml:space="preserve">
+        <value>Недостаточно игроков для старта игры</value>
+    </data>
+    <data name="game_already_running" xml:space="preserve">
+        <value>Игра уже запущена</value>
+    </data>
 </root>

+ 38 - 0
MafiaTelegramBot/Utilities.cs

@@ -1,9 +1,28 @@
 using System.Threading.Tasks;
+using MafiaTelegramBot.Models;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
 
 namespace MafiaTelegramBot
 {
     public static class Utilities
     {
+
+        public static Task<Message> GetResultCodeMessage(ResultCode code, long chatId)
+        {
+            return code switch
+            {
+                ResultCode.TooManyPlayers => Bot.SendWithMarkdown2(chatId, strings.too_many_players),
+                ResultCode.TooFewPlayers => Bot.SendWithMarkdown2(chatId, strings.too_few_players),
+                ResultCode.GameAlreadyRunning => Bot.SendWithMarkdown2(chatId, strings.game_already_running),
+                ResultCode.GameAlreadyExists => Bot.SendWithMarkdown2(chatId, strings.game_already_exists),
+                ResultCode.UserAlreadyInGame => Bot.SendWithMarkdown2(chatId, strings.user_already_in_game),
+                ResultCode.UserNotInGame => Bot.SendWithMarkdown2(chatId, strings.user_not_in_game),
+                ResultCode.RoomIsFilled => Bot.SendWithMarkdown2(chatId, strings.room_is_filled),
+                ResultCode.RoomDoesNotExist => Bot.SendWithMarkdown2(chatId, strings.room_does_not_exists),
+                _ => Bot.SendWithMarkdown2(chatId, strings.unexpected_error)
+            };
+        }
         public static async Task<string> ToMarkdownString(string res)
         {
             return await Task.Run(()=> res
@@ -14,5 +33,24 @@ namespace MafiaTelegramBot
                 .Replace("-", "\\-")
             );
         }
+        
+        public static async Task<string> EscapeSpecific(string src)
+        {
+            var result = src != null
+                ? await Task.Run(()=> src
+                    .Replace(".", "\\.")
+                    .Replace("`", "\\`")
+                    .Replace("@", "\\@")
+                    .Replace("#", "\\#")
+                    .Replace("!", "\\!")
+                    .Replace("*", "\\*")
+                    .Replace("_", "\\_")
+                    .Replace("'", "\\'")
+                    .Replace("~", "\\~")
+                    .Replace("[", "\\[")
+                )
+                :"";
+            return result;
+        }
     }
 }