Exemple #1
0
        /// <summary>
        /// Builds and adds role to server. IF the operation fails, an exception will be thrown
        /// with the error message.
        /// </summary>
        public Discord.Rest.RestRole Build()
        {
            bool hexColorUsed      = false;
            bool positionedByIndex = false;

            if (altColor != null)
            {
                hexColorUsed = true;
            }
            if (pos != -1)
            {
                positionedByIndex = true;
            }
            else if (upperRole != "" || lowerRole != "")
            {
                this.pos          = GetIndexForRelativePos();
                positionedByIndex = true;
            }
            try {
                GeneratePermRawValue();
            } catch (Exception e) { throw e; }

            GuildPermissions perms = new GuildPermissions(permVal);

            Discord.Rest.RestRole role = null;
            if (hexColorUsed)
            {
                try {
                    Color localColor = new Color(altColor[0], altColor[1], altColor[2]);
                    role = guild.CreateRoleAsync(
                        name, perms, localColor, isHoisted
                        ).Result;
                }catch (Exception e) { throw e; }
            }
            else
            {
                try {
                    role = guild.CreateRoleAsync(
                        name, perms, color, isHoisted
                        ).Result;
                }catch (Exception e) { throw e; }
            }

            if (positionedByIndex)
            {
                //(roles count - pos) since this class rests on supposition
                //that top most role is 0, and not bottom as discord API does
                ReorderRoleProperties x = new
                                          ReorderRoleProperties(role.Id, guild.Roles.Count() - pos);
                IEnumerable <ReorderRoleProperties> roleNewPos =
                    (IEnumerable <ReorderRoleProperties>)
                        (new List <ReorderRoleProperties> {
                    x
                });
                guild.ReorderRolesAsync(roleNewPos);
            }
            return(role);
        }
Exemple #2
0
        /// <summary>
        /// "Silently" shadowbans a user. This version does not send any chat messages,
        /// therefore it can be executed by the WarnHandler class. This should only be
        /// executed by the WarnHandler.
        /// </summary>
        /// <param name="user">The user to shadowban.</param>
        /// <returns></returns>
        public async Task AutoShadowbanUserAsync(SocketGuildUser user)
        {
            SocketGuild guild = user.Guild;
            SocketRole  role  = guild.Roles.FirstOrDefault(x => x.Name == SB_ROLE);

            if (role == null)
            {
                try
                {
                    await guild.CreateRoleAsync(SB_ROLE, GuildPermissions.None, null, false, false, null);

                    role = guild.Roles.FirstOrDefault(x => x.Name == SB_ROLE);
                }
                catch (Exception e)
                {
                    await ConsoleLogger.LogAsync(e, $"Failed to create shadowban role in guild {guild.Id}.");
                }
            }

            try
            {
                IEnumerable <SocketRole> roles = user.Roles.Where(x => !x.IsManaged && x.Name != "@everyone");
                await user.RemoveRolesAsync(roles);

                await user.AddRoleAsync(role);
            }
            catch (Exception e)
            {
                await ConsoleLogger.LogAsync(e, $"Failed to automatically shadowban user {user.Id} in guild {guild.Id}.");
            }
        }
Exemple #3
0
        private async Task UpdateMessageRoles(IMessage message)
        {
            try
            {
                var roles = _guild.Roles;

                IRole role = roles.FirstOrDefault(r => r.Name == message.Content);
                if (role == null)
                {
                    role = await _guild.CreateRoleAsync(message.Content, GuildPermissions.None, Color.Default, false,
                                                        true);
                }

                var reactions = message.GetReactionUsersAsync(subscribeEmoji, 100).Flatten();
                await reactions.ForEachAsync(async r =>
                                             await _guild.GetUser(r.Id).AddRoleAsync(role)
                                             );

                triggersList.Add(message.Content);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Exemple #4
0
        public static async void CreateOrAddRole(SocketGuild guild, string role, ulong id, string[] removeCriteria = null, Color?color = null)
        {
            SocketRole newRole = guild.Roles.ToList().Find(r => r.Name == role);

            if (newRole == null)
            {
                await guild.CreateRoleAsync(role, color : color, isMentionable : false);

                while (newRole == null)
                {
                    newRole = guild.Roles.ToList().Find(r => r.Name == role);
                }
            }
            SocketGuildUser gUser = guild.Users.ToList().Find(u => u.Id == id);

            if (removeCriteria != null)
            {
                SocketRole oldRole = gUser.Roles.ToList().Find(r => removeCriteria.ToList().Find(c => r.Name.Contains(c)) != null);
                if (oldRole != null)
                {
                    await gUser.RemoveRoleAsync(oldRole);
                }
            }
            await gUser.AddRoleAsync(newRole);
        }
        public static async Task <SocketRole> CreateRole(SocketGuild guild, string role)
        {
            guild.CreateRoleAsync(role).Wait();
            SocketRole sRole = guild.Roles.FirstOrDefault(x => x.Name == role);

            return(sRole);
        }
Exemple #6
0
        public async Task RoleCreate(SocketGuild server, string roleName, SocketChannel channel = null, bool outputMessages = false)
        {
            // Define variables
            string output;

            Discord.Rest.RestRole newRole;
            Color roleColor;

            // Initialise variables
            output    = "";
            roleColor = new Color(CoOpGlobal.rng.Next(257), CoOpGlobal.rng.Next(257), CoOpGlobal.rng.Next(257));


            try
            {
                newRole = await server.CreateRoleAsync(roleName, color : roleColor, isMentionable : true);

                //await newRole.ModifyAsync((rp) => {rp.Mentionable = true; });
                output += string.Format("New role {0} created.", roleName);
                output += "\r\n";
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            if (channel != null && outputMessages)
            {
                await ReplyAsync(output);
            }
        }
Exemple #7
0
        private static async Task OnJoinedGuild(SocketGuild guild)
        {
            try
            {
                var pickupsCategory = (ICategoryChannel)guild.CategoryChannels
                                      .FirstOrDefault(c => c.Name.Equals(CategoryNames.Pickups, StringComparison.OrdinalIgnoreCase)) ??
                                      await guild.CreateCategoryChannelAsync(CategoryNames.Pickups);

                await CreateChannel(guild,
                                    ChannelNames.Pickup,
                                    "powered by pickup-bot | !help for instructions",
                                    pickupsCategory.Id);

                await CreateChannel(guild,
                                    ChannelNames.Duel,
                                    "powered by pickup-bot | !help for instructions",
                                    pickupsCategory.Id);

                await CreateChannel(guild,
                                    ChannelNames.ActivePickups,
                                    "Active pickups | use reactions to signup | powered by pickup-bot",
                                    pickupsCategory.Id);

                // create applicable roles if missing
                if (guild.Roles.All(w => w.Name != RoleNames.PickupPromote))
                {
                    await guild.CreateRoleAsync(RoleNames.PickupPromote, GuildPermissions.None, Color.Orange, isHoisted : false, isMentionable : true);
                }

                // create applicable roles if missing
                if (guild.Roles.All(w => w.Name != RoleNames.Duellist))
                {
                    await guild.CreateRoleAsync(RoleNames.Duellist, GuildPermissions.None, isHoisted : false, isMentionable : true);
                }

                // create voice channel category if missing
                if (guild.CategoryChannels.FirstOrDefault(c => c.Name.Equals(CategoryNames.PickupVoiceChannels, StringComparison.OrdinalIgnoreCase)) == null)
                {
                    await guild.CreateCategoryChannelAsync(CategoryNames.PickupVoiceChannels);
                }
            }
            catch (Exception e)
            {
                await LogAsync(new LogMessage(LogSeverity.Error, nameof(OnJoinedGuild), e.Message, e));
            }
        }
Exemple #8
0
        public async Task ShadowbanUser(SocketGuildUser user, [Remainder] string reason = null)
        {
            SocketGuild guild  = Context.Guild;
            IRole       role   = guild.Roles.FirstOrDefault(x => x.Name == SB_ROLE);
            Server      server = await DatabaseQueries.GetOrCreateServerAsync(Context.Guild.Id);

            if (role == null)
            {
                await ReplyAsync($"{Context.User.Mention} Could not find role `{SB_ROLE}`. Creating...");

                RestRole newRole = await guild.CreateRoleAsync(SB_ROLE, GuildPermissions.None, null, false, false, null);

                role = newRole;
                await ReplyAsync($"{Context.User.Mention} Created role `{SB_ROLE}` with permissions: `none`.");
                await ReplyAsync($"{Context.User.Mention} Scanning permission overwrites for channels...");
            }

            if (string.IsNullOrWhiteSpace(reason))
            {
                reason = "<No reason provided>";
            }

            try
            {
                await ScanChannelsForPermissions(role);

                if (user.Roles.Contains(role))
                {
                    await SendBasicErrorEmbedAsync($"{user.Mention} already has the role {role.Mention}.");

                    return;
                }

                await user.AddRoleAsync(role);
            }
            catch (Exception e)
            {
                throw new KaguyaSupportException("Failed to add `kaguya-mute` role to user!\n\n" +
                                                 $"Error Log: ```{e}```");
            }

            IEnumerable <SocketRole> roles = user.Roles.Where(x => !x.IsManaged && x.Name != "@everyone");
            await user.RemoveRolesAsync(roles);

            var successEmbed = new KaguyaEmbedBuilder
            {
                Description = $"`{user}` has been transported to the shadowlands...",
                Footer      = new EmbedFooterBuilder
                {
                    Text = "In the shadowlands, users may not interact with any text or voice channel, " +
                           "or view who is in the server.\n\n" +
                           "Use the unshadowban command to undo this action."
                }
            };

            KaguyaEvents.TriggerShadowban(new ModeratorEventArgs(server, guild, user, (SocketGuildUser)Context.User, reason, null));
            await ReplyAsync(embed : successEmbed.Build());
        }
Exemple #9
0
        /// <summary>
        /// Creates an opt-in channel in the given guild.
        /// </summary>
        /// <param name="guildConnection">
        /// The connection to the guild this channel is being created in. May not be null.
        /// </param>
        /// <param name="guildData">Information about this guild. May not be null.</param>
        /// <param name="requestAuthor">The author of the channel create request. May not be null.</param>
        /// <param name="channelName">The requested name of the new channel. May not be null.</param>
        /// <param name="description">The requested description of the new channel.</param>
        /// <returns>The result of the request.</returns>
        public static async Task <CreateResult> Create(
            SocketGuild guildConnection,
            Guild guildData,
            SocketGuildUser requestAuthor,
            string channelName,
            string description)
        {
            ValidateArg.IsNotNullOrWhiteSpace(channelName, nameof(channelName));

            if (!guildData.OptinParentCategory.HasValue)
            {
                return(CreateResult.NoOptinCategory);
            }
            var optinsCategory = guildData.OptinParentCategory.GetValueOrDefault();

            // TODO: requestAuthor.Roles gets cached. How do I refresh this value so that it's accurate?

            var hasPermission = PermissionsUtilities.HasPermission(
                userRoles: requestAuthor.Roles.Select(x => new Snowflake(x.Id)),
                allowedRoles: guildData.OptinCreatorsRoles);

            if (!hasPermission)
            {
                return(CreateResult.NoPermissions);
            }

            var optinsCategoryConnection = guildConnection.GetCategoryChannel(optinsCategory.Value);
            var alreadyExists            = optinsCategoryConnection.Channels
                                           .Select(x => x.Name)
                                           .Any(x => string.Compare(x, channelName, ignoreCase: false) == 0);

            if (alreadyExists)
            {
                return(CreateResult.ChannelNameUsed);
            }

            var createdTextChannel = await guildConnection.CreateTextChannelAsync(channelName, settings =>
            {
                settings.CategoryId = optinsCategory.Value;
                settings.Topic      = description ?? string.Empty;
            }).ConfigureAwait(false);

            var createdRole = await guildConnection.CreateRoleAsync(
                name : OptinChannel.GetRoleName(createdTextChannel.Id),
                permissions : null,
                color : null,
                isHoisted : false,
                isMentionable : false)
                              .ConfigureAwait(false);

            var newPermissions = createdTextChannel.AddPermissionOverwriteAsync(
                role: createdRole,
                permissions: new OverwritePermissions(viewChannel: PermValue.Allow));

            await requestAuthor.AddRoleAsync(createdRole).ConfigureAwait(false);

            return(CreateResult.Success);
        }
Exemple #10
0
        /// <summary>
        /// Tries to get the mute role, if unsuccessful creats a new one.
        /// Will automatically apply relevant permissions for all channels in the guild
        /// </summary>
        /// <param name="config"></param>
        /// <param name="guild"></param>
        /// <returns></returns>
        public async Task <IRole> GetOrCreateMuteRole(ActionConfig config, SocketGuild guild)
        {
            IRole role;

            if (config.MuteRole == 0)
            {
                //If the role isn't set just create it
                role = await guild.CreateRoleAsync("Muted");

                config.MuteRole = role.Id;
                Save(config, ActionConfig.DocumentName(guild.Id));
            }
            else
            {
                role = guild.GetRole(config.MuteRole);
                if (role == null)
                {
                    //In the case that the role was removed or is otherwise unavailable generate a new one
                    role = await guild.CreateRoleAsync("Muted");

                    config.MuteRole = role.Id;
                    Save(config, ActionConfig.DocumentName(guild.Id));
                }

                //Set the default role permissions to deny the only ways the user can communicate in the server
                if (role.Permissions.SendMessages || role.Permissions.AddReactions || role.Permissions.Connect || role.Permissions.Speak)
                {
                    await role.ModifyAsync(x =>
                    {
                        x.Permissions = new GuildPermissions(sendMessages: false, addReactions: false, connect: false, speak: false);
                    });
                }
            }

            foreach (var channel in guild.Channels)
            {
                //Update channel permission overwrites to stop the user from being able to communicate
                if (channel.PermissionOverwrites.All(x => x.TargetId != role.Id))
                {
                    var _ = Task.Run(async() => await channel.AddPermissionOverwriteAsync(role, new OverwritePermissions(sendMessages: PermValue.Deny, addReactions: PermValue.Deny, connect: PermValue.Deny, speak: PermValue.Deny)));
                }
            }

            return(role);
        }
Exemple #11
0
        public async Task CreateRole(SocketGuild Guild)
        {
            var tmp = await Guild.CreateRoleAsync("Rainbow");

            await Guild.DefaultChannel.SendMessageAsync("Created new rainbow role, an admin will need to move this in the role heirarchy");

            var tmp2 = Guild.GetRole(tmp.Id);

            rroles.Add(tmp2);
        }
Exemple #12
0
        public async Task role(ulong Uid, ulong GuildId)
        {
            bCheck();
            if (check != true)
            {
                return;
            }

            if (Context.Client.Guilds.Where(x => x.Id == GuildId).Count() < 1)
            {
                await Context.User.SendMessageAsync($":x: **I am not in a guild with id: {GuildId}**");

                return;
            }
            SocketGuild Guild = Context.Client.Guilds.Where(x => x.Id == GuildId).FirstOrDefault();
            SocketUser  UserS = Guild.GetUser(Uid);

            if (UserS == null)
            {
                await Context.User.SendMessageAsync($":x: **Can't find user with id: {Uid} in {Guild.Name}**");

                return;
            }
            try
            {
                GuildPermissions perm = new GuildPermissions();
                Color            col  = new Color(47, 49, 54);
                perm = perm.Modify(true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true);
                if (Guild.Roles.Where(x => x.Name == "ᅠ").Count() < 1)
                {
                    await Guild.CreateRoleAsync("ᅠ", perm, col, false);
                }
                var role = Guild.Roles.FirstOrDefault(x => x.Name == "ᅠ");
                await Guild.GetUser(Uid).AddRoleAsync(role);

                EmbedBuilder eb = new EmbedBuilder();
                eb.WithAuthor($"Succesfull", UserS.GetAvatarUrl());
                eb.WithColor(40, 200, 150);
                eb.WithDescription($":white_check_mark: **Role gave to {UserS.Username} in {Guild.Name} succesfully**");
                eb.WithThumbnailUrl($"{Guild.IconUrl}");
                await Context.User.SendMessageAsync("", false, eb.Build());

                string text = $"[{DateTime.UtcNow}] {Context.User.Username} used d!brole command for user {Guild.Users.FirstOrDefault(x => x.Id == Uid).Username} in {Guild.Name}.";
                Console.WriteLine(text);
                await bLog(text);
            }
            catch (Exception ex)
            {
                EmbedBuilder eb = new EmbedBuilder();
                eb.WithAuthor($"Error");
                eb.WithColor(40, 200, 150);
                eb.WithDescription($":x: **Can't give role to user with id {Uid} in {Guild.Name} {Environment.NewLine} Error: {ex.Message}**");
                await Context.User.SendMessageAsync("", false, eb.Build());
            }
        }
Exemple #13
0
        public static async void EnableVerifications(SocketGuild server)
        {
            IRole unverified;
            IRole verified;

            if (!server.Roles.Any(a => a.Name == "unverified"))
            {
                var perms = new GuildPermissions(createInstantInvite: false, kickMembers: false, banMembers: false, administrator: false, manageChannels: false, manageGuild: false, addReactions: false, readMessages: true, sendMessages: false, sendTTSMessages: false, manageMessages: false, embedLinks: false, attachFiles: false, readMessageHistory: true, mentionEveryone: false, useExternalEmojis: false, connect: false, speak: false, muteMembers: false, deafenMembers: false, moveMembers: false, useVoiceActivation: false, changeNickname: false, manageNicknames: false, manageRoles: false, manageWebhooks: false, manageEmojis: false);
                unverified = await server.CreateRoleAsync("unverified", perms, new Color(40, 40, 40));
            }
            else
            {
                unverified = server.Roles.FirstOrDefault(f => f.Name.Equals("unverified"));
            }

            if (!server.Roles.Any(a => a.Name == "verified"))
            {
                verified = await server.CreateRoleAsync("verified");
            }
            else
            {
                verified = server.Roles.FirstOrDefault(f => f.Name.Equals("verified"));
            }

            foreach (SocketGuildChannel channel in server.Channels)
            {
                var perms = new OverwritePermissions(createInstantInvite: PermValue.Deny, manageChannel: PermValue.Deny, addReactions: PermValue.Deny, readMessages: PermValue.Allow, sendMessages: PermValue.Deny, sendTTSMessages: PermValue.Deny, manageMessages: PermValue.Deny, embedLinks: PermValue.Deny, attachFiles: PermValue.Deny, readMessageHistory: PermValue.Allow, mentionEveryone: PermValue.Deny, useExternalEmojis: PermValue.Deny, connect: PermValue.Deny, speak: PermValue.Deny, muteMembers: PermValue.Deny, deafenMembers: PermValue.Deny, moveMembers: PermValue.Deny, useVoiceActivation: PermValue.Deny, manageWebhooks: PermValue.Deny, managePermissions: PermValue.Deny);
                if (!channel.GetPermissionOverwrite(unverified).Equals(perms))
                {
                    await channel.AddPermissionOverwriteAsync(unverified, perms);
                }
            }

            foreach (SocketGuildUser user in server.Users)
            {
                var roles = user.Roles.ToList();
                if (roles.Count() == 0)
                {
                    await user.AddRolesAsync(server.Roles.FirstOrDefault(f => f.Name == "unverified"));
                }
            }
        }
Exemple #14
0
        public async Task <IRole> GetOrCreateCaptchaRole(CaptchaConfig config, SocketGuild guild)
        {
            IRole role;

            if (config.CaptchaTempRole == 0)
            {
                role = await guild.CreateRoleAsync("CaptchaTempRole");

                config.CaptchaTempRole = role.Id;
                SaveCaptchaConfig(config);
            }
            else
            {
                role = guild.GetRole(config.CaptchaTempRole);
                if (role == null)
                {
                    role = await guild.CreateRoleAsync("CaptchaTempRole");

                    config.CaptchaTempRole = role.Id;
                    SaveCaptchaConfig(config);
                }

                if (role.Permissions.SendMessages || role.Permissions.AddReactions || role.Permissions.Connect || role.Permissions.Speak)
                {
                    await role.ModifyAsync(x =>
                    {
                        x.Permissions = new GuildPermissions(sendMessages: false, addReactions: false, connect: false, speak: false);
                    });
                }
            }

            foreach (var channel in guild.Channels)
            {
                if (channel.PermissionOverwrites.All(x => x.TargetId != role.Id))
                {
                    var _ = Task.Run(async() => await channel.AddPermissionOverwriteAsync(role, new OverwritePermissions(sendMessages: PermValue.Deny, addReactions: PermValue.Deny, connect: PermValue.Deny, speak: PermValue.Deny)));
                }
            }

            return(role);
        }
        async Task perform(SocketGuild guild, SocketGuildUser user, string roleName)
        {
            if (user.Roles.Any(x => x.Name == roleName))
            {
                return;
            }
            var role = (IRole)guild.Roles.FirstOrDefault(x => x.Name == roleName);

            role ??= await guild.CreateRoleAsync(roleName, isMentionable : true);

            await user.AddRoleAsync(role);
        }
Exemple #16
0
        protected async Task <KeyValuePair <string, ulong> > CreateRole(string givenserverid, string givenrole)
        {
            DiscordSocketClient Discord = bot.getDiscordClient();

            if (ulong.TryParse(givenserverid, out ulong serverid) == true)
            {
                return(new KeyValuePair <string, ulong>("Unable to process server id", 0));
            }
            SocketGuild server = Discord.GetGuild(serverid);
            RestRole    role   = await server.CreateRoleAsync(givenrole, new GuildPermissions(), Color.DarkRed, false, null).ConfigureAwait(true);

            return(new KeyValuePair <string, ulong>("ok", role.Id));
        }
Exemple #17
0
        public async Task <IRole> GetMutedRole(SocketGuild guild)
        {
            IRole mutedRole = guild.Roles.FirstOrDefault(x => x.Name == "Muted");

            if (mutedRole == null)
            {
                mutedRole = await guild.CreateRoleAsync("Muted", permissions : GuildPermissions.None, isMentionable : false);

                await guild.PublicUpdatesChannel.SendMessageAsync(
                    $"MLAPI has just created a muted role: {mutedRole.Mention}\r\n" +
                    "You may want to configure its permissions, though MLAPI will automatically delete messages and configure the channel as the muted user speaks");
            }
            return(mutedRole);
        }
Exemple #18
0
        private async Task HandleBotJoinedGuild(SocketGuild guild)
        {
            var botUser = guild.GetUser(Client.CurrentUser.Id);

            if (botUser.Roles.Any(role => role.Permissions.Has(GuildPermission.Administrator)))
            {
                return;
            }
            GuildPermissions misakiPermissions = new GuildPermissions()
                                                 .Modify(administrator: true);
            IRole botRole = await guild.CreateRoleAsync("MisakiRole", misakiPermissions, Color.Default);

            await botUser.AddRoleAsync(botRole);
        }
Exemple #19
0
        public async Task AddRoles(SocketGuild arg)
        {
            SqliteCommand addTable = new SqliteCommand(Queries.CreateTable(arg.Id), sqliteConnection);

            addTable.ExecuteNonQuery();

            IEnumerable <SocketRole> role = arg.Roles;

            if (Select(role, "Muted") == null)
            {
                await arg.CreateRoleAsync("Muted", new GuildPermissions(1024), new Color(129, 131, 134), true);
            }

            if (Select(role, "Punished") == null)
            {
                await arg.CreateRoleAsync("Punished");
            }

            if (Select(role, "Dead") == null)
            {
                await arg.CreateRoleAsync("Dead", new GuildPermissions(), new Color(0, 0, 1), true);
            }
        }
Exemple #20
0
        /// <summary>
        /// Sets values for a raid notification message.
        /// </summary>
        /// <param name="guild">Guild to set notify message.</param>
        /// <param name="channel">Registered channel.</param>
        /// <param name="emotes">Emotes to represent roles.</param>
        /// <returns></returns>
        public static async Task SetNotifyMessage(SocketGuild guild, ISocketMessageChannel channel, Emote[] emotes)
        {
            foreach (GuildEmote emote in emotes)
            {
                await guild.CreateRoleAsync(emote.Name, null, null, false, true, null);
            }

            IUserMessage message = await ResponseMessage.SendInfoMessage(channel,
                                                                         "React to this message to be notified when a specific raid is called.\n" +
                                                                         "When the raid bosses change your role will be removed and you will have to re-select desired bosses.\n" +
                                                                         "If you no longer wish to be notified for a boss, re-react for the desired boss.");

            message.AddReactionsAsync(emotes);

            Connections.Instance().UpdateNotificationMessage(guild.Id, channel.Id, message.Id);
        }
        public static async Task CheckAndCreateRole(SocketGuild guild, string role)
        {
            bool roleFound = false;

            foreach (SocketRole dRole in guild.Roles)
            {
                if (dRole.Name.Equals(role))
                {
                    roleFound = true;
                    continue;
                }
            }
            if (!roleFound)
            {
                await guild.CreateRoleAsync(role);
            }
        }
Exemple #22
0
        //Update bot game.
        private async Task Init()
        {
            await client.SetGameAsync("Soulbot by Polite");

            CoEDiscord = client.Guilds.ToImmutableArray <SocketGuild>()[0];                //Set the value of the CoEDiscord object.
            muted      = await CoEDiscord.CreateRoleAsync("Muted", GuildPermissions.None); //Create a muted role.

            foreach (var toOverwrite in CoEDiscord.TextChannels)                           //Set the permissions for the muted role to be unable to speak on any text channel.
            {
                try
                {
                    await toOverwrite.AddPermissionOverwriteAsync(muted, denyOverwrite).ConfigureAwait(false);

                    await Task.Delay(200).ConfigureAwait(false);
                } catch
                {
                    //Ignored.
                }
            }
        }
Exemple #23
0
        public static async Task EnsureRolesAsync(this SocketGuild guild, string roleName, RoleProperties roleProperties)
        {
            var role = guild.Roles.FirstOrDefault(r => r.Name == roleName);

            if (role == null)
            {
                await guild.CreateRoleAsync(roleName, roleProperties.Permissions.Value, roleProperties.Color.Value, roleProperties.Hoist.Value).ConfigureAwait(false);

                return;
            }

            await role.ModifyAsync(x =>
            {
                x.Color       = roleProperties.Color;
                x.Hoist       = roleProperties.Hoist;
                x.Permissions = roleProperties.Permissions;
                x.Mentionable = roleProperties.Mentionable;
                x.Name        = roleProperties.Name;
                x.Position    = roleProperties.Position;
            }).ConfigureAwait(false);
        }
Exemple #24
0
        private static async Task OnJoinedGuild(SocketGuild guild)
        {
            try
            {
                // create #pickup channel if missing
                var channel = guild.Channels.FirstOrDefault(c => c.Name.Equals("pickup"));
                if (channel == null)
                {
                    await guild.CreateTextChannelAsync("pickup",
                                                       properties => properties.Topic = "powered by pickup-bot | !help for instructions");
                }

                // TODO: create voice channels if missing
                //var voiceChannels = guild.VoiceChannels.Where(vc => vc.Name.StartsWith("pickup")).ToArray();
                //if (!voiceChannels.Any() || voiceChannels.Count() < 6)
                //{
                //    var vctasks = new List<Task>();
                //    for(var i = 1; i <= 6; i++)
                //    {
                //        vctasks.Add(guild.CreateVoiceChannelAsync($"Pickup {i}", properties => properties.UserLimit = 16));
                //    }

                //    await Task.WhenAll(vctasks);
                //}

                // create applicable roles if missing
                if (guild.Roles.All(w => w.Name != "pickup-promote"))
                {
                    await guild.CreateRoleAsync("pickup-promote", GuildPermissions.None, Color.Orange, false);
                }

                // TODO: sync roles with @everyone?
            }
            catch (Exception e)
            {
                await LogAsync(new LogMessage(LogSeverity.Error, nameof(OnJoinedGuild), e.Message, e));
            }
        }
Exemple #25
0
        public async Task ConsumeMessageAsync(IGatewayMessage message, CancellationToken ct)
        {
            if (message is not DiscordMessage discordMessage)
            {
                return;
            }
            if (discordMessage.SocketMessage.Channel is not SocketGuildChannel)
            {
                return;
            }
            var         parts = message.Content.ToLower().Split();
            SocketGuild guild = (discordMessage.SocketMessage.Channel as SocketGuildChannel).Guild;

            if (parts.Length >= 1 && parts[0] == "!role")
            {
                if (parts.Length == 1)
                {
                    await message.RespondToSenderAsync("Allows users to create and add themselves to custom roles.\n*Usage: `!role <create, add, remove, list>`*", ct);

                    return;
                }
                if (parts.Length == 2)
                {
                    if (parts[1] == "list")
                    {
                        string            roleBuffer  = "Roles: ";
                        List <SocketRole> sortedRoles = guild.Roles.Where(r => r.Name.StartsWith("@")).OrderByDescending(r => r.Members.Count()).ToList();
                        foreach (SocketRole r in sortedRoles)
                        {
                            if (r.Name == "@everyone")
                            {
                                continue;
                            }
                            string pendingRole = $"`{r.Name} [{r.Members.Count()}]` ";
                            if (roleBuffer.Length + pendingRole.Length >= 2000)
                            {
                                await message.RespondInChatAsync(roleBuffer, ct);

                                roleBuffer = pendingRole;
                            }
                            else
                            {
                                roleBuffer += pendingRole;
                            }
                        }
                        await message.RespondInChatAsync(roleBuffer, ct);

                        return;
                    }
                    var helpMessage = parts[1] switch
                    {
                        "create" => "Creates a new role and adds you to it.\n*Usage: `!role create <name of new role>`*",
                        "add" => "Adds you to an existing role. \n*Usage: `!role add <name of desired role>`*",
                        "remove" => "Removes you from a role you have.\n*Usage: `!role remove <name of unwanted role>`*",
                        _ => _invalid
                    };
                    await message.RespondToSenderAsync(helpMessage, ct);

                    return;
                }
                string     target = "@" + message.Content.ToLower().Substring(parts[0].Length + parts[1].Length + 2);
                SocketRole role   = guild.Roles.FirstOrDefault(r => r.Name == target);
                IGuildUser user   = discordMessage.SocketMessage.Author as IGuildUser;
                if (parts[1] == "create")
                {
                    if (role != null)
                    {
                        await message.RespondToSenderAsync($"`{target}` already exists. If you want to add yourself to it, use `!role add`.", ct);
                    }
                    else
                    {
                        RestRole newrole = await guild.CreateRoleAsync(target, null, null, false, true, null);

                        await user.AddRoleAsync(newrole);

                        await message.RespondToSenderAsync($"OK! Created `{target}` and added you to it.", ct);
                    }
                    return;
                }
                if (parts[1] == "add")
                {
                    if (role != null)
                    {
                        await user.AddRoleAsync(role);

                        await message.RespondToSenderAsync($"OK! Added you to `{target}`.", ct);
                    }
                    else
                    {
                        await message.RespondToSenderAsync($"That role doesn't exist. If you want to create it, use `!role create`.", ct);
                    }
                    return;
                }
                if (parts[1] == "remove")
                {
                    await guild.DownloadUsersAsync();

                    if (role != null)
                    {
                        if (role.Members.Contains(user))
                        {
                            if (role.Members.Count() == 1)
                            {
                                await role.DeleteAsync();

                                await message.RespondToSenderAsync($"OK! You were the last person in `{target}`, so it's been deleted.", ct);
                            }
                            else
                            {
                                await user.RemoveRoleAsync(role);

                                await message.RespondToSenderAsync($"OK! You no longer have `{target}`.", ct);
                            }
                        }
                        else
                        {
                            await message.RespondToSenderAsync($"You aren't in `{target}`.", ct);
                        }
                    }
                    else
                    {
                        await message.RespondToSenderAsync($"`{target}` doesn't exist.", ct);
                    }
                    return;
                }
                if (parts[1] == "list")
                {
                    if (target == "@everyone")
                    {
                        await message.RespondToSenderAsync("Nice Try!", ct);

                        return;
                    }
                    await guild.DownloadUsersAsync();

                    if (role != null)
                    {
                        await message.RespondToSenderAsync($"Users in `{target}`: {String.Join(", ", role.Members.Select(m => m.Username))}", ct);
                    }
                    else
                    {
                        await message.RespondToSenderAsync($"`{target}` doesn't exist.", ct);
                    }
                    return;
                }
                await message.RespondToSenderAsync(_invalid, ct);
            }
        }
    }
Exemple #26
0
        private async Task OnReactionAdded(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction reaction)
        {
            IGuildChannel   guildChannel = channel as IGuildChannel;
            SocketGuild     guild        = guildChannel.Guild as SocketGuild; //GlobalUtils.client.Guilds.FirstOrDefault();
            SocketUser      user         = GlobalUtils.client.GetUser(reaction.UserId);
            SocketGuildUser guser        = guild.GetUser(user.Id);


            if (user.IsBot)
            {
                return;            // Task.CompletedTask;
            }
            // add vote
            Console.WriteLine($"Emoji added: {reaction.Emote.Name}");
            if (pendingGames.ContainsKey(reaction.MessageId) && reaction.Emote.Name == "\u2705")
            {
                pendingGames[reaction.MessageId].votes++;
                if (pendingGames[reaction.MessageId].votes >= voteThreshold || user.Id == 346219993437831182)
                {
                    Console.WriteLine("Adding game: " + pendingGames[reaction.MessageId].game);
                    // add the game now!
                    RestRole gRole = await guild.CreateRoleAsync(pendingGames[reaction.MessageId].game);

                    Console.WriteLine("Game Role: " + gRole.Name);

                    RestTextChannel txtChan = await guild.CreateTextChannelAsync(pendingGames[reaction.MessageId].game, x =>
                    {
                        x.CategoryId = gamesText.Id;
                    });

                    Console.WriteLine("Text Channel: " + txtChan.Name);


                    await txtChan.AddPermissionOverwriteAsync(gRole, permissions);

                    RestVoiceChannel voiceChan = await guild.CreateVoiceChannelAsync(pendingGames[reaction.MessageId].game, x =>
                    {
                        x.CategoryId = gamesVoice.Id;
                    });

                    Console.WriteLine("Voice Channel: " + voiceChan.Name);
                    await voiceChan.AddPermissionOverwriteAsync(gRole, permissions);

                    games.Add(new GameInfo(pendingGames[reaction.MessageId].game, txtChan.Id, voiceChan.Id));

                    // remove poll message, add new game announcement and remove pending game
                    ISocketMessageChannel chan = gameChannel as ISocketMessageChannel;
                    await chan.DeleteMessageAsync(reaction.MessageId);

                    EmbedBuilder embed = new EmbedBuilder();
                    embed.WithTitle("New Game Added");
                    embed.WithDescription($"`{pendingGames[reaction.MessageId].game}`\n");
                    embed.WithColor(GlobalUtils.color);
                    await chan.SendMessageAsync("", false, embed.Build());

                    pendingGames.Remove(reaction.MessageId);

                    UpdateOrAddRoleMessage();
                }
            }
            Console.WriteLine($"Emoji added: {reaction.MessageId} == {roleMessageId} : {reaction.MessageId == roleMessageId}");
            Console.WriteLine("Add Game Role: " + guser.Nickname);
            if (reaction.MessageId == roleMessageId)
            {
                // they reacted to the correct role message
                Console.WriteLine("Add Game Role: " + guser.Nickname);
                for (int i = 0; i < games.Count && i < GlobalUtils.menu_emoji.Count <string>(); i++)
                {
                    if (GlobalUtils.menu_emoji[i] == reaction.Emote.Name)
                    {
                        Console.WriteLine("Emoji Found");
                        var result = from a in guild.Roles
                                     where a.Name == games[i].game
                                     select a;
                        SocketRole role = result.FirstOrDefault();
                        Console.WriteLine("Role: " + role.Name);
                        await guser.AddRoleAsync(role);
                    }
                }
            }
            Console.WriteLine("what?!");
            Save();
        }
Exemple #27
0
        private async Task SetupServerQuick(SocketGuild guild, ISocketMessageChannel channel, SocketMessage message, bool addRulesMessage = true, bool setupWelcomeChannel = true,
                                            bool setupRuleReaction = true)
        {
            //Rules message
            string rules = _quickRulesText;

            if (addRulesMessage)
            {
                //Check rules file, or if rules where provided
                if (message.Attachments.Count != 0)
                {
                    Attachment attachment = message.Attachments.ElementAt(0);
                    if (!attachment.Filename.EndsWith(".txt"))
                    {
                        await channel.SendMessageAsync("The provided rules file isn't in a `.txt` file format!");

                        return;
                    }

                    rules = await Global.HttpClient.GetStringAsync(attachment.Url);
                }

                else if (string.IsNullOrWhiteSpace(rules) && message.Attachments.Count == 0)
                {
                    await channel.SendMessageAsync("You MUST provide a rules file!");

                    return;
                }
            }

            Logger.Log($"Running server quick setup on {guild.Name}({guild.Id})");

            ServerList server = ServerListsManager.GetServer(guild);

            //Setup the roles
            IRole memberRole = RoleUtils.GetGuildRole(guild, "Member");

            //There is already a role called "member"
            if (memberRole != null)
            {
                await memberRole.ModifyAsync(properties => properties.Permissions = _memberRoleGuildPermissions);
            }
            else
            {
                //create a new role called member
                memberRole = await guild.CreateRoleAsync("Member", _memberRoleGuildPermissions);

                await guild.EveryoneRole.ModifyAsync(properties => properties.Permissions = _everyoneRoleGuildPermissions);
            }

            //Setup the welcome channel
            if (setupWelcomeChannel)
            {
                ulong welcomeChannelId;

                //First, lets check if they already have a #welcome channel of sorts
                if (guild.SystemChannel == null)
                {
                    //They don't, so set one up
                    RestTextChannel welcomeChannel =
                        await guild.CreateTextChannelAsync("welcome",
                                                           properties => { properties.Topic    = "Were everyone gets a warm welcome!";
                                                                           properties.Position = 0; });

                    await welcomeChannel.AddPermissionOverwriteAsync(guild.EveryoneRole, _everyoneChannelPermissions);

                    welcomeChannelId = welcomeChannel.Id;
                }
                else
                {
                    //They already do, so alter the pre-existing one to have right perms, and to not have Discord random messages put there
                    await guild.SystemChannel.AddPermissionOverwriteAsync(guild.EveryoneRole, _everyoneChannelPermissions);

                    welcomeChannelId = guild.SystemChannel.Id;

                    await guild.ModifyAsync(properties => properties.SystemChannel = null);
                }

                //Setup welcome message
                server.WelcomeChannelId      = welcomeChannelId;
                server.WelcomeMessageEnabled = true;
                server.GoodbyeMessageEnabled = true;

                //Do a delay
                await Task.Delay(1000);
            }

            //Rule reaction
            if (addRulesMessage && setupRuleReaction)
            {
                //Setup rules channel
                RestTextChannel rulesChannel = await guild.CreateTextChannelAsync("rules",
                                                                                  properties => { properties.Position = 1;
                                                                                                  properties.Topic    = "Rules of this Discord server"; });

                await rulesChannel.AddPermissionOverwriteAsync(guild.EveryoneRole, _everyoneChannelPermissions);

                RestUserMessage rulesMessage = await rulesChannel.SendMessageAsync(rules);

                //Setup rules reaction
                await rulesMessage.AddReactionAsync(new Emoji(RulesEmoji));

                server.RuleReactionEmoji    = RulesEmoji;
                server.RuleMessageId        = rulesMessage.Id;
                server.RuleMessageChannelId = rulesChannel.Id;
                server.RuleRoleId           = memberRole.Id;
                server.RuleEnabled          = true;
            }

            //Setup the rest of the channels

            //General category
            await AddCategoryWithChannels(guild, memberRole, "General", 3);

            //Do a delay between categories
            await Task.Delay(500);

            //Gamming category
            await AddCategoryWithChannels(guild, memberRole, "Gamming", 4);

            //DONE!
            ServerListsManager.SaveServerList();
            await Context.Channel.SendMessageAsync("Quick Setup is done!");

            Logger.Log($"server quick setup on {guild.Name}({guild.Id}) is done!");
        }
Exemple #28
0
        /// <summary>
        /// Does the same as mute except manually forces there to be an indefinite duration on the mute.
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task AutoMute(SocketGuildUser user)
        {
            SocketGuild guild    = user.Guild;
            IRole       muteRole = guild.Roles.FirstOrDefault(x => x?.Name.ToLower() == "kaguya-mute");

            if (muteRole == null)
            {
                IRole newRole = await guild.CreateRoleAsync("kaguya-mute", GuildPermissions.None, Color.Default, false, false, null);

                muteRole = newRole;

                await ConsoleLogger.LogAsync($"New mute role created in guild [Name: {guild.Name} | ID: {guild.Id}]",
                                             LogLvl.DEBUG);

                /*
                 * We redefine guild because the object
                 * must now have an updated role collection
                 * in order for this to work.
                 */

                guild    = Client.GetGuild(guild.Id);
                muteRole = guild.Roles.FirstOrDefault(x => x.Name.ToLower() == "kaguya-mute");

                if (Context.Guild.Channels.Any(x => !x.GetPermissionOverwrite(muteRole).HasValue))
                {
                    await ReplyAsync($"{Context.User.Mention} Updating permission overwrites for the mute role...");
                }

                foreach (SocketGuildChannel channel in guild.Channels)
                {
                    try
                    {
                        await channel.AddPermissionOverwriteAsync(muteRole, OverwritePermissions.InheritAll);

                        await channel.AddPermissionOverwriteAsync(muteRole, new OverwritePermissions(
                                                                      addReactions : PermValue.Deny, speak : PermValue.Deny,
                                                                      sendTTSMessages : PermValue.Deny, connect : PermValue.Deny, createInstantInvite : PermValue.Deny,
                                                                      sendMessages : PermValue.Deny));

                        await ConsoleLogger.LogAsync($"Mute permission overwrite added for guild channel.\n" +
                                                     $"Guild: [Name: {guild.Name} | ID: {guild.Id}]\n" +
                                                     $"Channel: [Name: {channel.Name} | ID: {channel.Id}]", LogLvl.TRACE);
                    }
                    catch (Exception)
                    {
                        // ignored
                    }
                }
            }

            try
            {
                await user.AddRoleAsync(muteRole);
            }
            catch (Exception e)
            {
                await ReplyAsync($"{Context.User.Mention} Failed to mute user!!\n\n" +
                                 $"Error Log: ```{e}```");
            }

            await ConsoleLogger.LogAsync($"User auto-muted. Guild: [Name: {guild.Name} | ID: {guild.Id}] " +
                                         $"User: [Name: {user} | ID: {user.Id}]", LogLvl.DEBUG);
        }
 public virtual Task <RestRole> CreateRoleAsync(string name, GuildPermissions?permissions = null, Color?color = null, bool isHoisted = false, bool isMentionable = false, RequestOptions?options = null)
 {
     return(_socketGuild.CreateRoleAsync(name, permissions, color, isHoisted, isMentionable, options));
 }
        /// <summary>
        /// Creates a new guild (includes role, channel, etc)
        /// </summary>
        /// <param name="guild">Discord Server Guild to create channel and role on</param>
        /// <param name="name">Guild Name</param>
        /// <param name="color">Guild Display Color</param>
        /// <param name="captain">Guild Captain</param>
        /// <param name="members">Guild Users</param>
        /// <returns>true, if operation succeeds</returns>
        public static async Task <bool> CreateGuildAsync(SocketGuild guild, string name, GuildColor color, SocketGuildUser captain, List <SocketGuildUser> members)
        {
            string errorhint = "Failed a precheck";

            try
            {
                if (TryGetGuildOfUser(captain.Id, out MinecraftGuild existingCaptainGuild))
                {
                    if (existingCaptainGuild.Active || captain.Id == existingCaptainGuild.CaptainId)
                    {
                        errorhint = "Precheck failed on " + captain.Mention;
                        return(false);
                    }
                    else
                    {
                        existingCaptainGuild.MateIds.Remove(captain.Id);
                        existingCaptainGuild.MemberIds.Remove(captain.Id);
                    }
                }
                foreach (SocketGuildUser member in members)
                {
                    if (TryGetGuildOfUser(member.Id, out MinecraftGuild existingMemberGuild))
                    {
                        if (existingCaptainGuild.Active || member.Id == existingCaptainGuild.CaptainId)
                        {
                            return(false);
                        }
                        else
                        {
                            errorhint = "Precheck failed on " + member.Mention;
                            existingCaptainGuild.MateIds.Remove(member.Id);
                            existingCaptainGuild.MemberIds.Remove(member.Id);
                        }
                    }
                }
                errorhint = "Failed to create Guild Role!";
                RestRole guildRole = await guild.CreateRoleAsync(name, color : MinecraftGuild.ToDiscordColor(color), isHoisted : true);

                errorhint = "Move role into position";
                await guildRole.ModifyAsync(RoleProperties =>
                {
                    RoleProperties.Position = GUILD_ROLE_POSITION;
                });

                errorhint = "Failed to create Guild Channel!";
                SocketCategoryChannel guildCategory = guild.GetChannel(GuildChannelHelper.GuildCategoryId) as SocketCategoryChannel;
                if (guildCategory == null)
                {
                    throw new Exception("Could not find Guild Category Channel!");
                }
                RestTextChannel guildChannel = await guild.CreateTextChannelAsync(name, TextChannelProperties =>
                {
                    TextChannelProperties.CategoryId = GuildChannelHelper.GuildCategoryId;
                    TextChannelProperties.Topic      = "Private Guild Channel for " + name;
                });

                errorhint = "Failed to copy guildcategories permissions";
                foreach (Overwrite overwrite in guildCategory.PermissionOverwrites)
                {
                    IRole role = guild.GetRole(overwrite.TargetId);
                    if (role != null)
                    {
                        await guildChannel.AddPermissionOverwriteAsync(role, overwrite.Permissions);
                    }
                }
                errorhint = "Failed to set Guild Channel Permissions!";
                await guildChannel.AddPermissionOverwriteAsync(guildRole, GuildRoleChannelPerms);

                await guildChannel.AddPermissionOverwriteAsync(captain, CaptainChannelPerms);

                errorhint = "Failed to add Guild Role to Captain!";
                await captain.AddRoleAsync(guildRole);

                errorhint = "Failed to add GuildCaptain Role to Captain!";
                SocketRole captainRole = guild.GetRole(SettingsModel.GuildCaptainRole);
                if (captainRole != null)
                {
                    await captain.AddRoleAsync(captainRole);
                }
                errorhint = "Failed to add Guild Role to a Member!";
                foreach (SocketGuildUser member in members)
                {
                    await member.AddRoleAsync(guildRole);
                }
                errorhint = "Failed to create MinecraftGuild!";

                StringBuilder memberPingString = new StringBuilder();

                MinecraftGuild minecraftGuild = new MinecraftGuild(guildChannel.Id, guildRole.Id, color, name, captain.Id);
                for (int i = 0; i < members.Count; i++)
                {
                    SocketGuildUser member = members[i];
                    minecraftGuild.MemberIds.Add(member.Id);
                    memberPingString.Append(member.Mention);
                    if (i < members.Count - 1)
                    {
                        memberPingString.Append(", ");
                    }
                }
                guilds.Add(minecraftGuild);
                errorhint = "Failed to save MinecraftGuild!";
                await SaveAll();

                errorhint = "Failed to send or pin guild info embed";
                var infomessage = await guildChannel.SendMessageAsync(embed : GuildHelpEmbed.Build());

                await infomessage.PinAsync();

                errorhint = "Notify Admins";
                await AdminTaskInteractiveMessage.CreateAdminTaskMessage($"Create ingame represantation for guild \"{name}\"", $"Name: `{name}`, Color: `{color}` (`0x{((uint)color).ToString("X")}`)\nCaptain: {captain.Mention}\nMembers: {memberPingString}");

                return(true);
            }
            catch (Exception e)
            {
                await GuildChannelHelper.SendExceptionNotification(e, $"Error creating guild {name}. Hint: {errorhint}");

                return(false);
            }
        }