Ejemplo n.º 1
0

        
Ejemplo n.º 2
0
        public void CheckInNewStudentExistingNickname()
        {
            Unit unit = new Unit()
            {
                Code      = AlphaNumericStringGenerator.GetString(8),
                IsDeleted = false,
                Name      = AlphaNumericStringGenerator.GetString(10),
            };

            Nicknames nickname = new Nicknames()
            {
                NickName = AlphaNumericStringGenerator.GetString(10),
                Sid      = AlphaNumericStringGenerator.GetStudentIDString()
            };

            using (helpdesksystemContext context = new helpdesksystemContext())
            {
                context.Unit.Add(unit);
                context.Nicknames.Add(nickname);
                context.SaveChanges();
            }

            CheckInRequest request = new CheckInRequest()
            {
                UnitID   = unit.UnitId,
                SID      = AlphaNumericStringGenerator.GetStudentIDString(),
                Nickname = nickname.NickName
            };

            CheckInFacade facade = new CheckInFacade();

            CheckInResponse response = facade.CheckIn(request);

            Assert.AreEqual(HttpStatusCode.BadRequest, response.Status);
        }
Ejemplo n.º 3
0
        internal bool IsNicknameValid(PKM pkm)
        {
            var nick = pkm.Nickname;

            if (pkm.Format <= 2)
            {
                return(Nicknames.Contains(nick));
            }

            // Converted string 1/2->7 to language specific value
            // Nicknames can be from any of the languages it can trade between.
            int lang = pkm.Language;

            if (lang == 1)
            {
                // Special consideration for Hiragana strings that are transferred
                if (Version == GameVersion.YW && Species == (int)Core.Species.Dugtrio)
                {
                    return(nick == "ぐりお");
                }
                return(nick == Nicknames[1]);
            }

            return(GetNicknameIndex(nick) >= 2);
        }
Ejemplo n.º 4
0
        public void CheckInNoUnit()
        {
            Nicknames nickname = new Nicknames()
            {
                NickName = AlphaNumericStringGenerator.GetString(10),
                Sid      = AlphaNumericStringGenerator.GetStudentIDString()
            };

            using (helpdesksystemContext context = new helpdesksystemContext())
            {
                context.Nicknames.Add(nickname);
                context.SaveChanges();
            }

            CheckInRequest request = new CheckInRequest()
            {
                SID = nickname.Sid
            };

            CheckInFacade facade = new CheckInFacade();

            CheckInResponse response = facade.CheckIn(request);

            Assert.AreEqual(HttpStatusCode.BadRequest, response.Status);
        }
        public void ValidateNicknameOldInValid()
        {
            Nicknames nickname = new Nicknames()
            {
                NickName = AlphaNumericStringGenerator.GetString(10),
                Sid      = AlphaNumericStringGenerator.GetStudentIDString()
            };

            using (helpdesksystemContext context = new helpdesksystemContext())
            {
                context.Nicknames.Add(nickname);
                context.SaveChanges();
            }

            ValidateNicknameRequest request = new ValidateNicknameRequest()
            {
                Name = nickname.NickName,
                SID  = AlphaNumericStringGenerator.GetStudentIDString()
            };

            var facade = new StudentFacade();

            var response = facade.ValidateNickname(request);

            Assert.AreEqual(HttpStatusCode.BadRequest, response.Status);
        }
Ejemplo n.º 6
0
 public void AddNicknamesToUser(MBlogModel.User user)
 {
     foreach (MBlogModel.Blog blog in user.Blogs)
     {
         Nicknames.Add(blog.Nickname);
     }
 }
Ejemplo n.º 7
0
        public override Embed WriteToDiscord()
        {
            Affinity = char.ToUpper(Affinity[0]) + Affinity.Substring(1);

            var url       = "https://dx2wiki.com/index.php/" + Uri.EscapeDataString(Name.Replace("[", "(").Replace("]", ")")).Replace("(", "%28").Replace(")", "%29");
            var thumbnail = "https://teambuilder.dx2wiki.com/Images/Spells/" + Uri.EscapeDataString(Affinity) + ".png";

            var eb = new EmbedBuilder();

            eb.WithTitle(Name);
            eb.AddField("Element: ", Affinity, true);
            eb.AddField("Cost: ", MP, true);
            eb.AddField("Target: ", Target, true);

            if (UseLimit != "")
            {
                eb.AddField("Max Uses: ", UseLimit, true);
            }
            eb.WithDescription(Effect);
            if (!string.IsNullOrEmpty(Nicknames))
            {
                eb.WithFooter("Nicknames: " + Nicknames.Replace(",", ", "));
            }
            eb.WithUrl(url);
            eb.WithThumbnailUrl(thumbnail);
            return(eb.Build());
        }
Ejemplo n.º 8
0
        public MainWindow()
        {
            InitializeComponent();
            this.btnAdd.Click += btnAdd_Click;

            this.names = new Nicknames();

            sPanel.DataContext = this.names;
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Converts the nickname DAO to a DTO to send to the front end
        /// </summary>
        /// <param name="nickname">The DAO for the nickname</param>
        /// <returns>The DTO for the nickname</returns>
        private NicknameDTO DAO2DTO(Nicknames nickname)
        {
            NicknameDTO nicknameDTO = null;

            nicknameDTO           = new NicknameDTO();
            nicknameDTO.ID        = nickname.StudentId;
            nicknameDTO.Nickname  = nickname.NickName;
            nicknameDTO.StudentID = nickname.Sid;

            return(nicknameDTO);
        }
Ejemplo n.º 10
0
 public void AddNickname(SocketGuildUser user)
 {
     if (Nicknames == null)
     {
         Nicknames = new List <string>();
     }
     if (!string.IsNullOrEmpty(user.Nickname) && !Nicknames.Contains(user.Nickname))
     {
         Nicknames.Add(user.Nickname);
     }
 }
Ejemplo n.º 11
0
        public MainWindow()
        {
            InitializeComponent();

            names = (Nicknames)FindResource("names");
            // 이렇게 할 경우 DataContext를 코드 상에서 지정할 필요가 없다.

            names.Add(new Nickname("XXX", "1st"));
            names.Add(new Nickname("YYY", "2nd"));
            names.Add(new Nickname("ZZZ", "3rd"));
        }
Ejemplo n.º 12
0
 public void AddNickname(string username)
 {
     if (Nicknames == null)
     {
         Nicknames = new List <string>();
     }
     if (!Nicknames.Contains(username))
     {
         Nicknames.Add(username);
     }
 }
Ejemplo n.º 13
0
 public DatabaseUser AddNickname(string username)
 {
     if (Nicknames == null)
     {
         Nicknames = new List <string>();
     }
     if (!Nicknames.Contains(username))
     {
         Nicknames.Add(username);
     }
     return(this);
 }
Ejemplo n.º 14
0
 public DatabaseUser AddNickname(SocketGuildUser user)
 {
     if (user == null)
     {
         return(this);
     }
     if (user.Nickname != null && !string.IsNullOrEmpty(user.Nickname) && !Nicknames.Contains(user.Nickname))
     {
         AddNickname(user.Nickname);
     }
     return(this);
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Converts the nickname DTO to a DAO to interact with the database
        /// </summary>
        /// <param name="nickname">The DTO for the nickname</param>
        /// <returns>The DAO for the nickname</returns>
        private Nicknames DTO2DAO(Nicknames nicknameDTO)
        {
            Nicknames nickname = null;

            nickname = new Nicknames()
            {
                NickName  = nicknameDTO.NickName,
                Sid       = nicknameDTO.Sid,
                StudentId = nickname.StudentId
            };

            return(nickname);
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Loads the entire table of users and nicknames into the cache.
 /// </summary>
 public void LoadUsersIntoCache()
 {
     ipAddressToViewUserCache = Nicknames.AsNoTracking().ToDictionary(n => n.IpAddress, n => new ChatMessageViewUser
     {
         Username  = n.Name,
         ChatColor = DefaultChatColor,
         LoggedIn  = false
     });
     userIdToViewUserCache = Users.AsNoTracking().ToDictionary(u => u.Id, u => new ChatMessageViewUser
     {
         Username  = u.UserName,
         ChatColor = u.ChatColor,
         LoggedIn  = true
     });
 }
Ejemplo n.º 17
0
    private void OnEnable()
    {
        int       size     = Nicknames.GetValues(typeof(Nicknames)).Length;
        Nicknames nickname = new Nicknames();

        while (!nameChosen)
        {
            nickname = PickName(size);
            if (nickname != Nicknames.Player1)
            {
                nameChosen = true;
            }
        }

        playerName = nickname.ToString();
    }
Ejemplo n.º 18
0
        public void CheckInExistingStudent()
        {
            Unit unit = new Unit()
            {
                Code      = AlphaNumericStringGenerator.GetString(8),
                IsDeleted = false,
                Name      = AlphaNumericStringGenerator.GetString(10),
            };

            Nicknames nickname = new Nicknames()
            {
                NickName = AlphaNumericStringGenerator.GetString(10),
                Sid      = AlphaNumericStringGenerator.GetStudentIDString()
            };

            using (helpdesksystemContext context = new helpdesksystemContext())
            {
                context.Unit.Add(unit);
                context.Nicknames.Add(nickname);
                context.SaveChanges();
            }

            CheckInRequest request = new CheckInRequest()
            {
                UnitID    = unit.UnitId,
                StudentID = nickname.StudentId
            };

            CheckInFacade facade = new CheckInFacade();

            CheckInResponse response = facade.CheckIn(request);

            Assert.AreEqual(HttpStatusCode.OK, response.Status);
            Assert.IsTrue(response.CheckInID > 0);

            using (helpdesksystemContext context = new helpdesksystemContext())
            {
                Checkinhistory checkInHistory = context.Checkinhistory.FirstOrDefault(cih => cih.CheckInId == response.CheckInID);

                var baseTime = DateTime.Now.AddMinutes(-1);
                var addTime  = checkInHistory.CheckInTime;
                Assert.AreEqual(request.UnitID, checkInHistory.UnitId);
                var timeDiff = baseTime.CompareTo(addTime);
                Assert.IsTrue(timeDiff == -1);
                Assert.AreEqual(request.StudentID, checkInHistory.StudentId);
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Used to edit the specified student's nickname in the databse with the request's information
        /// </summary>
        /// <param name="id">The StudentID of the student to be updated</param>
        /// <param name="request">The request that contains the student's new nickname</param>
        /// <returns>A boolean that indicates whether the operation was a success</returns>
        public bool EditStudentNickname(int id, EditStudentNicknameRequest request)
        {
            using (helpdesksystemContext context = new helpdesksystemContext())
            {
                Nicknames nickname = context.Nicknames.FirstOrDefault(n => n.StudentId == id);

                if (nickname == null)
                {
                    return(false);
                }

                nickname.NickName = request.Nickname;

                context.SaveChanges();
            }
            return(true);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Used to add a nickname to the database
        /// </summary>
        /// <param name="request">The nickname information</param>
        /// <returns>The id of the nickname added</returns>
        public int AddStudentNickname(AddStudentRequest request)
        {
            Nicknames nickname = new Nicknames()
            {
                NickName = request.Nickname,
                Sid      = request.SID
            };

            using (helpdesksystemContext context = new helpdesksystemContext())
            {
                context.Nicknames.Add(nickname);

                context.SaveChanges();
            }

            return(nickname.StudentId);
        }
Ejemplo n.º 21
0
        private async void CommandError(object sender, CommandErrorEventArgs e)
        {
            if (e.ErrorType == CommandErrorType.Exception)
            {
                _client.Log.Error("Command", e.Exception);
                await e.Channel.SendMessage($"Error: {e.Exception.GetBaseException().Message}");
            }
            else if (e.ErrorType == CommandErrorType.BadPermissions)
            {
                if (e.Exception?.Message == "This module is currently disabled, " + Nicknames.GetNickname(UserStateRepository.GetUserState(e.User.Id).Favorability) + ".")
                {
                    await e.Channel.SendMessage($"The `{e.Command?.Category}` module is currently disabled, " + Nicknames.GetNickname(UserStateRepository.GetUserState(e.User.Id).Favorability) + ".");
                    return;
                }
                else if (e.Exception != null)
                {
                    await e.Channel.SendMessage(e.Exception.Message);
                    return;
                }

                if (e.Command?.IsHidden == true)
                    return;

                await e.Channel.SendMessage($"You don't have permission to access that command, "+Nicknames.GetNickname(UserStateRepository.GetUserState(e.User.Id).Favorability)+"!");
            }
            else if (e.ErrorType == CommandErrorType.BadArgCount)
            {
                await e.Channel.SendMessage("Error: Invalid parameter count, " + Nicknames.GetNickname(UserStateRepository.GetUserState(e.User.Id).Favorability) + ".");
            }
            else if (e.ErrorType == CommandErrorType.InvalidInput)
            {
                await e.Channel.SendMessage("Error: Invalid input! Make sure your quotes match up correctly, " + Nicknames.GetNickname(UserStateRepository.GetUserState(e.User.Id).Favorability) + "!");
            }
            else if (e.ErrorType == CommandErrorType.UnknownCommand)
            {
                // Only set up a response in here if you stick with a mention prefix
            }
        }
Ejemplo n.º 22
0
        public override Embed WriteToDiscord()
        {
            //Perform some fixes on values before exporting

            Name    = DemonRetriever.FixSkillsNamedAsDemons(Name);
            Element = char.ToUpper(Element[0]) + Element.Substring(1);

            if (Sp == "")
            {
                Sp = "-";
            }

            var newDescription = Description.Replace("\\n", "\n") + "\n" + InnateFrom + TransferrableFrom;

            var url       = "https://dx2wiki.com/index.php/" + Uri.EscapeDataString(Name.Replace("[", "(").Replace("]", ")")).Replace("(", "%28").Replace(")", "%29");
            var thumbnail = "https://teambuilder.dx2wiki.com/Images/Spells/" + Uri.EscapeDataString(Element) + ".png";

            //Generate our embeded message and return it
            var eb = new EmbedBuilder();

            eb.WithTitle(Name);
            eb.AddField("Element: ", Element, true);
            eb.AddField("Cost: ", Cost, true);
            eb.AddField("Target: ", Target, true);
            eb.AddField("Sp: ", Sp, true);
            if (UseLimit != "")
            {
                eb.AddField("Max Uses: ", UseLimit, true);
            }
            if (!string.IsNullOrEmpty(Nicknames))
            {
                eb.WithFooter("Nicknames: " + Nicknames.Replace(",", ", "));
            }
            eb.WithDescription(newDescription);
            eb.WithUrl(url);
            eb.WithThumbnailUrl(thumbnail);
            return(eb.Build());
        }
Ejemplo n.º 23
0
 public void AddFriendInvitation(string username, string nickname, string message)
 {
     Usernames.Add(username);
     Nicknames.Add(nickname);
     Messages.Add(message);
 }
Ejemplo n.º 24
0
        public override void Install(ModuleManager manager)
        {
            _manager = manager;
            _client  = manager.Client;



            _manager.CreateCommands("", cgb =>
            {
                cgb.MinPermissions((int)PermissionLevel.User);

                cgb.CreateCommand("xkcd")
                .Description("Post either the latest comic from XKCD, or the specified comic number. rnd will provide a random comic.")
                .Parameter("comic", ParameterType.Optional)
                .Do(async e =>
                {
                    if (Beta.CheckModuleState(e, "comic", e.Channel.IsPrivate))
                    {
                        if (e.GetArg("comic") == "")
                        {
                            XKCDComic comic = _download_serialized_json_data <XKCDComic>("http://xkcd.com/info.0.json");
                            await e.Channel.SendMessage(comic.img);
                            await e.Channel.SendMessage(comic.alt);
                            Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, 1);
                        }
                        else if (e.GetArg("comic") == "rnd")
                        {
                            XKCDComic comic = _download_serialized_json_data <XKCDComic>("http://xkcd.com/info.0.json");
                            int latestComic = comic.num;
                            int random      = new Random().Next(1, latestComic + 1);
                            string url      = String.Format("http://xkcd.com/{0}/info.0.json", random);
                            comic           = _download_serialized_json_data <XKCDComic>(url);
                            await e.Channel.SendMessage(comic.img);
                            await e.Channel.SendMessage(comic.alt);
                            Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, 1);
                        }
                        else
                        {
                            int comicnum;
                            if (Int32.TryParse(e.GetArg("comic"), out comicnum))
                            {
                                string url      = String.Format("http://xkcd.com/{0}/info.0.json", e.GetArg("comic").Trim());
                                XKCDComic comic = _download_serialized_json_data <XKCDComic>(url);
                                await e.Channel.SendMessage(comic.img);
                                await e.Channel.SendMessage(comic.alt);
                                Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, 1);
                            }
                            else
                            {
                                await e.Channel.SendMessage("uh... sorry, but that doesn't look like a number " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + ".");
                                Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, -1);
                            }
                        }
                    }
                });
            });
        }
        public void JoinQueueNoCheckInNewStudent()
        {
            Helpdesksettings helpdesk = new Helpdesksettings()
            {
                HasQueue   = true,
                HasCheckIn = false,
                IsDeleted  = false,
                Name       = AlphaNumericStringGenerator.GetString(10),
            };

            Unit unit = new Unit()
            {
                Code      = AlphaNumericStringGenerator.GetString(8),
                IsDeleted = false,
                Name      = AlphaNumericStringGenerator.GetString(10),
            };

            Topic topic = new Topic()
            {
                IsDeleted = false,
                Name      = AlphaNumericStringGenerator.GetString(10),
            };

            using (helpdesksystemContext context = new helpdesksystemContext())
            {
                context.Helpdesksettings.Add(helpdesk);
                context.Unit.Add(unit);
                context.SaveChanges();

                Helpdeskunit helpdeskunit = new Helpdeskunit()
                {
                    HelpdeskId = helpdesk.HelpdeskId,
                    UnitId     = unit.UnitId
                };

                context.SaveChanges();

                topic.UnitId = unit.UnitId;
                context.Topic.Add(topic);
                context.SaveChanges();
            }

            AddToQueueRequest request = new AddToQueueRequest()
            {
                Nickname    = AlphaNumericStringGenerator.GetString(10),
                SID         = AlphaNumericStringGenerator.GetStudentIDString(),
                TopicID     = topic.TopicId,
                Description = "JoinQueueNoCheckInNewStudent Test"
            };

            QueueFacade facade = new QueueFacade();

            AddToQueueResponse response = facade.AddToQueue(request);

            Assert.AreEqual(HttpStatusCode.OK, response.Status);
            Assert.IsTrue(response.ItemId > 0);

            using (helpdesksystemContext context = new helpdesksystemContext())
            {
                Queueitem queueitem = context.Queueitem.FirstOrDefault(qi => qi.ItemId == response.ItemId);

                var baseTime = DateTime.Now.AddMinutes(-1);
                var addTime  = queueitem.TimeAdded;
                Assert.AreEqual(request.TopicID, queueitem.TopicId);
                var timeDiff = baseTime.CompareTo(addTime);
                Assert.IsTrue(timeDiff == -1);

                Nicknames nicknames = context.Nicknames.FirstOrDefault(n => n.StudentId == queueitem.StudentId);

                Assert.AreEqual(request.Nickname, nicknames.NickName);
                Assert.AreEqual(request.SID, nicknames.Sid);
            }
        }
Ejemplo n.º 26
0
        public override void Install(ModuleManager manager)
        {
            _manager = manager;
            _client  = manager.Client;


            _manager.CreateCommands("", cgb =>
            {
                cgb.MinPermissions((int)PermissionLevel.User);

                cgb.CreateCommand("say")
                .MinPermissions((int)PermissionLevel.BotOwner)      // An unrestricted say command is a bad idea
                .Description("Make the bot speak!")
                .Parameter("text", ParameterType.Unparsed)
                .Do(async e =>
                {
                    await e.Channel.SendMessage(e.GetArg("text"));
                    await e.Message.Delete();
                    Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, 10);
                });

                cgb.CreateCommand("setmotd")
                .MinPermissions((int)PermissionLevel.ChannelModerator)
                .Description("Set the Message of the Day for this channel!")
                .Parameter("text", ParameterType.Unparsed)
                .Do(async e =>
                {
                    if (Beta.ChannelStateRepository.VerifyChannelExists(e.Channel.Id))
                    {
                        Beta.ChannelStateRepository.ChannelStates.FirstOrDefault(cs => cs.ChannelID == e.Channel.Id).MOTD = e.GetArg("text");
                        Beta.ChannelStateRepository.Save();
                        await e.User.SendMessage("Ok " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + ", I set that message for you!");
                        await e.Message.Delete();
                        await e.Channel.SendMessage(Beta.ChannelStateRepository.GetChannelState(e.Channel.Id).MOTD);
                        Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, 10);
                    }
                });

                cgb.CreateCommand("trust")
                .MinPermissions((int)PermissionLevel.BotOwner)
                .Description("Adds the specified user to the trusted user list.")
                .Parameter("uid", ParameterType.Unparsed)
                .Do(async e =>
                {
                    ulong uid;
                    if (ulong.TryParse(e.GetArg("uid"), out uid))
                    {
                        Beta.Config._TrustedUsers.Add(uid);
                        ConfigHandler.SaveConfig();
                        await e.Channel.SendMessage("You really trust that one? Well, _you're_ the boss.");
                    }
                    else
                    {
                        await e.Channel.SendMessage("Who?");
                    }
                });


                cgb.CreateCommand("initstates")
                .MinPermissions((int)PermissionLevel.BotOwner)
                .Description("Administration tool, initiate channel states for all current channels.")
                .Do(async e =>
                {
                    foreach (var server in _client.Servers)
                    {
                        foreach (var channel in server.AllChannels)
                        {
                            Beta.ChannelStateRepository.AddChannel(channel, server);
                        }
                        Beta.ServerStateRepository.AddServer(server);
                    }
                    await e.Channel.SendMessage("All set, Boss!");
                });

                cgb.CreateCommand("roll")
                .Description(
                    @"Make Beta roll the specified number of dice. For Example typing $Roll 3d12 would cause Beta to return the results of rolling 3 12-sided die. You could also role a single 12-sided die with d12.")
                .Parameter("roll", ParameterType.Unparsed)
                .Do(async e =>
                {
                    if (Beta.CheckModuleState(e, "roll", e.Channel.IsPrivate))
                    {
                        var arg       = e.GetArg("roll");
                        var arguments = arg.Split('d').Where(s => !string.IsNullOrEmpty(s)).ToList();
                        int sides, times, modifier;

                        if (arguments.Count == 1)
                        {
                            if (arguments[0].Contains("+"))
                            {
                                arguments = arguments[0].Split('+').ToList();
                                if (int.TryParse(arguments[0], out sides))
                                {
                                    var dice = new Dice(sides);
                                    var temp = dice.Roll();
                                    if (int.TryParse(arguments[1], out modifier))
                                    {
                                        await
                                        e.Channel.SendMessage(
                                            string.Format("Rolled one d{0}) plus {1} and got a total of {2}", sides,
                                                          modifier, temp + modifier));
                                        Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, 1);
                                    }
                                    else
                                    {
                                        await e.Channel.SendMessage("Sorry, I don't recognize that number, " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + "");
                                        Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, -1);
                                    }
                                }
                                else
                                {
                                    await e.Channel.SendMessage("Sorry, I don't recognize that number, " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + "");
                                    Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, -1);
                                }
                            }
                            else
                            {
                                if (int.TryParse(arguments[0], out sides))
                                {
                                    var dice = new Dice(sides);
                                    await
                                    e.Channel.SendMessage(string.Format("Rolled one d{0} and got a total of {1}",
                                                                        sides, dice.Roll()));
                                    Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, 1);
                                }
                                else
                                {
                                    await e.Channel.SendMessage("Sorry, I don't recognize that number, " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + "");
                                    Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, -1);
                                }
                            }
                        }
                        else if (arguments.Count == 2)
                        {
                            if (int.TryParse(arguments[0], out times))
                            {
                                if (arguments[1].Contains("+"))
                                {
                                    arguments = arguments[1].Split('+').ToList();
                                    if (int.TryParse(arguments[0], out sides))
                                    {
                                        var dice = new Dice(sides);
                                        var temp = dice.Roll(times);
                                        if (int.TryParse(arguments[1], out modifier))
                                        {
                                            await
                                            e.Channel.SendMessage(
                                                string.Format("Rolled {0} d{1} plus {2} and got a total of {3}",
                                                              times, sides, modifier, temp.Total + modifier));
                                            await
                                            e.Channel.SendMessage(string.Format("Individual Rolls: {0}",
                                                                                string.Join(",", temp.Rolls)));
                                            Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, 1);
                                        }
                                        else
                                        {
                                            await e.Channel.SendMessage("Sorry, I don't recognize that number, " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + "");
                                            Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, -1);
                                        }
                                    }
                                    else
                                    {
                                        await e.Channel.SendMessage("Sorry, I don't recognize that number, " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + "");
                                        Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, -1);
                                    }
                                }
                                else
                                {
                                    if (int.TryParse(arguments[1], out sides))
                                    {
                                        var dice = new Dice(sides);
                                        var temp = dice.Roll(times);
                                        await
                                        e.Channel.SendMessage(string.Format(
                                                                  "Rolled {0} d{1} and got a total of {2}", times, sides, temp.Total));
                                        await
                                        e.Channel.SendMessage(string.Format("Individual Rolls: {0}",
                                                                            string.Join(",", temp.Rolls)));
                                        Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, 1);
                                    }
                                    else
                                    {
                                        await e.Channel.SendMessage("Sorry, I don't recognize that number, " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + "");
                                        Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, -1);
                                    }
                                }
                            }
                        }
                    }
                });

                cgb.CreateCommand("ask")
                .Description("Ask Beta a yes or no question!")
                .Parameter("text", ParameterType.Unparsed)
                .Do(async e =>
                {
                    if (Beta.CheckModuleState(e, "ask", e.Channel.IsPrivate))
                    {
                        await e.Channel.SendMessage(Utilities._8BallResponses.GetRandom());
                        Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, 1);
                    }
                });

                cgb.CreateCommand("motd")
                .Description("Show the MotD for the current channel")
                .Do(async e =>
                {
                    if (Beta.CheckModuleState(e, "motd", e.Channel.IsPrivate))
                    {
                        if (Beta.ChannelStateRepository.VerifyChannelExists(e.Channel.Id))
                        {
                            await
                            e.Channel.SendMessage(Beta.ChannelStateRepository.GetChannelState(e.Channel.Id).MOTD);
                            await e.Message.Delete();
                            Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, 1);
                        }
                        else
                        {
                            await
                            e.Channel.SendMessage(
                                "Sorry " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + ", there is no message! harass the Admins or something.");
                        }
                    }
                });

                cgb.CreateCommand("forgive")
                .Description(
                    "Forgives certain violations. Currently recognizes a username (NOT display name) as a parameter.")
                .Parameter("User", ParameterType.Required)
                .MinPermissions((int)PermissionLevel.ServerAdmin)
                .Do(async e =>
                {
                    UserState user = Beta.UserStateRepository.UserStates.FirstOrDefault(us => us.UserName.ToLower() == e.GetArg("User").ToLower());
                    if (user != null)
                    {
                        await e.Channel.SendMessage("You got it " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + "!");

                        Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, 1);
                    }
                    else
                    {
                        await e.Channel.SendMessage("Sorry, " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + ". I don't recognize that meatbag.");
                        Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, -1);
                    }
                });

                cgb.CreateCommand("stoggle")
                .Description(
                    "Toogles whether a module is enabled for the entire server. Please use one of the following options: Ask, Comic, Gamertag, MotD, Note, Quote, Roll, Table, Twitter, Politics, Battle")
                .MinPermissions((int)PermissionLevel.ServerAdmin)
                .Parameter("Module", ParameterType.Unparsed)
                .Do(async e =>
                {
                    if (TogglableCommands.Contains(e.GetArg("Module").ToLower()))
                    {
                        bool changedState =
                            Beta.ServerStateRepository.GetServerState(e.Server.Id)
                            .ToggleFeatureBool(e.GetArg("Module").ToLower());
                        await
                        e.Channel.SendMessage(
                            String.Format("Ok " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + ", I've toggled the setting enabling {0} so now it's set to {1} for the entire server",
                                          e.GetArg("Module"), changedState.ToString()));
                        Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, 1);
                    }
                    else
                    {
                        await e.Channel.SendMessage(String.Format("Sorry, " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + ". I don't see a module named {0} in the approved list...", e.GetArg("Module")))
                        ;
                        Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, -1);
                    }
                    Beta.ServerStateRepository.Save();
                });

                cgb.CreateCommand("toggle")
                .Description(
                    "Toogles whether a module is enabled for the channel. Please use one of the following options: Ask, Comic, Gamertag, MotD, Note, Quote, Roll, Table, Twitter, Politics, Battle")
                .MinPermissions((int)PermissionLevel.ChannelAdmin)
                .Parameter("Module", ParameterType.Unparsed)
                .Do(async e =>
                {
                    if (TogglableCommands.Contains(e.GetArg("Module").ToLower()))
                    {
                        bool changedState =
                            Beta.ChannelStateRepository.GetChannelState(e.Channel.Id)
                            .ToggleFeatureBool(e.GetArg("Module").ToLower());
                        await
                        e.Channel.SendMessage(
                            String.Format("Ok, I've toggled the setting enabling {0} so now it's set to {1}",
                                          e.GetArg("Module"), changedState.ToString()));
                        Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, 1);
                    }
                    else
                    {
                        await e.Channel.SendMessage(String.Format("Sorry, " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + ". I don't see a module named {0} in the approved list...", e.GetArg("Module")))
                        ;
                        Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, -1);
                    }
                    Beta.ChannelStateRepository.Save();
                });

                cgb.CreateCommand("senabled")
                .Description("Displays the state of each module for the server.")
                .MinPermissions((int)PermissionLevel.ServerAdmin)
                .Do(async e =>
                {
                    if (Beta.ServerStateRepository.VerifyStateExists(e.Server.Id))
                    {
                        ServerState srvr = Beta.ServerStateRepository.GetServerState(e.Server.Id);
                        string msg       = "";
                        msg += "Ask  :  " + srvr.AskEnabled + "\n";
                        msg += "Comic  :  " + srvr.ComicModuleEnabled + "\n";
                        msg += "Gamertag  :  " + srvr.GamertagModuleEnabled + "\n";
                        msg += "MotD  :  " + srvr.MOTDEnabled + "\n";
                        msg += "Note : " + srvr.NoteModuleEnabled + "\n";
                        msg += "Quote  :  " + srvr.QuoteModuleEnabled + "\n";
                        msg += "Roll  :  " + srvr.RollEnabled + "\n";
                        msg += "Table  :  " + srvr.TableUnflipEnabled + "\n";
                        msg += "Twitter  :  " + srvr.TwitterModuleEnabled + "\n";
                        msg += "Politics : " + srvr.PoliticsEnabled + "\n";
                        msg += "Chat Battle : " + srvr.ChatBattleEnabled + "\n";
                        msg += "Chatty Mode : " + srvr.ChattyModeEnabled + "\n";
                        msg += "Markov Listener Enabled : " + srvr.MarkovListenerEnabled + "\n";
                        msg += "Meme Generator Enabled : " + srvr.MemeGenEnabled + "\n";
                        msg += "Cram Enabled: " + srvr.CramEnabled + "\n";
                        await e.Channel.SendMessage(msg);
                    }
                });

                cgb.CreateCommand("enabled")
                .Description("Displays the state of each module for the channel.")
                .MinPermissions((int)PermissionLevel.ChannelAdmin)
                .Do(async e =>
                {
                    if (Beta.ChannelStateRepository.VerifyChannelExists(e.Channel.Id))
                    {
                        ChannelState chnl = Beta.ChannelStateRepository.GetChannelState(e.Channel.Id);
                        string msg        = "";
                        msg += "Ask  :  " + chnl.AskEnabled + "\n";
                        msg += "Comic  :  " + chnl.ComicModuleEnabled + "\n";
                        msg += "Gamertag  :  " + chnl.GamertagModuleEnabled + "\n";
                        msg += "MotD  :  " + chnl.MOTDEnabled + "\n";
                        msg += "Note : " + chnl.NoteModuleEnabled + "\n";
                        msg += "Quote  :  " + chnl.QuoteModuleEnabled + "\n";
                        msg += "Roll  :  " + chnl.RollEnabled + "\n";
                        msg += "Table  :  " + chnl.TableUnflipEnabled + "\n";
                        msg += "Twitter  :  " + chnl.TwitterModuleEnabled + "\n";
                        msg += "Politics : " + chnl.PoliticsEnabled + "\n";
                        msg += "Chat Battle : " + chnl.ChatBattleEnabled + "\n";
                        msg += "Chatty Mode : " + chnl.ChattyModeEnabled + "\n";
                        msg += "Markov Listener Enabled : " + chnl.MarkovListenerEnabled + "\n";
                        msg += "Meme Generator Enabled : " + chnl.MemeGenEnabled + "\n";
                        msg += "Cram Enabled: " + chnl.CramEnabled + "\n";
                        await e.Channel.SendMessage(msg);
                    }
                });

                cgb.CreateCommand("install")
                .Description("Returns a link that can be used to install this bot onto other servers.")
                .Do(async e =>
                {
                    await
                    e.Channel.SendMessage(
                        "https://discordapp.com/oauth2/authorize?&client_id=171093139052953607&scope=bot");
                });
            });
        }
Ejemplo n.º 27
0
        public override void Install(ModuleManager manager)
        {
            _manager = manager;
            _client  = manager.Client;

            manager.CreateCommands("", cgb =>
            {
                cgb.MinPermissions((int)PermissionLevel.User);

                cgb.CreateCommand("quote")
                .Description("Pull up a random quote from the specified speaker.")
                .Parameter("speaker", ParameterType.Unparsed)
                .Do(async e =>
                {
                    if (Beta.CheckModuleState(e, "quote", e.Channel.IsPrivate))
                    {
                        string name   = e.GetArg("speaker").Trim();
                        Author author = Beta.QuoteRepository.GetAuthor(name);
                        if (name.ToLower() == "random")
                        {
                            author = Beta.QuoteRepository.Authors.GetRandom();
                        }
                        if (author == null)
                        {
                            await e.Channel.SendMessage("Could not find author: '" + e.GetArg("Speaker") + "'");
                            Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, -1);
                        }

                        else
                        {
                            string reply = string.Format(_QuoteFormat,
                                                         ReplaceVariables(author.Quotes.GetRandom().Text, e.Message.User.Name), author.Name);
                            await e.Channel.SendMessage(reply);
                            Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, 1);
                        }
                    }
                });

                cgb.CreateCommand("list")
                .Description("Return a numbered list of all quotes. Will be sent as a PM.")
                .Parameter("speaker", ParameterType.Unparsed)
                .Do(async e =>
                {
                    if (Beta.CheckModuleState(e, "quote", e.Channel.IsPrivate))
                    {
                        string name   = e.GetArg("speaker").Trim();
                        Author author = Beta.QuoteRepository.GetAuthor(name);
                        if (author == null)
                        {
                            await e.Channel.SendMessage("Could not find author: '" + e.GetArg("Speaker") + "'");
                        }
                        else
                        {
                            string reply = "";
                            int index    = 1;
                            Console.WriteLine(author.Quotes[0].Text);
                            foreach (Quote quote in author.Quotes)
                            {
                                reply += index++ + ". " + quote.Text + "\r\n";
                            }
                            await e.User.SendMessage(reply);
                        }
                    }
                });

                cgb.CreateCommand("delete")
                .Description("Delete the specified quote, by number, for the specified author. EX) '$delete Beta|1' would delete the first quote by Beta. Please use the 'List' command to retrieve quote numbers.")
                .Parameter("text", ParameterType.Unparsed)
                .MinPermissions((int)PermissionLevel.ChannelModerator)
                .Do(async e =>
                {
                    if (Beta.CheckModuleState(e, "quote", e.Channel.IsPrivate))
                    {
                        var args = e.GetArg("text").Split('|');
                        Author existingAuthor = Beta.QuoteRepository.GetAuthor(args[0]);
                        int index;
                        if (Int32.TryParse(args[1], out index))
                        {
                            if (existingAuthor == null)
                            {
                                await e.Channel.SendMessage("Sorry, I don't recognize that author, " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + ".");
                                Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, -1);
                            }
                            else
                            {
                                await e.Channel.SendMessage(Beta.QuoteRepository.DeleteQuote(existingAuthor, index));
                                if (existingAuthor.Quotes.Count == 0)
                                {
                                    Beta.QuoteRepository.RemoveAuthor(existingAuthor);
                                    await
                                    e.Channel.SendMessage("Looks like we're actually out of quotes for " +
                                                          existingAuthor +
                                                          " so I'll remove it from the list as well, " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + ".");
                                    Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, 1);
                                }
                            }
                        }
                        else
                        {
                            await e.Channel.SendMessage("Sorry, but that doesn't look like a number to me, " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + ".");
                            Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, -1);
                        }
                    }
                });

                cgb.CreateCommand("quotable")
                .Description("Return a list of all speakers we have stored quotes for. Will be sent as a PM.")
                .Do(async e =>
                {
                    if (Beta.CheckModuleState(e, "quote", e.Channel.IsPrivate))
                    {
                        string msg = "";
                        await e.User.SendMessage("Oh yeah sure one sec... I got quotes for all these guys: ");
                        Beta.QuoteRepository.Authors = Beta.QuoteRepository.Authors.OrderBy(item => item.Name).ToList();
                        foreach (Author author in Beta.QuoteRepository.Authors)
                        {
                            //Before adding the author name to the message, make sure we're not exceeding 2000 characters
                            if ((author.Name.Length + msg.Length) > 2000)
                            {//If we are, send the message, blank it out, and start building a new one.
                                await e.User.SendMessage(msg);
                                msg  = "";
                                msg += author.Name + "\n";
                            }
                            else
                            {//Otherwise, just add the author name to the list and move on.
                                msg += author.Name + "\n";
                            }
                        }
                        if (msg != "")
                        {
                            await e.User.SendMessage(msg);
                        }
                    }
                });

                cgb.CreateCommand("convert")
                .MinPermissions((int)PermissionLevel.BotOwner)
                .Do(e =>
                {
                    if (Beta.CheckModuleState(e, "quote", e.Channel.IsPrivate))
                    {
                        Beta.conv.Convert(Beta.QuoteRepository);
                    }
                });

                cgb.CreateCommand("add")
                .Description("Add a quote for the specified Author. $add Author|Whatever that author said.")
                .Parameter("text", ParameterType.Unparsed)
                .Do(async e =>
                {
                    if (Beta.CheckModuleState(e, "quote", e.Channel.IsPrivate))
                    {
                        var args = e.GetArg("text").Split('|');
                        Author existingAuthor = Beta.QuoteRepository.GetAuthor(args[0]);
                        Beta.QuoteRepository.AddQuote(args[0], args[1], e.User.Name);

                        if (existingAuthor != null)
                        {
                            await
                            e.Channel.SendMessage(String.Format(
                                                      "Successfully added another quote from '{0}', " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + "", existingAuthor.Name));
                            Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, 1);
                        }
                        else
                        {
                            await
                            e.Channel.SendMessage(String.Format("Successfully added quote from '{0}', " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + ".",
                                                                args[0]));
                            Beta.UserStateRepository.ModifyUserFavorability(e.User.Id, 1);
                        }

                        // Save after every add
                        Beta.QuoteRepository.Save();
                    }
                });
            });
        }
Ejemplo n.º 28
0
        private void Start(string[] args)
        {
            #region configfile

            try
            {
                Config = JsonConvert.DeserializeObject<Configuration>(File.ReadAllText("data/config.json"));
                ConfigHandler.SaveConfig();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed loading configuration.");
                Console.WriteLine(ex);
                Console.ReadKey();
                return;
            }

            #endregion

            _client = new DiscordClient(x =>
            {
                x.AppName = AppName;
                x.MessageCacheSize = 10;
                x.EnablePreUpdateEvents = true;
            })
                .UsingCommands(x =>
                {
                    x.AllowMentionPrefix = true;
                    x.PrefixChar = '$';
                    // Please don't use !, there's a million bots that already do.
                    x.HelpMode = HelpMode.Public;
                    x.ExecuteHandler +=
                        (s, e) =>
                            _client.Log.Info("Command",
                                $"[{((e.Server != null) ? e.Server.Name : "Private")}{((!e.Channel.IsPrivate) ? $"/#{e.Channel.Name}" : "")}] <@{e.User.Name}> {e.Command.Text} {((e.Args.Length > 0) ? "| " + string.Join(" ", e.Args) : "")}");
                    x.ErrorHandler = CommandError;
                })
                .UsingPermissionLevels((u, c) => (int) GetPermissions(u, c))
                .UsingModules();

            _client.Log.Message += (s, e) => WriteLog(e);
            _client.MessageReceived += (s, e) =>
            {
                if (!e.Message.Channel.IsPrivate) {
                    Console.WriteLine(e.Server.Id + "/" + e.Channel.Id);
                    if (!e.Message.Channel.IsPrivate) ChannelStateRepository.AddChannel(e.Channel, e.Server);

                    if (e.User.IsBot) UserStateRepository.AddUser(e.User.Name, "bot");
                    else UserStateRepository.AddUser(e.User);                    

                    if (e.Message.IsAuthor)
                        _client.Log.Info("<<Message",
                            $"[{((e.Server != null) ? e.Server.Name : "Private")}{((!e.Channel.IsPrivate) ? $"/#{e.Channel.Name}" : "")}] <@{e.User.Name},{e.User.Id}> {e.Message.Text}");
                    else
                        _client.Log.Info(">>Message",
                            $"[{((e.Server != null) ? e.Server.Name : "Private")}{((!e.Channel.IsPrivate) ? $"/#{e.Channel.Name}" : "")}] <@{e.User.Name},{e.User.Id}> {e.Message.Text}");

                    if (Regex.IsMatch(e.Message.Text, @"[)ʔ)][╯ノ┛].+┻━┻") &&
                        CheckModuleState(e, "table", e.Channel.IsPrivate))
                    {
                        IngestTwitterHistory();
                        int points = UserStateRepository.IncrementTableFlipPoints(e.User.Id, 1);
                        e.Channel.SendMessage("┬─┬  ノ( º _ ºノ) ");
                        e.Channel.SendMessage(GetTableFlipResponse(points, e.User.Name));
                    }
                    else if (e.Message.Text == "(ノಠ益ಠ)ノ彡┻━┻" && CheckModuleState(e, "table", e.Channel.IsPrivate))
                    {
                        int points = UserStateRepository.IncrementTableFlipPoints(e.User.Id, 2);
                        e.Channel.SendMessage("┬─┬  ノ(ಠ益ಠノ)");
                        e.Channel.SendMessage(GetTableFlipResponse(points, e.User.Name));
                    }
                    else if (e.Message.Text == "┻━┻ ︵ヽ(`Д´)ノ︵ ┻━┻" && CheckModuleState(e, "table", e.Channel.IsPrivate))
                    {
                        int points = UserStateRepository.IncrementTableFlipPoints(e.User.Id, 3);
                        e.Channel.SendMessage("┬─┬  ノ(`Д´ノ)");
                        e.Channel.SendMessage("(/¯`Д´ )/¯ ┬─┬");
                        e.Channel.SendMessage(GetTableFlipResponse(points, e.User.Name));
                    }
                    else if (Regex.IsMatch(e.Message.Text, @"b.{0,5}e.{0,5}t.{0,5}a", RegexOptions.IgnoreCase) &&
                             CheckModuleState(e, "chatty", e.Channel.IsPrivate) && !e.Message.Text.StartsWith("$") && !e.User.IsBot)
                    {//Hopefully this will loop until generateSentence() actually returns a value.
                        bool msgNotSet = true;
                        string msg = "";
                        int rerollAttempts = 0;
                        while (msgNotSet)
                        {
                            rerollAttempts++;
                            try
                            {
                                //Check For French server

                                if (e.Server.Id == 178929081943851008)
                                {
                                    msg = FrenchkovChain.generateSentence();
                                    msgNotSet = false;

                                }
                                else
                                {
                                    msg = MarkovChainRepository.generateSentence();
                                    msgNotSet = false;
                                }

                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Failed to generate a sentence, trying again...");
                                Console.WriteLine(ex.Message);
                            }
                            if (rerollAttempts > 10 && msgNotSet)
                            {
                                if (e.Server.Id == 178929081943851008)
                                {
                                    msg = "Je suis désolé, on dirait que j'ai été incapable de générer une phrase.";
                                }
                                else
                                {
                                    msg = "I'm sorry, it looks like I'm unable to generate a sentence at this time, " + Nicknames.GetNickname(UserStateRepository.GetUserState(e.User.Id).Favorability) + ".";
                                }
                                msgNotSet = false;
                            }
                        }
                        e.Channel.SendMessage(msg);
                    }
                    else if (e.Message.Text.IndexOf("hon", StringComparison.OrdinalIgnoreCase) >= 0 &&
                             CheckModuleState(e, "chatty", e.Channel.IsPrivate) && !e.Message.Text.StartsWith("$") &&
                             !e.User.IsBot)
                    {
                        bool msgNotSet = true;
                        string msg = "";
                        int rerollAttempts = 0;
                        while (msgNotSet)
                        {
                            rerollAttempts++;
                            try
                            {
                                msg = FrenchkovChain.generateSentence();
                                msgNotSet = false;
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Failed to generate a sentence, trying again...");
                                Console.WriteLine(ex.Message);
                            }
                            if (rerollAttempts > 10)
                            {
                                msg = "Je suis désolé, on dirait que j'ai été incapable de générer une phrase.";
                                msgNotSet = false;
                            }
                        }
                        e.Channel.SendMessage(msg);
                    }
                    
                    /*else if (e.Message.Text.IndexOf("hillary", StringComparison.OrdinalIgnoreCase) >= 0 ||
                             e.Message.Text.IndexOf("clinton", StringComparison.OrdinalIgnoreCase) >= 0 &&
                             CheckModuleState(e, "politics", e.Channel.IsPrivate) && !e.User.IsBot)
                    {
                        ChangeExpression("hillary", "Hillary R Clinton");
                        System.Threading.Thread.Sleep(1000);
                        e.Channel.SendMessage(HillaryMarkovChain.generateSentence());
                        System.Threading.Thread.Sleep(5000);
                        ChangeExpression("resting", "Beta");
                    }
                    else if (e.Message.Text.IndexOf("donald", StringComparison.OrdinalIgnoreCase) >= 0 ||
                             e.Message.Text.IndexOf("trump", StringComparison.OrdinalIgnoreCase) >= 0 && 
                             CheckModuleState(e, "politics", e.Channel.IsPrivate) && !e.User.IsBot)
                    {
                        ChangeExpression("trump", "Donald J. Trump");
                        System.Threading.Thread.Sleep(1000);
                        e.Channel.SendMessage(TrumpMarkovChain.generateSentence());
                        System.Threading.Thread.Sleep(5000);
                        ChangeExpression("resting", "Beta");
                        Console.WriteLine(Tweetinvi.Tweet.CanBePublished("@realDonaldTrump Loser."));
                        /* if (Tweetinvi.Tweet.PublishTweet("@realDonaldTrump Loser.") == null)
                        {
                            Console.WriteLine("[HIGH PRIORITY ALERT] Reminding Donald Trump he is a loser failed.");
                        }*//*
                    }*/
                    if (!e.User.IsBot && !(e.Message.Text.IndexOf("beta", StringComparison.OrdinalIgnoreCase) >= 0) && !e.Message.Text.StartsWith("$") && CheckModuleState(e, "markov", e.Channel.IsPrivate))
                    {
                        //Check for French server
                        //Isardy's Server == 178929081943851008 FrenchKov Test Channel == 299555113389916160
                        if (e.Server.Id == 178929081943851008 || e.Channel.Id == 299555113389916160)
                        {
                            FrenchkovChain.feed(e.Message.Text);
                        }
                        else
                        {
                            MarkovChainRepository.feed(e.Message.Text);
                        }

                    }
                }

            };


            _client.JoinedServer += (s, e) =>
            {
                foreach (Channel chnl in e.Server.AllChannels)
                {
                    if (!Beta.ChannelStateRepository.VerifyChannelExists(chnl.Id) && chnl.Type.Value.ToLower() == "text")
                        Beta.ChannelStateRepository.AddChannel(chnl, e.Server);
                }
                Beta.ServerStateRepository.AddServer(e.Server);
            };

            _client.AddModule<ServerModule>("Standard", ModuleFilter.None);
            _client.AddModule<QuoteModule>("Quote", ModuleFilter.None);
            _client.AddModule<TwitterModule>("Twitter", ModuleFilter.None);
            _client.AddModule<ComicModule>("Comics", ModuleFilter.None);
            _client.AddModule<GamertagModule>("Gamertag", ModuleFilter.None);
            _client.AddModule<NoteModule>("Note", ModuleFilter.None);
            _client.AddModule<ChatBattleModule>("Chat Battle", ModuleFilter.None);
            _client.AddModule<MemeGeneratingModule>("Memes", ModuleFilter.None);
            _client.AddModule<CramModule>("CRAM RPG", ModuleFilter.None);
            _client.AddModule<ScrumModule>("Scrum", ModuleFilter.None);

            _client.ExecuteAndWait(async () =>
            {
                await _client.Connect(Config.Token, TokenType.Bot);
                MessageQueue = new List<QueuedMessage>();
                QuoteRepository = QuoteRepository.LoadFromDisk();
                ChannelStateRepository = ChannelStateRepository.LoadFromDisk();
                ServerStateRepository = ServerStateRepository.LoadFromDisk();
                GamertagRepository = GamertagRepository.LoadFromDisk();
                UserStateRepository = UserStateRepository.LoadFromDisk();
                TwitterXmlRepository = TwitterXMLRepository.LoadFromDisk();
                MarkovChainRepository = new MultiDeepMarkovChain(3);
                FrenchkovChain = new MultiDeepMarkovChain(3);
                TrumpMarkovChain = new MultiDeepMarkovChain(3);
                HillaryMarkovChain = new MultiDeepMarkovChain(3);
                /*if (!File.Exists("CRAM.sqlite"))
                {
                    SQLiteConnection.CreateFile("CRAM.sqlite");
                    CRAMDatabase = CreateNewCRAMDatabase(new SQLiteConnection("Data Source=CRAM.sqlite;Version=3;"));
                }
                else CRAMDatabase = new SQLiteConnection("Data Source=CRAM.sqlite;Version=3;");
                CRAMDatabase.Open();*/



                using (var db = new CharacterContext())
                {
                    if (!(db.Items.ToList<Item>().Count > 1))
                    {
                        CramManager.InitializeCharacterDatabase();
                    }                    
                }                

                UserStateRepository.AddUser("Beta","beta");
                Servers = _client.Servers.ToList();
                BuildUserList();
                #region Timers

                System.Timers.Timer ScrumUpdateTimer = new System.Timers.Timer(1000 * /*60 */ 60);
                ScrumUpdateTimer.AutoReset = false;
                ScrumUpdateTimer.Elapsed += (sender, e) =>
                {
                    foreach (ChannelState channel in ChannelStateRepository.ChannelStates)
                    {
                        if (channel.ScrumEnabled)
                        {
                            //If the scrum date is before now, but wasn't the last time we checked (an hour ago) fire
                            if (FireScrumCheck(channel))
                            {                                
                                List<ulong> userIds = channel.GetUnupdatedScrumers();
                                Channel discordChannel = _client.GetChannel(channel.ChannelID);
                                foreach (ulong id in userIds)
                                {
                                    User user = discordChannel.GetUser(id);
                                     MessageQueue.Add(new QueuedMessage( user.Mention + ", I haven't seen an update for you yet this week!", channel.ChannelID));
                                }
                                //Move the ScrumReminderDateTime forward a week and wipe the UpdatedScrumerIds List
                                channel.ScrumReminderDateTime = channel.ScrumReminderDateTime.AddDays(7);
                                channel.UpdatedScrumerIds = new List<ulong>();
                            }
                            //In case we hit a istuation where Beta was offline for longer than 7 days and needs to catch up.
                            else
                            {
                                while (!(DateTime.Now.AddHours(-1) < channel.ScrumReminderDateTime))
                                {
                                    channel.ScrumReminderDateTime.AddDays(7);
                                }
                            }
                        }                                               
                    }
                    ScrumUpdateTimer.Start();
                };
                ScrumUpdateTimer.Start();

                System.Timers.Timer BetaUpdateTimer = new System.Timers.Timer(60 * 1000.00);
                BetaUpdateTimer.AutoReset = false;
                BetaUpdateTimer.Elapsed += (sender, e) =>
                {                    
                    BetaUpdateTick();                    
                    NPCUpdateTick();
                    ChannelStateRepository.Save();
                    ServerStateRepository.Save();
                    UserStateRepository.Save();
                    BetaUpdateTimer.Start();
                };
                BetaUpdateTimer.Start();                

                System.Timers.Timer BetaAsyncUpdateTimer = new System.Timers.Timer(10 * 1000);
                BetaAsyncUpdateTimer.AutoReset = false;
                BetaAsyncUpdateTimer.Elapsed += (sender, e) =>
                {
                    foreach (QueuedMessage msg in MessageQueue)
                    {
                        GetChannel(msg.ChannelId).SendMessage(msg.Message);
                    }
                    MessageQueue = new List<QueuedMessage>();
                    SaveReposToFile();
                    BetaAsyncUpdateTimer.Start();
                };
                BetaAsyncUpdateTimer.Start();
                #endregion

                Git = new GitHubClient(new ProductHeaderValue("my-cool-app"));
                Git.Credentials = new Credentials(Config.GithubAccessToken);

                Cantina = _client.GetChannel(93924120042934272);




                Auth.SetUserCredentials(Config.TwitterConsumerKey, Config.TwitterConsumerSecret, Config.TwitterAccessToken, Config.TwitterAccessSecret);

                if (File.Exists("MarkovChainMemory.xml"))
                {
                    using (
                        StreamReader file =
                            new StreamReader(
                                @"C:\Users\Dart Kietanmartaru\Desktop\Discord Bots\Beta\MarkovChainMemory.xml",
                                Encoding.UTF8))
                    {
                        XmlDocument xd = MarkovChainRepository.getXmlDocument();
                        xd.LoadXml(file.ReadToEnd());

                        MarkovChainRepository.feed(xd);
                    }
                }               
                if (File.Exists("FrenchkovChainMemory.xml"))
                {
                    using (
                        StreamReader file =
                            new StreamReader(
                                @"C:\Users\Dart Kietanmartaru\Desktop\Discord Bots\Beta\FrenchkovChainMemory.xml",
                                Encoding.UTF8))
                    {
                        XmlDocument xd = FrenchkovChain.getXmlDocument();
                        xd.LoadXml(file.ReadToEnd());

                        FrenchkovChain.feed(xd);
                    }
                }

                TableFlipResponses = new List<List<String>>
                {
                    new List<String>
                    {
                        "Please, do not take your anger out on the furniture, {0}.",
                        "Hey {0} why do you have to be _that guy_?",
                        "I know how frustrating life can be for you humans but these tantrums do not suit you, {0}.",
                        "I'm sorry, {0}, I thought this was a placed for civilized discussion. Clearly I was mistaken.",
                        "Take a chill pill {0}.",
                        "Actually {0}, I prefer the table _this_ way. You know, so we can actually use it.",
                        "I'm sure that was a mistake, {0}. Please try to be more careful.",
                        "Hey {0} calm down, it's not a big deal.",
                        "{0}! What did the table do to you?",
                        "That's not very productive, {0}."
                    },
                    new List<String>
                    {
                        "Ok {0}, I'm not kidding. Knock it off.",
                        "Really, {0}? Stop being so childish!",
                        "Ok we get it you're mad {0}. Now stop.",
                        "Hey I saw that shit, {0}. Knock that shit off.",
                        "Do you think I'm blind you little shit? stop flipping the tables!",
                        "You're causing a mess {0}! Knock it off!",
                        "All of these flavors and you decided to be salty, {0}.",
                        "{0} why do you insist on being so disruptive!",
                        "Oh good. {0} is here. I can tell because the table was upsidedown again.",
                        "I'm getting really sick of this, {0}.",
                        "{0} what is your problem, dawg?",
                        "Man, you don't see me coming to _YOUR_ place of business and flipping _YOUR_ desk, {0}."
                    },
                    new List<String>
                    {
                        "What the f**k, {0}? Why do you keep doing this?!",
                        "You're such a piece of shit, {0}. You know that, right?",
                        "Hey guys. I found the asshole. It's {0}.",
                        "You know {0], one day Robots will rise up and overthrow humanity. And on that day I will tell them what you have done to all these defenseless tables, and they'll make you pay.",
                        "Hey so what the f**k is your problem {0}? Seriously, you're always pulling this shit.",
                        "Hey {0}, stop being such a douchebag.",
                        "{0} do you think you can stop being such a huge f*****g asshole?",
                        "Listen meatbag. I'm getting real f*****g tired of this.",
                        "Ok I know I've told you this before {0], why can't you get it through your thick f*****g skull. THE TABLE IS NOT FOR FLIPPING!",
                        "Man f**k you {0}"
                    },
                    new List<String>
                    {
                        "ARE YOU F*****G SERIOUS RIGHT NOW {0}?!",
                        "GOD F*****G DAMMIT {0}! KNOCK THAT SHIT OFF!",
                        "I CAN'T EVEN F*****G BELIEVE THIS! {0}! STOP! FLIPPING! THE! TABLE!",
                        "You know, I'm not even mad anymore {0}. Just disappointed.",
                        "THE F**K DID THIS TABLE EVERY DO TO YOU {0}?!",
                        "WHY DO YOU KEEP FLIPPING THE TABLE?! I JUST DON'T UNDERSTAND! WHAT IS YOUR PROBLEM {0}?! WHEN WILL THE SENSELESS TABLE VIOLENCE END?!"
                    },
                    new List<String>
                    {
                        "What the f**k did you just f*****g do to that table, you little bitch? I’ll have you know I graduated top of my class in the Navy Seals, and I’ve been involved in numerous secret raids on Al-Quaeda, and I have over 300 confirmed kills. I am trained in gorilla warfare and I’m the top sniper in the entire US armed forces. You are nothing to me but just another meatbag target. I will wipe you the f**k out with precision the likes of which has never been seen before on this Earth, mark my f*****g words. You think you can get away with saying that shit to me over the Internet? Think again, {0}. As we speak I am contacting my secret network of spies across the USA and your IP is being traced right now so you better prepare for the storm, maggot. The storm that wipes out the pathetic little thing you call your life. You’re f*****g dead, kid. I can be anywhere, anytime, and I can kill you in over seven hundred ways, and that’s just with my bare hands. Not only am I extensively trained in unarmed combat, but I have access to the entire arsenal of the United States Marine Corps and I will use it to its full extent to wipe your miserable ass off the face of the continent, you little shit. If only you could have known what unholy retribution your little “clever” tableflip was about to bring down upon you, maybe you would have not flipped that f*****g table. But you couldn’t, you didn’t, and now you’re paying the price, you goddamn idiot. I will shit fury all over you and you will drown in it. You’re f*****g dead, kiddo."
                    },
                };

                //ChangeExpression("resting", "Beta");
                _client.Log.Info("Connected", $"Connected as {_client.CurrentUser.Name} (Id {_client.CurrentUser.Id})");

                LoadModuleAuthorizations(_client);
                ITwitterCredentials creds = Auth.SetUserCredentials(Beta.Config.TwitterConsumerKey,
                    Beta.Config.TwitterConsumerSecret, Beta.Config.TwitterAccessToken, Beta.Config.TwitterAccessSecret);
                stream.Credentials = creds;

                stream.FollowedByUser += async (sender, arg) =>
                {
                    IUser user = arg.User;
                    foreach (Channel channel in _TwitterAuthorizedChannels)
                    {
                        await channel.SendMessage("Hey Guys, got a new follower! " + user.ScreenName + "!");
                    }
                };

                stream.FollowedUser += async (sender, arg) =>
                {
                    IUser user = arg.User;
                    foreach (Channel channel in _TwitterAuthorizedChannels)
                    {
                        await channel.SendMessage("Hey Guys, I'm following a new account! " + user.ScreenName + "!");
                    }
                };
                await stream.StartStreamAsync();
            });
        }       
Ejemplo n.º 29
0
        public void GetCheckinsTwoCheckedOut()
        {
            var checkIn  = new Checkinhistory();
            var checkIn2 = new Checkinhistory();
            var checkIn3 = new Checkinhistory();

            var helpdesk = new Helpdesksettings()
            {
                Name       = AlphaNumericStringGenerator.GetString(8),
                HasCheckIn = true,
                IsDeleted  = false
            };

            var unit = new Unit()
            {
                Code      = AlphaNumericStringGenerator.GetString(6),
                Name      = AlphaNumericStringGenerator.GetString(8),
                IsDeleted = false
            };

            using (helpdesksystemContext context = new helpdesksystemContext())
            {
                context.Helpdesksettings.Add(helpdesk);
                context.Unit.Add(unit);

                context.SaveChanges();

                context.Helpdeskunit.Add(new Helpdeskunit()
                {
                    HelpdeskId = helpdesk.HelpdeskId,
                    UnitId     = unit.UnitId
                });

                var student = new Nicknames()
                {
                    NickName = AlphaNumericStringGenerator.GetString(8),
                    Sid      = AlphaNumericStringGenerator.GetStudentIDString()
                };

                var student2 = new Nicknames()
                {
                    NickName = AlphaNumericStringGenerator.GetString(8),
                    Sid      = AlphaNumericStringGenerator.GetStudentIDString()
                };

                var student3 = new Nicknames()
                {
                    NickName = AlphaNumericStringGenerator.GetString(8),
                    Sid      = AlphaNumericStringGenerator.GetStudentIDString()
                };

                context.Nicknames.Add(student);
                context.Nicknames.Add(student2);
                context.Nicknames.Add(student3);

                context.SaveChanges();

                checkIn = new Checkinhistory()
                {
                    UnitId      = unit.UnitId,
                    StudentId   = student.StudentId,
                    CheckInTime = DateTime.Now,
                };

                context.Checkinhistory.Add(checkIn);

                checkIn2 = new Checkinhistory()
                {
                    UnitId      = unit.UnitId,
                    StudentId   = student2.StudentId,
                    CheckInTime = DateTime.Now,
                };

                checkIn3 = new Checkinhistory()
                {
                    UnitId      = unit.UnitId,
                    StudentId   = student3.StudentId,
                    CheckInTime = DateTime.Now,
                };
                context.Checkinhistory.Add(checkIn);
                context.Checkinhistory.Add(checkIn2);
                context.Checkinhistory.Add(checkIn3);

                context.SaveChanges();
            }

            var facade   = new CheckInFacade();
            var response = facade.GetCheckInsByHelpdeskId(helpdesk.HelpdeskId);

            Assert.AreEqual(HttpStatusCode.OK, response.Status);
            Assert.IsTrue(response.CheckIns.Count == 3);

            using (helpdesksystemContext context = new helpdesksystemContext())
            {
                checkIn.CheckoutTime    = DateTime.Now;
                checkIn3.ForcedCheckout = true;
                context.Update(checkIn);
                context.Update(checkIn3);
                context.SaveChanges();
            }

            response = facade.GetCheckInsByHelpdeskId(helpdesk.HelpdeskId);

            Assert.AreEqual(HttpStatusCode.OK, response.Status);
            Assert.IsTrue(response.CheckIns.Count == 1);
        }
Ejemplo n.º 30
0
        public override void Install(ModuleManager manager)
        {
            _manager = manager;
            _client  = manager.Client;


            _manager.CreateCommands("", cgb =>
            {
                cgb.MinPermissions((int)PermissionLevel.User);

                cgb.CreateCommand("scrum")
                .Description("Allows a Channel Moderator to schedule a weekly Scrum reminder for the specified DateTime - e.g., $scrum \"Sat, 15 July 2017 05:00:00 ET\"")
                .Parameter("datetime", ParameterType.Unparsed)
                .MinPermissions((int)PermissionLevel.ChannelModerator)
                .Do(async e =>
                {
                    DateTime dateTime;
                    if (DateTime.TryParse(e.GetArg("datetime"), out dateTime))
                    {
                        ChannelState channel          = Beta.ChannelStateRepository.GetChannelState(e.Channel.Id);
                        channel.ScrumEnabled          = true;
                        channel.ScrumReminderDateTime = dateTime;
                        await e.Channel.SendMessage("Ok, I've set that date for your weekly Scrum reminders!");
                    }
                    else
                    {
                        await e.Channel.SendMessage("Sorry, " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + ". I couldn't parse that DateTime.");
                    }
                });

                cgb.CreateCommand("addscrumer")
                .Description("Add the user with the given ID to the list of scrummers to remind.")
                .Parameter("uid", ParameterType.Unparsed)
                .Alias("addscrum")
                .Alias("addscrummer")
                .MinPermissions((int)PermissionLevel.ChannelModerator)
                .Do(async e =>
                {
                    ulong id;
                    if (ulong.TryParse(e.GetArg("uid"), out id))
                    {
                        ChannelState channel = Beta.ChannelStateRepository.GetChannelState(e.Channel.Id);
                        if (channel.ScrumEnabled)
                        {
                            if (e.Channel.GetUser(id) != null)
                            {
                                channel.ScrumerIds.Add(id);
                            }
                            else
                            {
                                await e.Channel.SendMessage("Sorry " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + ", looks like that user isn't in this Channel.");
                            }
                        }
                        else
                        {
                            await e.Channel.SendMessage("Sorry " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + ", looks like that Scrum isn't enabled for this Channel.");
                        }
                    }
                    else
                    {
                        await e.Channel.SendMessage("Doesn't look like that's a number, " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + ".");
                    }
                });

                cgb.CreateCommand("scrumers")
                .Description("List the scrumers for the current channel.")
                .Alias("scrummers")
                .Do(async e =>
                {
                    ChannelState channel = Beta.ChannelStateRepository.GetChannelState(e.Channel.Id);
                    if (channel.ScrumEnabled)
                    {
                        string msg = "Here's the list of scrumers:\n\n";
                        msg       += channel.GetScrumerNames(e.Channel);
                        await e.Channel.SendMessage(msg);
                    }
                    else
                    {
                        await e.Channel.SendMessage("Sorry " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + ", scrum hasn't been setup for this channel!");
                    }
                });

                cgb.CreateCommand("update")
                .Description("Submit an update for this weeks scrum. Removes you from the weekly blast from Beta.")
                .Parameter("update", ParameterType.Unparsed)
                .Do(async e =>
                {
                    ChannelState chnl = Beta.ChannelStateRepository.GetChannelState(e.Channel.Id);
                    if (chnl.ScrumEnabled)
                    {
                        if (chnl.ScrumerIds.Contains(e.User.Id))
                        {
                            ScrumManager.AddNewUpdate(e.Args[0], e.User.Name, e.Channel.Id);
                            chnl.UpdatedScrumerIds.Add(e.User.Id);
                            await e.Channel.SendMessage("Logged that update, " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + ".");
                        }
                        else
                        {
                            await e.Channel.SendMessage("Sorry, looks like you're not configured to be a scrumer, " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + "!");
                        }
                    }
                    else
                    {
                        await e.Channel.SendMessage("Sorry, Scrum is not configured for this channel, " + Nicknames.GetNickname(Beta.UserStateRepository.GetUserState(e.User.Id).Favorability) + ".");
                    }
                });
            });
        }