Przeglądaj źródła

giving roles to player by nickname

Tigran 4 lat temu
rodzic
commit
0f3d446192

+ 55 - 2
MafiaTelegramBot/DataBase/Entity/OpenedRolesEntity.cs

@@ -1,8 +1,7 @@
+using System;
 using System.Collections.Generic;
-using System.ComponentModel;
 using System.ComponentModel.DataAnnotations;
 using System.ComponentModel.DataAnnotations.Schema;
-using System.Threading.Tasks;
 using MafiaTelegramBot.Resources;
 
 namespace MafiaTelegramBot.DataBase.Entity
@@ -103,5 +102,59 @@ namespace MafiaTelegramBot.DataBase.Entity
         {
             Hooker = true;
         }
+
+        public bool TryOpenRole(Roles role)
+        {
+            switch (role)
+            {
+                case Roles.All or Roles.Doctor or Roles.Mafia or Roles.Don or Roles.Cop or Roles.Villager or Roles.None: return false;
+                case Roles.Hooker:
+                    if (Hooker) return false;
+                    OpenHooker();
+                    return true;
+                case Roles.Elder:
+                    if (Elder) return false;
+                    OpenElder();
+                    return true;
+                case Roles.Werewolf:
+                    if (Werewolf) return false;
+                    OpenWerewolf();
+                    return true;
+                case Roles.Journalist:
+                    if (Journalist) return false;
+                    OpenJournalist();
+                    return true;
+                case Roles.Detective:
+                    if (Detective) return false;
+                    OpenDetective();
+                    return true;
+                case Roles.Dame:
+                    if (Dame) return false;
+                    OpenDame();
+                    return true;
+                case Roles.Parasite:
+                    if (Parasite) return false;
+                    OpenParasite();
+                    return true;
+                case Roles.Lawyer:
+                    if (Lawyer) return false;
+                    OpenLawyer();
+                    return true;
+                case Roles.Fool:
+                    if (Fool) return false;
+                    OpenFool();
+                    return true;
+                case Roles.Necromancer:
+                    if (Necromancer) return false;
+                    OpenNecromancer();
+                    return true;
+                case Roles.Bodyguard:
+                    if (Bodyguard) return false;
+                    OpenBodyguard();
+                    return true;
+                default:
+                    throw new ArgumentOutOfRangeException(nameof(role), role, null);
+            }
+        }
     }
 }

+ 6 - 0
MafiaTelegramBot/DataBase/EntityDao/UserDao.cs

@@ -71,5 +71,11 @@ namespace MafiaTelegramBot.DataBase.EntityDao
                 }
             });
         }
+
+        public static async Task<long> GetIdByUsername(string messageText)
+        {
+            var user = await DataBase.Users.FirstOrDefaultAsync(p => p.Username == messageText);
+            return user?.Id ?? -1;
+        }
     }
 }

+ 2 - 0
MafiaTelegramBot/Models/Bot.cs

@@ -85,6 +85,8 @@ namespace MafiaTelegramBot.Models
                 new ChooseGameModeQuery(),
                 new ConnectToRankedQuery(),
                 new ConnectToNotRankedQuery(),
+                new GiveToSelectedQuery(),
+                new GiveRoleQuery(),
             };
         }
         

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

@@ -46,6 +46,8 @@ namespace MafiaTelegramBot.Models.Commands
             
             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))

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

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

+ 27 - 0
MafiaTelegramBot/Models/Inlines/GiveRoleQuery.cs

@@ -0,0 +1,27 @@
+using System;
+using System.Threading.Tasks;
+using MafiaTelegramBot.DataBase.EntityDao;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Models.Inlines
+{
+    public class GiveRoleQuery : Query
+    {
+        protected override Callback Name => Callback.GiveRole;
+        protected override async Task<Message> Execute(Update update)
+        {
+            await DeletePreviousMessage(ChatId, update.CallbackQuery.Message.MessageId);
+            var data = update.CallbackQuery.Data.Split('|');
+            var target = long.Parse(data[2]);
+            if(!Enum.TryParse(data[3], out Roles role)) return await Bot.SendWithMarkdown2(ChatId, strings.unexpected_error);
+            var admin = await UserDao.GetPlayerById(UserId);
+            var user = await UserDao.GetPlayerById(target);
+            if(!user.OpenedRoles.TryOpenRole(role)) return await Bot.SendWithMarkdown2(ChatId, strings.user_now_has_role);
+            await Bot.SendStickerAsync(user.ChatId, Stickers.Sticker[role.ToString()]);
+            await Bot.SendWithMarkdown2(user.ChatId,
+                $"{admin.NickName} {strings.gives_to_you_role} {roles.ResourceManager.GetString(role.ToString())}");
+            return await Bot.SendWithMarkdown2(ChatId, $"{strings.role_successfully_issued_to} {user.NickName}");
+        }
+    }
+}

+ 18 - 0
MafiaTelegramBot/Models/Inlines/GiveToSelectedQuery.cs

@@ -0,0 +1,18 @@
+using System.Threading.Tasks;
+using MafiaTelegramBot.Models.Commands.CustomMessageHandlers;
+using MafiaTelegramBot.Resources;
+using Telegram.Bot.Types;
+
+namespace MafiaTelegramBot.Models.Inlines
+{
+    public class GiveToSelectedQuery : Query
+    {
+        protected override Callback Name => Callback.GiveToSelected;
+        
+        protected override async Task<Message> Execute(Update update)
+        {
+            await GiveRoleToPlayerHandler.AddToQueue(UserId);
+            return await Bot.SendWithMarkdown2(ChatId, strings.enter_username);
+        }
+    }
+}

+ 2 - 2
MafiaTelegramBot/Models/UpdateModel.cs

@@ -10,8 +10,8 @@ namespace MafiaTelegramBot.Models
     public abstract class UpdateModel<T> : ICloneable
     {
         protected abstract T Name { get; }
-        protected long ChatId { get; private set; }
-        protected long UserId { get; private set; }
+        protected long ChatId { get; set; }
+        protected long UserId { get; set; }
 
         protected abstract Task<Message> Execute(Update update);
 

+ 2 - 1
MafiaTelegramBot/Resources/Callback.cs

@@ -29,6 +29,7 @@ namespace MafiaTelegramBot.Resources
         ConnectToNotRanked,
         ConnectToRanked,
         GiveToAll,
-        GiveToSelected
+        GiveToSelected,
+        GiveRole
     }
 }

+ 18 - 0
MafiaTelegramBot/Resources/Keyboard.cs

@@ -1,3 +1,4 @@
+using System;
 using System.Collections.Generic;
 using MafiaTelegramBot.CustomCollections.Extensions;
 using MafiaTelegramBot.Game;
@@ -319,5 +320,22 @@ namespace MafiaTelegramBot.Resources
             { InlineKeyboardButton.WithCallbackData(strings.run_game, $"{Callback.StartGame}|{userId}") };
             return keyboard;
         }
+
+        public static InlineKeyboardMarkup GiveRoleKeyboard(long userId, long targetId)
+        {
+            var keyboard = new List<InlineKeyboardButton[]>();
+            foreach (var role in (Roles[]) Enum.GetValues(typeof(Roles)))
+            {
+                if(role is Roles.All or Roles.None or Roles.Mafia or Roles.Doctor or Roles.Don or Roles.Villager or Roles.Cop) continue;
+                keyboard.Add(new[]
+                {
+                    InlineKeyboardButton.WithCallbackData(
+                        roles.ResourceManager.GetString(role.ToString()),
+                        $"{Callback.GiveRole}|{userId}|{targetId}|{role}"
+                    )
+                });
+            }
+            return new InlineKeyboardMarkup(keyboard);
+        }
     }
 }

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

@@ -1208,5 +1208,41 @@ namespace MafiaTelegramBot {
                 return ResourceManager.GetString("give_role_to_selected_player", resourceCulture);
             }
         }
+        
+        internal static string enter_username {
+            get {
+                return ResourceManager.GetString("enter_username", resourceCulture);
+            }
+        }
+        
+        internal static string user_not_exists {
+            get {
+                return ResourceManager.GetString("user_not_exists", resourceCulture);
+            }
+        }
+        
+        internal static string choose_role_to_give {
+            get {
+                return ResourceManager.GetString("choose_role_to_give", resourceCulture);
+            }
+        }
+        
+        internal static string user_now_has_role {
+            get {
+                return ResourceManager.GetString("user_now_has_role", resourceCulture);
+            }
+        }
+        
+        internal static string gives_to_you_role {
+            get {
+                return ResourceManager.GetString("gives_to_you_role", resourceCulture);
+            }
+        }
+        
+        internal static string role_successfully_issued_to {
+            get {
+                return ResourceManager.GetString("role_successfully_issued_to", resourceCulture);
+            }
+        }
     }
 }

+ 18 - 0
MafiaTelegramBot/Resources/strings.resx

@@ -600,4 +600,22 @@
     <data name="give_role_to_selected_player" xml:space="preserve">
         <value>Выдать роль определенному игроку</value>
     </data>
+    <data name="enter_username" xml:space="preserve">
+        <value>Введите имя пользователя без @</value>
+    </data>
+    <data name="user_not_exists" xml:space="preserve">
+        <value>Пользователя нет в системе</value>
+    </data>
+    <data name="choose_role_to_give" xml:space="preserve">
+        <value>Выберите роль для выдачи</value>
+    </data>
+    <data name="user_now_has_role" xml:space="preserve">
+        <value>Пользователь уже обладает данной ролью</value>
+    </data>
+    <data name="gives_to_you_role" xml:space="preserve">
+        <value>выдал вам роль</value>
+    </data>
+    <data name="role_successfully_issued_to" xml:space="preserve">
+        <value>Роль успешно выдана игроку</value>
+    </data>
 </root>