Browse Source

MTB-22 change username realized

Tigran 4 years ago
parent
commit
a62b56057e

+ 13 - 7
MafiaTelegramBot/Controllers/MessageController.cs

@@ -3,6 +3,7 @@ using System.Threading;
 using System.Threading.Tasks;
 using MafiaTelegramBot.Models.Commands;
 using MafiaTelegramBot.Models.Inlines;
+using MafiaTelegramBot.Models.Replies;
 using Telegram.Bot;
 using Telegram.Bot.Exceptions;
 using Telegram.Bot.Types;
@@ -29,15 +30,18 @@ namespace MafiaTelegramBot.Controllers
             return Ok();
         }
         */
-        
-        public static async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
+
+        public static async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update,
+            CancellationToken cancellationToken)
         {
             try
             {
                 var handle = update.Type switch
                 {
                     //TODO handle other update type if needed
-                    UpdateType.Message => Command.Update(update),
+                    UpdateType.Message => update.Message.ReplyToMessage != null && update.Message.ReplyToMessage.Text != strings.start_message
+                        ? Reply.Update(update)
+                        : Command.Update(update),
                     UpdateType.CallbackQuery => Query.Update(update),
                     _ => UnknownUpdateHandlerAsync(update)
                 };
@@ -58,18 +62,20 @@ namespace MafiaTelegramBot.Controllers
                 await HandleErrorAsync(botClient, exception, cancellationToken);
             }
         }
-        
+
         private static Task UnknownUpdateHandlerAsync(Update update)
         {
             Console.WriteLine($"Unknown update type: {update.Type}");
             return Task.CompletedTask;
         }
-        
-        public static Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
+
+        public static Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception,
+            CancellationToken cancellationToken)
         {
             var errorMessage = exception switch
             {
-                ApiRequestException apiRequestException => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
+                ApiRequestException apiRequestException =>
+                    $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
                 _ => exception.ToString()
             };
 

+ 8 - 0
MafiaTelegramBot/DataBase/User.cs

@@ -1,3 +1,5 @@
+using System.Threading.Tasks;
+
 namespace MafiaTelegramBot.DataBase
 {
     public class User
@@ -16,5 +18,11 @@ namespace MafiaTelegramBot.DataBase
         public int GovernorWins { get; set; } = 0;
         public int DoctorGames { get; set; } = 0;
         public int DoctorWins { get; set; } = 0;
+
+        public async Task UpdateName(string name)
+        {
+            Username = name;
+            await UserDao.Update(this);
+        }
     }
 }

+ 15 - 1
MafiaTelegramBot/DataBase/UserDao.cs

@@ -1,17 +1,31 @@
+using System.Collections.Generic;
+using System.Linq;
 using System.Threading.Tasks;
 
 namespace MafiaTelegramBot.DataBase
 {
     public static class UserDao
     {
+        private static readonly List<User> _bd = new();
         public static async Task<User> GetUserById(long id)
         {
-            return ConvertToUser();
+            var user = _bd.FirstOrDefault(user1 => user1.Id == id);
+            if (user != null) return user;
+            user = new User {Id = id};
+            _bd.Add(user);
+            return user;
         }
 
         private static User ConvertToUser()
         {
             return new();
         }
+        
+        public static async Task<int> Update(User user)
+        {
+            var updateIndex = _bd.FindIndex(user1 => user1.Id == user.Id);
+            _bd[updateIndex] = user;
+            return updateIndex;
+        }
     }
 }

+ 15 - 2
MafiaTelegramBot/Models/Bot.cs

@@ -1,6 +1,7 @@
 using System.Collections.Generic;
 using MafiaTelegramBot.Models.Commands;
 using MafiaTelegramBot.Models.Inlines;
+using MafiaTelegramBot.Models.Replies;
 using MafiaTelegramBot.Resources;
 using Telegram.Bot;
 
@@ -11,9 +12,11 @@ namespace MafiaTelegramBot.Models
         private static TelegramBotClient _client;
         private static List<Command> _commandsList;
         private static List<Query> _queriesList;
+        private static List<Reply> _repliesList;
         
         public static IReadOnlyList<Command> Commands => _commandsList.AsReadOnly();
         public static IReadOnlyList<Query> Queries => _queriesList.AsReadOnly();
+        public static IReadOnlyList<Reply> Replies => _repliesList.AsReadOnly();
 
         public static TelegramBotClient Get()
         {
@@ -21,6 +24,7 @@ namespace MafiaTelegramBot.Models
 
             InitCommands();
             InitQueries();
+            InitReplies();
 
             _client = new TelegramBotClient(AppSettings.Token);
             //var hook = string.Format(AppSettings.Url, "api/message/update");
@@ -48,9 +52,18 @@ namespace MafiaTelegramBot.Models
             {
                 new MyRolesQuery(),
                 new ShopQuery(),
-                
                 new MakePrivateRoom(),
-                new SettingsQuery()
+                new SettingsQuery(),
+                new ChangeNameQuery(),
+            };
+        }
+        
+        private static void InitReplies()
+        {
+            //TODO fill inline keyboard array
+            _repliesList = new List<Reply>
+            {
+                new ChangeNameReply(),
             };
         }
     }

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

@@ -15,7 +15,8 @@ namespace MafiaTelegramBot.Models.Commands
         {
             var chatId = update.Message.Chat.Id;
             await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
-            var user = await UserDao.GetUserById(update.Message.From.Id);
+            var userId = update.Message.From.Id;
+            var user = await UserDao.GetUserById(userId);
             var winRate = user.Games < 1 ? 0.0 : Convert.ToDouble(user.Wins) / Convert.ToDouble(user.Games);
             var message =
                 $"__*{strings.statistics_for} _{user.Username}_*__\n" +

+ 19 - 0
MafiaTelegramBot/Models/Inlines/ChaneNameQuery.cs

@@ -0,0 +1,19 @@
+using System.Threading.Tasks;
+using Telegram.Bot.Types;
+using Telegram.Bot.Types.Enums;
+using Telegram.Bot.Types.ReplyMarkups;
+
+namespace MafiaTelegramBot.Models.Inlines
+{
+    public class ChangeNameQuery : Query
+    {
+        protected override string Name => strings.change_name_callback;
+
+        public override async Task<Message> Execute(Update update)
+        {
+            var chatId = update.CallbackQuery.Message.Chat.Id;
+            await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
+            return await Bot.Get().SendTextMessageAsync(chatId, strings.enter_your_name, replyMarkup: new ForceReplyMarkup());
+        }
+    }
+}

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

@@ -0,0 +1,22 @@
+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}");
+        }
+    }
+}

+ 15 - 0
MafiaTelegramBot/Models/Replies/Reply.cs

@@ -0,0 +1,15 @@
+using System.Threading.Tasks;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Models.Replies
+{
+    public abstract class Reply : UpdateModel
+    {
+        public static Task Update(Update update)
+        {
+            var commands = Bot.Replies;
+            var message = update.Message.ReplyToMessage.Text;
+            return FirstOrDefault(commands, message).Execute(update);
+        }
+    }
+}

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

@@ -96,6 +96,15 @@ namespace MafiaTelegramBot {
             }
         }
         
+        /// <summary>
+        ///   Looks up a localized string similar to Введите ваше имя.
+        /// </summary>
+        internal static string enter_your_name {
+            get {
+                return ResourceManager.GetString("enter_your_name", resourceCulture);
+            }
+        }
+        
         /// <summary>
         ///   Looks up a localized string similar to Число игр:.
         /// </summary>
@@ -159,6 +168,15 @@ namespace MafiaTelegramBot {
             }
         }
         
+        /// <summary>
+        ///   Looks up a localized string similar to Имя было обновлено на.
+        /// </summary>
+        internal static string name_updated {
+            get {
+                return ResourceManager.GetString("name_updated", resourceCulture);
+            }
+        }
+        
         /// <summary>
         ///   Looks up a localized string similar to Настройки.
         /// </summary>

+ 6 - 0
MafiaTelegramBot/Resources/strings.resx

@@ -81,4 +81,10 @@
     <data name="change_name_callback" xml:space="preserve">
         <value>change_name</value>
     </data>
+    <data name="enter_your_name" xml:space="preserve">
+        <value>Введите ваше имя</value>
+    </data>
+    <data name="name_updated" xml:space="preserve">
+        <value>Имя было обновлено на</value>
+    </data>
 </root>