Inheritance: IManagerItem
コード例 #1
0
 public bool IsInGame(User user)
 {
     foreach (var player in players)
         if (user == player)
             return true;
     return false;
 }
コード例 #2
0
 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();
 }
コード例 #3
0
 public Navigator GetNavigatorForUser(User u)
 {
     var fileName = FileLocForUser(u);
     if (File.Exists(fileName))
         return JsonConvert.DeserializeObject<Navigator>(File.ReadAllText(fileName));
     return null;
 }
コード例 #4
0
 public bool Join(User user)
 {
     if (players.Contains(user))
         return false;
     players.Add(user);
     return true;
 }
コード例 #5
0
 public NoContactHandler(TelegramBotReply reply, Chat originalGroup, User u, TelegramBot.TelegramBot bot)
 {
     reply.OnMessageNotSent += OnMessageNotSent;
     this.originalGroup = originalGroup;
     user = u;
     this.bot = bot;
 }
コード例 #6
0
 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);
     }
 }
コード例 #7
0
 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.");
 }
コード例 #8
0
 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);
 }
コード例 #9
0
 public PlayerRole GetRole(User user)
 {
     if (!players.Contains(user))
         throw new Exception("Player not found");
     return PlayerRoles[players.IndexOf(user)];
 }
コード例 #10
0
 public LeaveMessageConfirm(GameRegistry.Game game, User user)
 {
     this.game = game;
     this.user = user;
 }
コード例 #11
0
 internal Game(User host)
 {
     Host = host;
     players = new List<User>(new User[]{ host });
 }
コード例 #12
0
 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;
 }
コード例 #13
0
 public static bool IsInGame(User user)
 {
     foreach (var game in activeGames)
         if (game.IsInGame(user))
             return true;
     return false;
 }
コード例 #14
0
 internal static Game GetGameForHost(User from)
 {
     if (!usersPlaying.ContainsKey(from) || usersPlaying[from].Host != from)
         return null;
     return usersPlaying[from];
 }
コード例 #15
0
 private bool HasUserName(string name, User u)
 {
     return u.ToString().ToLower() == name;
 }
コード例 #16
0
        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");
        }
コード例 #17
0
 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");
     }
 }
コード例 #18
0
 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)
     );
 }
コード例 #19
0
 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);
 }
コード例 #20
0
 public void SaveNavigatorForUser(User u, Navigator n) => File.WriteAllText(FileLocForUser(u), JsonConvert.SerializeObject(n));
コード例 #21
0
        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);
        }
コード例 #22
0
 private string FileLocForUser(User u) => $"{NAVIGATORDIRECTORY}/{u.ID}.nav";
コード例 #23
0
 public void Leave(User from)
 {
     players.Remove(from);
     Stop();
 }
コード例 #24
0
 public static TelegramBotReply ReplyBotNoContact(TelegramBotReply reply, Chat originalGroup, User user)
 {
     reply.Tag = new NoContactHandler(reply, originalGroup, user, Spoilerbot);
     return reply;
 }
コード例 #25
0
 public MessageFlow(User u, params FlowObject[] objects)
 {
     _user = u;
     _flow = new List<FlowObject>(objects);
 }
コード例 #26
0
 public IgnoreLessonMessageHandler(User u)
 {
     u.MessageFlow = new MessageFlow(u, new FlowObject { Handler = this });
 }
コード例 #27
0
 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;
 }
コード例 #28
0
 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;
 }
コード例 #29
0
        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;

        }
コード例 #30
0
 private bool HasUserUsername(string username, User u)
 {
     return u.Username.ToLower() == username;
 }