Browse Source

MTB-22 Another username change logic

Tigran 4 years ago
parent
commit
fad08b9634

+ 4 - 32
MafiaTelegramBot/Controllers/MessageController.cs

@@ -11,26 +11,8 @@ using Telegram.Bot.Types.Enums;
 
 namespace MafiaTelegramBot.Controllers
 {
-    public static class MessageController //: ApiController
+    public static class MessageController
     {
-        /*
-        [Route(@api/message/update)]
-        public async Task<OkResult> UpdateCommand([FromBody]UpdateCommand update)
-        {
-            var commands = Bot.Commands;
-            var message = update.Message;
-            var client = await Bot.Get();
-            
-            foreach(var command in commands)
-            {
-                if (command.Contains(message.Text)) command.Execute(message, client);
-                break;
-            }
-            
-            return Ok();
-        }
-        */
-
         public static async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update,
             CancellationToken cancellationToken)
         {
@@ -38,8 +20,8 @@ namespace MafiaTelegramBot.Controllers
             {
                 var handle = update.Type switch
                 {
-                    //TODO handle other update type if needed
-                    UpdateType.Message => update.Message.ReplyToMessage != null && update.Message.ReplyToMessage.Text != strings.start_message
+                    UpdateType.Message => update.Message.ReplyToMessage != null &&
+                                          update.Message.ReplyToMessage.Text != strings.start_message
                         ? Reply.Update(update)
                         : Command.Update(update),
                     UpdateType.CallbackQuery => Query.Update(update),
@@ -47,16 +29,6 @@ namespace MafiaTelegramBot.Controllers
                 };
                 await handle;
             }
-            catch (NullReferenceException)
-            {
-                var command = update.Type switch
-                {
-                    UpdateType.Message => update.Message.Text,
-                    UpdateType.CallbackQuery => update.CallbackQuery.Data,
-                    _ => "unknown"
-                };
-                Console.WriteLine($"Command \"{command}\" not found");
-            }
             catch (Exception exception)
             {
                 await HandleErrorAsync(botClient, exception, cancellationToken);
@@ -65,7 +37,7 @@ namespace MafiaTelegramBot.Controllers
 
         private static Task UnknownUpdateHandlerAsync(Update update)
         {
-            Console.WriteLine($"Unknown update type: {update.Type}");
+            Console.WriteLine(update.Type);
             return Task.CompletedTask;
         }
 

+ 3 - 10
MafiaTelegramBot/DataBase/User.cs

@@ -1,3 +1,4 @@
+using System.Collections.Generic;
 using System.Threading.Tasks;
 
 namespace MafiaTelegramBot.DataBase
@@ -8,16 +9,8 @@ namespace MafiaTelegramBot.DataBase
         public string Username { get; set; } = "test";
         public int Games { get; set; } = 0;
         public int Wins { get; set; } = 0;
-        public int MafiaGames { get; set; } = 0;
-        public int MafiaWins { get; set; } = 0;
-        public int VillagerGames { get; set; } = 0;
-        public int VillagerWins { get; set; } = 0;
-        public int DonGames { get; set; } = 0;
-        public int DonWins { get; set; } = 0;
-        public int GovernorGames { get; set; } = 0;
-        public int GovernorWins { get; set; } = 0;
-        public int DoctorGames { get; set; } = 0;
-        public int DoctorWins { get; set; } = 0;
+        public Dictionary<string, int> RoleGames = new();
+        public Dictionary<string, int> RoleWins = new();
 
         public async Task UpdateName(string name)
         {

+ 8 - 7
MafiaTelegramBot/DataBase/UserDao.cs

@@ -6,13 +6,14 @@ namespace MafiaTelegramBot.DataBase
 {
     public static class UserDao
     {
-        private static readonly List<User> _bd = new();
+        private static readonly List<User> DataBase = new();
         public static async Task<User> GetUserById(long id)
         {
-            var user = _bd.FirstOrDefault(user1 => user1.Id == id);
+            User user = null;
+            await Task.Run(()=> user = DataBase.FirstOrDefault(user1 => user1.Id == id));
             if (user != null) return user;
             user = new User {Id = id};
-            _bd.Add(user);
+            DataBase.Add(user);
             return user;
         }
 
@@ -21,11 +22,11 @@ namespace MafiaTelegramBot.DataBase
             return new();
         }
         
-        public static async Task<int> Update(User user)
+        public static async Task Update(User user)
         {
-            var updateIndex = _bd.FindIndex(user1 => user1.Id == user.Id);
-            _bd[updateIndex] = user;
-            return updateIndex;
+            var updateIndex = 0;
+            await Task.Run(() => updateIndex = DataBase.FindIndex(user1 => user1.Id == user.Id));
+            DataBase[updateIndex] = user;
         }
     }
 }

+ 7 - 2
MafiaTelegramBot/Models/Bot.cs

@@ -18,6 +18,8 @@ namespace MafiaTelegramBot.Models
         public static IReadOnlyList<Query> Queries => _queriesList.AsReadOnly();
         public static IReadOnlyList<Reply> Replies => _repliesList.AsReadOnly();
 
+        public static readonly List<long> UsersThatChangesNickname = new();
+
         public static TelegramBotClient Get()
         {
             if (_client != null) return _client;
@@ -41,7 +43,10 @@ namespace MafiaTelegramBot.Models
                 new StartCommand(),
                 new CreateGameCommand(),
                 new ConnectGameCommand(),
-                new ShowProfileCommand()
+                new ShowProfileCommand(),
+                
+                //it always in end of array, handle all messages, that doesn't contains command string
+                new CustomMessageHandlingCommand()
             };
         }
         
@@ -63,7 +68,7 @@ namespace MafiaTelegramBot.Models
             //TODO fill inline keyboard array
             _repliesList = new List<Reply>
             {
-                new ChangeNameReply(),
+                
             };
         }
     }

+ 1 - 1
MafiaTelegramBot/Models/Commands/CreateGameCommand.cs

@@ -13,7 +13,7 @@ namespace MafiaTelegramBot.Models.Commands
             var chatId = update.Message.Chat.Id;
             await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
 
-            var message = "Задайте настройки комнаты";
+            var message = strings.set_room_settings;
             
             var inlineKeyboard = new InlineKeyboardMarkup(new[]
             {

+ 26 - 0
MafiaTelegramBot/Models/Commands/CustomMessageHandlingCommand.cs

@@ -0,0 +1,26 @@
+using System.Threading.Tasks;
+using MafiaTelegramBot.DataBase;
+using Telegram.Bot.Types;
+using Telegram.Bot.Types.Enums;
+
+namespace MafiaTelegramBot.Models.Commands
+{
+    public class CustomMessageHandlingCommand : Command
+    {
+        protected override string Name => "";
+        public override async Task<Message> Execute(Update update)
+        {
+            var chatId = update.Message.Chat.Id;
+            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
+            var message = update.Message.Text;
+            var userId = update.Message.From.Id;
+            if (Bot.UsersThatChangesNickname.Remove(userId))
+            {
+                var user = await UserDao.GetUserById(userId);
+                await user.UpdateName(message);
+                return await Bot.Get().SendTextMessageAsync(chatId, $"{strings.name_updated} {message}");
+            }
+            return await Bot.Get().SendTextMessageAsync(chatId, $"{strings.command_not_found} _*\\({message}\\)*_", ParseMode.MarkdownV2);
+        }
+    }
+}

+ 4 - 2
MafiaTelegramBot/Models/Inlines/ChaneNameQuery.cs

@@ -1,7 +1,6 @@
 using System.Threading.Tasks;
 using Telegram.Bot.Types;
 using Telegram.Bot.Types.Enums;
-using Telegram.Bot.Types.ReplyMarkups;
 
 namespace MafiaTelegramBot.Models.Inlines
 {
@@ -12,8 +11,11 @@ namespace MafiaTelegramBot.Models.Inlines
         public override async Task<Message> Execute(Update update)
         {
             var chatId = update.CallbackQuery.Message.Chat.Id;
+            var data = update.CallbackQuery.Data;
+            var userId = long.Parse(data.Split('|')[1]);
             await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
-            return await Bot.Get().SendTextMessageAsync(chatId, strings.enter_your_name, replyMarkup: new ForceReplyMarkup());
+            Bot.UsersThatChangesNickname.Add(userId);
+            return await Bot.Get().SendTextMessageAsync(chatId, strings.enter_your_name);
         }
     }
 }

+ 1 - 2
MafiaTelegramBot/Models/Inlines/MakePrivateRoom.cs

@@ -1,5 +1,4 @@
 using System.Threading.Tasks;
-using MafiaTelegramBot.Models.Commands;
 using Telegram.Bot.Types;
 using Telegram.Bot.Types.Enums;
 using Telegram.Bot.Types.ReplyMarkups;
@@ -14,7 +13,7 @@ namespace MafiaTelegramBot.Models.Inlines
             var chatId = update.CallbackQuery.Message.Chat.Id;
             await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
 
-            var message = "Выберите";
+            var message = strings.choose;
             
             var inlineKeyboard = new InlineKeyboardMarkup(new[]
             {

+ 1 - 1
MafiaTelegramBot/Models/Inlines/SettingsQuery.cs

@@ -16,7 +16,7 @@ namespace MafiaTelegramBot.Models.Inlines
             await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
             var userId = update.CallbackQuery.From.Id;
             var user = await UserDao.GetUserById(userId);
-            var inlineKeyboard = new InlineKeyboardMarkup(InlineKeyboardButton.WithCallbackData(strings.change_name, strings.change_name_callback));
+            var inlineKeyboard = new InlineKeyboardMarkup(InlineKeyboardButton.WithCallbackData(strings.change_name, $"{strings.change_name_callback}|{userId}"));
             return await Bot.Get().SendTextMessageAsync(chatId, $"{strings.your_name} {user.Username}", replyMarkup: inlineKeyboard);
         }
     }

+ 0 - 22
MafiaTelegramBot/Models/Replies/ChangeNameReply.cs

@@ -1,22 +0,0 @@
-using System.Threading.Tasks;
-using MafiaTelegramBot.DataBase;
-using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
-
-namespace MafiaTelegramBot.Models.Replies
-{
-    public class ChangeNameReply : Reply
-    {
-        protected override string Name => strings.enter_your_name;
-        public override async Task<Message> Execute(Update update)
-        {
-            var chatId = update.Message.Chat.Id;
-            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
-            var userId = update.Message.From.Id;
-            var user = await UserDao.GetUserById(userId);
-            var newName = update.Message.Text;
-            await user.UpdateName(newName);
-            return await Bot.Get().SendTextMessageAsync(chatId, $"{strings.name_updated} {newName}");
-        }
-    }
-}

+ 27 - 0
MafiaTelegramBot/Resources/strings.Designer.cs

@@ -78,6 +78,24 @@ namespace MafiaTelegramBot {
             }
         }
         
+        /// <summary>
+        ///   Looks up a localized string similar to Выберите.
+        /// </summary>
+        internal static string choose {
+            get {
+                return ResourceManager.GetString("choose", resourceCulture);
+            }
+        }
+        
+        /// <summary>
+        ///   Looks up a localized string similar to Команда не найдена.
+        /// </summary>
+        internal static string command_not_found {
+            get {
+                return ResourceManager.GetString("command_not_found", resourceCulture);
+            }
+        }
+        
         /// <summary>
         ///   Looks up a localized string similar to Присоединиться к игре.
         /// </summary>
@@ -177,6 +195,15 @@ namespace MafiaTelegramBot {
             }
         }
         
+        /// <summary>
+        ///   Looks up a localized string similar to Задайте настройки комнаты.
+        /// </summary>
+        internal static string set_room_settings {
+            get {
+                return ResourceManager.GetString("set_room_settings", resourceCulture);
+            }
+        }
+        
         /// <summary>
         ///   Looks up a localized string similar to Настройки.
         /// </summary>

+ 9 - 0
MafiaTelegramBot/Resources/strings.resx

@@ -87,4 +87,13 @@
     <data name="name_updated" xml:space="preserve">
         <value>Имя было обновлено на</value>
     </data>
+    <data name="command_not_found" xml:space="preserve">
+        <value>Команда не найдена</value>
+    </data>
+    <data name="set_room_settings" xml:space="preserve">
+        <value>Задайте настройки комнаты</value>
+    </data>
+    <data name="choose" xml:space="preserve">
+        <value>Выберите</value>
+    </data>
 </root>