Parcourir la source

Refactoring sending and getting messages

Tigran il y a 4 ans
Parent
commit
2a47efef22
86 fichiers modifiés avec 894 ajouts et 1057 suppressions
  1. 8 8
      MafiaTelegramBot.sln.DotSettings.user
  2. 0 25
      MafiaTelegramBot/.dockerignore
  3. 85 0
      MafiaTelegramBot/Commands/Bot.cs
  4. 0 0
      MafiaTelegramBot/Commands/ChannelPost/ChannelPost.cs
  5. 0 0
      MafiaTelegramBot/Commands/ChannelPost/GiveawayChannelPost.cs
  6. 0 0
      MafiaTelegramBot/Commands/Inlines/ApplyRolesChangeQuery.cs
  7. 0 0
      MafiaTelegramBot/Commands/Inlines/BackToProfileQuery.cs
  8. 0 0
      MafiaTelegramBot/Commands/Inlines/ChangeNickNameQuery.cs
  9. 0 0
      MafiaTelegramBot/Commands/Inlines/ChangeRolesQuery.cs
  10. 0 0
      MafiaTelegramBot/Commands/Inlines/ChooseGameModeQuery.cs
  11. 0 0
      MafiaTelegramBot/Commands/Inlines/ChooseGameTypeQuery.cs
  12. 0 0
      MafiaTelegramBot/Commands/Inlines/ChooseRoomViewQuery.cs
  13. 0 0
      MafiaTelegramBot/Commands/Inlines/ConnectToNotRankedQuery.cs
  14. 0 0
      MafiaTelegramBot/Commands/Inlines/ConnectToPrivateRoomQuery.cs
  15. 0 0
      MafiaTelegramBot/Commands/Inlines/ConnectToPublicRoomQuery.cs
  16. 0 0
      MafiaTelegramBot/Commands/Inlines/ConnectToRankedQuery.cs
  17. 0 0
      MafiaTelegramBot/Commands/Inlines/ConnectToSelectedRoomQuery.cs
  18. 0 0
      MafiaTelegramBot/Commands/Inlines/ContinueQuery.cs
  19. 0 0
      MafiaTelegramBot/Commands/Inlines/GiveRoleQuery.cs
  20. 0 0
      MafiaTelegramBot/Commands/Inlines/GiveToAllQuery.cs
  21. 0 1
      MafiaTelegramBot/Commands/Inlines/GiveToSelectedQuery.cs
  22. 0 0
      MafiaTelegramBot/Commands/Inlines/KickSelectedPlayerQuery.cs
  23. 0 0
      MafiaTelegramBot/Commands/Inlines/PackInfoQuery.cs
  24. 2 2
      MafiaTelegramBot/Commands/Inlines/PackOpenQuery.cs
  25. 0 0
      MafiaTelegramBot/Commands/Inlines/PlayersCountSettingsQuery.cs
  26. 0 0
      MafiaTelegramBot/Commands/Inlines/Query.cs
  27. 0 0
      MafiaTelegramBot/Commands/Inlines/SetPlayersMaximumQuery.cs
  28. 0 0
      MafiaTelegramBot/Commands/Inlines/SettingsProfileQuery.cs
  29. 0 0
      MafiaTelegramBot/Commands/Inlines/SettingsRoomQuery.cs
  30. 0 0
      MafiaTelegramBot/Commands/Inlines/ShopMenuQuery.cs
  31. 0 0
      MafiaTelegramBot/Commands/Inlines/ShowMyExtendedStatsQuery.cs
  32. 1 1
      MafiaTelegramBot/Commands/Inlines/ShowMyPacksQuery.cs
  33. 0 0
      MafiaTelegramBot/Commands/Inlines/ShowMyRolesQuery.cs
  34. 0 0
      MafiaTelegramBot/Commands/Inlines/StartGameQuery.cs
  35. 0 0
      MafiaTelegramBot/Commands/Inlines/SwitchTimerQuery.cs
  36. 22 0
      MafiaTelegramBot/Commands/Messages/AdminPanelMessageHandler.cs
  37. 35 0
      MafiaTelegramBot/Commands/Messages/ChangeNicknameMessageHandler.cs
  38. 19 0
      MafiaTelegramBot/Commands/Messages/CommandNotFoundMessageHandler.cs
  39. 22 0
      MafiaTelegramBot/Commands/Messages/ConnectGameMessageHandler.cs
  40. 22 0
      MafiaTelegramBot/Commands/Messages/CreateGameMessageHandler.cs
  41. 48 0
      MafiaTelegramBot/Commands/Messages/CreateRoomMessageHandler.cs
  42. 30 0
      MafiaTelegramBot/Commands/Messages/DissolveRoomMessageHandler.cs
  43. 39 0
      MafiaTelegramBot/Commands/Messages/EnterCodeMessageHandler.cs
  44. 22 0
      MafiaTelegramBot/Commands/Messages/FastGameMessageHandler.cs
  45. 38 0
      MafiaTelegramBot/Commands/Messages/GiveRoleToPlayerMessageHandler.cs
  46. 28 0
      MafiaTelegramBot/Commands/Messages/KickPlayerMessageHandler.cs
  47. 23 0
      MafiaTelegramBot/Commands/Messages/LeaveMessageHandler.cs
  48. 31 0
      MafiaTelegramBot/Commands/Messages/LookPlayersListMessageHandler.cs
  49. 61 0
      MafiaTelegramBot/Commands/Messages/MessageHandler.cs
  50. 28 0
      MafiaTelegramBot/Commands/Messages/RoomSettingsMessageHandler.cs
  51. 35 0
      MafiaTelegramBot/Commands/Messages/ShowProfileMessageHandler.cs
  52. 31 0
      MafiaTelegramBot/Commands/Messages/StartGameMessageHandler.cs
  53. 71 0
      MafiaTelegramBot/Commands/Messages/StartMessageHandler.cs
  54. 23 0
      MafiaTelegramBot/Commands/Messages/UserInGameMessageHandler.cs
  55. 20 0
      MafiaTelegramBot/Commands/UpdateHandler.cs
  56. 26 15
      MafiaTelegramBot/Controllers/MessageController.cs
  57. 2 4
      MafiaTelegramBot/Controllers/RoomController.cs
  58. 6 0
      MafiaTelegramBot/CustomCollections/Extensions/DictionaryExtension.cs
  59. 3 1
      MafiaTelegramBot/DataBase/Entity/UserEntity.cs
  60. 22 22
      MafiaTelegramBot/DataBase/EntityDao/UserDao.cs
  61. 0 18
      MafiaTelegramBot/Dockerfile
  62. 43 84
      MafiaTelegramBot/Game/Player.cs
  63. 0 193
      MafiaTelegramBot/Models/Bot.cs
  64. 0 18
      MafiaTelegramBot/Models/Commands/AdminPanelCommand.cs
  65. 0 72
      MafiaTelegramBot/Models/Commands/Command.cs
  66. 0 21
      MafiaTelegramBot/Models/Commands/ConnectGameCommand.cs
  67. 0 20
      MafiaTelegramBot/Models/Commands/CreateGameCommand.cs
  68. 0 20
      MafiaTelegramBot/Models/Commands/CustomMessageHandlers/ChangeNicknameHandler.cs
  69. 0 35
      MafiaTelegramBot/Models/Commands/CustomMessageHandlers/CreateRoomHandler.cs
  70. 0 24
      MafiaTelegramBot/Models/Commands/CustomMessageHandlers/EnterCodeHandler.cs
  71. 0 39
      MafiaTelegramBot/Models/Commands/CustomMessageHandlers/GiveRoleToPlayerHandler.cs
  72. 0 30
      MafiaTelegramBot/Models/Commands/DissolveRoomCommand.cs
  73. 0 21
      MafiaTelegramBot/Models/Commands/FastGameCommand.cs
  74. 0 29
      MafiaTelegramBot/Models/Commands/KickPlayerCommand.cs
  75. 0 23
      MafiaTelegramBot/Models/Commands/LeaveCommand.cs
  76. 0 30
      MafiaTelegramBot/Models/Commands/LookPlayersListCommand.cs
  77. 0 28
      MafiaTelegramBot/Models/Commands/RoomSettingsCommand.cs
  78. 0 31
      MafiaTelegramBot/Models/Commands/ShowProfileCommand.cs
  79. 0 76
      MafiaTelegramBot/Models/Commands/StartCommand.cs
  80. 0 30
      MafiaTelegramBot/Models/Commands/StartGameCommand.cs
  81. 0 28
      MafiaTelegramBot/Models/Payments/Payment.cs
  82. 0 15
      MafiaTelegramBot/Models/Payments/RandomRolePayment.cs
  83. 0 46
      MafiaTelegramBot/Models/UpdateModel.cs
  84. 7 6
      MafiaTelegramBot/Other/GiveAway.cs
  85. 28 28
      MafiaTelegramBot/Resources/Keyboard.cs
  86. 13 13
      MafiaTelegramBot/Utilities.cs

+ 8 - 8
MafiaTelegramBot.sln.DotSettings.user

@@ -1,14 +1,14 @@
 <wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
 	
-	<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=0ea868fa_002D7cf8_002D466b_002Dbf25_002Dc540fc960a6b/@EntryIndexedValue">&lt;SessionState ContinuousTestingMode="0" IsActive="True" Name="Killing_Player_In_Summing_Up_Phase #2" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"&gt;
-  &lt;TestAncestor&gt;
-    &lt;TestId&gt;xUnit::BB1857E4-418E-4AE5-8437-43EBD1D903FB::net5.0::MafiaTelegramBotTests.Game.Tests.GameRooms.Tests.GameRoomTests&lt;/TestId&gt;
-  &lt;/TestAncestor&gt;
+	<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=0ea868fa_002D7cf8_002D466b_002Dbf25_002Dc540fc960a6b/@EntryIndexedValue">&lt;SessionState ContinuousTestingMode="0" IsActive="True" Name="Killing_Player_In_Summing_Up_Phase #2" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"&gt;&#xD;
+  &lt;TestAncestor&gt;&#xD;
+    &lt;TestId&gt;xUnit::BB1857E4-418E-4AE5-8437-43EBD1D903FB::net5.0::MafiaTelegramBotTests.Game.Tests.GameRooms.Tests.GameRoomTests&lt;/TestId&gt;&#xD;
+  &lt;/TestAncestor&gt;&#xD;
 &lt;/SessionState&gt;</s:String>
-	<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=fbf9be8e_002Dabe2_002D485d_002Dbae0_002D5fd4fbd8c901/@EntryIndexedValue">&lt;SessionState ContinuousTestingMode="0" Name="Killing_Player_In_Summing_Up_Phase" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"&gt;
-  &lt;TestAncestor&gt;
-    &lt;TestId&gt;xUnit::BB1857E4-418E-4AE5-8437-43EBD1D903FB::net5.0::MafiaTelegramBotTests.Game.Tests.GameRooms.Tests.GameRoomTests.Killing_Player_In_Summing_Up_Phase&lt;/TestId&gt;
-  &lt;/TestAncestor&gt;
+	<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=fbf9be8e_002Dabe2_002D485d_002Dbae0_002D5fd4fbd8c901/@EntryIndexedValue">&lt;SessionState ContinuousTestingMode="0" Name="Killing_Player_In_Summing_Up_Phase" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"&gt;&#xD;
+  &lt;TestAncestor&gt;&#xD;
+    &lt;TestId&gt;xUnit::BB1857E4-418E-4AE5-8437-43EBD1D903FB::net5.0::MafiaTelegramBotTests.Game.Tests.GameRooms.Tests.GameRoomTests.Killing_Player_In_Summing_Up_Phase&lt;/TestId&gt;&#xD;
+  &lt;/TestAncestor&gt;&#xD;
 &lt;/SessionState&gt;</s:String>
 	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=MafiaTelegramBot_002Fappsettings/@EntryIndexedValue">True</s:Boolean>
 	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=MafiaTelegramBot_002FResources_002Fkeyboard/@EntryIndexedValue">False</s:Boolean>

+ 0 - 25
MafiaTelegramBot/.dockerignore

@@ -1,25 +0,0 @@
-**/.dockerignore
-**/.env
-**/.git
-**/.gitignore
-**/.project
-**/.settings
-**/.toolstarget
-**/.vs
-**/.vscode
-**/.idea
-**/*.*proj.user
-**/*.dbmdl
-**/*.jfm
-**/azds.yaml
-**/bin
-**/charts
-**/docker-compose*
-**/Dockerfile*
-**/node_modules
-**/npm-debug.log
-**/obj
-**/secrets.dev.yaml
-**/values.dev.yaml
-LICENSE
-README.md

+ 85 - 0
MafiaTelegramBot/Commands/Bot.cs

@@ -0,0 +1,85 @@
+using System;
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot;
+using Telegram.Bot.Types.Enums;
+using Telegram.Bot.Types.ReplyMarkups;
+using static MafiaTelegramBot.Logs;
+
+namespace MafiaTelegramBot.Models
+{
+    public static class Bot
+    {
+        private static TelegramBotClient _client;
+
+        public static readonly List<long> UsersThatChangesNickname = new();
+        public static readonly Dictionary<long, string> UsersThatCreatesRoom = new();
+        public static readonly List<long> UserThatEntersPrivateCode = new();
+
+        public static TelegramBotClient Client
+        {
+            get
+            {
+                if (_client != null) return _client;
+                _client = new TelegramBotClient(AppSettings.Token);
+                return _client;
+            }
+        }
+
+        public static async Task<Telegram.Bot.Types.Message> SendStickerAsync(long chatId, string fileId)
+        {
+            try
+            {
+                return await Get().SendStickerAsync(chatId, fileId, true);
+            }
+            catch (Exception e)
+            {
+                LogOutError(e.Message);
+                return new Telegram.Bot.Types.Message();
+            }
+        }
+
+        public static async Task<Telegram.Bot.Types.Message> SendHyperLink(long chatId, string message)
+        {
+            try
+            {
+                return await Get().SendTextMessageAsync(chatId, message, ParseMode.Html, disableNotification: true);
+            }
+            catch (Exception e)
+            {
+                LogOutError(e.Message);
+                return new Telegram.Bot.Types.Message();
+            }
+        }
+        
+        public static async Task<Telegram.Bot.Types.Message> SendWithMarkdown2(long chatId, string message, IReplyMarkup replyMarkup = null)
+        {
+            try
+            {
+                var editedMessage = await Utilities.ToMarkdownString(message);
+                return await Get().SendTextMessageAsync(chatId, editedMessage,
+                    ParseMode.MarkdownV2, replyMarkup: replyMarkup, disableNotification: true);
+            }
+            catch (Exception e)
+            {
+                LogOutError(e.Message);
+                return new Telegram.Bot.Types.Message();
+            }
+        }
+
+        public static async Task<Telegram.Bot.Types.Message> EditMessageAsync(long chatId, int messageId, string message, InlineKeyboardMarkup keyboard = null)
+        {
+            try
+            {
+                var editedMessage = await Utilities.ToMarkdownString(message);
+                return await Get().EditMessageTextAsync(chatId, messageId, editedMessage, ParseMode.MarkdownV2, replyMarkup: keyboard);
+            }
+            catch (Exception e)
+            {
+                LogOutError(e.Message);
+                return new Telegram.Bot.Types.Message();
+            }
+        }
+    }
+}

+ 0 - 0
MafiaTelegramBot/Models/ChannelPost/ChannelPost.cs → MafiaTelegramBot/Commands/ChannelPost/ChannelPost.cs


+ 0 - 0
MafiaTelegramBot/Models/ChannelPost/GiveawayChannelPost.cs → MafiaTelegramBot/Commands/ChannelPost/GiveawayChannelPost.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/ApplyRolesChangeQuery.cs → MafiaTelegramBot/Commands/Inlines/ApplyRolesChangeQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/BackToProfileQuery.cs → MafiaTelegramBot/Commands/Inlines/BackToProfileQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/ChangeNickNameQuery.cs → MafiaTelegramBot/Commands/Inlines/ChangeNickNameQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/ChangeRolesQuery.cs → MafiaTelegramBot/Commands/Inlines/ChangeRolesQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/ChooseGameModeQuery.cs → MafiaTelegramBot/Commands/Inlines/ChooseGameModeQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/ChooseGameTypeQuery.cs → MafiaTelegramBot/Commands/Inlines/ChooseGameTypeQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/ChooseRoomViewQuery.cs → MafiaTelegramBot/Commands/Inlines/ChooseRoomViewQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/ConnectToNotRankedQuery.cs → MafiaTelegramBot/Commands/Inlines/ConnectToNotRankedQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/ConnectToPrivateRoomQuery.cs → MafiaTelegramBot/Commands/Inlines/ConnectToPrivateRoomQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/ConnectToPublicRoomQuery.cs → MafiaTelegramBot/Commands/Inlines/ConnectToPublicRoomQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/ConnectToRankedQuery.cs → MafiaTelegramBot/Commands/Inlines/ConnectToRankedQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/ConnectToSelectedRoomQuery.cs → MafiaTelegramBot/Commands/Inlines/ConnectToSelectedRoomQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/ContinueQuery.cs → MafiaTelegramBot/Commands/Inlines/ContinueQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/GiveRoleQuery.cs → MafiaTelegramBot/Commands/Inlines/GiveRoleQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/GiveToAllQuery.cs → MafiaTelegramBot/Commands/Inlines/GiveToAllQuery.cs


+ 0 - 1
MafiaTelegramBot/Models/Inlines/GiveToSelectedQuery.cs → MafiaTelegramBot/Commands/Inlines/GiveToSelectedQuery.cs

@@ -1,5 +1,4 @@
 using System.Threading.Tasks;
-using MafiaTelegramBot.Models.Commands.CustomMessageHandlers;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot.Types;
 

+ 0 - 0
MafiaTelegramBot/Models/Inlines/KickSelectedPlayerQuery.cs → MafiaTelegramBot/Commands/Inlines/KickSelectedPlayerQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/PackInfoQuery.cs → MafiaTelegramBot/Commands/Inlines/PackInfoQuery.cs


+ 2 - 2
MafiaTelegramBot/Models/Inlines/PackOpenQuery.cs → MafiaTelegramBot/Commands/Inlines/PackOpenQuery.cs

@@ -14,8 +14,8 @@ namespace MafiaTelegramBot.Models.Inlines
         {
             await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
             var user = await UserDao.GetPlayerById(UserId);
-            if (user.User.PackCount <= 0) return await Bot.SendWithMarkdown2(ChatId, strings.you_havent_pack);
-            user.User.PackCount--;
+            if (user.Info.PackCount <= 0) return await Bot.SendWithMarkdown2(ChatId, strings.you_havent_pack);
+            user.Info.PackCount--;
             var baseRole = await GetRandomBaseRole(user.OpenedRoles);
             if (user.OpenedRoles.TryOpenRole(baseRole))
             {

+ 0 - 0
MafiaTelegramBot/Models/Inlines/PlayersCountSettingsQuery.cs → MafiaTelegramBot/Commands/Inlines/PlayersCountSettingsQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/Query.cs → MafiaTelegramBot/Commands/Inlines/Query.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/SetPlayersMaximumQuery.cs → MafiaTelegramBot/Commands/Inlines/SetPlayersMaximumQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/SettingsProfileQuery.cs → MafiaTelegramBot/Commands/Inlines/SettingsProfileQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/SettingsRoomQuery.cs → MafiaTelegramBot/Commands/Inlines/SettingsRoomQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/ShopMenuQuery.cs → MafiaTelegramBot/Commands/Inlines/ShopMenuQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/ShowMyExtendedStatsQuery.cs → MafiaTelegramBot/Commands/Inlines/ShowMyExtendedStatsQuery.cs


+ 1 - 1
MafiaTelegramBot/Models/Inlines/ShowMyPacksQuery.cs → MafiaTelegramBot/Commands/Inlines/ShowMyPacksQuery.cs

@@ -13,7 +13,7 @@ namespace MafiaTelegramBot.Models.Inlines
             await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
             var player = await UserDao.GetPlayerById(UserId);
             await Bot.SendStickerAsync(ChatId, Stickers.Sticker["Pool"]);
-            return await Bot.SendWithMarkdown2(ChatId, $"{strings.your_packs} {player.User.PackCount}", Keyboard.PackKeyboard(player.Id));
+            return await Bot.SendWithMarkdown2(ChatId, $"{strings.your_packs} {player.Info.PackCount}", Keyboard.PackKeyboard(player.Id));
         }
     }
 }

+ 0 - 0
MafiaTelegramBot/Models/Inlines/ShowMyRolesQuery.cs → MafiaTelegramBot/Commands/Inlines/ShowMyRolesQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/StartGameQuery.cs → MafiaTelegramBot/Commands/Inlines/StartGameQuery.cs


+ 0 - 0
MafiaTelegramBot/Models/Inlines/SwitchTimerQuery.cs → MafiaTelegramBot/Commands/Inlines/SwitchTimerQuery.cs


+ 22 - 0
MafiaTelegramBot/Commands/Messages/AdminPanelMessageHandler.cs

@@ -0,0 +1,22 @@
+using System.Threading.Tasks;
+using MafiaTelegramBot.Controllers;
+using MafiaTelegramBot.Game;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands.Messages
+{
+    public class AdminPanelMessageHandler : MessageHandler
+    {
+        protected override string Command => keyboard.admin_panel;
+        public override async Task<Message> Execute(Update update)
+        {
+            if (User.Info.IsAdmin)
+                return await MessageController.SendText(User.Info, strings.start_message, Keyboard.AdminPanelKeyboard());
+            return await new CommandNotFound(User).Execute(update);
+        }
+
+
+        public AdminPanelMessageHandler(Player player) : base(player) { }
+    }
+}

+ 35 - 0
MafiaTelegramBot/Commands/Messages/ChangeNicknameMessageHandler.cs

@@ -0,0 +1,35 @@
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using MafiaTelegramBot.Controllers;
+using MafiaTelegramBot.CustomCollections.Extensions;
+using MafiaTelegramBot.Game;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands.Messages
+{
+    public class ChangeNicknameHandler : MessageHandler
+    {
+        protected override string Command => "";
+        
+        private static readonly List<long> Queue = new();
+
+        public static void AddToQueue(long id)
+        {
+            Queue.AddUnique(id);
+        }
+
+        public override bool IsMatches(string command)
+        {
+            return User != null ? Queue.Contains(User.Info.Id) : base.IsMatches(command);
+        }
+
+        public override async Task<Message> Execute(Update update)
+        {
+            User.Info.NickName = update.Message.Text;
+            Queue.Remove(User.Info.Id);
+            return await MessageController.SendText(User.Info,$"{strings.name_updated} {update.Message.Text}");
+        }
+
+        public ChangeNicknameHandler(Player player) : base(player) { }
+    }
+}

+ 19 - 0
MafiaTelegramBot/Commands/Messages/CommandNotFoundMessageHandler.cs

@@ -0,0 +1,19 @@
+using System.Threading.Tasks;
+using MafiaTelegramBot.Controllers;
+using MafiaTelegramBot.Game;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands.Messages
+{
+    public class CommandNotFound : MessageHandler
+    {
+        protected override string Command => "";
+        
+        public override async Task<Message> Execute(Update update)
+        {
+            return await MessageController.SendText(User.Info, $"{strings.command_not_found} {update.Message.Text}");
+        }
+
+        public CommandNotFound(Player player) : base(player) { }
+    }
+}

+ 22 - 0
MafiaTelegramBot/Commands/Messages/ConnectGameMessageHandler.cs

@@ -0,0 +1,22 @@
+using System.Threading.Tasks;
+using MafiaTelegramBot.Controllers;
+using MafiaTelegramBot.Game;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands.Messages
+{
+    public class ConnectGameMessageHandler : MessageHandler
+    {
+        protected override string Command => keyboard.connect_game;
+
+        public override async Task<Message> Execute(Update update)
+        {
+            if (User.GetRoomName() != "")
+                return await MessageController.SendText(User.Info, strings.user_already_in_game);
+            return await MessageController.SendText(User.Info, strings.choose_type_room, Keyboard.RoomTypeKeyboard());
+        }
+
+        public ConnectGameMessageHandler(Player player) : base(player) { }
+    }
+}

+ 22 - 0
MafiaTelegramBot/Commands/Messages/CreateGameMessageHandler.cs

@@ -0,0 +1,22 @@
+using System.Threading.Tasks;
+using MafiaTelegramBot.Controllers;
+using MafiaTelegramBot.Game;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands.Messages
+{
+    public class CreateGameMessageHandler : MessageHandler
+    {
+        protected override string Command => keyboard.create_game;
+
+        public override async Task<Message> Execute(Update update)
+        {
+            if (User.GetRoomName() != "")
+                return await MessageController.SendText(User.Info, strings.user_already_in_game);
+            return await MessageController.SendText(User.Info, strings.choose_game_view, Keyboard.ChooseRoomView());
+        }
+
+        public CreateGameMessageHandler(Player player) : base(player) { }
+    }
+}

+ 48 - 0
MafiaTelegramBot/Commands/Messages/CreateRoomMessageHandler.cs

@@ -0,0 +1,48 @@
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using MafiaTelegramBot.Controllers;
+using MafiaTelegramBot.CustomCollections.Extensions;
+using MafiaTelegramBot.Game;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands.Messages
+{
+    public class CreateRoomHandler : MessageHandler
+    {
+        protected override string Command => "";
+        
+        private static readonly Dictionary<long, string> Queue = new();
+
+        public static void AddToQueue(long id, string param)
+        {
+            Queue.AddUniqueOrReplaceByKey(id, param);
+        }
+
+        public override bool IsMatches(string command)
+        {
+            return User != null ? Queue.ContainsKey(User.Info.Id) : base.IsMatches(command);
+        }
+
+        public override async Task<Message> Execute(Update update)
+        {
+            var param = Queue[User.Info.Id];
+            Queue.Remove(User.Info.Id);
+            var isPrivate = param[0] == Constants.PRIVATE + '0';
+            var isExtended = param[1] == Constants.EXTENDED + '0';
+            var isRanking = param[2] == Constants.RANKING + '0';
+            var roomName = update.Message.Text;
+            var resultCode = await RoomController.CreateNewGame(User, roomName, isExtended, isPrivate, isRanking);
+            var result = resultCode == ResultCode.CodeOk
+                ? await MessageController.SendText(User.Info, $"{strings.room_with_name} {roomName} {strings.was_created}\n", Keyboard.OwnerGameMenu)
+                : await MessageController.SendText(User.Info, Utilities.GetResultCodeMessage(resultCode));
+            if (resultCode == ResultCode.CodeOk && isPrivate)
+                await MessageController.SendText(User.Info, $"{strings.secret_key_is} {roomName}: {RoomEncrypter.GetCode(roomName)}");
+            if (resultCode == ResultCode.CodeOk && !isRanking)
+                await MessageController.SendTextWithHtml(User.Info, $"<a href='https://t.me/{AppSettings.Name}?start=room_key={RoomEncrypter.GetCode(roomName)}'>{strings.link}</a>");
+            return result;
+        }
+
+        public CreateRoomHandler(Player player) : base(player) { }
+    }
+}

+ 30 - 0
MafiaTelegramBot/Commands/Messages/DissolveRoomMessageHandler.cs

@@ -0,0 +1,30 @@
+using System.Threading.Tasks;
+using MafiaTelegramBot.Controllers;
+using MafiaTelegramBot.Game;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands.Messages
+{
+    public class DissolveRoomMessageHandler : MessageHandler
+    {
+        protected override string Command => keyboard.dissolve_room;
+        public override async Task<Message> Execute(Update update) 
+        { 
+            var roomKey = RoomEncrypter.GetCode(User.GetRoomName());
+            var room = RoomController.GetRoom(roomKey);
+            if(room == null)
+                return await MessageController.SendText(User.Info, strings.room_does_not_exists);
+            if (!User.Equals(room.Owner))
+                return await MessageController.SendText(User.Info, update.Message.Text);
+            var resultCode = await RoomController.LeaveFromGame(User);
+            var result = resultCode == ResultCode.CodeOk
+                ? await MessageController.SendText(User.Info, strings.room_dissolved, User.Info.IsAdmin ? Keyboard.AdminMainMenu : Keyboard.MainMenu)
+                : await MessageController.SendText(User.Info, Utilities.GetResultCodeMessage(resultCode));
+            if (resultCode == ResultCode.CodeOk) await RoomController.DissolveRoom(roomKey);
+            return result;
+        }
+
+        public DissolveRoomMessageHandler(Player player) : base(player) { }
+    }
+}

+ 39 - 0
MafiaTelegramBot/Commands/Messages/EnterCodeMessageHandler.cs

@@ -0,0 +1,39 @@
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using MafiaTelegramBot.Controllers;
+using MafiaTelegramBot.CustomCollections.Extensions;
+using MafiaTelegramBot.Game;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands.Messages
+{
+    public class EnterCodeHandler : MessageHandler
+    {
+        protected override string Command => "";
+        
+        private static readonly List<long> Queue = new();
+
+        public static void AddToQueue(long id)
+        {
+            Queue.AddUnique(id);
+        }
+
+        public override bool IsMatches(string command)
+        {
+            return User != null ? Queue.Contains(User.Info.Id) : base.IsMatches(command);
+        }
+        
+        public override async Task<Message> Execute(Update update)
+        {
+            var roomKey = update.Message.Text;
+            var resultCode = await RoomController.ConnectToGame(User, roomKey);
+            var result = resultCode == ResultCode.CodeOk
+                ? MessageController.SendText(User.Info, strings.successful_entry_into_room, Keyboard.PlayerGameMenu)
+                : MessageController.SendText(User.Info, Utilities.GetResultCodeMessage(resultCode));
+            return await result;
+        }
+
+        public EnterCodeHandler(Player player) : base(player) { }
+    }
+}

+ 22 - 0
MafiaTelegramBot/Commands/Messages/FastGameMessageHandler.cs

@@ -0,0 +1,22 @@
+using System.Threading.Tasks;
+using MafiaTelegramBot.Controllers;
+using MafiaTelegramBot.Game;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands.Messages
+{
+    public class FastGameMessageHandler : MessageHandler
+    {
+        protected override string Command => keyboard.fast_game;
+        public override async Task<Message> Execute(Update update)
+        {
+            if (User.GetRoomName() != "")
+                return await MessageController.SendText(User.Info, strings.user_already_in_game);
+            await RoomController.ConnectToFastGame(User);
+            return await MessageController.SendText(User.Info, strings.you_connect_to_fast_game, Keyboard.PlayerGameMenu);
+        }
+
+        public FastGameMessageHandler(Player player) : base(player) { }
+    }
+}

+ 38 - 0
MafiaTelegramBot/Commands/Messages/GiveRoleToPlayerMessageHandler.cs

@@ -0,0 +1,38 @@
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using MafiaTelegramBot.Controllers;
+using MafiaTelegramBot.CustomCollections.Extensions;
+using MafiaTelegramBot.DataBase.EntityDao;
+using MafiaTelegramBot.Game;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands.Messages
+{
+    public class GiveRoleToPlayerHandler : MessageHandler
+    {
+        protected override string Command => "";
+        
+        private static readonly List<long> Queue = new();
+
+        public static void AddToQueue(long id)
+        {
+            Queue.AddUnique(id);
+        }
+
+        public override bool IsMatches(string command)
+        {
+            return User != null ? Queue.Contains(User.Info.Id) : base.IsMatches(command);
+        }
+        
+        public override async Task<Message> Execute(Update update)
+        {
+            Queue.Remove(User.Info.Id);
+            var targetId = await UserDao.GetIdByUsername(update.Message.Text);
+            if (targetId == -1) return await MessageController.SendText(User.Info, strings.user_not_exists);
+            return await MessageController.SendText(User.Info, strings.choose_role_to_give, Keyboard.GiveRoleKeyboard(targetId));
+        }
+
+        public GiveRoleToPlayerHandler(Player player) : base(player) { }
+    }
+}

+ 28 - 0
MafiaTelegramBot/Commands/Messages/KickPlayerMessageHandler.cs

@@ -0,0 +1,28 @@
+using System.Threading.Tasks;
+using MafiaTelegramBot.Controllers;
+using MafiaTelegramBot.Game;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands.Messages
+{
+    public class KickPlayerMessageHandler : MessageHandler
+    {
+        protected override string Command => keyboard.kick_player;
+        public override async Task<Message> Execute(Update update)
+        {
+            var roomKey = RoomEncrypter.GetCode(User.GetRoomName());
+            var room = RoomController.GetRoom(roomKey);
+            if(room == null)
+                return await MessageController.SendText(User.Info, strings.room_does_not_exists);
+            if (!User.Equals(room.Owner))
+                return await new CommandNotFound(User).Execute(update);
+            var players = await room.GetPlayers();
+            if (players.Count > 0)
+                return await MessageController.SendText(User.Info, strings.kick_user, Keyboard.KickKeyboard(players));
+            return await MessageController.SendText(User.Info, strings.users_list_empty);
+        }
+
+        public KickPlayerMessageHandler(Player player) : base(player) { }
+    }
+}

+ 23 - 0
MafiaTelegramBot/Commands/Messages/LeaveMessageHandler.cs

@@ -0,0 +1,23 @@
+using System.Threading.Tasks;
+using MafiaTelegramBot.Controllers;
+using MafiaTelegramBot.Game;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands.Messages
+{
+    public class LeaveMessageHandler : MessageHandler
+    {
+        protected override string Command => keyboard.leave;
+
+        public override async Task<Message> Execute(Update update)
+        {
+            var resultCode = await RoomController.LeaveFromGame(User);
+            return resultCode == ResultCode.CodeOk
+                ? await MessageController.SendText(User.Info, strings.you_leave_from_game, User.Info.IsAdmin ? Keyboard.AdminMainMenu : Keyboard.MainMenu)
+                : await MessageController.SendText(User.Info, Utilities.GetResultCodeMessage(resultCode));
+        }
+
+        public LeaveMessageHandler(Player player) : base(player) { }
+    }
+}

+ 31 - 0
MafiaTelegramBot/Commands/Messages/LookPlayersListMessageHandler.cs

@@ -0,0 +1,31 @@
+using System.Linq;
+using System.Threading.Tasks;
+using MafiaTelegramBot.Controllers;
+using MafiaTelegramBot.Game;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands.Messages
+{
+    public class LookPlayersListMessageHandler : MessageHandler
+    {
+        protected override string Command => keyboard.look_players_list;
+
+        public override async Task<Message> Execute(Update update)
+        {
+            var roomKey = RoomEncrypter.GetCode(User.GetRoomName());
+            var room = RoomController.GetRoom(roomKey);
+            if(room == null)
+                return await MessageController.SendText(User.Info, strings.room_does_not_exists);
+            var users = RoomController.GetPlayers(roomKey);
+            var list = users.Count > 1
+                ? users.Where(player => !player.Equals(User))
+                    .Aggregate($"{strings.users_list} {users.Count}\n\n @{User.Info.Username}\n{strings.you}",
+                        (current, player) => current + $"\n \n@{player.Info.Username}\n{player.Info.NickName}")
+                : strings.users_list_empty;
+            return await MessageController.SendText(User.Info, list);
+        }
+
+        public LookPlayersListMessageHandler(Player player) : base(player) { }
+    }
+}

+ 61 - 0
MafiaTelegramBot/Commands/Messages/MessageHandler.cs

@@ -0,0 +1,61 @@
+using System;
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using MafiaTelegramBot.DataBase.EntityDao;
+using MafiaTelegramBot.Game;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands.Messages
+{
+    public class MessageHandler : UpdateHandler
+    {
+        private static readonly List<MessageHandler> List = new()
+        {
+            // Переносим обработку сообщений в другой класс, если игрок находится в комнате
+            new UserInGameMessageHandler(null),
+            
+            // Эти обработчики впереди, так как они зависят от наличия игрока в очереди, т.е. игрок должен написать какое-то сообщение
+            new GiveRoleToPlayerHandler(null),
+            new ChangeNicknameHandler(null),
+            new CreateRoomHandler(null),
+            new EnterCodeHandler(null),
+            
+            // Остальные обработчики
+            new AdminPanelMessageHandler(null),
+            new ConnectGameMessageHandler(null),
+            new CreateGameMessageHandler(null),
+            new DissolveRoomMessageHandler(null),
+            new FastGameMessageHandler(null),
+            new KickPlayerMessageHandler(null),
+            new LeaveMessageHandler(null),
+            new LookPlayersListMessageHandler(null),
+            new RoomSettingsMessageHandler(null),
+            new ShowProfileMessageHandler(null),
+            new StartMessageHandler(null),
+            new StartGameMessageHandler(null),
+        };
+        
+        public static async Task<UpdateHandler> Factory(User user, string message)
+        {
+            // Объект пользователя
+            var player = await UserDao.GetPlayerById(user.Id) ?? await UserDao.AddNew(user);
+            
+            // Если игрок заблокирован, то нафиг его
+            if (player.Info.IsBlocked) return new MessageHandler(player);
+            
+            // Устанавливаем игроку время активности на текущее
+            player.SetActive();
+            
+            // Возвращаем объект, если есть подходящая команда
+            foreach (var item in List)
+                if(item.IsMatches(message))
+                    if (Activator.CreateInstance(item.GetType(), player) is UpdateHandler handler)
+                        if(handler.IsMatches(message)) return handler;
+            
+            // Возвращаем команда не найдена, если код дошел до сюда
+            return new CommandNotFound(player);
+        }
+
+        public MessageHandler(Player player) : base(player) { }
+    }
+}

+ 28 - 0
MafiaTelegramBot/Commands/Messages/RoomSettingsMessageHandler.cs

@@ -0,0 +1,28 @@
+using System.Threading.Tasks;
+using MafiaTelegramBot.Controllers;
+using MafiaTelegramBot.Game;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands.Messages
+{
+    public class RoomSettingsMessageHandler : MessageHandler
+    {
+        protected override string Command => keyboard.room_settings;
+
+        public override async Task<Message> Execute(Update update)
+        {
+            var roomKey = RoomEncrypter.GetCode(User.GetRoomName());
+            var room = RoomController.GetRoom(roomKey);
+            if(room == null)
+                return await MessageController.SendText(User.Info, strings.room_does_not_exists);
+            if (!User.Equals(room.Owner))
+                return await new CommandNotFound(User).Execute(update);
+            var status = room.TimerEnabled ? strings.enabled : strings.disabled;
+            return await MessageController.SendText(User.Info, strings.what_settings, 
+                Keyboard.SettingsRoomKeyboard($"{strings.timer}: {status}"));
+        }
+
+        public RoomSettingsMessageHandler(Player player) : base(player) { }
+    }
+}

+ 35 - 0
MafiaTelegramBot/Commands/Messages/ShowProfileMessageHandler.cs

@@ -0,0 +1,35 @@
+using System;
+using System.Linq;
+using System.Threading.Tasks;
+using MafiaTelegramBot.Controllers;
+using MafiaTelegramBot.Game;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands.Messages
+{
+    public class ShowProfileMessageHandler : MessageHandler
+    {
+        protected override string Command => keyboard.show_profile;
+
+        public override async Task<Message> Execute(Update update)
+        {
+            var rolesList = Enum.GetValues(typeof(Roles)).Cast<Roles>().ToList();
+            rolesList.Remove(Roles.None);
+            rolesList.Remove(Roles.All);
+            var allStatsRow = User.Statistics[Roles.All];
+            var message =
+                $"{strings.statistics_for} {User.Info.NickName}\n" +
+                $"{strings.games_count} {allStatsRow.Games}\n" +
+                $"{strings.wins_count} {allStatsRow.Wins}\n" +
+                $"{strings.winrate} {(int)(allStatsRow.GetWinrate()*100)}%\n" +
+                $"{strings.rate} {User.Info.RankNumber}";
+            return await MessageController.SendText(User.Info, message, Keyboard.ProfileKeyboard());
+            
+        }
+
+        public ShowProfileMessageHandler(Player player) : base(player)
+        {
+        }
+    }
+}

+ 31 - 0
MafiaTelegramBot/Commands/Messages/StartGameMessageHandler.cs

@@ -0,0 +1,31 @@
+using System.Threading.Tasks;
+using MafiaTelegramBot.Controllers;
+using MafiaTelegramBot.Game;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands.Messages
+{
+    public class StartGameMessageHandler : MessageHandler
+    {
+        protected override string Command => keyboard.begin_game;
+        public override async Task<Message> Execute(Update update)
+        {
+            var roomKey = RoomEncrypter.GetCode(User.GetRoomName());
+            var room = RoomController.GetRoom(roomKey);
+            if(room == null)
+                return await MessageController.SendText(User.Info, strings.room_does_not_exists);
+            if (!User.Equals(room.Owner))
+                return await new CommandNotFound(User).Execute(update);
+            if (room.IsExtended) return await MessageController.SendText(User.Info, strings.continue_question, Keyboard.StartExtendedRoomKeyboard());
+            var result = await MessageController.SendText(User.Info, strings.game_process_started);
+            var resultCode = await room.Prepare();
+            if (resultCode != ResultCode.CodeOk)
+                return await MessageController.SendText(User.Info, Utilities.GetResultCodeMessage(resultCode));
+            room.Start();
+            return result;
+        }
+
+        public StartGameMessageHandler(Player player) : base(player) { }
+    }
+}

+ 71 - 0
MafiaTelegramBot/Commands/Messages/StartMessageHandler.cs

@@ -0,0 +1,71 @@
+using System;
+using System.Threading.Tasks;
+using MafiaTelegramBot.Controllers;
+using MafiaTelegramBot.Game;
+using MafiaTelegramBot.Other;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands.Messages
+{
+    public class StartMessageHandler : MessageHandler
+    {
+        protected override string Command => "/start";
+
+        public override async Task<Message> Execute(Update update)
+        {
+            var command = update.Message.Text.Split(' ');
+            if (command.Length == 2)
+            {
+                var values = command[1].Split('=');
+                return values[0] switch
+                {
+                    "giveaway_id" => await GiveawayCommand(User, int.Parse(values[1])),
+                    "room_key" => await ConnectToGameCommand(User, values[1]),
+                    "fast_game" => await ConnectToFastGameCommand(User, values[1]),
+                    _ => new Message()
+                };
+            }
+            if (User.GetRoomName() != "")
+                return await MessageController.SendText(User.Info, strings.prefer_leave_from_room);
+            return await MessageController.SendText(User.Info, strings.start_message, User.Info.IsAdmin ? Keyboard.AdminMainMenu : Keyboard.MainMenu);
+        }
+
+        private static async Task<Message> GiveawayCommand(Player player, int id)
+        {
+            try
+            {
+                var giveaway = GiveAway.OpenedGiveaways[id];
+                return await giveaway.GivePrizeTo(player) == ResultCode.NowYouGetPrizeFromThisGiveaway
+                    ? await MessageController.SendText(player.Info, strings.now_you_get_prize_from_this_giveaway)
+                    : new Message();
+            }
+            catch (Exception)
+            {
+                return await MessageController.SendText(player.Info, strings.giveaway_now_ended);
+            }
+        }
+
+        private static async Task<Message> ConnectToGameCommand(Player player, string roomKey)
+        {
+            if (player.GetRoomName() != "")
+                return await MessageController.SendText(player.Info, strings.prefer_leave_from_room);
+            var code = await RoomController.ConnectToGame(player, roomKey);
+            return code == ResultCode.CodeOk
+                ? await MessageController.SendText(player.Info, strings.successful_entry_into_room, Keyboard.PlayerGameMenu)
+                : await MessageController.SendText(player.Info, Utilities.GetResultCodeMessage(code));
+        }
+
+        private static async Task<Message> ConnectToFastGameCommand(Player player, string roomKey)
+        {
+            if (player.GetRoomName() != "")
+                return await MessageController.SendText(player.Info, strings.prefer_leave_from_room);
+            var code = await RoomController.ConnectToFastGame(player, roomKey);
+            return code == ResultCode.CodeOk
+                ? await MessageController.SendText(player.Info, strings.you_connect_to_fast_game, Keyboard.PlayerGameMenu)
+                : await MessageController.SendText(player.Info, Utilities.GetResultCodeMessage(code));
+        }
+
+        public StartMessageHandler(Player player) : base(player) { }
+    }
+}

+ 23 - 0
MafiaTelegramBot/Commands/Messages/UserInGameMessageHandler.cs

@@ -0,0 +1,23 @@
+using System.Threading.Tasks;
+using MafiaTelegramBot.Game;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands.Messages
+{
+    public class UserInGameMessageHandler : MessageHandler
+    {
+        protected override string Command => "";
+
+        public override bool IsMatches(string command)
+        {
+            return User != null ? User.GetRoomName()!= "" : base.IsMatches(command);
+        }
+
+        public override Task<Message> Execute(Update update)
+        {
+            return base.Execute(update);
+        }
+
+        public UserInGameMessageHandler(Player player) : base(player) { }
+    }
+}

+ 20 - 0
MafiaTelegramBot/Commands/UpdateHandler.cs

@@ -0,0 +1,20 @@
+using System.Threading.Tasks;
+using MafiaTelegramBot.Game;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Commands
+{
+    public class UpdateHandler
+    {
+        protected virtual string Command { get; } = "";
+        protected Player User { get; }
+        
+        public virtual async Task<Message> Execute(Update update) { return new Message(); }
+
+        public virtual bool IsMatches(string command) { return command.Contains(Command); }
+
+        public UpdateHandler(Player player) { User = player; }
+        
+        public UpdateHandler() { }
+    }
+}

+ 26 - 15
MafiaTelegramBot/Controllers/MessageController.cs

@@ -1,45 +1,46 @@
 using System;
 using System.Threading;
 using System.Threading.Tasks;
+using MafiaTelegramBot.Commands;
+using MafiaTelegramBot.Commands.Messages;
+using MafiaTelegramBot.DataBase.Entity;
 using MafiaTelegramBot.Models;
-using MafiaTelegramBot.Models.ChannelPost;
-using MafiaTelegramBot.Models.Commands;
-using MafiaTelegramBot.Models.Inlines;
 using Telegram.Bot;
 using Telegram.Bot.Exceptions;
 using Telegram.Bot.Types;
 using Telegram.Bot.Types.Enums;
+using Telegram.Bot.Types.ReplyMarkups;
 using static MafiaTelegramBot.Logs;
+#pragma warning disable 1998
 
 namespace MafiaTelegramBot.Controllers
 {
     public static class MessageController
     {
-        public static async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update,
-            CancellationToken cancellationToken)
+        public static async Task HandleUpdateAsync(ITelegramBotClient bot, Update update, CancellationToken ct)
         {
             try
             {
-                var handle = update.Type switch
+                var handler = update.Type switch
                 {
-                    UpdateType.Message => Command.Update(update),
-                    UpdateType.CallbackQuery => Query.Update(update),
-                    UpdateType.PreCheckoutQuery => Bot.AnswerPreCheckoutQuery(update.PreCheckoutQuery.Id),
-                    UpdateType.ChannelPost => ChannelPost.Update(update),
-                    _ => UnknownUpdateHandlerAsync(update)
+                    UpdateType.Message => await MessageHandler.Factory(update.Message.From, update.Message.Text),
+                    // UpdateType.CallbackQuery => Query.Update(update),
+                    // UpdateType.ChannelPost => ChannelPost.Update(update),
+                    // UpdateType.ChatMember => ChatMember.Update(update),
+                    _ => await UnknownUpdateHandlerAsync(update)
                 };
-                await handle;
+                var unused = await handler.Execute(update);
             }
             catch (Exception exception)
             {
-                await HandleErrorAsync(botClient, exception, cancellationToken);
+                await HandleErrorAsync(bot, exception, ct);
             }
         }
 
-        private static Task UnknownUpdateHandlerAsync(Update update)
+        private static async Task<UpdateHandler> UnknownUpdateHandlerAsync(Update update)
         {
             LogOut(update.Type.ToString());
-            return Task.CompletedTask;
+            return new UpdateHandler();
         }
 
         public static Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception,
@@ -56,5 +57,15 @@ namespace MafiaTelegramBot.Controllers
             }
             return Task.CompletedTask;
         }
+
+        public static async Task<Message> SendText(UserEntity info, string message, IReplyMarkup keyboard = null)
+        {
+            return await Bot.Client.SendTextMessageAsync(info.ChatId, message, replyMarkup: keyboard, disableNotification: true);
+        }
+        
+        public static async Task<Message> SendTextWithHtml(UserEntity info, string message, IReplyMarkup keyboard = null)
+        {
+            return await Bot.Client.SendTextMessageAsync(info.ChatId, message, ParseMode.Html, replyMarkup: keyboard, disableNotification: true);
+        }
     }
 }

+ 2 - 4
MafiaTelegramBot/Controllers/RoomController.cs

@@ -32,7 +32,7 @@ namespace MafiaTelegramBot.Controllers
             });
         }
 
-        public static async Task<ResultCode> ConnectToFastGame(Player player)
+        public static async Task ConnectToFastGame(Player player)
         {
             return await Task.Run(async () =>
             {
@@ -69,7 +69,6 @@ namespace MafiaTelegramBot.Controllers
                 if (room.Players.Count > Constants.MEMORY_CLEANER_PLAYERS_COUNT) room.StopTimer();
                 await room.PlayersMessageChannel.SendExcept(player.Id, $"{player.NickName} {strings.connected_to_game}");
                 room.PlayersMessageChannel.AddPerson(player.ChatId);
-                await Bot.SendWithMarkdown2(player.ChatId, strings.you_connect_to_fast_game, Keyboard.PlayerGameMenu);
                 await Bot.SendHyperLink(player.ChatId, $"<a href='https://t.me/{AppSettings.Name}?start=fast_game={RoomEncrypter.GetCode(room.RoomName)}'>{strings.link}</a>");
                 if (room.Players.Count == Constants.PLAYERS_TO_START_FAST_GAME)
                 {
@@ -87,8 +86,7 @@ namespace MafiaTelegramBot.Controllers
                 var result = await ConnectToGame(player, roomKey);
                 if (result != ResultCode.CodeOk) return result;
                 var room = GetRoom(roomKey);
-                await Bot.SendWithMarkdown2(player.ChatId, strings.you_connect_to_fast_game, Keyboard.PlayerGameMenu);
-                await Bot.SendHyperLink(player.ChatId, $"<a href='https://t.me/{AppSettings.Name}?start=fast_game={RoomEncrypter.GetCode(room.RoomName)}'>{strings.link}</a>");
+                await MessageController.SendTextWithHtml(player.Info, $"<a href='https://t.me/{AppSettings.Name}?start=fast_game={RoomEncrypter.GetCode(room.RoomName)}'>{strings.link}</a>");
                 if (room.Players.Count == Constants.PLAYERS_TO_START_FAST_GAME)
                 {
                     await room.Prepare();

+ 6 - 0
MafiaTelegramBot/CustomCollections/Extensions/DictionaryExtension.cs

@@ -21,5 +21,11 @@ namespace MafiaTelegramBot.CustomCollections.Extensions
             dictionary.Add(k, v);
             return true;
         }
+        
+        public static void AddUniqueOrReplaceByKey<TK, TV>(this Dictionary<TK,TV> dictionary, TK k, TV v)
+        {
+            if (dictionary.ContainsKey(k)) dictionary[k] = v;
+            else dictionary.Add(k, v);
+        }
     }
 }

+ 3 - 1
MafiaTelegramBot/DataBase/Entity/UserEntity.cs

@@ -19,8 +19,10 @@ namespace MafiaTelegramBot.DataBase.Entity
         
         [Column("rank_number") , MaxLength(127)] public int RankNumber { get; set; } = 0;
         
-        [Column("is_admin"), MaxLength(127)] public int IsAdmin { get; set; } = 0;
+        [Column("is_admin"), MaxLength(11)] public bool IsAdmin { get; set; } = false;
 
         [Column("pack_count"), MaxLength(127)] public int PackCount { get; set; } = 0;
+
+        [Column("is_blocked"), MaxLength(11)] public bool IsBlocked { get; set; } = false;
     }
 }

+ 22 - 22
MafiaTelegramBot/DataBase/EntityDao/UserDao.cs

@@ -7,6 +7,7 @@ using MafiaTelegramBot.DataBase.Entity;
 using MafiaTelegramBot.Game;
 using MafiaTelegramBot.Resources;
 using Microsoft.EntityFrameworkCore;
+using Telegram.Bot.Types;
 using static MafiaTelegramBot.Logs;
 
 namespace MafiaTelegramBot.DataBase.EntityDao
@@ -23,32 +24,37 @@ namespace MafiaTelegramBot.DataBase.EntityDao
                 Interval = Constants.MEMORY_CLEANER_INTERVAL,
                 AutoReset = true
             };
-            memoryCleaner.Elapsed += async (_, _) =>
-            {
-                await CleanupMemory();
-            };
+            memoryCleaner.Elapsed += CleanupMemory;
             memoryCleaner.Start();
         }
-        
+
         public static async Task<Player> GetPlayerById(long id)
         {
+            if (!await UserExists(id)) return null;
             if (ActiveUsers.ContainsKey(id)) return ActiveUsers[id];
-            var user = await Task.Run(()=> DataBase.Users.First(user1 => user1.Id == id));
             var player = new Player
             {
-                User = user,
+                Info = await Task.Run(()=> DataBase.Users.First(user1 => user1.Id == id)),
                 OpenedRoles = await OpenedRolesDao.GetOpenedRolesById(id),
                 Achievements = await AchievementsDao.GetAchievementsProgressById(id),
                 Statistics = await StatisticsDao.GetStatisticsListById(id)
             };
-            ActiveUsers.Add(user.Id, player);
+            ActiveUsers.Add(player.Info.Id, player);
             return player;
         }
         
-        public static async Task AddNew(UserEntity user)
+        public static async Task<Player> AddNew(User user)
         {
-            DataBase.Users.Add(user);
+            var newUser = new UserEntity
+            {
+                Id = user.Id,
+                ChatId = user.Id,
+                Username = user.Username,
+                NickName = user.FirstName + (user.FirstName != "" && user.LastName != "" ? " " : "") + user.LastName
+            };
+            DataBase.Users.Add(newUser);
             await DataBase.SaveChangesAsync();
+            return await GetPlayerById(user.Id);
         }
 
         public static async Task<bool> UserExists(long id)
@@ -57,19 +63,13 @@ namespace MafiaTelegramBot.DataBase.EntityDao
             return await DataBase.Users.AnyAsync(user => user.Id == id);
         }
 
-        private static async Task CleanupMemory()
+        private static async void CleanupMemory(object o, ElapsedEventArgs elapsedEventArgs)
         {
             try
             {
                 await DataBase.SaveChangesAsync();
-                LogOut("Saving changes");
                 foreach (var (id, player) in ActiveUsers)
-                {
-                    if (player.GetLastActivityInterval()
-                            .CompareTo(Constants.PLAYER_INACTIVE_INTERVAL) == 1
-                        && player.IsPlaying == false)
-                        ActiveUsers.Remove(id);
-                }
+                    if (player.IsInactive()) ActiveUsers.Remove(id);
             }
             catch (Exception e)
             {
@@ -77,11 +77,11 @@ namespace MafiaTelegramBot.DataBase.EntityDao
             }
         }
 
-        public static async Task<long> GetIdByUsername(string messageText)
+        public static async Task<long> GetIdByUsername(string username)
         {
-            var player = ActiveUsers.Values.FirstOrDefault(p=> p.Username == messageText);
-            if (player != null) return player.Id;
-            var user = await DataBase.Users.FirstOrDefaultAsync(p => p.Username == messageText);
+            var player = ActiveUsers.Values.FirstOrDefault(p=> p.Info.Username == username);
+            if (player != null) return player.Info.Id;
+            var user = await DataBase.Users.FirstOrDefaultAsync(p => p.Username == username);
             return user?.Id ?? -1;
         }
     }

+ 0 - 18
MafiaTelegramBot/Dockerfile

@@ -1,18 +0,0 @@
-FROM mcr.microsoft.com/dotnet/runtime:5.0 AS base
-WORKDIR /app
-
-FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
-WORKDIR /src
-COPY ["MafiaTelegramBot/MafiaTelegramBot.csproj", "MafiaTelegramBot/"]
-RUN dotnet restore "MafiaTelegramBot/MafiaTelegramBot.csproj"
-COPY . .
-WORKDIR "/src/MafiaTelegramBot"
-RUN dotnet build "MafiaTelegramBot.csproj" -c Release -o /app/build
-
-FROM build AS publish
-RUN dotnet publish "MafiaTelegramBot.csproj" -c Release -o /app/publish
-
-FROM base AS final
-WORKDIR /app
-COPY --from=publish /app/publish .
-ENTRYPOINT ["dotnet", "MafiaTelegramBot.dll"]

+ 43 - 84
MafiaTelegramBot/Game/Player.cs

@@ -5,16 +5,19 @@ using System.Linq;
 using System.Threading.Tasks;
 using MafiaTelegramBot.CustomCollections;
 using MafiaTelegramBot.DataBase.Entity;
-using MafiaTelegramBot.DataBase.EntityDao;
 using MafiaTelegramBot.Game.GameRoles;
 using MafiaTelegramBot.Models;
 using MafiaTelegramBot.Resources;
-using Newtonsoft.Json;
 
 namespace MafiaTelegramBot.Game
 {
     public class Player
     {
+        public UserEntity Info = new ();
+        public StatisticsList Statistics = new ();
+        public OpenedRolesEntity OpenedRoles = new ();
+        public AchievementsEntity Achievements = new ();
+        
         public GameRooms.GameRoom.Role CurrentRole = new NoneRole();
         public int TurnOrder = -1;
         private string _roomName = "";
@@ -27,57 +30,21 @@ namespace MafiaTelegramBot.Game
         public bool CanBeBlockedNight = true;
         public bool CanBeBlockedDay = true;
 
-        public long Id
-        {
-            get => User.Id;
-            set => User.Id = value;
-        }
-
-        public long ChatId
-        {
-            get => User.ChatId;
-            set => User.ChatId = value;
-        }
-        
-        public string Username
-        {
-            get => User.Username;
-            set => User.Username = value;
-        }
-        
-        public string NickName
-        {
-            get => User.NickName;
-            set => User.NickName = value;
-        }
-        
-        public int RankNumber
-        {
-            get => User.RankNumber;
-            set => User.RankNumber = value;
-        }
-        
-        public bool IsAdmin
-        {
-            get => User.IsAdmin > 0;
-            set => User.IsAdmin = value ? 1 : 0;
-        }
-
-        public UserEntity User = new ();
-        public StatisticsList Statistics = new ();
-        public OpenedRolesEntity OpenedRoles = new ();
-        public AchievementsEntity Achievements = new ();
-
         public void SetActive()
         {
             _lastActivity = DateTime.Now;
         }
 
-        public TimeSpan GetLastActivityInterval()
+        private TimeSpan GetLastActivityInterval()
         {
             return DateTime.Now.Subtract(_lastActivity);
         }
 
+        public bool IsInactive()
+        {
+            return GetLastActivityInterval().CompareTo(Constants.PLAYER_INACTIVE_INTERVAL) == 1 && !IsPlaying;
+        }
+
         public string GetRoomName()
         {
             return _roomName;
@@ -99,12 +66,7 @@ namespace MafiaTelegramBot.Game
 
         public override bool Equals(object? obj)
         {
-            return obj is Player player && player.Id == Id;
-        }
-
-        public override int GetHashCode()
-        {
-            return Id.GetHashCode();
+            return obj is Player player && player.Info.Id == Info.Id;
         }
 
         public Roles GetRole()
@@ -137,9 +99,8 @@ namespace MafiaTelegramBot.Game
                     Achievements.DoctorHeals++;
                     if (Achievements.DoctorHeals == 10)
                     {
-                        await Bot.SendWithMarkdown2(ChatId,
-                            $"{strings.congrats} {roles.Bodyguard}! {strings.you_can_use}");
-                        await Bot.SendStickerAsync(ChatId, Stickers.Sticker[Roles.Bodyguard.ToString()]);
+                        await Bot.SendWithMarkdown2(Info.ChatId, $"{strings.congrats} {roles.Bodyguard}! {strings.you_can_use}");
+                        await Bot.SendStickerAsync(Info.ChatId, Stickers.Sticker[Roles.Bodyguard.ToString()]);
                         OpenedRoles.OpenBodyguard();
                     }
                 });
@@ -155,9 +116,8 @@ namespace MafiaTelegramBot.Game
                     Achievements.DoctorHeals++;
                     if (Achievements.DoctorHeals == 50)
                     {
-                        await Bot.SendWithMarkdown2(ChatId,
-                            $"{strings.congrats} {roles.Necromancer}! {strings.you_can_use}");
-                        await Bot.SendStickerAsync(ChatId, Stickers.Sticker[Roles.Necromancer.ToString()]);
+                        await Bot.SendWithMarkdown2(Info.ChatId, $"{strings.congrats} {roles.Necromancer}! {strings.you_can_use}");
+                        await Bot.SendStickerAsync(Info.ChatId, Stickers.Sticker[Roles.Necromancer.ToString()]);
                         OpenedRoles.OpenNecromancer();
                     }
                 });
@@ -173,9 +133,8 @@ namespace MafiaTelegramBot.Game
                     Achievements.CopDispatches++;
                     if (Achievements.CopDispatches == 3)
                     {
-                        await Bot.SendWithMarkdown2(ChatId,
-                            $"{strings.congrats} {roles.Fool}! {strings.you_can_use}");
-                        await Bot.SendStickerAsync(ChatId, Stickers.Sticker[Roles.Fool.ToString()]);
+                        await Bot.SendWithMarkdown2(Info.ChatId, $"{strings.congrats} {roles.Fool}! {strings.you_can_use}");
+                        await Bot.SendStickerAsync(Info.ChatId, Stickers.Sticker[Roles.Fool.ToString()]);
                         OpenedRoles.OpenFool();
                     }
                 });
@@ -188,9 +147,9 @@ namespace MafiaTelegramBot.Game
             {
                 Task.Run(async () =>
                 {
-                    await Bot.SendWithMarkdown2(ChatId,
+                    await Bot.SendWithMarkdown2(Info.ChatId,
                         $"{strings.congrats} {roles.Journalist}! {strings.you_can_use}");
-                    await Bot.SendStickerAsync(ChatId, Stickers.Sticker[Roles.Journalist.ToString()]);
+                    await Bot.SendStickerAsync(Info.ChatId, Stickers.Sticker[Roles.Journalist.ToString()]);
                     OpenedRoles.OpenJournalist();
                 });
             }
@@ -205,9 +164,9 @@ namespace MafiaTelegramBot.Game
                     Achievements.GamesWhereCopCheckOnlyMafia++;
                     if (Achievements.GamesWhereCopCheckOnlyMafia == 3)
                     {
-                        await Bot.SendWithMarkdown2(ChatId,
+                        await Bot.SendWithMarkdown2(Info.ChatId,
                             $"{strings.congrats} {roles.Detective}! {strings.you_can_use}");
-                        await Bot.SendStickerAsync(ChatId, Stickers.Sticker[Roles.Detective.ToString()]);
+                        await Bot.SendStickerAsync(Info.ChatId, Stickers.Sticker[Roles.Detective.ToString()]);
                         OpenedRoles.OpenDetective();
                     }
                 });
@@ -223,9 +182,9 @@ namespace MafiaTelegramBot.Game
                     Achievements.HaveSexWithDon++;
                     if (Achievements.HaveSexWithDon == 5)
                     {
-                        await Bot.SendWithMarkdown2(ChatId,
+                        await Bot.SendWithMarkdown2(Info.ChatId,
                             $"{strings.congrats} {roles.Dame}! {strings.you_can_use}");
-                        await Bot.SendStickerAsync(ChatId, Stickers.Sticker[Roles.Dame.ToString()]);
+                        await Bot.SendStickerAsync(Info.ChatId, Stickers.Sticker[Roles.Dame.ToString()]);
                         OpenedRoles.OpenDame();
                     }
                 }
@@ -241,9 +200,9 @@ namespace MafiaTelegramBot.Game
                     Achievements.NotDispatchedOnSecondStage++;
                     if (Achievements.NotDispatchedOnSecondStage == 2)
                     {
-                        await Bot.SendWithMarkdown2(ChatId,
+                        await Bot.SendWithMarkdown2(Info.ChatId,
                             $"{strings.congrats} {roles.Elder}! {strings.you_can_use}");
-                        await Bot.SendStickerAsync(ChatId, Stickers.Sticker[Roles.Elder.ToString()]);
+                        await Bot.SendStickerAsync(Info.ChatId, Stickers.Sticker[Roles.Elder.ToString()]);
                         OpenedRoles.OpenElder();
                     }
                 }
@@ -259,9 +218,9 @@ namespace MafiaTelegramBot.Game
                     Achievements.MafiaSoloWins++;
                     if (Achievements.MafiaSoloWins == 3)
                     {
-                        await Bot.SendWithMarkdown2(ChatId,
+                        await Bot.SendWithMarkdown2(Info.ChatId,
                             $"{strings.congrats} {roles.Lawyer}! {strings.you_can_use}");
-                        await Bot.SendStickerAsync(ChatId, Stickers.Sticker[Roles.Lawyer.ToString()]);
+                        await Bot.SendStickerAsync(Info.ChatId, Stickers.Sticker[Roles.Lawyer.ToString()]);
                         OpenedRoles.OpenLawyer();
                     }
                 });
@@ -281,9 +240,9 @@ namespace MafiaTelegramBot.Game
                     else if ((Achievements.PreviousGameWinColor == 1 && color == 2)
                              || (Achievements.PreviousGameWinColor == 2 && color == 1))
                     {
-                        await Bot.SendWithMarkdown2(ChatId,
+                        await Bot.SendWithMarkdown2(Info.ChatId,
                             $"{strings.congrats} {roles.Werewolf}! {strings.you_can_use}");
-                        await Bot.SendStickerAsync(ChatId, Stickers.Sticker[Roles.Werewolf.ToString()]);
+                        await Bot.SendStickerAsync(Info.ChatId, Stickers.Sticker[Roles.Werewolf.ToString()]);
                         OpenedRoles.OpenWerewolf();
                     }
                     else
@@ -300,9 +259,9 @@ namespace MafiaTelegramBot.Game
             {
                 Task.Run(async () =>
                 {
-                    await Bot.SendWithMarkdown2(ChatId,
+                    await Bot.SendWithMarkdown2(Info.ChatId,
                         $"{strings.congrats} {roles.Hooker}! {strings.you_can_use}");
-                    await Bot.SendStickerAsync(ChatId, Stickers.Sticker[Roles.Hooker.ToString()]);
+                    await Bot.SendStickerAsync(Info.ChatId, Stickers.Sticker[Roles.Hooker.ToString()]);
                     OpenedRoles.OpenHooker();
                 });
             }
@@ -314,7 +273,7 @@ namespace MafiaTelegramBot.Game
             {
                 await Task.Run(async () =>
                 {
-                    team.Remove(Id);
+                    team.Remove(Info.Id);
                     if (Achievements.PlayerWinTeam == "")
                     {
                         Achievements.PlayerWinTeam = BuildString(team);
@@ -343,9 +302,9 @@ namespace MafiaTelegramBot.Game
                                 if (secondCross.Count == 0) Achievements.PlayerWinTeamTwo = BuildString(team);
                                 else
                                 {
-                                    await Bot.SendWithMarkdown2(ChatId,
+                                    await Bot.SendWithMarkdown2(Info.ChatId,
                                         $"{strings.congrats} {roles.Parasite}! {strings.you_can_use}");
-                                    await Bot.SendStickerAsync(ChatId, Stickers.Sticker[Roles.Parasite.ToString()]);
+                                    await Bot.SendStickerAsync(Info.ChatId, Stickers.Sticker[Roles.Parasite.ToString()]);
                                     OpenedRoles.OpenParasite();
                                 }
                             }
@@ -371,7 +330,7 @@ namespace MafiaTelegramBot.Game
 
         public char GetRank()
         {
-            return RankNumber switch
+            return Info.RankNumber switch
             {
                 <100 => 'a',
                 >=100 and <300 => 'b',
@@ -386,22 +345,22 @@ namespace MafiaTelegramBot.Game
             {
                 case 'a':
                 {
-                    RankNumber += CurrentRole.RankingCost;
+                    Info.RankNumber += CurrentRole.RankingCost;
                     return CurrentRole.RankingCost;
                 }
                 case 'b':
                 {
-                    RankNumber += CurrentRole.RankingCost;
+                    Info.RankNumber += CurrentRole.RankingCost;
                     return CurrentRole.RankingCost;
                 }
                 case 'c':
                 {
-                    RankNumber += (int)(CurrentRole.RankingCost * Statistics[Roles.All].GetWinrate());
+                    Info.RankNumber += (int)(CurrentRole.RankingCost * Statistics[Roles.All].GetWinrate());
                     return (int)(CurrentRole.RankingCost * Statistics[Roles.All].GetWinrate());
                 }
                 case 'd':
                 {
-                    RankNumber += (int)(CurrentRole.RankingCost * Statistics[Roles.All].GetWinrate());
+                    Info.RankNumber += (int)(CurrentRole.RankingCost * Statistics[Roles.All].GetWinrate());
                     return (int)(CurrentRole.RankingCost * Statistics[Roles.All].GetWinrate());
                 }
                 default: return 0;
@@ -414,17 +373,17 @@ namespace MafiaTelegramBot.Game
             {
                 case 'b':
                 {
-                    RankNumber -= CurrentRole.RankingCost;
+                    Info.RankNumber -= CurrentRole.RankingCost;
                     return CurrentRole.RankingCost;
                 }
                 case 'c':
                 {
-                    RankNumber -= (int)(CurrentRole.RankingCost * Statistics[Roles.All].GetWinrate());
+                    Info.RankNumber -= (int)(CurrentRole.RankingCost * Statistics[Roles.All].GetWinrate());
                     return (int)(CurrentRole.RankingCost * Statistics[Roles.All].GetWinrate());
                 }
                 case 'd':
                 {
-                    RankNumber -= CurrentRole.RankingCost;
+                    Info.RankNumber -= CurrentRole.RankingCost;
                     return CurrentRole.RankingCost;
                 }
                 default: return 0;

+ 0 - 193
MafiaTelegramBot/Models/Bot.cs

@@ -1,193 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using MafiaTelegramBot.DataBase.EntityDao;
-using MafiaTelegramBot.Game;
-using MafiaTelegramBot.Models.Commands;
-using MafiaTelegramBot.Models.Inlines;
-using MafiaTelegramBot.Models.Payments;
-using MafiaTelegramBot.Resources;
-using Telegram.Bot;
-using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
-using Telegram.Bot.Types.ReplyMarkups;
-using static MafiaTelegramBot.Logs;
-
-namespace MafiaTelegramBot.Models
-{
-    public static class Bot
-    {
-        private static TelegramBotClient _client;
-        private static List<Command> _commandsList;
-        private static List<Query> _queriesList;
-        private static List<Payment> _paymentsList;
-        
-        public static IReadOnlyList<Command> Commands => _commandsList.AsReadOnly();
-        public static IReadOnlyList<Query> Queries => _queriesList.AsReadOnly();
-        public static IReadOnlyList<Payment> Payments => _paymentsList.AsReadOnly();
-
-        public static readonly List<long> UsersThatChangesNickname = new();
-        public static readonly Dictionary<long, string> UsersThatCreatesRoom = new();
-        public static readonly List<long> UserThatEntersPrivateCode = new();
-
-        public static TelegramBotClient Get()
-        {
-            if (_client != null) return _client;
-            InitCommands();
-            InitQueries();
-            InitPayments();
-            _client = new TelegramBotClient(AppSettings.Token);
-            return _client;
-        }
-
-        private static void InitCommands()
-        {
-            //TODO fill commands array
-            _commandsList = new List<Command>
-            {
-                new StartCommand(),
-                new CreateGameCommand(),
-                new ConnectGameCommand(),
-                new ShowProfileCommand(),
-                new RoomSettingsCommand(),
-                new LeaveCommand(),
-                new LookPlayersListCommand(),
-                new KickPlayerCommand(),
-                new DissolveRoomCommand(),
-                new StartGameCommand(),
-                new AdminPanelCommand(),
-                new FastGameCommand(),
-            };
-        }
-        
-        private static void InitQueries()
-        {
-            //TODO fill inline keyboard array
-            _queriesList = new List<Query>
-            {
-                new ShowMyRolesQuery(),
-                new ShopMenuQuery(),
-                new SettingsProfileQuery(),
-                new ChangeNickNameQuery(),
-                new SettingsRoomQuery(),
-                new ConnectToPrivateRoomQuery(),
-                new SetPlayersMaximumQuery(),
-                new ConnectToPublicRoomQuery(),
-                new ConnectToSelectedRoomQuery(),
-                new KickSelectedPlayerQuery(),
-                new SwitchTimerQuery(),
-                new ChangeRolesQuery(),
-                new PlayersCountSettingsQuery(),
-                new ApplyRolesChangeQuery(),
-                new StartGameQuery(),
-                new ShowMyExtendedStatsQuery(),
-                new ChooseRoomViewQuery(),
-                new ChooseGameTypeQuery(),
-                new ChooseGameModeQuery(),
-                new ConnectToRankedQuery(),
-                new ConnectToNotRankedQuery(),
-                new GiveToSelectedQuery(),
-                new GiveRoleQuery(),
-                new GiveToAllQuery(),
-                new ContinueQuery(),
-                new PackInfoQuery(),
-                new PackOpenQuery(),
-                new ShowMyPacksQuery(),
-                new BackToProfileQuery(),
-            };
-        }
-        
-        private static void InitPayments()
-        {
-            //TODO fill inline keyboard array
-            _paymentsList = new List<Payment>
-            {
-                new RandomRolePayment()
-            };
-        }
-
-        public static async Task<Message> SendStickerAsync(long chatId, string fileId)
-        {
-            try
-            {
-                return await Get().SendStickerAsync(chatId, fileId, true);
-            }
-            catch (Exception e)
-            {
-                LogOutError(e.Message);
-                return new Message();
-            }
-        }
-
-        public static async Task<Message> SendHyperLink(long chatId, string message)
-        {
-            try
-            {
-                return await Get().SendTextMessageAsync(chatId, message, ParseMode.Html, disableNotification: true);
-            }
-            catch (Exception e)
-            {
-                LogOutError(e.Message);
-                return new Message();
-            }
-        }
-        
-        public static async Task<Message> SendWithMarkdown2(long chatId, string message, IReplyMarkup replyMarkup = null)
-        {
-            try
-            {
-                var editedMessage = await Utilities.ToMarkdownString(message);
-                return await Get().SendTextMessageAsync(chatId, editedMessage,
-                    ParseMode.MarkdownV2, replyMarkup: replyMarkup, disableNotification: true);
-            }
-            catch (Exception e)
-            {
-                LogOutError(e.Message);
-                return new Message();
-            }
-        }
-
-        public static async Task<Message> EditMessageAsync(long chatId, int messageId, string message, InlineKeyboardMarkup keyboard = null)
-        {
-            try
-            {
-                var editedMessage = await Utilities.ToMarkdownString(message);
-                return await Get().EditMessageTextAsync(chatId, messageId, editedMessage, ParseMode.MarkdownV2, replyMarkup: keyboard);
-            }
-            catch (Exception e)
-            {
-                LogOutError(e.Message);
-                return new Message();
-            }
-        }
-
-        public static async Task AnswerPreCheckoutQuery(string preCheckoutQueryId)
-        {
-            var token = new CancellationToken();
-            await Get().AnswerPreCheckoutQueryAsync(preCheckoutQueryId, token);
-        }
-
-        public static async Task RegisterNewUser(Update update)
-        {
-            var chatId = update.Message.Chat.Id;
-            var userId = update.Message.From.Id;
-            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 nickName = "";
-            if (firstName != "") nickName += firstName;
-            if(lastName != "") nickName += nickName != "" ? $" {lastName}" : lastName;
-            var user = new Player
-            {
-                Id = userId,
-                ChatId = chatId,
-                Username = username,
-                NickName =  nickName
-            };
-            await UserDao.AddNew(user.User);
-            await StatisticsDao.CreatePlayerStats(user.Id);
-            UserDao.ActiveUsers.Add(user.Id, user);
-        }
-    }
-}

+ 0 - 18
MafiaTelegramBot/Models/Commands/AdminPanelCommand.cs

@@ -1,18 +0,0 @@
-using System.Threading.Tasks;
-using MafiaTelegramBot.DataBase.EntityDao;
-using MafiaTelegramBot.Resources;
-using Telegram.Bot.Types;
-
-namespace MafiaTelegramBot.Models.Commands
-{
-    public class AdminPanelCommand : Command
-    {
-        protected override string Name => keyboard.admin_panel;
-        protected override async Task<Message> Execute(Update update)
-        {
-            var user = await UserDao.GetPlayerById(UserId);
-            if (user.IsAdmin) return await Bot.SendWithMarkdown2(ChatId, strings.start_message, Keyboard.AdminPanelKeyboard(UserId));
-            return await Bot.SendWithMarkdown2(ChatId, $"{strings.command_not_found} _*({update.Message.Text})*_");
-        }
-    }
-}

+ 0 - 72
MafiaTelegramBot/Models/Commands/Command.cs

@@ -1,72 +0,0 @@
-#nullable enable
-using System;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-using MafiaTelegramBot.Controllers;
-using MafiaTelegramBot.DataBase.EntityDao;
-using MafiaTelegramBot.Game;
-using MafiaTelegramBot.Models.Commands.CustomMessageHandlers;
-using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
-
-namespace MafiaTelegramBot.Models.Commands
-{
-    public abstract class Command : UpdateModel<string>
-    {
-        private static readonly Dictionary<string, Command> CustomHandlers = new()
-        {
-            {"UsersThatChangesNickname", new ChangeNicknameHandler()},
-            {"UsersThatCreatesRoom", new CreateRoomHandler()},
-            {"UserThatEntersPrivateCode", new EnterCodeHandler()},
-        };
-
-        protected override bool IsMatches(string command)
-        {
-            return command == Name;
-        }
-
-        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);
-            
-            if (!await UserDao.UserExists(userId)) await Bot.RegisterNewUser(update);
-            
-            var user = await UserDao.GetPlayerById(userId);
-            if (user.Username != update.Message.From.Username) user.Username = update.Message.From.Username;
-            user.SetActive();
-            var commands = Bot.Commands;
-            var message = update.Message.Text;
-            
-            if (user.IsPlaying)
-            {
-                var roomKey = RoomEncrypter.GetCode(user.GetRoomName());
-                var room = RoomController.GetRoom(roomKey);
-                if(room == null)
-                    return await Bot.SendWithMarkdown2(chatId, strings.room_does_not_exists);
-                return await room.MHandler.Handle(update);
-            }
-            
-            var command = FirstOrDefault(commands, message);
-            if(command != null) return await ((Command?) command.Clone(chatId, userId))!.Execute(update);
-            if (await GiveRoleToPlayerHandler.ContainsInQueue(userId))
-                return await new GiveRoleToPlayerHandler(userId, chatId).Execute(update);
-            if (Bot.UsersThatChangesNickname.Remove(userId))
-                return await ((Command?) CustomHandlers["UsersThatChangesNickname"].Clone(chatId, userId))!.Execute(update);
-            if (Bot.UsersThatCreatesRoom.ContainsKey(userId))
-                return await ((Command?) CustomHandlers["UsersThatCreatesRoom"].Clone(chatId, userId))!.Execute(update);
-            if (Bot.UserThatEntersPrivateCode.Remove(userId))
-                return await ((Command?) CustomHandlers["UserThatEntersPrivateCode"].Clone(chatId, userId))!.Execute(update);
-            if (user.GetRoomName() == "")
-                return await Bot.SendWithMarkdown2(chatId, $"{strings.command_not_found} _*({message})*_");
-            {
-                var roomKey = RoomEncrypter.GetCode(user.GetRoomName());
-                var room = RoomController.GetRoom(roomKey);
-                if(room == null)
-                    return await Bot.SendWithMarkdown2(chatId, strings.room_does_not_exists);
-                return await room.MHandler.Handle(update);
-            }
-        }
-    }
-}

+ 0 - 21
MafiaTelegramBot/Models/Commands/ConnectGameCommand.cs

@@ -1,21 +0,0 @@
-using System.Threading.Tasks;
-using MafiaTelegramBot.DataBase.EntityDao;
-using MafiaTelegramBot.Resources;
-using Telegram.Bot.Types;
-
-namespace MafiaTelegramBot.Models.Commands
-{
-    public class ConnectGameCommand : Command
-    {
-        protected override string Name => keyboard.connect_game;
-
-        protected override async Task<Message> Execute(Update update)
-        {
-            var user = await UserDao.GetPlayerById(UserId);
-            if (user.GetRoomName() != "")
-                return await Bot.SendWithMarkdown2(ChatId, strings.user_already_in_game);
-            return await Bot.SendWithMarkdown2(ChatId, strings.choose_type_room, 
-                Keyboard.RoomTypeKeyboard(UserId));
-        }
-    }
-}

+ 0 - 20
MafiaTelegramBot/Models/Commands/CreateGameCommand.cs

@@ -1,20 +0,0 @@
-using System.Threading.Tasks;
-using MafiaTelegramBot.DataBase.EntityDao;
-using MafiaTelegramBot.Resources;
-using Telegram.Bot.Types;
-
-namespace MafiaTelegramBot.Models.Commands
-{
-    public class CreateGameCommand : Command
-    {
-        protected override string Name => keyboard.create_game;
-
-        protected override async Task<Message> Execute(Update update)
-        {
-            var user = await UserDao.GetPlayerById(UserId);
-            if (user.GetRoomName() != "")
-                return await Bot.SendWithMarkdown2(ChatId, strings.user_already_in_game);
-            return await Bot.SendWithMarkdown2(ChatId, strings.choose_game_view, Keyboard.ChooseRoomView(UserId));
-        }
-    }
-}

+ 0 - 20
MafiaTelegramBot/Models/Commands/CustomMessageHandlers/ChangeNicknameHandler.cs

@@ -1,20 +0,0 @@
-using System.Threading.Tasks;
-using MafiaTelegramBot.DataBase.EntityDao;
-using Telegram.Bot.Types;
-
-namespace MafiaTelegramBot.Models.Commands.CustomMessageHandlers
-{
-    public class ChangeNicknameHandler : Command
-    {
-        protected override string Name => "ChangeNicknameHandler";
-
-        protected override async Task<Message> Execute(Update update)
-        {
-            var newNickname = update.Message.Text;
-            var escapedNickName = await Utilities.EscapeSpecific(newNickname);
-            var user = await UserDao.GetPlayerById(UserId);
-            user.NickName = newNickname;
-            return await Bot.SendWithMarkdown2(ChatId, $"{strings.name_updated} _*{escapedNickName}*_");
-        }
-    }
-}

+ 0 - 35
MafiaTelegramBot/Models/Commands/CustomMessageHandlers/CreateRoomHandler.cs

@@ -1,35 +0,0 @@
-using System.Threading.Tasks;
-using MafiaTelegramBot.Controllers;
-using MafiaTelegramBot.DataBase.EntityDao;
-using MafiaTelegramBot.Game;
-using MafiaTelegramBot.Resources;
-using Telegram.Bot.Types;
-
-namespace MafiaTelegramBot.Models.Commands.CustomMessageHandlers
-{
-    public class CreateRoomHandler : Command
-    {
-        protected override string Name => "CreateRoomHandler";
-
-        protected override async Task<Message> Execute(Update update)
-        {
-            var param = Bot.UsersThatCreatesRoom[UserId];
-            Bot.UsersThatCreatesRoom.Remove(UserId);
-            var isPrivate = param[0] == Constants.PRIVATE + '0';
-            var isExtended = param[1] == Constants.EXTENDED + '0';
-            var isRanking = param[2] == Constants.RANKING + '0';
-            var user = await UserDao.GetPlayerById(UserId);
-            var roomName = update.Message.Text;
-            var resultCode = await RoomController.CreateNewGame(user, roomName, isExtended, isPrivate, isRanking);
-            var result = resultCode == ResultCode.CodeOk
-                ? await Bot.SendWithMarkdown2(ChatId, 
-                    $"{strings.room_with_name} _*{roomName}*_ {strings.was_created}\n", Keyboard.OwnerGameMenu)
-                : await Utilities.GetResultCodeMessage(resultCode, ChatId);
-            if (resultCode == ResultCode.CodeOk && isPrivate)
-                await Bot.SendWithMarkdown2(ChatId, $"{strings.secret_key_is} _*{roomName}*_: ```{RoomEncrypter.GetCode(roomName)}```");
-            if (resultCode == ResultCode.CodeOk && !isRanking)
-                await Bot.SendHyperLink(ChatId, $"<a href='https://t.me/{AppSettings.Name}?start=room_key={RoomEncrypter.GetCode(roomName)}'>{strings.link}</a>");
-            return result;
-        }
-    }
-}

+ 0 - 24
MafiaTelegramBot/Models/Commands/CustomMessageHandlers/EnterCodeHandler.cs

@@ -1,24 +0,0 @@
-using System.Threading.Tasks;
-using MafiaTelegramBot.Controllers;
-using MafiaTelegramBot.DataBase.EntityDao;
-using MafiaTelegramBot.Resources;
-using Telegram.Bot.Types;
-
-namespace MafiaTelegramBot.Models.Commands.CustomMessageHandlers
-{
-    public class EnterCodeHandler : Command
-    {
-        protected override string Name => "EnterCodeHandler";
-
-        protected override async Task<Message> Execute(Update update)
-        {
-            var user = await UserDao.GetPlayerById(UserId);
-            var roomKey = update.Message.Text;
-            var resultCode = await RoomController.ConnectToGame(user, roomKey);
-            var result = resultCode == ResultCode.CodeOk
-                ? Bot.SendWithMarkdown2(ChatId, strings.successful_entry_into_room, Keyboard.PlayerGameMenu)
-                : Utilities.GetResultCodeMessage(resultCode, ChatId);
-            return await result;
-        }
-    }
-}

+ 0 - 39
MafiaTelegramBot/Models/Commands/CustomMessageHandlers/GiveRoleToPlayerHandler.cs

@@ -1,39 +0,0 @@
-using System.Collections.Generic;
-using System.Threading.Tasks;
-using MafiaTelegramBot.CustomCollections.Extensions;
-using MafiaTelegramBot.DataBase.EntityDao;
-using MafiaTelegramBot.Resources;
-using Telegram.Bot.Types;
-
-namespace MafiaTelegramBot.Models.Commands.CustomMessageHandlers
-{
-    public class GiveRoleToPlayerHandler : Command
-    {
-        protected override string Name => "GiveRoleToPlayerHandler";
-        private static List<long> _queue = new ();
-
-        public GiveRoleToPlayerHandler(long userId, long chatId)
-        {
-            UserId = userId;
-            ChatId = chatId;
-        }
-        
-        protected override async Task<Message> Execute(Update update)
-        {
-            _queue.Remove(UserId);
-            var targetId = await UserDao.GetIdByUsername(update.Message.Text);
-            if (targetId == -1) return await Bot.SendWithMarkdown2(ChatId, strings.user_not_exists);
-            return await Bot.SendWithMarkdown2(ChatId, strings.choose_role_to_give, Keyboard.GiveRoleKeyboard(UserId, targetId));
-        }
-
-        public static Task AddToQueue(long id)
-        {
-            return Task.FromResult(_queue.AddUnique(id));
-        }
-
-        public static Task<bool> ContainsInQueue(long id)
-        {
-            return Task.FromResult(_queue.Contains(id));
-        }
-    }
-}

+ 0 - 30
MafiaTelegramBot/Models/Commands/DissolveRoomCommand.cs

@@ -1,30 +0,0 @@
-using System.Threading.Tasks;
-using MafiaTelegramBot.Controllers;
-using MafiaTelegramBot.DataBase.EntityDao;
-using MafiaTelegramBot.Game;
-using MafiaTelegramBot.Resources;
-using Telegram.Bot.Types;
-
-namespace MafiaTelegramBot.Models.Commands
-{
-    public class DissolveRoomCommand : Command
-    {
-        protected override string Name => keyboard.dissolve_room;
-        protected override async Task<Message> Execute(Update update)
-        { 
-            var user = await UserDao.GetPlayerById(UserId);
-            var roomKey = RoomEncrypter.GetCode(user.GetRoomName());
-            var room = RoomController.GetRoom(roomKey);
-            if(room == null)
-                return await Bot.SendWithMarkdown2(ChatId, strings.room_does_not_exists);
-            if (!user.Equals(room.Owner))
-                return await Bot.SendWithMarkdown2(ChatId, $"{strings.command_not_found} _*({update.Message.Text})*_");
-            var resultCode = await RoomController.LeaveFromGame(user);
-            var result = resultCode == ResultCode.CodeOk
-                ? await Bot.SendWithMarkdown2(ChatId, strings.room_dissolved, user.IsAdmin ? Keyboard.AdminMainMenu : Keyboard.MainMenu)
-                : await Utilities.GetResultCodeMessage(resultCode, ChatId);
-            if (resultCode == ResultCode.CodeOk) await RoomController.DissolveRoom(roomKey);
-            return result;
-        }
-    }
-}

+ 0 - 21
MafiaTelegramBot/Models/Commands/FastGameCommand.cs

@@ -1,21 +0,0 @@
-using System.Threading.Tasks;
-using MafiaTelegramBot.Controllers;
-using MafiaTelegramBot.DataBase.EntityDao;
-using MafiaTelegramBot.Resources;
-using Telegram.Bot.Types;
-
-namespace MafiaTelegramBot.Models.Commands
-{
-    public class FastGameCommand : Command
-    {
-        protected override string Name => keyboard.fast_game;
-        protected override async Task<Message> Execute(Update update)
-        {
-            var player = await UserDao.GetPlayerById(UserId);
-            if (player.GetRoomName() != "")
-                return await Bot.SendWithMarkdown2(ChatId, strings.user_already_in_game);
-            await RoomController.ConnectToFastGame(player);
-            return new Message();
-        }
-    }
-}

+ 0 - 29
MafiaTelegramBot/Models/Commands/KickPlayerCommand.cs

@@ -1,29 +0,0 @@
-using System.Threading.Tasks;
-using MafiaTelegramBot.Controllers;
-using MafiaTelegramBot.DataBase.EntityDao;
-using MafiaTelegramBot.Game;
-using MafiaTelegramBot.Resources;
-using Telegram.Bot.Types;
-
-namespace MafiaTelegramBot.Models.Commands
-{
-    public class KickPlayerCommand : Command
-    {
-        protected override string Name => keyboard.kick_player;
-        protected override async Task<Message> Execute(Update update)
-        {
-            var user = await UserDao.GetPlayerById(UserId);
-            var roomKey = RoomEncrypter.GetCode(user.GetRoomName());
-            var room = RoomController.GetRoom(roomKey);
-            if(room == null)
-                return await Bot.SendWithMarkdown2(ChatId, strings.room_does_not_exists);
-            if (!user.Equals(room.Owner))
-                return await Bot.SendWithMarkdown2(ChatId, $"{strings.command_not_found} _*({update.Message.Text})*_");
-            var players = await room.GetPlayers();
-            if (players.Count > 0)
-                return await Bot.SendWithMarkdown2(ChatId, strings.kick_user, Keyboard.KickKeyboard(players));
-            return await Bot.SendWithMarkdown2(ChatId, strings.users_list_empty);
-        }
-        
-    }
-}

+ 0 - 23
MafiaTelegramBot/Models/Commands/LeaveCommand.cs

@@ -1,23 +0,0 @@
-using System.Threading.Tasks;
-using MafiaTelegramBot.Controllers;
-using MafiaTelegramBot.DataBase.EntityDao;
-using MafiaTelegramBot.Resources;
-using Telegram.Bot.Types;
-
-namespace MafiaTelegramBot.Models.Commands
-{
-    public class LeaveCommand : Command
-    {
-        protected override string Name => keyboard.leave;
-
-        protected override async Task<Message> Execute(Update update)
-        {
-            var user = await UserDao.GetPlayerById(UserId);
-            var roomName = user.GetRoomName();
-            var resultCode = await RoomController.LeaveFromGame(user);
-            return resultCode == ResultCode.CodeOk
-                ? await Bot.SendWithMarkdown2(ChatId, $"{strings.you_leave_from_game} _*{roomName}*_", user.IsAdmin ? Keyboard.AdminMainMenu : Keyboard.MainMenu)
-                : await Utilities.GetResultCodeMessage(resultCode, ChatId);
-        }
-    }
-}

+ 0 - 30
MafiaTelegramBot/Models/Commands/LookPlayersListCommand.cs

@@ -1,30 +0,0 @@
-using System.Linq;
-using System.Threading.Tasks;
-using MafiaTelegramBot.Controllers;
-using MafiaTelegramBot.DataBase.EntityDao;
-using MafiaTelegramBot.Game;
-using MafiaTelegramBot.Resources;
-using Telegram.Bot.Types;
-
-namespace MafiaTelegramBot.Models.Commands
-{
-    public class LookPlayersListCommand : Command
-    {
-        protected override string Name => keyboard.look_players_list;
-
-        protected override async Task<Message> Execute(Update update)
-        {
-            var user = await UserDao.GetPlayerById(UserId);
-            var roomKey = RoomEncrypter.GetCode(user.GetRoomName());
-            var room = RoomController.GetRoom(roomKey);
-            if(room == null)
-                return await Bot.SendWithMarkdown2(ChatId, strings.room_does_not_exists);
-            var users = RoomController.GetPlayers(roomKey);
-            var list = users.Count > 1
-                ? users.Where(player => !player.Equals(user))
-                    .Aggregate($"{strings.users_list} {users.Count}\n\n @{user.Username}\n{strings.you}", (current, player) => current + $"\n \n@{player.Username}\n{player.NickName}")
-                : strings.users_list_empty;
-            return await Bot.SendWithMarkdown2(ChatId, list);
-        }
-    }
-}

+ 0 - 28
MafiaTelegramBot/Models/Commands/RoomSettingsCommand.cs

@@ -1,28 +0,0 @@
-using System.Threading.Tasks;
-using MafiaTelegramBot.Controllers;
-using MafiaTelegramBot.DataBase.EntityDao;
-using MafiaTelegramBot.Game;
-using MafiaTelegramBot.Resources;
-using Telegram.Bot.Types;
-
-namespace MafiaTelegramBot.Models.Commands
-{
-    public class RoomSettingsCommand : Command
-    {
-        protected override string Name => keyboard.room_settings;
-
-        protected override async Task<Message> Execute(Update update)
-        {
-            var user = await UserDao.GetPlayerById(UserId);
-            var roomKey = RoomEncrypter.GetCode(user.GetRoomName());
-            var room = RoomController.GetRoom(roomKey);
-            if(room == null)
-                return await Bot.SendWithMarkdown2(ChatId, strings.room_does_not_exists);
-            if (!user.Equals(room.Owner))
-                return await Bot.SendWithMarkdown2(ChatId, $"{strings.command_not_found} _*({update.Message.Text})*_");
-            var status = room.TimerEnabled ? strings.enabled : strings.disabled;
-            return await Bot.SendWithMarkdown2(ChatId, strings.what_settings, 
-                Keyboard.SettingsRoomKeyboard(UserId, $"{strings.timer}: {status}"));
-        }
-    }
-}

+ 0 - 31
MafiaTelegramBot/Models/Commands/ShowProfileCommand.cs

@@ -1,31 +0,0 @@
-using System;
-using System.Linq;
-using System.Threading.Tasks;
-using MafiaTelegramBot.DataBase.EntityDao;
-using MafiaTelegramBot.Resources;
-using Telegram.Bot.Types;
-
-namespace MafiaTelegramBot.Models.Commands
-{
-    public class ShowProfileCommand : Command
-    {
-        protected override string Name => keyboard.show_profile;
-
-        protected override async Task<Message> Execute(Update update)
-        { 
-            var user = await UserDao.GetPlayerById(UserId);
-            var rolesList = Enum.GetValues(typeof(Roles)).Cast<Roles>().ToList();
-            rolesList.Remove(Roles.None);
-            rolesList.Remove(Roles.All);
-            var allStatsRow = user.Statistics[Roles.All];
-            var message =
-                $"__*{strings.statistics_for} _{user.NickName}_*__\n" +
-                $"{strings.games_count} {allStatsRow.Games}\n" +
-                $"{strings.wins_count} {allStatsRow.Wins}\n" +
-                $"{strings.winrate} {(int)(allStatsRow.GetWinrate()*100)}%\n" +
-                $"{strings.rate} {user.RankNumber}";
-            return await Bot.SendWithMarkdown2(ChatId, message, Keyboard.ProfileKeyboard(UserId));
-            
-        }
-    }
-}

+ 0 - 76
MafiaTelegramBot/Models/Commands/StartCommand.cs

@@ -1,76 +0,0 @@
-using System;
-using System.Threading.Tasks;
-using MafiaTelegramBot.Controllers;
-using MafiaTelegramBot.DataBase.EntityDao;
-using MafiaTelegramBot.Game;
-using MafiaTelegramBot.Other;
-using MafiaTelegramBot.Resources;
-using Telegram.Bot.Types;
-
-namespace MafiaTelegramBot.Models.Commands
-{
-    public class StartCommand : Command
-    {
-        protected override string Name => "/start";
-
-        protected override async Task<Message> Execute(Update update)
-        {
-            var command = update.Message.Text.Split(' ');
-            var player = await UserDao.GetPlayerById(UserId);
-            if (command.Length == 2)
-            {
-                var values = command[1].Split('=');
-                return values[0] switch
-                {
-                    "giveaway_id" => await GiveawayCommand(player, int.Parse(values[1])),
-                    "room_key" => await ConnectToGameCommand(player, values[1]),
-                    "fast_game" => await ConnectToFastGameCommand(player, values[1]),
-                    _ => new Message()
-                };
-            }
-            if (player.GetRoomName() != "")
-                return await Bot.SendWithMarkdown2(ChatId, $"{strings.prefer_leave_from_room} {player.GetRoomName()}");
-            return await Bot.SendWithMarkdown2(ChatId, strings.start_message, player.IsAdmin ? Keyboard.AdminMainMenu : Keyboard.MainMenu);
-        }
-
-        protected override bool IsMatches(string command)
-        {
-            return command.Contains(Name);
-        }
-
-        private async Task<Message> GiveawayCommand(Player player, int id)
-        {
-            try
-            {
-                var giveaway = GiveAway.OpenedGiveaways[id];
-                return await giveaway.GivePrizeTo(player) == ResultCode.NowYouGetPrizeFromThisGiveaway
-                    ? await Bot.SendWithMarkdown2(player.ChatId, strings.now_you_get_prize_from_this_giveaway)
-                    : new Message();
-            }
-            catch (Exception)
-            {
-                return await Bot.SendWithMarkdown2(ChatId, strings.giveaway_now_ended, Keyboard.PlayerGameMenu);
-            }
-        }
-
-        private async Task<Message> ConnectToGameCommand(Player player, string roomKey)
-        {
-            if (player.GetRoomName() != "")
-                return await Bot.SendWithMarkdown2(ChatId, $"{strings.prefer_leave_from_room} {player.GetRoomName()}");
-            var code = await RoomController.ConnectToGame(player, roomKey);
-            return code == ResultCode.CodeOk
-                ? await Bot.SendWithMarkdown2(ChatId, strings.successful_entry_into_room, Keyboard.PlayerGameMenu)
-                : await Utilities.GetResultCodeMessage(code, ChatId);
-        }
-
-        private async Task<Message> ConnectToFastGameCommand(Player player, string roomKey)
-        {
-            if (player.GetRoomName() != "")
-                return await Bot.SendWithMarkdown2(ChatId, $"{strings.prefer_leave_from_room} {player.GetRoomName()}");
-            var code = await RoomController.ConnectToFastGame(player, roomKey);
-            return code == ResultCode.CodeOk
-                ? new Message()
-                : await Utilities.GetResultCodeMessage(code, ChatId);
-        }
-    }
-}

+ 0 - 30
MafiaTelegramBot/Models/Commands/StartGameCommand.cs

@@ -1,30 +0,0 @@
-using System.Threading.Tasks;
-using MafiaTelegramBot.Controllers;
-using MafiaTelegramBot.DataBase.EntityDao;
-using MafiaTelegramBot.Game;
-using MafiaTelegramBot.Resources;
-using Telegram.Bot.Types;
-
-namespace MafiaTelegramBot.Models.Commands
-{
-    public class StartGameCommand : Command
-    {
-        protected override string Name => keyboard.begin_game;
-        protected override async Task<Message> Execute(Update update)
-        {
-            var player = await UserDao.GetPlayerById(UserId);
-            var roomKey = RoomEncrypter.GetCode(player.GetRoomName());
-            var room = RoomController.GetRoom(roomKey);
-            if(room == null)
-                return await Bot.SendWithMarkdown2(ChatId, strings.room_does_not_exists);
-            if (!player.Equals(room.Owner))
-                return await Bot.SendWithMarkdown2(ChatId, $"{strings.command_not_found} _*({update.Message.Text})*_");
-            if (room.IsExtended) return await Bot.SendWithMarkdown2(player.ChatId, strings.continue_question, Keyboard.StartExtendedRoomKeyboard(UserId));
-            var result = await Bot.SendWithMarkdown2(player.ChatId, strings.game_process_started);
-            var resultCode = await room.Prepare();
-            if (resultCode != ResultCode.CodeOk) return await Utilities.GetResultCodeMessage(resultCode, ChatId);
-            room.Start();
-            return result;
-        }
-    }
-}

+ 0 - 28
MafiaTelegramBot/Models/Payments/Payment.cs

@@ -1,28 +0,0 @@
-#nullable enable
-using System;
-using System.Threading.Tasks;
-using Telegram.Bot.Types;
-
-namespace MafiaTelegramBot.Models.Payments
-{
-    public abstract class Payment : UpdateModel<string>
-    {
-
-        protected override bool IsMatches(string command)
-        {
-            return command == Name;
-        }
-        public static Task<Message> Update(Update update)
-        {
-            throw new NotImplementedException();
-            /*var payments = Bot.Payments;
-            var message = update.PreCheckoutQuery;
-            var userId = update.Message.From.Id;
-            var chatId = update.Message.Chat.Id;
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
-            var command = FirstOrDefault(payments, message);
-            if(command != null) return await ((Payment?) command.Clone(chatId, userId))!.Execute(update);
-            return await Bot.SendWithMarkdown2(chatId, $"{strings.command_not_found} _*({"message"})*_");*/
-        }
-    }
-}

+ 0 - 15
MafiaTelegramBot/Models/Payments/RandomRolePayment.cs

@@ -1,15 +0,0 @@
-using System.Threading.Tasks;
-using MafiaTelegramBot.Resources;
-using Telegram.Bot.Types;
-
-namespace MafiaTelegramBot.Models.Payments
-{
-    public class RandomRolePayment : Payment
-    {
-        protected override string Name => Payloads.RandomRole.ToString();
-        protected override Task<Message> Execute(Update update)
-        {
-            throw new System.NotImplementedException();
-        }
-    }
-}

+ 0 - 46
MafiaTelegramBot/Models/UpdateModel.cs

@@ -1,46 +0,0 @@
-#nullable enable
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-using Telegram.Bot.Types;
-
-namespace MafiaTelegramBot.Models
-{
-    public abstract class UpdateModel<T> : ICloneable
-    {
-        protected abstract T Name { get; }
-        protected long ChatId { get; set; }
-        protected long UserId { get; set; }
-
-        protected abstract Task<Message> Execute(Update update);
-
-        protected abstract bool IsMatches(String command);
-
-        protected static UpdateModel<T>? FirstOrDefault(IReadOnlyList<UpdateModel<T>> list, string data)
-        {
-            return (from item in list
-                where item.IsMatches(data)
-                select item).FirstOrDefault();
-        }
-
-        protected static async Task DeletePreviousMessage(long chatId, int messageId)
-        {
-            await Bot.Get().DeleteMessageAsync(chatId, messageId);
-        }
-
-        public object? Clone(long chatId, long userId)
-        {
-            var clone = (UpdateModel<T>?) MemberwiseClone();
-            if(clone == null) return clone;
-            clone.ChatId = chatId;
-            clone.UserId = userId;
-            return clone;
-        }
-
-        public object Clone()
-        {
-            return MemberwiseClone();
-        }
-    }
-}

+ 7 - 6
MafiaTelegramBot/Other/GiveAway.cs

@@ -1,6 +1,7 @@
 using System.Collections.Generic;
 using System.Linq;
 using System.Threading.Tasks;
+using MafiaTelegramBot.Controllers;
 using MafiaTelegramBot.DataBase.Entity;
 using MafiaTelegramBot.DataBase.EntityDao;
 using MafiaTelegramBot.Game;
@@ -61,23 +62,23 @@ namespace MafiaTelegramBot.Other
 
         public async Task<ResultCode> GivePrizeTo(Player player)
         {
-            if (!await TryDecreaseCount(player.Id)) return ResultCode.NowYouGetPrizeFromThisGiveaway;
+            if (!await TryDecreaseCount(player.Info.Id)) return ResultCode.NowYouGetPrizeFromThisGiveaway;
             if (_prize is Roles.All) return await GivePackToUser(player);
             var firstPrize = _prize;
             if (player.OpenedRoles.TryOpenRole(firstPrize))
             {
-                await Bot.SendStickerAsync(player.ChatId, Stickers.Sticker[firstPrize.ToString()]);
-                await Bot.SendWithMarkdown2(player.ChatId,$"{strings.congratulations_you_open_role} {roles.ResourceManager.GetString(firstPrize.ToString())}");
+                await MessageController.SendText(player.Info, Stickers.Sticker[firstPrize.ToString()]);
+                await MessageController.SendText(player.Info,$"{strings.congratulations_you_open_role} {roles.ResourceManager.GetString(firstPrize.ToString())}");
             }
-            else await Bot.SendWithMarkdown2(player.ChatId,$"{strings.you_got_role} {roles.ResourceManager.GetString(firstPrize.ToString())} ({strings.now_opened})");
+            else await MessageController.SendText(player.Info,$"{strings.you_got_role} {roles.ResourceManager.GetString(firstPrize.ToString())} ({strings.now_opened})");
             return ResultCode.CodeOk;
         }
 
         private static async Task<ResultCode> GivePackToUser(Player player)
         {
-            player.User.PackCount++;
+            player.Info.PackCount++;
             await Bot.SendStickerAsync(player.ChatId, Stickers.Sticker["Pool"]);
-            await Bot.SendWithMarkdown2(player.ChatId, $"{strings.your_packs} {player.User.PackCount}", Keyboard.PackKeyboard(player.Id));
+            await Bot.SendWithMarkdown2(player.ChatId, $"{strings.your_packs} {player.Info.PackCount}", Keyboard.PackKeyboard(player.Id));
             return ResultCode.CodeOk;
         }
 

+ 28 - 28
MafiaTelegramBot/Resources/Keyboard.cs

@@ -64,30 +64,30 @@ namespace MafiaTelegramBot.Resources
             });
         }
 
-        public static InlineKeyboardMarkup RoomTypeKeyboard(long userId)
+        public static InlineKeyboardMarkup RoomTypeKeyboard()
         {
             return new(new[]
             {
-                InlineKeyboardButton.WithCallbackData(strings.normal_game, $"{Callback.ConnectToNotRanked}|{userId}|0"),
-                InlineKeyboardButton.WithCallbackData(strings.ranking_game, $"{Callback.ConnectToRanked}|{userId}|0"),
+                InlineKeyboardButton.WithCallbackData(strings.normal_game, $"{Callback.ConnectToNotRanked}"),
+                InlineKeyboardButton.WithCallbackData(strings.ranking_game, $"{Callback.ConnectToRanked}"),
             });
         }
 
-        public static InlineKeyboardMarkup AdminPanelKeyboard(long userId)
+        public static InlineKeyboardMarkup AdminPanelKeyboard()
         {
-            return new( new[]
+            return new InlineKeyboardMarkup( new[]
                 {
-                    new [] { InlineKeyboardButton.WithCallbackData(strings.give_roles_to_all_players, $"{Callback.GiveToAll}|{userId}|0") },
-                    new [] { InlineKeyboardButton.WithCallbackData(strings.give_role_to_selected_player, $"{Callback.GiveToSelected}|{userId}|0") },
+                    new [] { InlineKeyboardButton.WithCallbackData(strings.give_roles_to_all_players, $"{Callback.GiveToAll}") },
+                    new [] { InlineKeyboardButton.WithCallbackData(strings.give_role_to_selected_player, $"{Callback.GiveToSelected}") },
                 });
         }
 
-        public static InlineKeyboardMarkup ChooseRoomView(long userId)
+        public static InlineKeyboardMarkup ChooseRoomView()
         {
             return new InlineKeyboardMarkup(new[]
             {
-                InlineKeyboardButton.WithCallbackData(strings._public, $"{Callback.ChooseRoomView}|{userId}|{Constants.PUBLIC}"),
-                InlineKeyboardButton.WithCallbackData(strings._private, $"{Callback.ChooseRoomView}|{userId}|{Constants.PRIVATE}"),
+                InlineKeyboardButton.WithCallbackData(strings._public, $"{Callback.ChooseRoomView}|{Constants.PUBLIC}"),
+                InlineKeyboardButton.WithCallbackData(strings._private, $"{Callback.ChooseRoomView}|{Constants.PRIVATE}"),
             });
         }
 
@@ -143,19 +143,19 @@ namespace MafiaTelegramBot.Resources
             });
         }
 
-        public static InlineKeyboardMarkup ProfileKeyboard(long userId)
+        public static InlineKeyboardMarkup ProfileKeyboard()
         {
             return new InlineKeyboardMarkup(new[]
             {
                 new[] {
-                    InlineKeyboardButton.WithCallbackData(strings.shop, $"{Callback.ShopMenu}|{userId}"),
-                    InlineKeyboardButton.WithCallbackData(strings.settings, $"{Callback.SettingsProfile}|{userId}")
+                    InlineKeyboardButton.WithCallbackData(strings.shop, Callback.ShopMenu.ToString()),
+                    InlineKeyboardButton.WithCallbackData(strings.settings, Callback.SettingsProfile.ToString())
                 },
                 new[] {
-                    InlineKeyboardButton.WithCallbackData(strings.my_roles, $"{Callback.ShowMyRoles}|{userId}"),
-                    InlineKeyboardButton.WithCallbackData(strings.my_packs, $"{Callback.ShowMyPacks}|{userId}")
+                    InlineKeyboardButton.WithCallbackData(strings.my_roles, Callback.ShowMyRoles.ToString()),
+                    InlineKeyboardButton.WithCallbackData(strings.my_packs, Callback.ShowMyPacks.ToString())
                 },
-                new [] {InlineKeyboardButton.WithCallbackData(strings.extended_stats, $"{Callback.ShowMyExtendedStats}|{userId}")}
+                new [] {InlineKeyboardButton.WithCallbackData(strings.extended_stats, Callback.ShowMyExtendedStats.ToString())}
             });
         }
 
@@ -216,8 +216,8 @@ namespace MafiaTelegramBot.Resources
             {
                 inlineButtons[i] = new[]
                 {
-                    InlineKeyboardButton.WithCallbackData($"{users[i].NickName} {strings.kick}",
-                        $"{Callback.KickUser}|{users[i].Id}")
+                    InlineKeyboardButton.WithCallbackData(users[i].Info.NickName,
+                        $"{Callback.KickUser}|{users[i].Info.Id}")
                 };
             }
             return new InlineKeyboardMarkup(inlineButtons);
@@ -290,22 +290,22 @@ namespace MafiaTelegramBot.Resources
             return inlineButtons;
         }
 
-        public static InlineKeyboardMarkup SettingsRoomKeyboard(long userId, string timerStatus)
+        public static InlineKeyboardMarkup SettingsRoomKeyboard(string timerStatus)
         {
 
-            return new (new[]
+            return new InlineKeyboardMarkup(new[]
             {
-                new[] { InlineKeyboardButton.WithCallbackData(timerStatus, $"{Callback.SwitchTimer}|{userId}") },
-                new[] { InlineKeyboardButton.WithCallbackData(strings.players_count, $"{Callback.PlayersCount}|{userId}") },
+                new[] { InlineKeyboardButton.WithCallbackData(timerStatus, Callback.SwitchTimer.ToString()) },
+                new[] { InlineKeyboardButton.WithCallbackData(strings.players_count, Callback.PlayersCount.ToString()) },
             });
         }
 
-        public static InlineKeyboardMarkup StartExtendedRoomKeyboard(long userId)
+        public static InlineKeyboardMarkup StartExtendedRoomKeyboard()
         {
-            return new (new[]
+            return new InlineKeyboardMarkup(new[]
             {
-                new[] { InlineKeyboardButton.WithCallbackData(strings.run_game, $"{Callback.StartGame}|{userId}") },
-                new[] { InlineKeyboardButton.WithCallbackData(strings.change_roles, $"{Callback.ChangeRoles}|{userId}") }
+                new[] { InlineKeyboardButton.WithCallbackData(strings.run_game, Callback.StartGame.ToString()) },
+                new[] { InlineKeyboardButton.WithCallbackData(strings.change_roles, Callback.ChangeRoles.ToString()) }
             });
         }
 
@@ -342,7 +342,7 @@ namespace MafiaTelegramBot.Resources
             return keyboard;
         }
 
-        public static InlineKeyboardMarkup GiveRoleKeyboard(long userId, long targetId)
+        public static InlineKeyboardMarkup GiveRoleKeyboard(long targetId)
         {
             var keyboard = new List<InlineKeyboardButton[]>();
             foreach (var role in (Roles[]) Enum.GetValues(typeof(Roles)))
@@ -352,7 +352,7 @@ namespace MafiaTelegramBot.Resources
                 {
                     InlineKeyboardButton.WithCallbackData(
                         roles.ResourceManager.GetString(role.ToString()),
-                        $"{Callback.GiveRole}|{userId}|{targetId}|{role}"
+                        $"{Callback.GiveRole}|{targetId}|{role}"
                     )
                 });
             }

+ 13 - 13
MafiaTelegramBot/Utilities.cs

@@ -36,22 +36,22 @@ namespace MafiaTelegramBot
             },
         };
         
-        public static Task<Message> GetResultCodeMessage(ResultCode code, long chatId)
+        public static string GetResultCodeMessage(ResultCode code)
         {
             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),
-                ResultCode.RolesNotEqualPlayers => Bot.SendWithMarkdown2(chatId, strings.players_not_equal_roles),
-                ResultCode.NotEnoughMafia => Bot.SendWithMarkdown2(chatId, strings.not_enogh_mafia),
-                ResultCode.TooMuchMafia => Bot.SendWithMarkdown2(chatId, strings.too_much_mafia),
-                _ => Bot.SendWithMarkdown2(chatId, strings.unexpected_error)
+                ResultCode.TooManyPlayers => strings.too_many_players,
+                ResultCode.TooFewPlayers => strings.too_few_players,
+                ResultCode.GameAlreadyRunning => strings.game_already_running,
+                ResultCode.GameAlreadyExists => strings.game_already_exists,
+                ResultCode.UserAlreadyInGame => strings.user_already_in_game,
+                ResultCode.UserNotInGame => strings.user_not_in_game,
+                ResultCode.RoomIsFilled => strings.room_is_filled,
+                ResultCode.RoomDoesNotExist => strings.room_does_not_exists,
+                ResultCode.RolesNotEqualPlayers => strings.players_not_equal_roles,
+                ResultCode.NotEnoughMafia => strings.not_enogh_mafia,
+                ResultCode.TooMuchMafia => strings.too_much_mafia,
+                _ => strings.unexpected_error
             };
         }
         public static async Task<string> ToMarkdownString(string src)