Inheritance: IManagerItem
 public bool IsInGame(User user)
 {
     foreach (var player in players)
         if (user == player)
             return true;
     return false;
 }
 static void Main(string[] args)
 {
     Bot = new TelegramBot.TelegramBot(Settings.APIKEY);
     #region DEBUG
     if (false)
     {
         User host = new DebugUser { First_Name = "Debug", Last_Name = "Sander", Username = "******", ID = DebugUser.GetNextID() };
         UserManager.Instance.GetValue(ref host);
         GameRegistry.HostGame(host);
         for (int i = 0; i < 8; i++)
         {
             User user = new DebugUser { First_Name = "Debug", Last_Name = "test" + i, Username = "******" + i, ID = DebugUser.GetNextID() };
             UserManager.Instance.GetValue(ref user);
             GameRegistry.JoinGame(host, user);
         }
     }
     #endregion
     GameRegistry.bot = Bot;
     var admin = new User { First_Name = "Sander", Last_Name = "van 't Einde", ID = 8225698, Username = "******" };
     Bot.Admins.Add(UserManager.Instance.GetValue(ref admin));
     Bot.MessageHandler.RegisterMessageHandler(
         new HostMessageHandler(),
         new JoinMessageHandler(),
         new UnknownMessageHandler(),
         new ViewPlayersMessageHandler(),
         new LeaveMessageHandler(),
         new StartMessageHandler(),
         new RequestMembershipMessageHandler()
     );
     Bot.Start();
 }
 public Navigator GetNavigatorForUser(User u)
 {
     var fileName = FileLocForUser(u);
     if (File.Exists(fileName))
         return JsonConvert.DeserializeObject<Navigator>(File.ReadAllText(fileName));
     return null;
 }
 public bool Join(User user)
 {
     if (players.Contains(user))
         return false;
     players.Add(user);
     return true;
 }
 public NoContactHandler(TelegramBotReply reply, Chat originalGroup, User u, TelegramBot.TelegramBot bot)
 {
     reply.OnMessageNotSent += OnMessageNotSent;
     this.originalGroup = originalGroup;
     user = u;
     this.bot = bot;
 }
 private async Task AnnounceMessage(User u, TelegramBot.TelegramBot bot, string message)
 {
     GameRegistry.Game game;
     GameRegistry.IsInGame(u, out game);
     var msg = Message(-1, $"{u.Bold()} {message}", userMarkup: true);
     foreach(var user in game.Players)
     {
         msg.ChatId = user.ID;
         await msg.HandleReply(bot);
     }
 }
 private static void Login(string[] args)
 {
     if (args?.Length == 0)
     {
         bot.PrintError("No parameters given");
         return;
     }
     var user = string.Join(" ", args);
     var exist = UserManager.Instance.GetUserByUsername("_" + user);
     if (exist == null)
     {
         exist = new DebugUser { First_Name = "Debug", Last_Name = user, Username = "******" + user, ID = DebugUser.GetNextID() };
         UserManager.Instance.GetValue(ref exist);
     }
     loggedIn = exist;
     bot.PrintSuccess($"{exist} logged in.");
 }
 private async Task<TelegramBotReply> onPlayerPicked(User u, TelegramBot.TelegramBot bot, Message m, GameRegistry.Game game)
 {
     const string viewMembership = "is picking someone to view his/her membership";
     var flowObj = new PickPlayerFlow(game, onPickedMembershipTarget);
     if (u == m.From)
     {
         await AnnounceMessage(u, bot, viewMembership);
         m.From.MessageFlow = new MessageFlow(u, new FlowObject { Handler = flowObj });
         return Message(m, "You cheating bastard! Pick the one you would like to view the membership off.", replyMarkup: flowObj.GetKeyboard());
     }
     else
     {
         await AnnounceMessage(u, bot, viewMembership);
         u.MessageFlow = new MessageFlow(u, new FlowObject { Handler = flowObj });
         await Message(u.ID, "You've been chosen to view somebody's membership. Please pick one.", replyMarkup: flowObj.GetKeyboard()).HandleReply(bot);
     }
     return Message(m, $"You have chosen {u.Bold()} to pick a player", replyMarkup: HostMessageHandler.HostKeyboard, userMarkup: true);
 }
 public PlayerRole GetRole(User user)
 {
     if (!players.Contains(user))
         throw new Exception("Player not found");
     return PlayerRoles[players.IndexOf(user)];
 }
 public LeaveMessageConfirm(GameRegistry.Game game, User user)
 {
     this.game = game;
     this.user = user;
 }
 internal Game(User host)
 {
     Host = host;
     players = new List<User>(new User[]{ host });
 }
 public static bool IsInGame(User user, out Game game)
 {
     foreach (var g in activeGames)
         if (g.IsInGame(user))
         {
             game = g;
             return true;
         }
     game = null;
     return false;
 }
 public static bool IsInGame(User user)
 {
     foreach (var game in activeGames)
         if (game.IsInGame(user))
             return true;
     return false;
 }
 internal static Game GetGameForHost(User from)
 {
     if (!usersPlaying.ContainsKey(from) || usersPlaying[from].Host != from)
         return null;
     return usersPlaying[from];
 }
 private bool HasUserName(string name, User u)
 {
     return u.ToString().ToLower() == name;
 }
        private static void CreateBot(string apikey, string username)
        {
            Console.WriteLine("Creating bot");
            Bot = DebugMode ? new TelegramBot.TelegramBot(Settings.TESTAPIKEY) : new TelegramBot.TelegramBot(Settings.APIKEY);
            Bot.Logging = true;
            Bot.LoggingFilePath = "windesheimbot";
            Bot.DefaultMarkup = new ReplyKeyboardMarkup(new string[,]{
                {"/rooster", "/nu"},
                {"/vandaag", "/morgen"},
                {"/volgendeweek", "/help"},
                {"/klasrooster", "/docentrooster" },
                { "/klas", "/docent" },
                {"/contact", "/settings" }
            });
            Bot.OfflineNotification = @"Het lijkt erop dat ik off-line was toen ik één van je vorige berichten ontving.
Ik ben nu weer on-line en kan weer berichten ontvangen!

Krijg je dit bericht vaker? Het zou maar zo kunnen zijn dat de server van Telegram overbelast is.";
            var admin = new User { First_Name = "Sander", Last_Name = "van 't Einde", ID = 8225698, Username = "******" };
            Bot.Admins.Add(UserManager.Instance.GetValue(ref admin));
            Bot.PrintNotification("Bot created");
            Bot.InlineHandler = typeof(InlineHandler);
            if(DebugMode)
                Bot.PrintWarning("Debugmode enabled");
        }
 private void UserDisplay(User u, UserPreferences preferences, StringBuilder sb, int i)
 {
     if (i > 1)
         for (var j = 0; j < 2; j++)
             sb.AppendLine();
     sb.Append($"{i}) {u.First_Name ?? string.Empty} {u.Last_Name ?? string.Empty}");
     if (u.Username != null)
         sb.Append($" (@{u.Username})");
     sb.AppendLine();
     if (preferences.LastUpdate.Ticks == 0)
         sb.Append("Last seen: Unknown");
     else
     {
         var date = DateTime.Now - preferences.LastUpdate ;
         sb.Append($"Last seen: {date.Days}d{date.Hours}h{date.Minutes}m{date.Seconds}s");
     }
 }
 protected TelegramBotReply FormatRoosterResponse(Rooster rooster, User user)
 {
     var preferences = PreferenceRegistry.GetUserPreferencesForUser(user);
     bool isKlas = rooster.RoosterFor.GetType().Name == nameof(Klas);
     if (preferences.ReceiveRoosterAsImage && rooster.Lessen.Count > 0)
     {
         TemplateRoosterFormatToImageProvider provider;
         if (isKlas) provider = RoosterFormatToImageProvider.Instance; else provider = DocentRoosterFormatToImageProvider.Instance;
         var bitmap = provider.GetImageForRooster(rooster, preferences);
         if (bitmap != null)
         {
             var stream = new MemoryStream();
             bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
             return Photo(user.ID, stream, "rooster.png");
         }
     }
     return Message
     (
         user.ID,
         isKlas ? RoosterFormatProvider.Instance.FormatRooster(rooster, preferences) : DocentRoosterFormatProvider.Instance.FormatRooster(rooster, preferences)
     );
 }
 private async Task<TelegramBotReply> onPickedMembershipTarget(User u, TelegramBot.TelegramBot bot, Message m, GameRegistry.Game game)
 {
     await AnnounceMessage(m.From, bot, $"has chosen to view {u.Bold()}'s membership");
     return Message(m, $"The role of {u.Bold()} is {game.GetRole(u).Membership.Bold()}", replyMarkup: game.Host == m.From ? HostMessageHandler.HostKeyboard : JoinMessageHandler.JoinedPlayerKeyboard, userMarkup: true);
 }
 public void SaveNavigatorForUser(User u, Navigator n) => File.WriteAllText(FileLocForUser(u), JsonConvert.SerializeObject(n));
        internal async Task<TelegramBotReply> GetRoosterForDocentOrKlas(string command, string[] arguments, User from, RoosterFor roosterFor, bool useUserPreferences = true)
        {

            if (roosterFor == null)
                return Message(from.ID, "Je hebt nog geen klas of docent gekoppeld!\n\rGebruik /klas om een klas te koppelen, of /docent om een docent te koppelen");
            var date = DateTime.Now;
            var userPreferences = PreferenceRegistry.GetUserPreferencesForUser(from);
            DateTime? restrict = null;
            switch (command.ToLower())
            {
                case "/rooster":
                    if (arguments != null && arguments.Length > 0)
                    {
                        string[] datesStr = arguments[0].Split('-');
                        if (datesStr.Length < 2)
                            return WrongDateFormat(from.ID);
                        int[] datesInt = new int[datesStr.Length];
                        for (var i = 0; i < datesStr.Length; i++)
                            try
                            {
                                datesInt[i] = Convert.ToInt32(datesStr[i]);
                            }
                            catch (FormatException)
                            {
                                return WrongDateFormat(from.ID);
                            }
                        try
                        {
                            date = new DateTime(datesInt.Length >= 3 ? datesInt[2] : date.Year, datesInt[1], datesInt[0]);
                            if (Math.Abs((DateTime.Now - date).TotalDays) > 365)
                                return WrongDateFormat(from.ID);

                        }
                        catch (ArgumentOutOfRangeException) //Thrown door DateTime als er onjuiste gegevens in staan.
                        {
                            return WrongDateFormat(from.ID);
                        }
                        if (arguments?.Length > 1 && arguments[1] == "week")
                            date = date.WeekendDate();
                        else
                            restrict = date;
                    }
                    else
                    {
                        date = date.WeekendDate();
                    }
                    break;
                case "/vandaag":
                    restrict = date;
                    break;
                case "/morgen":
                    var morgen = date.AddDays(1);
                    date = morgen;
                    restrict = morgen;
                    break;
                case "/volgendeweek":
                    date = date.WeekendDate().AddDays(7);
                    break;
                default:
                    return Message(from.ID, "Er is iets fout gegaan bij het verwerken van je verzoek");
            }
            var result = useUserPreferences ? await GetResult(userPreferences, date, restrict) : await GetResult(roosterFor, date, restrict);
            var rooster = result.Rooster;
            if (rooster == null)
                return Message(from.ID, result != null ? result.ErrorMessage : "Er is iets fout gegaan bij het ophalen van het rooster.");
            else if (CountWithoutIgnoredLessen(rooster.Lessen, PreferenceRegistry.GetUserPreferencesForUser(from)) == 0)
            {
                string value = null;
                switch (command.ToLower())
                {
                    case "/rooster":
                        value = "deze week"; break;
                    case "/vandaag":
                        value = "vandaag"; break;
                    case "/morgen":
                        value = "morgen"; break;
                    case "/volgendeweek":
                        value = "volgende week"; break;
                }
                return Message(from.ID, $"Je hebt {value} geen lessen");
            }
            return FormatRoosterResponse(rooster,from);
        }
 private string FileLocForUser(User u) => $"{NAVIGATORDIRECTORY}/{u.ID}.nav";
 public void Leave(User from)
 {
     players.Remove(from);
     Stop();
 }
 public static TelegramBotReply ReplyBotNoContact(TelegramBotReply reply, Chat originalGroup, User user)
 {
     reply.Tag = new NoContactHandler(reply, originalGroup, user, Spoilerbot);
     return reply;
 }
 public MessageFlow(User u, params FlowObject[] objects)
 {
     _user = u;
     _flow = new List<FlowObject>(objects);
 }
 public IgnoreLessonMessageHandler(User u)
 {
     u.MessageFlow = new MessageFlow(u, new FlowObject { Handler = this });
 }
 private void GetBot()
 {
     var response = HttpClient.PostAsync(URL + "getme", null).Result;
     if (response.StatusCode != HttpStatusCode.OK)
         throw new BotNotFoundException("Couldn't fetch the bot from the Telegram Server. Is the API key correct? Is Telegram down?");
     var str = response.Content.ReadAsStringAsync().Result;
     var reply = JsonConvert.DeserializeObject<ReplyFromTelegram<User>>(str);
     if (!reply.Ok)
         throw new BotNotFoundException("Couldn't fetch the bot from the Telegram Server. The Bot was not found!");
     Bot = reply.Result;
 }
 public static Game HostGame(User host)
 {
     if (usersPlaying.ContainsKey(host))
         return usersPlaying[host];
     var game = new Game(host);
     usersPlaying.Add(host, game);
     activeGames.Add(game);
     return game;
 }
        public static int JoinGame(User host, User join)
        {
            if (!usersPlaying.ContainsKey(host))
                return JOIN_HOSTNOTFOUND;
            if (usersPlaying.ContainsKey(join))
                return JOIN_JOINISHOST;
            if (usersPlaying[host].PlayerCount == 10)
                return JOIN_PARTYFULL;
            if (usersPlaying[host].Join(join))
                return JOIN_SUCCESS;
            else
                return JOIN_ALLREADYJOINED;

        }
 private bool HasUserUsername(string username, User u)
 {
     return u.Username.ToLower() == username;
 }