public List <Command> Init(IValkyrjaClient iClient)
        {
            this.Client = iClient as ValkyrjaClient <Config>;
            List <Command> commands = new List <Command>();

// !exampleCommand
            Command newCommand = new Command("exampleCommand");

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "This is an example command.";
            newCommand.ManPage             = new ManPage("<arg1> [arg2]", "`<arg1>` - Something.\n\n`[arg2]` - Optional something else.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                await e.SendReplySafe("Boo!");
            };
            commands.Add(newCommand);

            return(commands);
        }
Exemplo n.º 2
0
        public async Task RunAndWait(int shardIdOverride = -1)
        {
            while (true)
            {
                this.Bot = new ValkyrjaClient(shardIdOverride);
                InitModules();

                try
                {
                    await this.Bot.Connect();

                    this.Bot.Events.Initialize += InitCommands;
                    await Task.Delay(-1);
                }
                catch (Exception e)
                {
                    await this.Bot.LogException(e, "--ValkyrjaClient crashed.");

                    this.Bot.Dispose();
                }
            }
        }
Exemplo n.º 3
0
        public Events(DiscordSocketClient discordClient, ValkyrjaClient valkyrjaClient)
        {
            this.Client = valkyrjaClient;

            discordClient.Log += OnLogEntryAdded;

            discordClient.JoinedGuild            += OnGuildJoined;
            discordClient.LeftGuild              += OnGuildLeft;
            discordClient.GuildAvailable         += OnGuildAvailable;
            discordClient.GuildUnavailable       += OnGuildUnavailable;
            discordClient.GuildUpdated           += OnGuildUpdated;
            discordClient.GuildMembersDownloaded += OnGuildMembersDownloaded;
            discordClient.GuildMemberUpdated     += OnGuildMemberUpdated;

            discordClient.RoleCreated += OnRoleCreated;
            discordClient.RoleUpdated += OnRoleUpdated;
            discordClient.RoleDeleted += OnRoleDeleted;

            discordClient.ChannelCreated   += OnChannelCreated;
            discordClient.ChannelUpdated   += OnChannelUpdated;
            discordClient.ChannelDestroyed += OnChannelDestroyed;

            discordClient.MessageReceived += OnMessageReceived;
            discordClient.MessageUpdated  += OnMessageUpdated;
            discordClient.MessageDeleted  += OnMessageDeleted;

            discordClient.ReactionAdded    += OnReactionAdded;
            discordClient.ReactionRemoved  += OnReactionRemoved;
            discordClient.ReactionsCleared += OnReactionsCleared;

            discordClient.UserJoined            += OnUserJoined;
            discordClient.UserLeft              += OnUserLeft;
            discordClient.UserIsTyping          += OnUserTyping;
            discordClient.UserUpdated           += OnUserUpdated;
            discordClient.UserVoiceStateUpdated += OnUserVoiceStateUpdated;
            discordClient.UserBanned            += OnUserBanned;
            discordClient.UserUnbanned          += OnUserUnbanned;
        }
Exemplo n.º 4
0
        public List <Command> Init(IValkyrjaClient iClient)
        {
            this.Client = iClient as ValkyrjaClient;
            List <Command> commands = new List <Command>();

            this.Client.Events.MessageReceived += OnMessageReceived;

// !cookies
            Command newCommand = new Command("cookies");

            newCommand.Type        = CommandType.Standard;
            newCommand.Description = "Check how many cookies you've got.";
            newCommand.ManPage     = new ManPage("", "");
            newCommand.IsPremiumServerwideCommand = true;
            newCommand.RequiredPermissions        = PermissionType.Everyone;
            newCommand.OnExecute += async e => {
                if (!e.Server.Config.KarmaEnabled)
                {
                    await e.SendReplySafe(KarmaDisabledString);

                    return;
                }

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                UserData      userData  = dbContext.GetOrAddUser(e.Server.Id, e.Message.Author.Id);

                int    articleIndex = e.Server.Config.KarmaCurrencySingular[0] == ':' ? 1 : 0;
                string article      = e.Server.Config.KarmaCurrencySingular[articleIndex] == 'a' ? "an" : "a";
                await e.SendReplySafe(string.Format("Hai **{0}**, you have {1} {2}!\nYou can {4} one with the `{3}{4}` command, or you can give {5} {6} to your friend using `{3}give @friend`",
                                                    e.Message.Author.GetNickname(), userData.KarmaCount,
                                                    (userData.KarmaCount == 1 ? e.Server.Config.KarmaCurrencySingular : e.Server.Config.KarmaCurrency),
                                                    e.Server.Config.CommandPrefix, e.Server.Config.KarmaConsumeCommand,
                                                    article, e.Server.Config.KarmaCurrencySingular));

                dbContext.Dispose();
            };
            commands.Add(newCommand);

// !nom
            newCommand             = new Command("nom");
            newCommand.Type        = CommandType.Standard;
            newCommand.Description = "Eat one of your cookies!";
            newCommand.ManPage     = new ManPage("", "");
            newCommand.IsPremiumServerwideCommand = true;
            newCommand.RequiredPermissions        = PermissionType.Everyone;
            newCommand.OnExecute += async e => {
                if (!e.Server.Config.KarmaEnabled)
                {
                    await e.SendReplySafe(KarmaDisabledString);

                    return;
                }

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                UserData      userData  = dbContext.GetOrAddUser(e.Server.Id, e.Message.Author.Id);

                if (userData.KarmaCount <= 0)
                {
                    await e.SendReplySafe(string.Format("Umm... I'm sorry **{0}** you don't have any {1} left =(",
                                                        e.Message.Author.GetNickname(), e.Server.Config.KarmaCurrency));

                    dbContext.Dispose();
                    return;
                }

                userData.KarmaCount -= 1;
                dbContext.SaveChanges();

                await e.SendReplySafe(string.Format("**{0}** just {1} one of {2} {3}! {4} {5} left.",
                                                    e.Message.Author.GetNickname(), e.Server.Config.KarmaConsumeVerb,
                                                    (this.Client.IsGlobalAdmin(e.Message.Author.Id) ? "her" : "their"), e.Server.Config.KarmaCurrency,
                                                    (this.Client.IsGlobalAdmin(e.Message.Author.Id) ? "She has" : "They have"), userData.KarmaCount));// Because i can :P

                dbContext.Dispose();
            };
            commands.Add(newCommand);

// !give
            newCommand             = new Command("give");
            newCommand.Type        = CommandType.Standard;
            newCommand.Description = "Give one of your cookies to a friend =]";
            newCommand.ManPage     = new ManPage("<@user>", "`<@user>` - User mention of a user to receive a cookie.");
            newCommand.IsPremiumServerwideCommand = true;
            newCommand.RequiredPermissions        = PermissionType.Everyone;
            newCommand.OnExecute += async e => {
                if (!e.Server.Config.KarmaEnabled)
                {
                    await e.SendReplySafe(KarmaDisabledString);

                    return;
                }

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                UserData      userData  = dbContext.GetOrAddUser(e.Server.Id, e.Message.Author.Id);
                if (userData.KarmaCount == 0)
                {
                    await e.SendReplySafe($"Umm... I'm sorry **{e.Message.Author.GetNickname()}**, you don't have any {e.Server.Config.KarmaCurrency} left =(");

                    dbContext.Dispose();
                    return;
                }

                if (e.Message.MentionedUsers == null || !e.Message.MentionedUsers.Any() || e.Message.MentionedUsers.Count() > e.Server.Config.KarmaLimitMentions)
                {
                    await e.SendReplySafe($"You have to @mention your friend who will receive the {e.Server.Config.KarmaCurrencySingular}. You can mention up to {e.Server.Config.KarmaLimitMentions} people at the same time.");

                    dbContext.Dispose();
                    return;
                }

                int             count     = 0;
                StringBuilder   userNames = new StringBuilder();
                List <UserData> users     = this.Client.GetMentionedUsersData(dbContext, e);

                foreach (UserData mentionedUser in users)
                {
                    if (userData.KarmaCount == 0)
                    {
                        break;
                    }

                    userData.KarmaCount--;
                    mentionedUser.KarmaCount++;

                    userNames.Append((count++ == 0 ? "" : count == users.Count ? ", and " : ", ") + (e.Server.Guild.GetUser(mentionedUser.UserId)?.GetNickname() ?? "nobody"));
                }

                if (count > 0)
                {
                    dbContext.SaveChanges();
                }

                int    articleIndex = e.Server.Config.KarmaCurrencySingular[0] == ':' ? 1 : 0;
                string article      = e.Server.Config.KarmaCurrencySingular[articleIndex] == 'a' ? "an" : "a";
                string response     = $"**{userNames}** received {article} {e.Server.Config.KarmaCurrencySingular} of friendship from **{e.Message.Author.GetNickname()}** =]";
                if (count < users.Count)
                {
                    response += "\nBut I couldn't give out more, as you don't have any left =(";
                }

                dbContext.Dispose();
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);


            return(commands);
        }
Exemplo n.º 5
0
        public List <Command> Init(IValkyrjaClient iClient)
        {
            this.Client = iClient as ValkyrjaClient;
            List <Command> commands = new List <Command>();

// !memo
            Command newCommand = new Command("memo");

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Display your (or other) memo.";
            newCommand.ManPage             = new ManPage("[@user]", "`[@user]` - Optional username or mention to display memo of someone else.");
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Config.MemoEnabled)
                {
                    await e.SendReplySafe("Memo is disabled on this server.");

                    return;
                }

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                string        response  = "";

                if (!string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    string     expression = e.TrimmedMessage.ToLower();
                    SocketUser user       = e.Message.MentionedUsers.FirstOrDefault();
                    if (user == null)
                    {
                        user = e.Server.Guild.Users.FirstOrDefault(u => (u?.Username != null && u.Username.ToLower() == expression) || (u?.Nickname != null && u.Nickname.ToLower() == expression));
                    }

                    if (user == null)
                    {
                        response = NotFoundString;
                    }
                    else
                    {
                        UserData userData = dbContext.GetOrAddUser(e.Server.Id, user.Id);
                        if (string.IsNullOrEmpty(userData.Memo))
                        {
                            response = string.Format(NoMemoOtherString, user.GetNickname(), e.CommandId);
                        }
                        else
                        {
                            response = string.Format(MemoOtherString, user.GetNickname(), e.CommandId, userData.Memo);
                        }
                    }
                }
                else
                {
                    UserData userData = dbContext.GetOrAddUser(e.Server.Id, e.Message.Author.Id);
                    if (string.IsNullOrEmpty(userData.Memo))
                    {
                        response = string.Format(NoMemoString, e.CommandId);
                    }
                    else
                    {
                        response = string.Format(MemoString, e.CommandId, userData.Memo);
                    }
                }

                dbContext.Dispose();
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);

// !setMemo
            newCommand                     = new Command("setMemo");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Set your memo.";
            newCommand.ManPage             = new ManPage("<memo text>", "`<memo text>` - Text to be recorded as your memo.");
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Config.MemoEnabled)
                {
                    await e.SendReplySafe("Memo is disabled on this server.");

                    return;
                }

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                string        response  = "";

                UserData userData = dbContext.GetOrAddUser(e.Server.Id, e.Message.Author.Id);
                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    userData.Memo = "";
                    response      = ClearedString;
                }
                else
                {
                    userData.Memo = e.TrimmedMessage;
                    response      = string.Format(SetString, userData.Memo);
                }

                dbContext.SaveChanges();
                dbContext.Dispose();
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);

// !profile
            newCommand                     = new Command("profile");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Display your (or other) profile. Get Help: setProfile --help";
            newCommand.ManPage             = new ManPage("[@user]", "`[@user]` - Optional username or mention to display profile of someone else.");
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                if (!this.Client.IsPremium(e.Server) && !this.Client.IsTrialServer(e.Server.Id))
                {
                    await e.SendReplySafe("User profiles are a subscriber-only feature.");

                    return;
                }

                if (!e.Server.Config.ProfileEnabled)
                {
                    await e.SendReplySafe("User profiles are disabled on this server.");

                    return;
                }

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);

                if (!string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    string     expression = e.TrimmedMessage.ToLower();
                    SocketUser user       = e.Message.MentionedUsers.FirstOrDefault();
                    if (user == null)
                    {
                        user = e.Server.Guild.Users.FirstOrDefault(u => (u?.Username != null && u.Username == e.TrimmedMessage) || (u?.Nickname != null && u.Nickname == e.TrimmedMessage));
                    }
                    if (user == null)
                    {
                        user = e.Server.Guild.Users.FirstOrDefault(u => (u?.Username != null && u.Username.ToLower() == expression) || (u?.Nickname != null && u.Nickname.ToLower() == expression));
                    }
                    if (user == null)
                    {
                        user = e.Server.Guild.Users.FirstOrDefault(u => (u?.Username != null && u.Username.ToLower().Contains(expression)) || (u?.Nickname != null && u.Nickname.ToLower().Contains(expression)));
                    }

                    if (user == null)
                    {
                        await e.SendReplySafe(NotFoundString);
                    }
                    else if (user.Id == this.Client.DiscordClient.CurrentUser.Id)
                    {
                        await e.SendReplySafe(null, embed : GetValkyrjaEmbed(user as SocketGuildUser));
                    }
                    else
                    {
                        await e.SendReplySafe(null, embed : GetProfileEmbed(dbContext, e.Server, user as SocketGuildUser));
                    }
                }
                else
                {
                    await e.SendReplySafe(null, embed : GetProfileEmbed(dbContext, e.Server, e.Message.Author as SocketGuildUser));
                }

                dbContext.Dispose();
            };
            commands.Add(newCommand);

// !sendProfile
            newCommand                     = new Command("sendProfile");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Send your profile to preconfigured introduction channel. Get Help: setProfile --help";
            newCommand.ManPage             = new ManPage("", "");
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                if (!this.Client.IsPremium(e.Server) && !this.Client.IsTrialServer(e.Server.Id))
                {
                    await e.SendReplySafe("User profiles are a subscriber-only feature.");

                    return;
                }

                IMessageChannel channel = null;
                if (!e.Server.Config.ProfileEnabled || e.Server.Config.ProfileChannelId == 0 || (channel = e.Server.Guild.GetTextChannel(e.Server.Config.ProfileChannelId)) == null)
                {
                    await e.SendReplySafe("User profiles do not have a channel configured.");

                    return;
                }

                List <IMessage> messages = new List <IMessage>();
                await foreach (IReadOnlyCollection <IMessage> list in channel.GetMessagesAsync(0, Direction.After, 1000, CacheMode.AllowDownload))
                {
                    IMessage message = list.FirstOrDefault(m => guid.TryParse(this.UserIdRegex.Match(m.Content).Value, out guid id) && id == e.Message.Author.Id);
                    if (message != null)
                    {
                        await message.DeleteAsync();
                    }
                }

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);

                await channel.SendMessageAsync($"<@{e.Message.Author.Id}>'s introduction:", embed : GetProfileEmbed(dbContext, e.Server, e.Message.Author as SocketGuildUser));

                await e.SendReplySafe("It haz been done.");

                dbContext.Dispose();
            };
            commands.Add(newCommand);

// !getProfile
            newCommand                     = new Command("getProfile");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Get the source used to set your profile.";
            newCommand.ManPage             = new ManPage("", "");
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                if (!this.Client.IsPremium(e.Server) && !this.Client.IsTrialServer(e.Server.Id))
                {
                    await e.SendReplySafe("User profiles are a subscriber-only feature.");

                    return;
                }

                if (!e.Server.Config.ProfileEnabled)
                {
                    await e.SendReplySafe("User profiles are disabled on this server.");

                    return;
                }

                StringBuilder response              = new StringBuilder();
                ServerContext dbContext             = ServerContext.Create(this.Client.DbConnectionString);
                IEnumerable <ProfileOption> options = dbContext.ProfileOptions.AsQueryable().Where(o => o.ServerId == e.Server.Id).AsEnumerable().OrderBy(o => o.Order);
                foreach (ProfileOption option in options)
                {
                    UserProfileOption userOption = dbContext.UserProfileOptions.AsQueryable().FirstOrDefault(o => o.ServerId == e.Server.Id && o.UserId == e.Message.Author.Id && o.Option == option.Option);
                    if (userOption == null || string.IsNullOrWhiteSpace(userOption.Value))
                    {
                        continue;
                    }

                    response.Append($"{userOption.Option} {userOption.Value} ");
                }
                response.Append("\n```");

                string responseString = "There ain't no profile to get! >_<";
                if (response.Length > 0)
                {
                    responseString = $"```\n{e.Server.Config.CommandPrefix}setProfile {response.ToString()}";
                }
                await e.SendReplySafe(responseString);

                dbContext.Dispose();
            };
            commands.Add(newCommand);

// !setProfile
            newCommand                     = new Command("setProfile");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Set your profile.";
            newCommand.ManPage             = new ManPage("[--help]", "`[--help]` - Display options configured for this server.");
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                if (!this.Client.IsPremium(e.Server) && !this.Client.IsTrialServer(e.Server.Id))
                {
                    await e.SendReplySafe("User profiles are a subscriber-only feature.");

                    return;
                }

                if (!e.Server.Config.ProfileEnabled)
                {
                    await e.SendReplySafe("User profiles are disabled on this server.");

                    return;
                }

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                StringBuilder response  = new StringBuilder();

                IEnumerable <ProfileOption> options = dbContext.ProfileOptions.AsQueryable().Where(o => o.ServerId == e.Server.Id).AsEnumerable().OrderBy(o => o.Order);
                int maxOptionLength = 0;
                foreach (ProfileOption option in options)
                {
                    if (maxOptionLength < option.OptionAlt.Length)
                    {
                        maxOptionLength = option.OptionAlt.Length;
                    }
                }

                MatchCollection emptyOptions = this.ProfileEmptyOptionRegex.Matches(e.TrimmedMessage);

                if (string.IsNullOrEmpty(e.TrimmedMessage) || (emptyOptions.Count > 0 && emptyOptions.Cast <Match>().Any(o => o.Value == "-h" || o.Value == "--help")))
                {
                    response.AppendLine("```md\nSet your profile fields with the following parameters:");
                    foreach (ProfileOption o in options)
                    {
                        response.Append($"  [ {o.Option} ][ {o.OptionAlt}");
                        response.Append(' ', maxOptionLength - o.OptionAlt.Length);
                        response.AppendLine($" ] | {o.Label}");
                    }

                    response.AppendLine($"\nExample:\n  {e.Server.Config.CommandPrefix}{e.CommandId} --twitter @RheaAyase -y youtube.com/RheaAyase");
                    response.AppendLine($"\nTo null one of the options you have already set, leave it empty:\n  {e.Server.Config.CommandPrefix}{e.CommandId} --twitter -y\n```");
                    dbContext.Dispose();
                    await e.SendReplySafe(response.ToString());

                    return;
                }

                foreach (Match match in emptyOptions)
                {
                    ProfileOption option = options.FirstOrDefault(o => o.Option == match.Value || o.OptionAlt == match.Value);
                    if (option == null)
                    {
                        continue;
                    }
                    UserProfileOption userOption = dbContext.UserProfileOptions.AsQueryable().FirstOrDefault(o => o.ServerId == e.Server.Id && o.UserId == e.Message.Author.Id && o.Option == option.Option);
                    if (userOption == null)
                    {
                        continue;
                    }

                    dbContext.UserProfileOptions.Remove(userOption);
                }

                MatchCollection matches = this.ProfileParamRegex.Matches(e.TrimmedMessage);
                foreach (Match match in matches)
                {
                    string optionString = this.ProfileOptionRegex.Match(match.Value).Value;
                    string value        = match.Value.Substring(optionString.Length + 1).Replace('`', '\'');
                    if (value.Length >= UserProfileOption.ValueCharacterLimit)
                    {
                        await e.SendReplySafe($"`{optionString}` is too long! (It's {value.Length} characters while the limit is {UserProfileOption.ValueCharacterLimit})");

                        dbContext.Dispose();
                        return;
                    }

                    ProfileOption option = options.FirstOrDefault(o => o.Option == optionString || o.OptionAlt == optionString);
                    if (option == null)
                    {
                        await e.SendReplySafe($"Unknown option: `{optionString}`");

                        dbContext.Dispose();
                        return;
                    }

                    UserProfileOption userOption = dbContext.UserProfileOptions.AsQueryable().FirstOrDefault(o => o.ServerId == e.Server.Id && o.UserId == e.Message.Author.Id && o.Option == option.Option);
                    if (userOption == null)
                    {
                        userOption = new UserProfileOption()
                        {
                            ServerId = e.Server.Id,
                            UserId   = e.Message.Author.Id,
                            Option   = option.Option
                        };
                        dbContext.UserProfileOptions.Add(userOption);
                    }

                    userOption.Value = value;
                }

                dbContext.SaveChanges();

                await e.Channel.SendMessageAsync("", embed : GetProfileEmbed(dbContext, e.Server, e.Message.Author as SocketGuildUser));

                dbContext.Dispose();
            };
            commands.Add(newCommand);

            return(commands);
        }
Exemplo n.º 6
0
        public List <Command> Init(IValkyrjaClient iClient)
        {
            this.Client = iClient as ValkyrjaClient;
            List <Command> commands = new List <Command>();

            this.Client.Events.MessageReceived += OnMessageReceived;

// !lvl
            Command newCommand = new Command("lvl");

            newCommand.Type        = CommandType.Standard;
            newCommand.Description = "Find out what's your level!";
            newCommand.ManPage     = new ManPage("", "");
            newCommand.IsPremiumServerwideCommand = true;
            newCommand.RequiredPermissions        = PermissionType.Everyone;
            newCommand.OnExecute += async e => {
                if (!e.Server.Config.ExpEnabled)
                {
                    await e.SendReplySafe(ExpDisabledString);

                    return;
                }

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                UserData      userData  = dbContext.GetOrAddUser(e.Server.Id, e.Message.Author.Id);

                string response = string.Format(LevelNullString, userData.Level);

                SocketRole role = null;
                if (userData.Level > 0 &&
                    (role = e.Server.Roles.Values.Where(r => r.ExpLevel == userData.Level)
                            .Select(r => e.Server.Guild.GetRole(r.RoleId)).FirstOrDefault()) != null)
                {
                    response = string.Format(LevelString, role.Name, userData.Level);
                }

                Int64 expAtLevel = GetTotalExpAtLevel(e.Server.Config.BaseExpToLevelup, userData.Level + 1);
                Int64 expToLevel = expAtLevel - userData.Exp;

                if (e.Server.Config.ExpPerMessage != 0 && e.Server.Config.ExpPerAttachment != 0)
                {
                    response += string.Format(ThingsToLevel, expToLevel / e.Server.Config.ExpPerMessage, expToLevel / e.Server.Config.ExpPerAttachment);
                }
                else if (e.Server.Config.ExpPerMessage != 0)
                {
                    response += string.Format(MessagesToLevel, expToLevel / e.Server.Config.ExpPerMessage);
                }
                else if (e.Server.Config.ExpPerAttachment != 0)
                {
                    response += string.Format(ImagesToLevel, expToLevel / e.Server.Config.ExpPerAttachment);
                }

                await e.SendReplySafe(response);

                dbContext.Dispose();
            };
            commands.Add(newCommand);

// !lockExp
            newCommand             = new Command("lockExp");
            newCommand.Type        = CommandType.Standard;
            newCommand.Description = "Locks, or unlocks, someones experience and therefore also activity role assignment.";
            newCommand.ManPage     = new ManPage("<@user>", "`<@user>` - User mentions or IDs who to lock out of the experience system.");
            newCommand.IsPremiumServerwideCommand = true;
            newCommand.RequiredPermissions        = PermissionType.ServerOwner | PermissionType.Admin | PermissionType.Moderator | PermissionType.SubModerator;
            newCommand.OnExecute += async e => {
                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    await e.SendReplySafe("A who?");

                    return;
                }

                ServerContext   dbContext         = ServerContext.Create(this.Client.DbConnectionString);
                List <UserData> mentionedUserData = this.Client.GetMentionedUsersData(dbContext, e);
                if (!mentionedUserData.Any())
                {
                    dbContext.Dispose();
                    await e.SendReplySafe("A who?");

                    return;
                }
                foreach (UserData userData in mentionedUserData)
                {
                    userData.ExpLocked = !userData.ExpLocked;
                }

                string response = "";
                if (mentionedUserData.Any(u => u.ExpLocked))
                {
                    response += "I've locked " + mentionedUserData.Where(u => u.ExpLocked).Select(u => $"<@{u.UserId}>").ToNames("", "");
                }
                if (mentionedUserData.Any(u => !u.ExpLocked))
                {
                    response += "I've unlocked " + mentionedUserData.Where(u => !u.ExpLocked).Select(u => $"<@{u.UserId}>").ToNames("", "");
                }

                dbContext.SaveChanges();
                dbContext.Dispose();

                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);


            return(commands);
        }
Exemplo n.º 7
0
        public List <Command> Init(IValkyrjaClient iClient)
        {
            this.Client = iClient as ValkyrjaClient;
            List <Command> commands = new List <Command>();

            this.Client.Events.UserJoined      += OnUserJoined;
            this.Client.Events.ReactionAdded   += OnReactionAdded;
            this.Client.Events.ReactionRemoved += OnReactionRemoved;

// !publicRoles
            Command newCommand = new Command("publicRoles");

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "See what Public Roles can you join on this server.";
            newCommand.ManPage             = new ManPage("", "");
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                List <RoleConfig> publicRoles = e.Server.Roles.Values.Where(r => r.PermissionLevel == RolePermissionLevel.Public).ToList();
                if (publicRoles == null || publicRoles.Count == 0)
                {
                    await e.SendReplySafe(ErrorNoPublicRoles);

                    return;
                }

                ServerContext dbContext       = ServerContext.Create(this.Client.DbConnectionString);
                StringBuilder responseBuilder = new StringBuilder(e.Server.Localisation.GetString("role_publicroles_print", e.Server.Config.CommandPrefix));
                Dictionary <Int64, List <RoleConfig> > groupRoles   = new Dictionary <Int64, List <RoleConfig> >();
                Dictionary <Int64, RoleGroupConfig>    groupConfigs = dbContext.PublicRoleGroups.AsQueryable().Where(g => g.ServerId == e.Server.Id).ToDictionary(g => g.GroupId);
                dbContext.Dispose();

                foreach (RoleConfig roleConfig in publicRoles)
                {
                    SocketRole role = e.Server.Guild.GetRole(roleConfig.RoleId);
                    if (role == null)
                    {
                        continue;
                    }

                    if (!groupRoles.ContainsKey(roleConfig.PublicRoleGroupId))
                    {
                        List <RoleConfig> tempGroup = publicRoles.Where(r => r.PublicRoleGroupId == roleConfig.PublicRoleGroupId).ToList();
                        groupRoles.Add(roleConfig.PublicRoleGroupId, tempGroup);
                    }
                }

                string GetRoleNames(List <RoleConfig> roleConfigs)
                {
                    return(e.Server.Guild.Roles.Where(r => roleConfigs.Any(rc => rc.RoleId == r.Id))
                           .Select(r => r.Name).ToNames());
                }

                if (groupRoles.ContainsKey(0))
                {
                    responseBuilder.Append(GetRoleNames(groupRoles[0]));
                }

                foreach (KeyValuePair <Int64, List <RoleConfig> > groupRole in groupRoles)
                {
                    if (groupRole.Key == 0)
                    {
                        continue;
                    }

                    RoleGroupConfig groupConfig  = groupConfigs.ContainsKey(groupRole.Key) ? groupConfigs[groupRole.Key] : new RoleGroupConfig();
                    string          name         = string.IsNullOrEmpty(groupConfig.Name) ? ("Group #" + groupRole.Key.ToString()) : groupConfig.Name;
                    string          limitVerbose = groupConfig.RoleLimit == 0 ? "any" : groupConfig.RoleLimit.ToString();
                    responseBuilder.Append(e.Server.Localisation.GetString("role_publicroles_group", name, limitVerbose));

                    responseBuilder.Append(GetRoleNames(groupRole.Value));
                }

                await e.SendReplySafe(responseBuilder.ToString());
            };
            commands.Add(newCommand);

// !roleCounts
            newCommand                     = new Command("roleCounts");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Get some numbers about public roles for specific group.";
            newCommand.ManPage             = new ManPage("<expression>", "`<expression>` - An expression using which to search for a role group.");
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                string expression = e.TrimmedMessage;

                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                IEnumerable <RoleGroupConfig> roleGroups  = dbContext.PublicRoleGroups.AsQueryable().Where(g => g.ServerId == e.Server.Id);
                IEnumerable <RoleGroupConfig> foundGroups = null;

                if (string.IsNullOrEmpty(expression) || (
                        !(foundGroups = roleGroups.Where(g => g.Name == expression)).Any() &&
                        !(foundGroups = roleGroups.Where(g => (g.Name?.ToLower() ?? "") == expression.ToLower())).Any() &&
                        !(foundGroups = roleGroups.Where(g => g.Name?.ToLower().Contains(expression.ToLower()) ?? false)).Any()))
                {
                    await e.SendReplySafe(ErrorGroupNotFound);

                    dbContext.Dispose();
                    return;
                }

                if (foundGroups.Count() > 1)
                {
                    await e.SendReplySafe(ErrorTooManyGroupsFound);

                    dbContext.Dispose();
                    return;
                }

                await e.Server.Guild.DownloadUsersAsync();

                Int64 groupId = foundGroups.First().GroupId;
                dbContext.Dispose();

                IEnumerable <guid>       roleIds  = e.Server.Roles.Values.Where(r => r.PublicRoleGroupId == groupId).Select(r => r.RoleId);
                IEnumerable <SocketRole> roles    = e.Server.Guild.Roles.Where(r => roleIds.Contains(r.Id));
                StringBuilder            response = new StringBuilder();
                foreach (SocketRole role in roles)
                {
                    response.AppendLine($"**{role.Name}**: `{role.Members.Count()}`");
                }

                await e.SendReplySafe(response.ToString());
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("countGroup"));
            commands.Add(newCommand.CreateAlias("countRoles"));

// !join
            newCommand                     = new Command("join");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Grab a public role for yourself.";
            newCommand.ManPage             = new ManPage("<expression>", "`<expression>` - An expression using which to search for a public role.");
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.SendReplySafe(ErrorPermissionsString);

                    return;
                }

                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    await e.SendReplySafe(e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId));

                    return;
                }

                List <RoleConfig> publicRoles = e.Server.Roles.Values.Where(r => r.PermissionLevel == RolePermissionLevel.Public).ToList();
                if (publicRoles == null || publicRoles.Count == 0)
                {
                    await e.SendReplySafe(ErrorNoPublicRoles);

                    return;
                }

                IEnumerable <SocketRole> roles      = e.Server.Guild.Roles.Where(r => publicRoles.Any(rc => rc.RoleId == r.Id));
                IEnumerable <SocketRole> foundRoles = null;
                if (!(foundRoles = roles.Where(r => r.Name == e.TrimmedMessage)).Any() &&
                    !(foundRoles = roles.Where(r => r.Name.ToLower() == e.TrimmedMessage.ToLower())).Any() &&
                    !(foundRoles = roles.Where(r => r.Name.ToLower().Contains(e.TrimmedMessage.ToLower()))).Any())
                {
                    await e.SendReplySafe(ErrorRoleNotFound);

                    return;
                }

                if (foundRoles.Count() > 1)
                {
                    await e.SendReplySafe(ErrorTooManyFound);

                    return;
                }

                RoleGroupConfig    groupConfig  = null;
                IEnumerable <guid> groupRoleIds = null;
                SocketRole         roleToAssign = foundRoles.First();
                Int64 groupId = publicRoles.First(r => r.RoleId == roleToAssign.Id).PublicRoleGroupId;

                if (groupId != 0)
                {
                    groupRoleIds = publicRoles.Where(r => r.PublicRoleGroupId == groupId).Select(r => r.RoleId);
                    int userHasCount = (e.Message.Author as SocketGuildUser).Roles.Count(r => groupRoleIds.Any(id => id == r.Id));

                    if (userHasCount > 0)
                    {
                        ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                        groupConfig = dbContext.PublicRoleGroups.AsQueryable().FirstOrDefault(g => g.ServerId == e.Server.Id && g.GroupId == groupId);
                        dbContext.Dispose();

                        if (groupConfig != null && groupConfig.RoleLimit > 1 && userHasCount >= groupConfig.RoleLimit)
                        {
                            await e.SendReplySafe($"You can only have {groupConfig.RoleLimit} roles from the `{groupConfig.Name}` group.");

                            return;
                        }
                    }
                }

                bool   removed  = false;
                string response = e.Server.Localisation.GetString("role_join_done");
                try
                {
                    SocketGuildUser user = (e.Message.Author as SocketGuildUser);

                    if (groupRoleIds != null && (groupConfig == null || groupConfig.RoleLimit == 1))
                    {
                        foreach (guid id in groupRoleIds)
                        {
                            if (user.Roles.All(r => r.Id != id))
                            {
                                continue;
                            }

                            SocketRole roleToLeave = e.Server.Guild.GetRole(id);
                            if (roleToLeave == null)
                            {
                                continue;
                            }

                            await user.RemoveRoleAsync(roleToLeave);

                            removed = true;
                        }
                    }

                    await user.AddRoleAsync(roleToAssign);
                } catch (HttpException exception)
                {
                    await e.Server.HandleHttpException(exception, $"This happened in <#{e.Channel.Id}> when executing command `{e.CommandId}`");

                    response = Utils.HandleHttpException(exception);
                } catch (Exception exception)
                {
                    await this.Client.LogException(exception, e);

                    response = $"Unknown error, please poke <@{this.Client.GlobalConfig.AdminUserId}> to take a look x_x";
                }

                if (removed)
                {
                    response += e.Server.Localisation.GetString("role_join_exclusiveremoved");
                }

                await e.SendReplySafe(response);

                if (this.Client.Events.LogPublicRoleJoin != null)
                {
                    await this.Client.Events.LogPublicRoleJoin(e.Server, e.Message.Author as SocketGuildUser, roleToAssign.Name);
                }
            };
            commands.Add(newCommand);

// !leave
            newCommand                     = new Command("leave");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Dispose of your public role.";
            newCommand.ManPage             = new ManPage("<expression>", "`<expression>` - An expression using which to search for a public role.");
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.SendReplySafe(ErrorPermissionsString);

                    return;
                }

                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    await e.SendReplySafe(e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId));

                    return;
                }

                List <RoleConfig> publicRoles = e.Server.Roles.Values.Where(r => r.PermissionLevel == RolePermissionLevel.Public).ToList();
                if (publicRoles == null || publicRoles.Count == 0)
                {
                    await e.SendReplySafe(ErrorNoPublicRoles);

                    return;
                }

                IEnumerable <SocketRole> roles      = e.Server.Guild.Roles.Where(r => publicRoles.Any(rc => rc.RoleId == r.Id));
                IEnumerable <SocketRole> foundRoles = null;
                if (!(foundRoles = roles.Where(r => r.Name == e.TrimmedMessage)).Any() &&
                    !(foundRoles = roles.Where(r => r.Name.ToLower() == e.TrimmedMessage.ToLower())).Any() &&
                    !(foundRoles = roles.Where(r => r.Name.ToLower().Contains(e.TrimmedMessage.ToLower()))).Any())
                {
                    await e.SendReplySafe(ErrorRoleNotFound);

                    return;
                }

                if (foundRoles.Count() > 1)
                {
                    await e.SendReplySafe(ErrorTooManyFound);

                    return;
                }

                string response = e.Server.Localisation.GetString("role_leave_done");
                try
                {
                    await(e.Message.Author as SocketGuildUser)?.RemoveRoleAsync(foundRoles.First());
                } catch (HttpException exception)
                {
                    await e.Server.HandleHttpException(exception, $"This happened in <#{e.Channel.Id}> when executing command `{e.CommandId}`");

                    response = Utils.HandleHttpException(exception);
                } catch (Exception exception)
                {
                    await this.Client.LogException(exception, e);

                    response = $"Unknown error, please poke <@{this.Client.GlobalConfig.AdminUserId}> to take a look x_x";
                }

                await e.SendReplySafe(response);

                if (this.Client.Events.LogPublicRoleLeave != null)
                {
                    await this.Client.Events.LogPublicRoleLeave(e.Server, e.Message.Author as SocketGuildUser, foundRoles.First().Name);
                }
            };
            commands.Add(newCommand);

// !memberRoles
            newCommand                     = new Command("memberRoles");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "See what Member Roles you can assign to others.";
            newCommand.ManPage             = new ManPage("", "");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin | PermissionType.Moderator | PermissionType.SubModerator;
            newCommand.OnExecute          += async e => {
                SocketGuildUser moderator = e.Message.Author as SocketGuildUser;
                if (moderator == null)
                {
                    await this.HandleException(new NullReferenceException("Message author is not a SocketGuildUser"), e.Message.Author.Id.ToString(), e.Server.Id);

                    return;
                }

                List <guid> memberRoles = e.Server.Roles.Values.Where(r => r.PermissionLevel == RolePermissionLevel.Member).Select(r => r.RoleId).ToList();
                memberRoles.AddRange(e.Server.CategoryMemberRoles.Where(rc => moderator.Roles.Any(r => r.Id == rc.ModRoleId)).Select(r => r.MemberRoleId));
                if (memberRoles == null || memberRoles.Count == 0)
                {
                    await e.SendReplySafe(ErrorNoMemberRoles);

                    return;
                }

                string response = e.Server.Localisation.GetString("role_memberroles_print",
                                                                  e.Server.Config.CommandPrefix,
                                                                  e.Server.Guild.Roles.Where(r => memberRoles.Any(rc => rc == r.Id)).Select(r => r.Name).ToNames()
                                                                  );

                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);

// !promote
            newCommand                     = new Command("promote");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Assign someone a member role.";
            newCommand.ManPage             = new ManPage("<@users> <expression>", "`<@users>` - User mention(s) (or IDs) whom to assign the member role.\n\n`<expression>` - An expression using which to search for a member role.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin | PermissionType.Moderator | PermissionType.SubModerator;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.SendReplySafe(ErrorPermissionsString);

                    return;
                }

                SocketGuildUser moderator = e.Message.Author as SocketGuildUser;
                if (moderator == null)
                {
                    await this.HandleException(new NullReferenceException("Message author is not a SocketGuildUser"), e.Message.Author.Id.ToString(), e.Server.Id);

                    return;
                }

                List <IGuildUser> users;
                if (string.IsNullOrEmpty(e.TrimmedMessage) || !(users = await this.Client.GetMentionedGuildUsers(e)).Any() || e.MessageArgs.Length <= users.Count)
                {
                    await e.SendReplySafe(e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId));

                    return;
                }

                List <guid> memberRoles = e.Server.Roles.Values.Where(r => r.PermissionLevel == RolePermissionLevel.Member).Select(r => r.RoleId).ToList();
                memberRoles.AddRange(e.Server.CategoryMemberRoles.Where(rc => moderator.Roles.Any(r => r.Id == rc.ModRoleId)).Select(r => r.MemberRoleId));

                if (memberRoles == null || memberRoles.Count == 0)
                {
                    await e.SendReplySafe(ErrorNoMemberRoles);

                    return;
                }

                string expression = e.TrimmedMessage.Substring(e.TrimmedMessage.IndexOf(e.MessageArgs[users.Count]));

                IEnumerable <SocketRole> roles      = e.Server.Guild.Roles.Where(r => memberRoles.Any(rc => rc == r.Id));
                IEnumerable <SocketRole> foundRoles = null;
                if (!(foundRoles = roles.Where(r => r.Name == expression)).Any() &&
                    !(foundRoles = roles.Where(r => r.Name.ToLower() == expression.ToLower())).Any() &&
                    !(foundRoles = roles.Where(r => r.Name.ToLower().Contains(expression.ToLower()))).Any())
                {
                    await e.SendReplySafe(ErrorRoleNotFound);

                    return;
                }

                if (foundRoles.Count() > 1)
                {
                    await e.SendReplySafe(ErrorTooManyFound);

                    return;
                }

                string     response = e.Server.Localisation.GetString("role_promote_done");
                SocketRole role     = foundRoles.First();
                try
                {
                    foreach (IGuildUser user in users)
                    {
                        await user.AddRoleAsync(role);

                        if (this.Client.Events.LogPromote != null)
                        {
                            await this.Client.Events.LogPromote(e.Server, user, role.Name, e.Message.Author as SocketGuildUser);
                        }
                    }
                } catch (HttpException exception)
                {
                    await e.Server.HandleHttpException(exception, $"This happened in <#{e.Channel.Id}> when executing command `{e.CommandId}`");

                    response = Utils.HandleHttpException(exception);
                } catch (Exception exception)
                {
                    await this.Client.LogException(exception, e);

                    response = $"Unknown error, please poke <@{this.Client.GlobalConfig.AdminUserId}> to take a look x_x";
                }

                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);

// !demote
            newCommand                     = new Command("demote");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Remove a member role from someone.";
            newCommand.ManPage             = new ManPage("<@users> <expression>", "`<@users>` - User mention(s) (or IDs) whom to remove the member role.\n\n`<expression>` - An expression using which to search for a member role.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin | PermissionType.Moderator | PermissionType.SubModerator;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.SendReplySafe(ErrorPermissionsString);

                    return;
                }

                SocketGuildUser moderator = e.Message.Author as SocketGuildUser;
                if (moderator == null)
                {
                    await this.HandleException(new NullReferenceException("Message author is not a SocketGuildUser"), e.Message.Author.Id.ToString(), e.Server.Id);

                    return;
                }

                List <IGuildUser> users;
                if (string.IsNullOrEmpty(e.TrimmedMessage) || !(users = await this.Client.GetMentionedGuildUsers(e)).Any() || e.MessageArgs.Length <= users.Count)
                {
                    await e.SendReplySafe(e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId));

                    return;
                }

                List <guid> memberRoles = e.Server.Roles.Values.Where(r => r.PermissionLevel == RolePermissionLevel.Member).Select(r => r.RoleId).ToList();
                memberRoles.AddRange(e.Server.CategoryMemberRoles.Where(rc => moderator.Roles.Any(r => r.Id == rc.ModRoleId)).Select(r => r.MemberRoleId));

                if (memberRoles == null || memberRoles.Count == 0)
                {
                    await e.SendReplySafe(ErrorNoMemberRoles);

                    return;
                }

                string expression = e.TrimmedMessage.Substring(e.TrimmedMessage.IndexOf(e.MessageArgs[users.Count]));

                IEnumerable <SocketRole> roles      = e.Server.Guild.Roles.Where(r => memberRoles.Any(rc => rc == r.Id));
                IEnumerable <SocketRole> foundRoles = null;
                if (!(foundRoles = roles.Where(r => r.Name == expression)).Any() &&
                    !(foundRoles = roles.Where(r => r.Name.ToLower() == expression.ToLower())).Any() &&
                    !(foundRoles = roles.Where(r => r.Name.ToLower().Contains(expression.ToLower()))).Any())
                {
                    await e.SendReplySafe(ErrorRoleNotFound);

                    return;
                }

                if (foundRoles.Count() > 1)
                {
                    await e.SendReplySafe(ErrorTooManyFound);

                    return;
                }

                SocketRole role     = foundRoles.First();
                string     response = e.Server.Localisation.GetString("role_demote_done");
                try
                {
                    foreach (IGuildUser user in users)
                    {
                        await user.RemoveRoleAsync(role);

                        if (this.Client.Events.LogDemote != null)
                        {
                            await this.Client.Events.LogDemote(e.Server, user, role.Name, e.Message.Author as SocketGuildUser);
                        }
                    }
                } catch (HttpException exception)
                {
                    await e.Server.HandleHttpException(exception, $"This happened in <#{e.Channel.Id}> when executing command `{e.CommandId}`");

                    response = Utils.HandleHttpException(exception);
                } catch (Exception exception)
                {
                    await this.Client.LogException(exception, e);

                    response = $"Unknown error, please poke <@{this.Client.GlobalConfig.AdminUserId}> to take a look x_x";
                }

                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);

// !categoryMembers
            newCommand                     = new Command("categoryMembers");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Configure category member roles.";
            newCommand.ManPage             = new ManPage("<add> <modRoleId> <memberRoleId> | <reset> <modRoleId> | <resetAll>", "`<add>` - An instruction to add the following roles as a moderator who can assign the member role.\n\n`<reset>` - An instruction to clear all the member roles associated with the specified moderator role ID.\n\n`<modRoleId>` - Moderator role ID to be added or reset. \n\n`<memberRoleId>` Member role ID to be added.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                string response = "Invalid arguments:\n" + e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId);

                if (e.MessageArgs == null || e.MessageArgs.Length < 1)
                {
                    await e.SendReplySafe(response);

                    return;
                }

                guid modRoleId;
                IEnumerable <CategoryMemberRole> rolesToRemove;
                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                switch (e.MessageArgs[0].ToLower())
                {
                case "add":
                    if (!guid.TryParse(e.MessageArgs[1], out modRoleId) || !guid.TryParse(e.MessageArgs[2], out guid memberRoleId))
                    {
                        break;
                    }
                    dbContext.GetOrAddMemberRole(e.Server.Id, modRoleId, memberRoleId);
                    dbContext.SaveChanges();

                    response = "Sure.";
                    break;

                case "reset":
                    if (!guid.TryParse(e.MessageArgs[1], out modRoleId))
                    {
                        break;
                    }
                    rolesToRemove = dbContext.CategoryMemberRoles.AsQueryable().Where(r => r.ServerId == e.Server.Id && r.ModRoleId == modRoleId);
                    if (rolesToRemove.Any())
                    {
                        dbContext.CategoryMemberRoles.RemoveRange(rolesToRemove);
                        dbContext.SaveChanges();
                    }

                    response = "Sure.";
                    break;

                case "resetAll":
                    rolesToRemove = dbContext.CategoryMemberRoles.AsQueryable().Where(r => r.ServerId == e.Server.Id);
                    if (rolesToRemove.Any())
                    {
                        dbContext.CategoryMemberRoles.RemoveRange(rolesToRemove);
                        dbContext.SaveChanges();
                    }

                    response = "Sure.";
                    break;

                default:
                    break;
                }

                dbContext.Dispose();
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);

// !promoteEveryone
            newCommand                     = new Command("promoteEveryone");
            newCommand.Type                = CommandType.Operation;
            newCommand.Description         = "Assign everyone a role identified by it's ID. Use the `getRole` command to get the ID.";
            newCommand.ManPage             = new ManPage("<roleID>", "`<roleID>` - Specific Role ID of a role.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.SendReplySafe(ErrorPermissionsString);

                    return;
                }

                SocketRole role = null;
                if (string.IsNullOrEmpty(e.TrimmedMessage) ||
                    !guid.TryParse(e.TrimmedMessage, out guid id) || id < int.MaxValue ||
                    (role = e.Server.Guild.Roles.FirstOrDefault(r => r.Id == id)) == null)
                {
                    await e.SendReplySafe(ErrorRoleNotFoundId);

                    return;
                }

                await e.SendReplySafe(PromoteEveryoneResponseString);

                await e.Server.Guild.DownloadUsersAsync();

                List <SocketGuildUser> users = e.Server.Guild.Users.ToList();

                int  i          = 0;
                int  count      = 0;
                int  exceptions = 0;
                bool canceled   = await e.Operation.While(() => i < users.Count, async() => {
                    try
                    {
                        SocketGuildUser user = users[i++];
                        if (user.Roles.Any(r => r.Id == role.Id))
                        {
                            return(false);
                        }

                        await user.AddRoleAsync(role);
                        count++;
                    }
                    catch (Exception)
                    {
                        if (++exceptions > 10)
                        {
                            return(true);
                        }
                    }

                    return(false);
                });

                if (canceled)
                {
                    return;
                }

                string response = exceptions > 10 ? ErrorPromoteEveryone : ($"Done! I've assigned `{role.Name}` to `{count}` member" + (count != 1 ? "s." : "."));
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);

// !demoteEveryone
            newCommand                     = new Command("demoteEveryone");
            newCommand.Type                = CommandType.Operation;
            newCommand.Description         = "Remove a role from everyone, identified by roleID. Use the `getRole` command to get the ID.";
            newCommand.ManPage             = new ManPage("<roleID>", "`<roleID>` - Specific Role ID of a role.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.SendReplySafe(ErrorPermissionsString);

                    return;
                }

                SocketRole role = null;
                if (string.IsNullOrEmpty(e.TrimmedMessage) ||
                    !guid.TryParse(e.TrimmedMessage, out guid id) || id < int.MaxValue ||
                    (role = e.Server.Guild.Roles.FirstOrDefault(r => r.Id == id)) == null)
                {
                    await e.SendReplySafe(ErrorRoleNotFoundId);

                    return;
                }

                await e.SendReplySafe(DemoteEveryoneResponseString);

                await e.Server.Guild.DownloadUsersAsync();

                List <SocketGuildUser> users = e.Server.Guild.Users.ToList();

                int  i          = 0;
                int  count      = 0;
                int  exceptions = 0;
                bool canceled   = await e.Operation.While(() => i < users.Count, async() => {
                    try
                    {
                        SocketGuildUser user = users[i++];
                        if (!user.Roles.Any(r => r.Id == role.Id))
                        {
                            return(false);
                        }

                        await user.RemoveRoleAsync(role);
                        count++;
                    }
                    catch (Exception)
                    {
                        if (++exceptions > 10)
                        {
                            return(true);
                        }
                    }

                    return(false);
                });

                if (canceled)
                {
                    return;
                }

                string response = exceptions > 10 ? ErrorDemoteEveryone : ($"Done! I've removed `{role.Name}` from `{count}` member" + (count != 1 ? "s." : "."));
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);

// !countWithoutRoles
            newCommand                     = new Command("countWithoutRoles");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Count how many users do not have any role.";
            newCommand.ManPage             = new ManPage("", "");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                await e.SendReplySafe(WorkingOnItString);

                await e.Server.Guild.DownloadUsersAsync();

                int count = e.Server.Guild.Users.Count(u => !u.IsBot && u.Roles.All(r => r.Id == e.Server.Id));
                await e.SendReplySafe(string.Format(FoundCountString, count));
            };
            commands.Add(newCommand);

// !kickWithoutRoles
            newCommand                     = new Command("kickWithoutRoles");
            newCommand.Type                = CommandType.Operation;
            newCommand.Description         = "Kick all the users who do not have any role.";
            newCommand.ManPage             = new ManPage("", "");
            newCommand.RequiredPermissions = PermissionType.ServerOwner;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.KickMembers)
                {
                    await e.SendReplySafe(ErrorPermissionsString);

                    return;
                }

                await e.SendReplySafe(WorkingOnItString);

                await e.Server.Guild.DownloadUsersAsync();

                List <SocketGuildUser> users = e.Server.Guild.Users.ToList();

                int  i          = 0;
                int  count      = 0;
                int  exceptions = 0;
                bool canceled   = await e.Operation.While(() => i < users.Count, async() => {
                    try
                    {
                        SocketGuildUser user = users[i++];
                        if (user.IsBot || e.Server.Guild.OwnerId == user.Id || user.Roles.Any(r => r.Id != e.Server.Id))
                        {
                            return(false);
                        }

                        await user.KickAsync();
                        count++;
                    }
                    catch (Exception)
                    {
                        if (++exceptions > 10)
                        {
                            return(true);
                        }
                    }

                    return(false);
                });

                if (canceled)
                {
                    return;
                }

                string response = exceptions > 10 ? ErrorKickWithoutRole : $"Done! I've kicked `{count}` members who had no roles! You know what to press to pay respects!";
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);


            return(commands);
        }
Exemplo n.º 8
0
        public List <Command> Init(IValkyrjaClient iClient)
        {
            this.Client = iClient as ValkyrjaClient;
            List <Command> commands = new List <Command>();

            this.Client.Events.MessageReceived += OnMessageReceived;

// !tempChannel
            Command newCommand = new Command("tempChannel");

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Creates a temporary voice channel. This channel will be destroyed when it becomes empty, with grace period of three minutes since it's creation.";
            newCommand.ManPage             = new ManPage("[userLimit] <channelName>", "`[userLimit]` - Optional user limit.\n\n`<channelName>` - Name of the new temporary voice channel.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin | PermissionType.Moderator | PermissionType.SubModerator;
            newCommand.OnExecute          += async e => {
                if (e.Server.Config.TempChannelCategoryId == 0)
                {
                    await e.SendReplySafe("This command has to be configured on the config page (\"other\" section) <https://valkyrja.app/config>");

                    return;
                }

                if (string.IsNullOrWhiteSpace(e.TrimmedMessage))
                {
                    await e.SendReplySafe($"Usage: `{e.Server.Config.CommandPrefix}tempChannel <name>` or `{e.Server.Config.CommandPrefix}tempChannel [userLimit] <name>`");

                    return;
                }

                int           limit   = 0;
                bool          limited = int.TryParse(e.MessageArgs[0], out limit);
                StringBuilder name    = new StringBuilder();
                for (int i = limited ? 1 : 0; i < e.MessageArgs.Length; i++)
                {
                    name.Append(e.MessageArgs[i]);
                    name.Append(" ");
                }
                string responseString = string.Format(TempChannelConfirmString, name.ToString());

                try
                {
                    RestVoiceChannel tempChannel = null;
                    if (limited)
                    {
                        tempChannel = await e.Server.Guild.CreateVoiceChannelAsync(name.ToString(), c => {
                            c.CategoryId = e.Server.Config.TempChannelCategoryId;
                            c.UserLimit  = limit;
                        });
                    }
                    else
                    {
                        tempChannel = await e.Server.Guild.CreateVoiceChannelAsync(name.ToString(), c => c.CategoryId = e.Server.Config.TempChannelCategoryId);
                    }

                    if (e.Server.Config.TempChannelGiveAdmin)
                    {
                        await tempChannel.AddPermissionOverwriteAsync(e.Message.Author, new OverwritePermissions(manageChannel : PermValue.Allow, manageRoles : PermValue.Allow, moveMembers : PermValue.Allow, muteMembers : PermValue.Allow, deafenMembers : PermValue.Allow));
                    }

                    ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                    ChannelConfig channel   = dbContext.Channels.AsQueryable().FirstOrDefault(c => c.ServerId == e.Server.Id && c.ChannelId == tempChannel.Id);
                    if (channel == null)
                    {
                        channel = new ChannelConfig {
                            ServerId  = e.Server.Id,
                            ChannelId = tempChannel.Id
                        };

                        dbContext.Channels.Add(channel);
                    }

                    channel.Temporary = true;
                    dbContext.SaveChanges();
                    dbContext.Dispose();
                }
                catch (HttpException exception)
                {
                    await e.Server.HandleHttpException(exception, $"This happened in <#{e.Channel.Id}> when trying to create a temporary channel.");
                }
                catch (Exception exception)
                {
                    await this.Client.LogException(exception, e);

                    responseString = string.Format(ErrorUnknownString, this.Client.GlobalConfig.AdminUserId);
                }

                await e.SendReplySafe(responseString);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("tmp"));
            commands.Add(newCommand.CreateAlias("tc"));

// !mentionRole
            newCommand                     = new Command("mentionRole");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Mention a role with a message. Use with the name of the role as the first parameter and the message will be the rest.";
            newCommand.ManPage             = new ManPage("<roleName> <message text>", "`<roleName>` - Name of the role to be mentioned with a ping.\n\n`<message text>` - Text that will be said with the role mention.");
            newCommand.DeleteRequest       = true;
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.SendReplySafe(ErrorPermissionsString);

                    return;
                }

                if (e.MessageArgs == null || e.MessageArgs.Length < 2)
                {
                    await e.SendReplySafe($"Usage: `{e.Server.Config.CommandPrefix}{e.CommandId} <roleName> <message text>`");

                    return;
                }

                IEnumerable <SocketRole> foundRoles = null;
                if (!(foundRoles = e.Server.Guild.Roles.Where(r => r.Name == e.MessageArgs[0])).Any() &&
                    !(foundRoles = e.Server.Guild.Roles.Where(r => r.Name.ToLower() == e.MessageArgs[0].ToLower())).Any() &&
                    !(foundRoles = e.Server.Guild.Roles.Where(r => r.Name.ToLower().Contains(e.MessageArgs[0].ToLower()))).Any())
                {
                    await e.SendReplySafe(ErrorRoleNotFound);

                    return;
                }

                if (foundRoles.Count() > 1)
                {
                    await e.SendReplySafe(ErrorTooManyFound);

                    return;
                }

                SocketRole role    = foundRoles.First();
                string     message = e.TrimmedMessage.Substring(e.TrimmedMessage.IndexOf(e.MessageArgs[1]));

                await role.ModifyAsync(r => r.Mentionable = true);

                await Task.Delay(100);

                await e.SendReplySafe($"{role.Mention} {message}", allowedMentions : new AllowedMentions(AllowedMentionTypes.Users | AllowedMentionTypes.Everyone | AllowedMentionTypes.Roles));

                await Task.Delay(100);

                await role.ModifyAsync(r => r.Mentionable = false);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("announce"));

// !cheatsheet
            newCommand                     = new Command("cheatsheet");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Send an embed cheatsheet with various moderation commands.";
            newCommand.ManPage             = new ManPage("", "");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                EmbedBuilder embedBuilder = new EmbedBuilder();
                embedBuilder.WithTitle("Moderation commands").WithColor(16711816).WithFields(
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}op`").WithValue("Distinguish yourself as a moderator when addressing people, and allow the use of `!mute`, `!kick` & `!ban` commands."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}mute @user(s) duration`").WithValue("Mute mentioned user(s) for `duration` (use `m`, `h` and `d`, e.g. 1h15m. This will effectively move them to the `#chill-zone` channel."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}kick @user(s) reason`").WithValue("Kick mentioned `@users` (or IDs) with specific `reason`."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}ban @user(s) duration reason`").WithValue("Ban mentioned `@users` (or IDs) for `duration` (use `h` and `d`, e.g. 1d12h, or zero `0d` for permanent) with specific `reason`."),
                    new EmbedFieldBuilder().WithName("`reason`").WithValue("Reason parameter of the above `kick` and `ban` commands is stored in the database as a _warning_ and also PMed to the user. Please provide proper descriptions."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}issueWarning @user(s) message`").WithValue("The same as `addWarning`, but also PM this message to the user(s)"),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}addWarning @user(s) message`").WithValue("Add a `message` to the database, taking notes of peoples naughty actions."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}removeWarning @user`").WithValue("Remove the last added warning from the `@user` (or ID)"),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}whois @user`").WithValue("Search for a `@user` (or ID, or name) who is present on the server."),
                    new EmbedFieldBuilder().WithName($"`{e.Server.Config.CommandPrefix}find expression`").WithValue("Search for a user using more complex search through all the past nicknames, etc... This will also go through people who are not on the server anymore."),
                    new EmbedFieldBuilder().WithName($"`whois/find`").WithValue("Both whois and find commands will return information about the user, when was their account created, when did they join, their past names and nicknames, and all the previous warnings and bans.")
                    );

                RestUserMessage msg = await e.Channel.SendMessageAsync(embed : embedBuilder.Build());

                await msg.PinAsync();

                embedBuilder = new EmbedBuilder();
                embedBuilder.WithTitle("Moderation guidelines").WithColor(16711816).WithDescription("for implementing the [theory](http://rhea-ayase.eu/articles/2017-04/Moderation-guidelines) in real situations.\n")
                .WithFields(
                    new EmbedFieldBuilder().WithName("__Talking to people__").WithValue("~"),
                    new EmbedFieldBuilder().WithName("Don't use threats.").WithValue("a) **Imposed consequences** - what you can do with your power (kick, ban,...) These are direct threats, avoid them.\nb) **Natural consequences** - implied effects of members actions. These can include \"the community is growing to dislike you,\" or \"see you as racist,\" etc..."),
                    new EmbedFieldBuilder().WithName("Identify what is the underlying problem.").WithValue("a) **Motivation problem** - the member is not motivated to behave in acceptable manner - is a troll or otherwise enjoys being mean to people.\nb) **Ability problem** - the member may be direct without \"filters\" and their conversation often comes off as offensive while they just state things the way they see them: http://www.mit.edu/~jcb/tact.html"),
                    new EmbedFieldBuilder().WithName("Conversation should follow:").WithValue("1) **Explain** the current situation / problem.\n2) **Establish safety** - you're not trying to ban them or discourage them from participating.\n3) **Call to action** - make sure to end the conversation with an agreement about what steps will be taken towards improvement.\n"),
                    new EmbedFieldBuilder().WithName("__Taking action__").WithValue("~"),
                    new EmbedFieldBuilder().WithName("Always log every action").WithValue("with `warnings`, and always check every member and their history."),
                    new EmbedFieldBuilder().WithName("Contents of our channels should not be disrespectful towards anyone, think about minorities.").WithValue("a) Discussion topic going wild, the use of racial/homophobic or other improper language should be pointed out with an explanation that it is not cool towards minorities within our community.\nb) A member being plain disrespectful on purpose... Mute them, see their reaction to moderation talk and act on it."),
                    new EmbedFieldBuilder().WithName("Posting or even spamming inappropriate content").WithValue("should result in immediate mute and only then followed by explaining correct behavior based on all of the above points."),
                    new EmbedFieldBuilder().WithName("Repeated offense").WithValue("a) 1d ban, 3d ban, 7d ban - are your options depending on how severe it is.\nb) Permanent ban should be brought up for discussion with the rest of the team."),
                    new EmbedFieldBuilder().WithName("Member is disrespectful to the authority.").WithValue("If you get into conflict yourself, someone is disrespectful to you as a moderator, trolling and challenging your authority - step back and ask for help, mention `@Staff` in the mod channel, and let 3rd party deal with it.")
                    );

                msg = await e.Channel.SendMessageAsync(embed : embedBuilder.Build());

                await msg.PinAsync();
            };
            commands.Add(newCommand);

// !embed
            newCommand             = new Command("embed");
            newCommand.Type        = CommandType.Standard;
            newCommand.Description = "Build an embed. Use without arguments for help.";
            newCommand.ManPage     = new ManPage("<options>", "Use any combination of:\n" +
                                                 "`--channel     ` - Channel where to send the embed.\n" +
                                                 "`--edit <msgId>` - Replace a MessageId with a new embed (use after --channel)\n" +
                                                 "`--title       ` - Title\n" +
                                                 "`--description ` - Description\n" +
                                                 "`--footer      ` - Footer\n" +
                                                 "`--color       ` - #rrggbb hex color used for the embed stripe.\n" +
                                                 "`--image       ` - URL of a Hjuge image in the bottom.\n" +
                                                 "`--thumbnail   ` - URL of a smol image on the side.\n" +
                                                 "`--fieldName   ` - Create a new field with specified name.\n" +
                                                 "`--fieldValue  ` - Text value of a field - has to follow a name.\n" +
                                                 "`--fieldInline ` - Use to set the field as inline.\n" +
                                                 "Where you can repeat the field* options multiple times.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                await this.Client.SendEmbedFromCli(e);
            };
            commands.Add(newCommand);

// !addEmoji
            newCommand                     = new Command("addEmoji");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Add an emoji reaction to a message.";
            newCommand.ManPage             = new ManPage("<messageId> <emojis>", "`<messageId>` - ID of the message (in the current channel)\n\n`<emojis>` - Emojis that will be added as a reaction.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (e.MessageArgs == null || e.MessageArgs.Length < 2 || !guid.TryParse(e.MessageArgs[0], out guid messageId))
                {
                    await e.SendReplySafe("Invalid parameters:\n" + e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId));

                    return;
                }

                List <IEmote> emotes = new List <IEmote>();
                for (int i = 1; i < e.MessageArgs.Length; i++)
                {
                    if (Emote.TryParse(e.MessageArgs[i], out Emote emote))
                    {
                        emotes.Add(emote);
                    }
                    else
                    {
                        emotes.Add(new Emoji(e.MessageArgs[i]));
                    }
                }

                if (!emotes.Any())
                {
                    await e.SendReplySafe("No emotes found:\n" + e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId));

                    return;
                }

                string response = "K.";
                try
                {
                    IMessage msg = await e.Channel.GetMessageAsync(messageId);

                    switch (msg)
                    {
                    case RestUserMessage message:
                        await message.AddReactionsAsync(emotes.ToArray());

                        break;

                    case SocketUserMessage message:
                        await message.AddReactionsAsync(emotes.ToArray());

                        break;

                    default:
                        response = "Failed to fetch a message with that ID. Did you use this command in a correct channel?";
                        break;
                    }
                }
                catch (Exception)
                {
                    response = "You've dun goof'd, eh?";
                }

                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);

            return(commands);
        }
Exemplo n.º 9
0
        public async Task Update(IValkyrjaClient iClient)
        {
            ValkyrjaClient client    = iClient as ValkyrjaClient;
            ServerContext  dbContext = ServerContext.Create(client.DbConnectionString);
            bool           save      = false;
            //DateTime minTime = DateTime.MinValue + TimeSpan.FromMinutes(1);

            //Channels
            List <ChannelConfig> channelsToRemove = new List <ChannelConfig>();

            foreach (ChannelConfig channelConfig in dbContext.Channels.AsQueryable().Where(c => c.Temporary))
            {
                Server server;
                if (!client.Servers.ContainsKey(channelConfig.ServerId) ||
                    (server = client.Servers[channelConfig.ServerId]) == null)
                {
                    continue;
                }

                //Temporary voice channels
                SocketGuildChannel channel = server.Guild.GetChannel(channelConfig.ChannelId);
                if (channel != null &&
                    channel.CreatedAt < DateTimeOffset.UtcNow - this.TempChannelDelay &&
                    !channel.Users.Any())
                {
                    try
                    {
                        await channel.DeleteAsync();

                        channelConfig.Temporary = false;
                        channelsToRemove.Add(channelConfig);
                        save = true;
                    }
                    catch (HttpException e)
                    {
                        await server.HandleHttpException(e, $"Failed to delete temporary voice channel `{channel.Name}`");
                    }
                    catch (Exception e)
                    {
                        await this.HandleException(e, "Delete temporary voice channel", server.Id);
                    }
                }
                else if (channel == null)
                {
                    channelConfig.Temporary = false;
                    channelsToRemove.Add(channelConfig);
                    save = true;
                }
            }

            if (channelsToRemove.Any())
            {
                dbContext.Channels.RemoveRange(channelsToRemove);
            }

            if (save)
            {
                dbContext.SaveChanges();
            }
            dbContext.Dispose();
        }
Exemplo n.º 10
0
        public List <Command> Init(IValkyrjaClient iClient)
        {
            this.Client = iClient as ValkyrjaClient;
            List <Command> commands = new List <Command>();

// !lfgBump
            Command newCommand = new Command("lfgBump");

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "";
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.IsHidden            = true;
            newCommand.OnExecute          += async e => {
                if (!this.ServerConfigurations.ContainsKey(e.Server.Id))
                {
                    return;
                }

                await this.ServerConfigurations[e.Server.Id].Bump(e);
            };
            commands.Add(newCommand);

// !lfgRemove
            newCommand                     = new Command("lfgRemove");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "";
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.IsHidden            = true;
            newCommand.OnExecute          += async e => {
                if (!this.ServerConfigurations.ContainsKey(e.Server.Id))
                {
                    return;
                }

                await this.ServerConfigurations[e.Server.Id].DeletePreviousMessages(e);

                await e.SendReplySafe("Byeee!");
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("removeRecruitment"));

// !lfgFind
            newCommand                     = new Command("lfgFind");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "";
            newCommand.RequiredPermissions = PermissionType.OwnerOnly;
            newCommand.IsHidden            = true;
            newCommand.OnExecute          += async e => {
                if (!this.ServerConfigurations.ContainsKey(e.Server.Id))
                {
                    return;
                }

                await this.ServerConfigurations[e.Server.Id].Find(e);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("removeRecruitment"));

// !lfg
            newCommand                     = new Command("lfg");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "";
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.IsHidden            = true;
            newCommand.OnExecute          += async e => {
                if (!this.ServerConfigurations.ContainsKey(e.Server.Id))
                {
                    return;
                }

                await this.ServerConfigurations[e.Server.Id].SendOrReplaceEmbed(e);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("recruitment"));
            commands.Add(newCommand.CreateCopy("staticAether"));
            commands.Add(newCommand.CreateCopy("staticPrimal"));
            commands.Add(newCommand.CreateCopy("staticCrystal"));
            commands.Add(newCommand.CreateCopy("staticLight"));
            commands.Add(newCommand.CreateCopy("staticChaos"));
            commands.Add(newCommand.CreateCopy("staticElemental"));
            commands.Add(newCommand.CreateCopy("staticGaia"));
            commands.Add(newCommand.CreateCopy("staticMana"));

            return(commands);
        }
Exemplo n.º 11
0
        public List <Command> Init(IValkyrjaClient iClient)
        {
            this.Client = iClient as ValkyrjaClient;
            List <Command> commands = new List <Command>();

// !getQuote
            Command newCommand = new Command("getQuote");

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Get a random quote, or a quote with specific id, oooor search for a quote by a specific user!";
            newCommand.ManPage             = new ManPage("[ID | @user]", "`[ID]` - Optional IDentificator of a specific quote.\n\n`[@user]` - Optional username or mention to display quote by a specific user.");
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                string        response  = "";

                IEnumerable <Quote> quotes = dbContext.Quotes.AsQueryable().Where(q => q.ServerId == e.Server.Id);

                if (!quotes.Any())
                {
                    response = "There ain't no quotes here! Add some first :]";
                }
                else if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    int   count = quotes.Count();
                    Int64 id    = Utils.Random.Next(0, count);
                    response = quotes.FirstOrDefault(q => q.Id == id)?.ToString();
                }
                else
                {
                    Int64  id       = 0;
                    string username = "";
                    string nickname = "";
                    if (Int64.TryParse(e.TrimmedMessage, out id))
                    {
                        response = quotes.FirstOrDefault(q => q.Id == id)?.ToString();
                    }
                    else
                    {
                        if (e.Message.MentionedUsers.Any())
                        {
                            username = e.Message.MentionedUsers.FirstOrDefault()?.Username.ToLower();
                            nickname = (e.Message.MentionedUsers.FirstOrDefault() as IGuildUser)?.Nickname?.ToLower();
                        }
                        else
                        {
                            username = e.MessageArgs[0].ToLower();
                        }
                        quotes = quotes.Where(q => q.Username.ToLower().Contains(username) ||
                                              (!string.IsNullOrEmpty(nickname) && q.Username.ToLower().Contains(nickname)));
                        int count = quotes.Count();
                        if (count > 0)
                        {
                            id       = Utils.Random.Next(0, count);
                            response = quotes.Skip((int)id).FirstOrDefault()?.ToString();
                        }
                    }
                }

                if (string.IsNullOrEmpty(response))
                {
                    response = "I didn't find no such quote.";
                }

                await e.SendReplySafe(response);

                dbContext.Dispose();
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("quote"));

// !findQuote
            newCommand                     = new Command("findQuote");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Search for a quote with a message content expression.";
            newCommand.ManPage             = new ManPage("<expression>", "`<expression>` - An expression based on which matching quotes will be returned.");
            newCommand.RequiredPermissions = PermissionType.Everyone;
            newCommand.OnExecute          += async e => {
                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                StringBuilder response  = new StringBuilder();

                IEnumerable <Quote> quotes = dbContext.Quotes.AsQueryable().Where(q => q.ServerId == e.Server.Id);

                if (!quotes.Any())
                {
                    response.Append("There ain't no quotes here! Add some first :]");
                }
                else if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    response.Append("What am I looking for?");
                }
                else
                {
                    quotes = quotes.Where(q => q.Value.Contains(e.TrimmedMessage));
                    int count = quotes.Count();
                    if (count > 3)
                    {
                        response.Append("I found too many, displaying only the first three. Be more specific!");
                    }
                    else if (count == 0)
                    {
                        response.Append("I didn't find no such quote.");
                    }

                    foreach (Quote quote in quotes.Take(3))
                    {
                        response.AppendLine($"\n**Quote `{quote.Id}`:**")
                        .AppendLine(quote.ToString());
                    }
                }

                dbContext.Dispose();
                await e.SendReplySafe(response.ToString());
            };
            commands.Add(newCommand);

// !removeQuote
            newCommand                     = new Command("removeQuote");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Remove the last created quote, or specify ID to be removed.";
            newCommand.ManPage             = new ManPage("[ID]", "`[ID]` - Optional IDentificator of a specific quote to be removed.");
            newCommand.RequiredPermissions = PermissionType.SubModerator;
            newCommand.OnExecute          += async e => {
                ServerContext       dbContext = ServerContext.Create(this.Client.DbConnectionString);
                IEnumerable <Quote> quotes    = dbContext.Quotes.AsQueryable().Where(q => q.ServerId == e.Server.Id);
                if (!quotes.Any())
                {
                    await e.SendReplySafe("There ain't no quotes here! Add some first :]");

                    dbContext.Dispose();
                    return;
                }

                Int64 id    = 0;
                int   count = quotes.Count();
                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    id = count - 1;
                }
                else if (!Int64.TryParse(e.TrimmedMessage, out id) || id >= count || id < 0)
                {
                    await e.SendReplySafe("Invalid argument.");

                    dbContext.Dispose();
                    return;
                }

                Quote quote = quotes.FirstOrDefault(q => q.Id == id);
                if (quote != null)
                {
                    dbContext.Quotes.Remove(quote);
                    if (quote.Id != count - 1)
                    {
                        Quote replacement    = dbContext.Quotes.AsQueryable().First(q => q.ServerId == e.Server.Id && q.Id == count - 1);
                        Quote newReplacement = replacement.Clone(quote.Id);
                        dbContext.Quotes.Remove(replacement);
                        dbContext.Quotes.Add(newReplacement);
                    }
                    dbContext.SaveChanges();
                }

                await e.SendReplySafe($"Removed:\n {quote.ToString()}");

                dbContext.Dispose();
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("rmQuote"));

// !addQuote
            newCommand                     = new Command("addQuote");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Add a new quote! Use with a username or mention as the first parameter, and the text as second. (Or you can just use a message ID.)";
            newCommand.ManPage             = new ManPage("<MessageId> | <@user text>", "`<MessageId>` - ID of a message which will be added as a quote.\n\n`<@user text>` - An alternative way to create a quote based on a mention of a user to be used as the author, and plain text for the content.");
            newCommand.RequiredPermissions = PermissionType.SubModerator;
            newCommand.OnExecute          += async e => {
                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                string        response  = "I've no idea what are you trying to tell me.\nUse with a username or mention as the first parameter, and the text as second. (Or you can just use a message ID.)";
                Quote         quote     = null;

                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    response = "Wut?";
                }
                else if (guid.TryParse(e.TrimmedMessage, out guid messageId))
                {
                    IMessage message = await e.Channel.GetMessageAsync(messageId);

                    if (message != null)
                    {
                        quote = new Quote()
                        {
                            CreatedTime = new DateTime(message.CreatedAt.Ticks),
                            Username    = message.Author.Username,
                            Value       = message.Content.Replace('`', '\'') +
                                          (message.Attachments.Any() ? (" " + message.Attachments.FirstOrDefault()?.Url + " ") : "")
                        };
                    }
                    else
                    {
                        response = "Message not found.";
                    }
                }
                else if (e.MessageArgs.Length > 1)
                {
                    string username = e.Message.MentionedUsers.FirstOrDefault()?.Username ?? e.MessageArgs[0];
                    quote = new Quote()
                    {
                        CreatedTime = DateTime.UtcNow,
                        Username    = username,
                        Value       = e.TrimmedMessage.Substring(e.MessageArgs[0].Length).Replace('`', '\'').Trim('"').Trim()
                    };
                }

                if (quote != null)
                {
                    response       = "Unexpected database error :<";
                    quote.ServerId = e.Server.Id;
                    quote.Id       = dbContext.Quotes.AsQueryable().Count(q => q.ServerId == e.Server.Id);

                    dbContext.Quotes.Add(quote);
                    dbContext.SaveChanges();

                    response = $"**Quote created with ID** `{quote.Id}`:\n{quote.ToString()}";
                }

                dbContext.Dispose();
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);


            return(commands);
        }
Exemplo n.º 12
0
        public List <Command> Init(IValkyrjaClient iClient)
        {
            this.Client = iClient as ValkyrjaClient;
            List <Command> commands = new List <Command>();

            this.Client.Events.UserJoined      += OnUserJoined;
            this.Client.Events.MessageReceived += OnMessageReceived;

// !unverify
            Command newCommand = new Command("unverify");

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Remove verified status from someone.";
            newCommand.ManPage             = new ManPage("<@user>", "`<@user>` - User mention of a user to have their verified status removed.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Config.CodeVerificationEnabled && !e.Server.Config.CaptchaVerificationEnabled)
                {
                    await e.SendReplySafe("Verification is disabled on this server.");

                    return;
                }

                string          response       = "Done.";
                ServerContext   dbContext      = ServerContext.Create(this.Client.DbConnectionString);
                List <UserData> mentionedUsers = this.Client.GetMentionedUsersData(dbContext, e);
                IRole           role           = e.Server.Guild.GetRole(e.Server.Config.VerifyRoleId);
                if (!mentionedUsers.Any() || role == null)
                {
                    await e.SendReplySafe(UserNotFoundString);

                    dbContext.Dispose();
                    return;
                }

                try
                {
                    foreach (UserData userData in mentionedUsers)
                    {
                        userData.Verified = false;
                        SocketGuildUser user = e.Server.Guild.GetUser(userData.UserId);
                        if (user != null)
                        {
                            await user.RemoveRoleAsync(role);
                        }
                    }

                    dbContext.SaveChanges();
                }
                catch (Exception)
                {
                    response = "Invalid configuration or permissions.";
                }

                dbContext.Dispose();
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);

// !verify
            newCommand             = new Command("verify");
            newCommand.Type        = CommandType.Standard;
            newCommand.Description = "This will send you (or someone else) some info about verification.";
            newCommand.ManPage     = new ManPage("[@user [force]]", "`[@user]` - Optional user mention of someone else to send them the info.\n\n`[force]` - Optional administrative indicator that will directly verify mentioned user.");
            newCommand.OnExecute  += async e => {
                if ((!e.Server.Config.CodeVerificationEnabled && !e.Server.Config.CaptchaVerificationEnabled) || e.Server.Config.VerifyRoleId == 0)
                {
                    await e.SendReplySafe("Verification is disabled on this server.");

                    return;
                }

                ServerContext   dbContext      = ServerContext.Create(this.Client.DbConnectionString);
                List <UserData> mentionedUsers = this.Client.GetMentionedUsersData(dbContext, e);
                string          response       = InvalidParametersString;
                PmErrorCode     result         = PmErrorCode.Undefined;

                // Admin verified someone.
                if (e.MessageArgs != null && e.MessageArgs.Length > 1 &&
                    e.Server.IsAdmin(e.Message.Author as SocketGuildUser) &&
                    e.MessageArgs[e.MessageArgs.Length - 1] == "force")
                {
                    if (!mentionedUsers.Any())
                    {
                        await e.SendReplySafe(UserNotFoundString);

                        dbContext.Dispose();
                        return;
                    }

                    await VerifyUsers(e.Server, mentionedUsers);                     // actually verify people

                    response = string.Format(VerifiedString, mentionedUsers.Select(u => u.UserId).ToMentions());
                    result   = PmErrorCode.Undefined;
                }
                else if (string.IsNullOrEmpty(e.TrimmedMessage))                  // Verify the author.
                {
                    UserData userData = dbContext.GetOrAddUser(e.Server.Id, e.Message.Author.Id);
                    result = await VerifyUsersPm(e.Server, new List <UserData> {
                        userData
                    });

                    if (result == PmErrorCode.Undefined)
                    {
                        response = AlreadyVerifiedString;
                    }
                }
                else if (mentionedUsers.Any())                  // Verify mentioned users.
                {
                    result = await VerifyUsersPm(e.Server, mentionedUsers);

                    if (result == PmErrorCode.Undefined)
                    {
                        response = AlreadyVerifiedString;
                    }
                }

                switch (result)
                {
                case PmErrorCode.Success:
                    response = SentString;
                    break;

                case PmErrorCode.Failed:
                    response = FailedPmString;
                    break;

                case PmErrorCode.ThresholdExceeded:
                    response = DidntPmString;
                    break;

                case PmErrorCode.Thrown500:
                    response = DiscordPoopString;
                    break;

                case PmErrorCode.UserNull:
                    response = UserNotFoundString;
                    break;

                case PmErrorCode.Unknown:
                    response = "Unknown error.";
                    break;
                }

                if (mentionedUsers.Any())
                {
                    dbContext.SaveChanges();
                }

                dbContext.Dispose();
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);


            return(commands);
        }
Exemplo n.º 13
0
        public List <Command> Init(IValkyrjaClient iClient)
        {
            this.Client = iClient as ValkyrjaClient;
            List <Command> commands = new List <Command>();

// !restrictAlert
            Command newCommand = new Command("restrictAlert");

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Restrict alert logging to search only one channel. Use with `set #channel` or `reset` argument.";
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.ManPage             = new ManPage("<set #channel | reset>", "`<set #channel>` - Restrict the alert-logging to keep an eye only on this specific #channel.\n\n`<reset>` - Reset the restriction, alert-logging will keep an eye on all the channels.");
            newCommand.OnExecute          += async e => {
                string        response  = "";
                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                ServerConfig  config    = dbContext.ServerConfigurations.AsQueryable().FirstOrDefault(c => c.ServerId == e.Server.Id);
                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    response = "Invalid arguments.\n" + e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId);
                }
                else if (config == null)
                {
                    response = "Server config was not found in the database. Please try again in a few minutes or contact support.";
                }
                else if (e.MessageArgs[0].ToLower() == "reset")
                {
                    config.AlertWhitelistId = 0;
                    response = "Done.";
                    dbContext.SaveChanges();
                }
                else if (e.MessageArgs.Length != 2 || e.MessageArgs[0].ToLower() != "set")
                {
                    response = "Invalid arguments.\n" + e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId);
                }
                else if (e.MessageArgs.Length == 2 && guid.TryParse(e.MessageArgs[1].Trim('<', '#', '>'), out ulong channelid) && e.Server.Guild.GetChannel(channelid) != null)
                {
                    config.AlertWhitelistId = channelid;
                    response = "Done.";
                    dbContext.SaveChanges();
                }
                else
                {
                    response = "Channel not found.";
                }

                dbContext.Dispose();
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);

// !getRole
            newCommand                     = new Command("getRole");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Get a name, id and color of `roleID` or `roleName` parameter.";
            newCommand.ManPage             = new ManPage("<RoleId | roleName>", "`<RoleId | roleName>` - Role to be displayed.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                guid              id         = 0;
                SocketRole        roleFromId = null;
                List <SocketRole> roles      = null;
                if (string.IsNullOrEmpty(e.TrimmedMessage) ||
                    (!(guid.TryParse(e.TrimmedMessage, out id) && (roleFromId = e.Server.Guild.GetRole(id)) != null) &&
                     !(roles = e.Server.Guild.Roles.Where(r => r.Name.ToLower().Contains(e.TrimmedMessage.ToLower())).ToList()).Any()))
                {
                    await e.SendReplySafe("Role not found.");

                    return;
                }

                if (roleFromId != null)
                {
                    roles = new List <SocketRole>();
                    roles.Add(roleFromId);
                }

                StringBuilder response = new StringBuilder();
                foreach (SocketRole role in roles)
                {
                    string hex = BitConverter.ToString(new byte[] { role.Color.R, role.Color.G, role.Color.B }).Replace("-", "");
                    response.AppendLine($"Role: `{role.Name}`\n  Id: `{role.Id}`\n  Position: `{role.Position}`\n  Color: `rgb({role.Color.R},{role.Color.G},{role.Color.B})` | `hex(#{hex})`");
                }

                await e.SendReplySafe(response.ToString());
            };
            commands.Add(newCommand);

// !membersOf
            newCommand                     = new Command("membersOf");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Display a list of members of a role.";
            newCommand.ManPage             = new ManPage("<RoleId | roleName>", "`<RoleId | roleName>` - Members of this role will be printed.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                SocketRole role = e.Server.GetRole(e.TrimmedMessage, out string response);
                if (role == null)
                {
                    await e.SendReplySafe(response);

                    return;
                }

                await e.Server.Guild.DownloadUsersAsync();

                List <string> names = role.Members.Select(u => u.GetUsername()).ToList();
                names.Sort();

                response = names.Count == 0 ? "Nobody has this role." : $"Members of `{role.Name}` are:\n" + names.ToNamesList();
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("listMembers"));

// !createRole
            newCommand                     = new Command("createRole");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Create a role with specified name.";
            newCommand.ManPage             = new ManPage("<roleName>", "`<roleName>` - Name of the new role.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.Message.Channel.SendMessageSafe(ErrorPermissionsString);

                    return;
                }
                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    await e.SendReplySafe("What role? Name? Do you want me to come up with something silly or what?");

                    return;
                }

                RestRole role = await e.Server.Guild.CreateRoleAsync(e.TrimmedMessage, GuildPermissions.None);

                string response = $"Role created: `{role.Name}`\n  Id: `{role.Id}`";
                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);

// !createRoles
            newCommand                     = new Command("createRoles");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Create roles with specified names.";
            newCommand.ManPage             = new ManPage("<roleName1, roleName2, ...>", "`<roleName>` - Name of the new role. Use quotes if you want a name with multiple words/spaces.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.Message.Channel.SendMessageSafe(ErrorPermissionsString);

                    return;
                }
                if (string.IsNullOrEmpty(e.TrimmedMessage))
                {
                    await e.SendReplySafe("Invalid arguments.\n" + e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId));

                    return;
                }

                StringBuilder response = new StringBuilder("Roles created:\n");

                for (int i = 0; i < e.MessageArgs.Length; i++)
                {
                    RestRole role = await e.Server.Guild.CreateRoleAsync(e.MessageArgs[i], GuildPermissions.None);

                    response.AppendLine($"`{role.Id}` | `{role.Name}`");
                }

                await e.SendReplySafe(response.ToString());
            };
            commands.Add(newCommand);

// !createPublicRoles
            newCommand                     = new Command("createPublicRoles");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Create public roles with specified names.";
            newCommand.ManPage             = new ManPage("<groupName> <roleName1, roleName2, ...>", "`<groupName>` - Name of the Role Group under which these roles will be created.\n\n`<roleName>` - Name of the new role. Use quotes if you want a name with multiple words/spaces.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.Message.Channel.SendMessageSafe(ErrorPermissionsString);

                    return;
                }
                if (e.MessageArgs == null || e.MessageArgs.Length < 2)
                {
                    await e.SendReplySafe("Invalid arguments.\n" + e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId));

                    return;
                }

                StringBuilder response = new StringBuilder("Roles created:\n");

                Int64         groupId   = 1;
                ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
                IEnumerable <RoleGroupConfig> roleGroups = dbContext.PublicRoleGroups.AsQueryable().Where(g => g.ServerId == e.Server.Id);
                foreach (RoleGroupConfig group in roleGroups)
                {
                    if (groupId < group.GroupId)
                    {
                        groupId = group.GroupId;
                    }
                }

                RoleGroupConfig roleGroup = new RoleGroupConfig()
                {
                    ServerId  = e.Server.Id,
                    GroupId   = groupId,
                    Name      = e.MessageArgs[0],
                    RoleLimit = 1
                };
                dbContext.PublicRoleGroups.Add(roleGroup);

                bool save = true;
                for (int i = 1; i < e.MessageArgs.Length; i++)
                {
                    try
                    {
                        RestRole role = await e.Server.Guild.CreateRoleAsync(e.MessageArgs[i], GuildPermissions.None);

                        RoleConfig roleConfig = new RoleConfig()
                        {
                            ServerId          = e.Server.Id,
                            RoleId            = role.Id,
                            PermissionLevel   = RolePermissionLevel.Public,
                            PublicRoleGroupId = groupId
                        };
                        dbContext.Roles.Add(roleConfig);

                        response.AppendLine($"`{role.Id}` | `{role.Name}`");
                    }
                    catch (Exception)
                    {
                        save = false;
                        response.AppendLine($"__Something went wrong__ :/");
                        break;
                    }
                }

                if (save)
                {
                    dbContext.SaveChanges();
                }
                dbContext.Dispose();

                await e.SendReplySafe(response.ToString());
            };
            commands.Add(newCommand);

// !prune
            newCommand                     = new Command("prune");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Kicks out all the inactive members.";
            newCommand.ManPage             = new ManPage("<n> [roleIDs] [yes]", "`<n>` - Number of days of user inactivity.\n\n`[roleIDs]` - An optional, whitespace delimited list of role IDs to include in the prune.\n\n`[yes]` - If specified \"yes\" will actually prune, only returns the counts otherwise.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner;
            newCommand.OnExecute          += async e => {
                int n = 0;
                if (e.MessageArgs == null || e.MessageArgs.Length < 1 || !int.TryParse(e.MessageArgs[0], out n))
                {
                    await e.SendReplySafe("Invalid Arguments.\n" + e.Command.ManPage.ToString(e.Server.Config.CommandPrefix + e.CommandId));

                    return;
                }
                bool   prune    = e.MessageArgs.Length > 1 && e.MessageArgs[e.MessageArgs.Length - 1].ToLower() == "yes";
                guid[] roleIDs  = e.MessageArgs.Length > 2 || (!prune && e.MessageArgs.Length > 1) ? e.MessageArgs.Skip(1).TakeWhile(r => guid.TryParse(r, out guid _)).Select(guid.Parse).ToArray() : null;
                string response = "";
                try
                {
                    int count = await e.Server.Guild.PruneUsersAsync(n, !prune, roleIDs);

                    response = prune ? $"I've kicked out `{count}` humans.\n_\\*waves*_" : $"I can kick out `{count}` humans. Should you wish to proceed, append `yes` to the command arguments (you can edit your message) as follows:\n `{e.Server.Config.CommandPrefix + e.CommandId} {e.TrimmedMessage} yes`";
                }
                catch (HttpException exception)
                {
                    await e.Server.HandleHttpException(exception, $"Command failed to prune users in <#{e.Channel.Id}>");

                    response = Utils.HandleHttpException(exception);
                }
                catch (Exception exception)
                {
                    await this.HandleException(exception, "Command prune", e.Server.Id);

                    response = "Unknown error.";
                }

                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);

/*
 * // !createTempRole
 *                      newCommand = new Command("createTempRole");
 *                      newCommand.Type = CommandType.Standard;
 *                      newCommand.Description = "`createTempRole name time` Create a role with specified name, which will be destroyed after specified time (e.g. `7d` or `12h` or `1d12h`)";
 *                      newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
 *                      newCommand.OnExecute += async e => {
 *                              ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
 *                              RoleConfig roleConfig = await CreateTempRole(e, dbContext);
 *                              if( roleConfig != null )
 *                                      dbContext.SaveChanges();
 *                              dbContext.Dispose();
 *                      };
 *                      commands.Add(newCommand);
 *
 * // !createTempPublicRole
 *                      newCommand = new Command("createTempPublicRole");
 *                      newCommand.Type = CommandType.Standard;
 *                      newCommand.Description = "`createTempRole name time` Create a role with specified name, which will be destroyed after specified time (e.g. `7d` or `12h` or `1d12h`) This role will also become a public - use the `join` command to get it.";
 *                      newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
 *                      newCommand.OnExecute += async e => {
 *                              ServerContext dbContext = ServerContext.Create(this.Client.DbConnectionString);
 *                              RoleConfig roleConfig = await CreateTempRole(e, dbContext);
 *                              if( roleConfig != null )
 *                              {
 *                                      roleConfig.PermissionLevel = RolePermissionLevel.Public;
 *                                      dbContext.SaveChanges();
 *                              }
 *                              dbContext.Dispose();
 *                      };
 *                      commands.Add(newCommand);*/

// !createColourRoles
            newCommand                     = new Command("createColourRoles");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Create 9 roles with various colours, you can find emoji representations of these colours in Valhalla - the Valkyrja support server.";
            newCommand.ManPage             = new ManPage("", "");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.SendReplySafe(ErrorPermissionsString);

                    return;
                }

                await e.Server.Guild.CreateRoleAsync("purple", GuildPermissions.None, new Color(180, 136, 209));

                await e.Server.Guild.CreateRoleAsync("pink", GuildPermissions.None, new Color(255, 183, 255));

                await e.Server.Guild.CreateRoleAsync("orange", GuildPermissions.None, new Color(255, 165, 105));

                await e.Server.Guild.CreateRoleAsync("lightOrange", GuildPermissions.None, new Color(255, 186, 158));

                await e.Server.Guild.CreateRoleAsync("lightYellow", GuildPermissions.None, new Color(223, 223, 133));

                await e.Server.Guild.CreateRoleAsync("yellow", GuildPermissions.None, new Color(201, 192, 67));

                await e.Server.Guild.CreateRoleAsync("blue", GuildPermissions.None, new Color(92, 221, 255));

                await e.Server.Guild.CreateRoleAsync("cyan", GuildPermissions.None, new Color(150, 232, 221));

                await e.Server.Guild.CreateRoleAsync("green", GuildPermissions.None, new Color(46, 204, 113));

                await e.SendReplySafe("I've created them roles, but you're gonna have to set them up yourself at <https://valkyrja.app/config> because I don't know the details!\n" +
                                      $"_You can use my colour emojis to set them up as reaction assigned roles. Get them in Valhalla: {GlobalConfig.DiscordInvite}_");
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("createColorRoles"));

// !removeStreamPermission
            newCommand                     = new Command("removeStreamPermission");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Removes Stream permission from all the roles.";
            newCommand.ManPage             = new ManPage("", "");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin;
            newCommand.OnExecute          += async e => {
                if (!e.Server.Guild.CurrentUser.GuildPermissions.ManageRoles)
                {
                    await e.SendReplySafe("I ain't got the permissions.");

                    return;
                }

                int highestRolePosition = 0;
                foreach (SocketRole role in e.Server.Guild.Roles)
                {
                    if (role.Position > highestRolePosition)
                    {
                        highestRolePosition = role.Position;
                    }
                }

                if (e.Server.Guild.CurrentUser.Hierarchy < highestRolePosition)
                {
                    await e.SendReplySafe("I am not the top role in hierarchy. I really have to be on top to disable that thing on all the roles!");

                    return;
                }

                int    exceptions = 0;
                string response   = "Done with exceptions:\n";
                foreach (SocketRole role in e.Server.Guild.Roles.Where(r => r.Position < e.Server.Guild.CurrentUser.Hierarchy))
                {
                    try
                    {
                        await role.ModifyAsync(r => r.Permissions = new Optional <GuildPermissions>(role.Permissions.Modify(stream: false)));
                    }
                    catch (Exception)
                    {
                        response += $"`{role.Name}`\n";
                        if (++exceptions > 5)
                        {
                            response += "...and probably more...";
                            break;
                        }
                    }
                }

                if (exceptions == 0)
                {
                    response = "Done.";
                }

                await e.SendReplySafe(response);
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateAlias("removeGolivePermission"));

            return(commands);
        }
Exemplo n.º 14
0
        public List <Command> Init(IValkyrjaClient iClient)
        {
            this.Client = iClient as ValkyrjaClient <Config>;
            List <Command> commands = new List <Command>();

            this.Client.Events.MessageReceived += OnMessageReceived;
            this.Client.Events.MessageUpdated  += OnMessageUpdated;

// !contact
            Command newCommand = new Command("contact");

            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Create a new modmail thread with the mentioned user.";
            newCommand.ManPage             = new ManPage("<userId>", "`<userId>` - User mention or ID with whom to initiate a discussion.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin | PermissionType.Moderator | PermissionType.SubModerator;
            newCommand.OnExecute          += async e => {
                List <guid> userIds = this.Client.GetMentionedUserIds(e);
                if (string.IsNullOrEmpty(e.TrimmedMessage) || userIds.Count != 1)
                {
                    await e.SendReplySafe("A who?");

                    return;
                }

                ITextChannel channel = await FindOrCreateThread(userIds.First(), true, false);

                if (channel == null)
                {
                    await e.SendReplySafe("Failed to create a channel.");

                    return;
                }

                await e.SendReplySafe($"Thread open: <#{channel.Id}>");
            };
            commands.Add(newCommand);

// !reply
            newCommand                     = new Command("reply");
            newCommand.Type                = CommandType.Standard;
            newCommand.DeleteRequest       = true;
            newCommand.Description         = "Reply in the current thread.";
            newCommand.ManPage             = new ManPage("<message text>", "`<message text>` - Message that will be sent to the user.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin | PermissionType.Moderator | PermissionType.SubModerator;
            newCommand.OnExecute          += async e => {
                if (string.IsNullOrEmpty(e.TrimmedMessage) && (!e.Message.Attachments?.Any() ?? false))
                {
                    await e.SendReplySafe("I can't send an empty message.");

                    return;
                }

                Match match = this.IdRegex.Match(e.Channel.Topic ?? "");
                if (!match.Success || !guid.TryParse(match.Value, out guid userId))
                {
                    await e.SendReplySafe("This does not seem to be a modmail thread. This command can only be used in a modmail thread channel.");

                    return;
                }

                Embed embed = GetMessageEmbed(e.Message);
                await SendModmailPm(e, userId, null, embed);
            };
            commands.Add(newCommand);

// !anonReply
            newCommand                     = new Command("anonReply");
            newCommand.Type                = CommandType.Standard;
            newCommand.DeleteRequest       = true;
            newCommand.Description         = "Reply in the current thread anonymously.";
            newCommand.ManPage             = new ManPage("<message text>", "`<message text>` - Message that will be sent to the user.");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin | PermissionType.Moderator | PermissionType.SubModerator;
            newCommand.OnExecute          += async e => {
                if (string.IsNullOrEmpty(e.TrimmedMessage) && (!e.Message.Attachments?.Any() ?? false))
                {
                    await e.SendReplySafe("I can't send an empty message.");

                    return;
                }

                Match match = this.IdRegex.Match(e.Channel.Topic ?? "");
                if (!match.Success || !guid.TryParse(match.Value, out guid userId))
                {
                    await e.SendReplySafe("This does not seem to be a modmail thread. This command can only be used in a modmail thread channel.");

                    return;
                }

                uint  color = uint.Parse(this.Client.Config.ModmailEmbedColorMods.TrimStart('#'), System.Globalization.NumberStyles.AllowHexSpecifier);
                Embed embed = GetMessageEmbed("Moderators", e.Server.Guild.IconUrl, "Moderator", color, e.Message);
                await SendModmailPm(e, userId, null, embed);
            };
            commands.Add(newCommand);

// !close
            newCommand                     = new Command("close");
            newCommand.Type                = CommandType.Standard;
            newCommand.Description         = "Close the current modmail thread.";
            newCommand.ManPage             = new ManPage("", "");
            newCommand.RequiredPermissions = PermissionType.ServerOwner | PermissionType.Admin | PermissionType.Moderator | PermissionType.SubModerator;
            newCommand.OnExecute          += async e => {
                await CloseThread(e, e.CommandId.ToLower() == "close");

                await e.Message.AddReactionAsync(new Emoji("✅"));
            };
            commands.Add(newCommand);
            commands.Add(newCommand.CreateCopy("silentClose"));

            return(commands);
        }