Command.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #nullable enable
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using MafiaTelegramBot.Controllers;
  5. using MafiaTelegramBot.DataBase.EntityDao;
  6. using MafiaTelegramBot.Game;
  7. using MafiaTelegramBot.Models.Commands.CustomMessageHandlers;
  8. using Telegram.Bot.Types;
  9. using Telegram.Bot.Types.Enums;
  10. namespace MafiaTelegramBot.Models.Commands
  11. {
  12. public abstract class Command : UpdateModel<string>
  13. {
  14. private static readonly Dictionary<string, Command> CustomHandlers = new()
  15. {
  16. {"UsersThatChangesNickname", new ChangeNicknameHandler()},
  17. {"UsersThatCreatesRoom", new CreateRoomHandler()},
  18. {"UserThatEntersPrivateCode", new EnterCodeHandler()},
  19. };
  20. protected override bool IsMatches(string command)
  21. {
  22. return command == Name;
  23. }
  24. public static async Task<Message> Update(Update update)
  25. {
  26. var chatId = update.Message.Chat.Id;
  27. await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
  28. var userId = update.Message.From.Id;
  29. var commands = Bot.Commands;
  30. var message = update.Message.Text;
  31. var startCommand = new StartCommand();
  32. //TODO refactor later
  33. if (message.Contains(startCommand.Name)) return await ((Command?) startCommand.Clone(chatId, userId))!.Execute(update);
  34. var user = await UserDao.GetPlayerById(userId);
  35. if (user.IsPlaying)
  36. {
  37. var roomKey = RoomEncrypter.GetCode(user.GetRoomName());
  38. var room = RoomController.GetRoom(roomKey);
  39. return await room.MHandler.Handle(update);
  40. }
  41. var command = FirstOrDefault(commands, message);
  42. if(command != null) return await ((Command?) command.Clone(chatId, userId))!.Execute(update);
  43. if (Bot.UsersThatChangesNickname.Remove(userId))
  44. return await ((Command?) CustomHandlers["UsersThatChangesNickname"].Clone(chatId, userId))!.Execute(update);
  45. if (Bot.UsersThatCreatesRoom.ContainsKey(userId))
  46. return await ((Command?) CustomHandlers["UsersThatCreatesRoom"].Clone(chatId, userId))!.Execute(update);
  47. if (Bot.UserThatEntersPrivateCode.Remove(userId))
  48. return await ((Command?) CustomHandlers["UserThatEntersPrivateCode"].Clone(chatId, userId))!.Execute(update);
  49. return await Bot.SendWithMarkdown2(chatId, $"{strings.command_not_found} _*\\({message}\\)*_");
  50. }
  51. }
  52. }