コード例 #1
0
        public async Task AutoRoleAsync(SocketGuildUser user)
        {
            var configGuild = Configuration.Guilds[user.Guild.Id];

            if (user.IsBot)
            {
                var roles = user.Guild.Roles.Where(r => configGuild.BotAutoRoles.Contains(r.Id));
                await user.AddRolesAsync(roles);
            }
            else
            {
                var roles = user.Guild.Roles.Where(r => configGuild.AutoRoles.Contains(r.Id));
                await user.AddRolesAsync(roles);
            }
        }
コード例 #2
0
ファイル: MuteCommands.cs プロジェクト: djnorthlight/WhaleBot
        public async Task UnmuteCommand([Remainder] SocketGuildUser mutee)
        {
            GuildSetup  setup;
            CachedRoles roles;

            using (var db = new DatabaseContext())
            {
                roles = db.CachedRoles.FirstOrDefault(x => x.UserId == mutee.Id);
                setup = db.GuildSetups.FirstOrDefault(x => x.GuildId == Context.Guild.Id);
                db.CachedRoles.Remove(db.CachedRoles.FirstOrDefault(x => x.UserId == mutee.Id));
                db.SaveChanges();
            }

            List <SocketRole> addroles = new List <SocketRole>();

            foreach (var role in roles.RoleIds)
            {
                addroles.Add(Context.Guild.GetRole(role));
            }

            await mutee.AddRolesAsync(addroles);

            await mutee.RemoveRoleAsync(Context.Guild.GetRole(setup.MutedRoleId));

            await ReplyAsync($"Unmuted {mutee.Mention} 👌");
        }
コード例 #3
0
ファイル: UserJoinEvent.cs プロジェクト: Everneth/Gatekeeper
        public async Task JoinGuildEventAsync(SocketGuildUser user)
        {
            if (user.IsBot)
            {
                return;
            }

            var applyChannel   = user.Guild.Channels.SingleOrDefault(c => c.Name == "apply") as SocketTextChannel;
            var generalChannel = user.Guild.Channels.SingleOrDefault(c => c.Name == "town-square") as SocketTextChannel;

            if (_database.PlayerExists(user))
            {
                var roles = user.Guild.Roles.Where(r => r.Name == "Citizen" || r.Name == "Synced");
                await user.AddRolesAsync(roles);

                // since users with the citizen role do not have access to #apply, we should notify them in town-square
                await generalChannel.SendMessageAsync("Hi " + user.Mention + "! \nMy name is Jasper. Welcome ***back*** to the Everneth SMP Discord server!\n\n " +
                                                      "I see that you have already been whitelisted and have Citizen'ed you. Have fun!");
            }
            else
            {
                await applyChannel.SendMessageAsync("Hi " + user.Mention + "! \nMy name is Jasper. Welcome to the Everneth SMP Discord server!\n " +
                                                    "To get you started I have some information on how to apply using discord! Just follow these simple steps to get your application in.\n\n" +
                                                    "**1)** Please visit <https://everneth.com/rules/> and at a minimum read Sections 1, 2, 4, and 5. There are more in the rules but the rest of the sections cover rules for staff and how to change our rules.\n" +
                                                    "**2)** Make note of the secret word (Found in the rules!). You will need this for your application to be accepted.\n" +
                                                    "**3)** Use this channel to run the `/apply` command.\n" +
                                                    "**4)** Answer the questions asked by the bot and when ready, submit your application!\n" +
                                                    "**5)** Once you put your app in, start chatting in our discord! I will begin keeping tabs on you and will move you to Pending once you have met the requirements! (Shouldn't take you but maybe 30 minutes to an hour!)\n **If you have a friend, they can confirm they know you and you skip to pending!**\n" +
                                                    "**6)** Once you meet requirements, staff will vote on your application in Discord. if approved, you will get changed to Citizen automatically and whitelisted.\n\n" +
                                                    "**And thats it!** Good luck!\n\n ***Jasper** - Your friendly guild bouncer and welcoming committee*\n\n **PS:** __If you are already whitelisted and still received this message, please login to the game and use `/discord sync` and link your account!__");
            }
        }
コード例 #4
0
ファイル: AutorolesModule.cs プロジェクト: yebafan/DustyBot
        private Task HandleUserJoined(SocketGuildUser guildUser)
        {
            TaskHelper.FireForget(async() =>
            {
                try
                {
                    var settings = await _settings.Read <RolesSettings>(guildUser.Guild.Id, false);
                    if (settings == null)
                    {
                        return;
                    }

                    if (settings.AutoAssignRoles.Count <= 0)
                    {
                        return;
                    }

                    var roles = guildUser.Guild.Roles.Where(x => settings.AutoAssignRoles.Contains(x.Id)).ToList();
                    if (roles.Count <= 0)
                    {
                        return;
                    }

                    _logger.WithScope(guildUser).LogInformation("Auto-assigning {Count} role(s)", roles.Count);

                    await guildUser.AddRolesAsync(roles);
                }
                catch (Exception ex)
                {
                    _logger.WithScope(guildUser).LogError(ex, "Failed to process greeting event");
                }
            });

            return(Task.CompletedTask);
        }
コード例 #5
0
        private async Task <bool> AssignHostRole(SocketGuild guild, SocketGuildUser host)
        {
            var currentHost = guild.GetRole(RunHostData.RoleId);
            var runPinner   = guild.GetRole(RunHostData.PinnerRoleId);

            Log.Information("Assigning roles...");
            if (host == null || host.HasRole(currentHost))
            {
                return(false);
            }

            try
            {
                await host.AddRolesAsync(new[] { currentHost, runPinner });

                await _db.AddTimedRole(currentHost.Id, guild.Id, host.Id, DateTime.UtcNow.AddHours(4.5));

                await _db.AddTimedRole(runPinner.Id, guild.Id, host.Id, DateTime.UtcNow.AddHours(4.5));

                return(true);
            }
            catch (Exception e)
            {
                Log.Error(e, "Failed to add host role to {User}!", currentHost?.ToString() ?? "null");
                return(false);
            }
        }
コード例 #6
0
        private async Task HandleUserJoined(SocketGuildUser arg)
        {
            var roles = await _serverHelper.GetAutoRolesAsync(arg.Guild);

            if (roles.Count > 0)
            {
                await arg.AddRolesAsync(roles);
            }

            var channelId = await _servers.GetWelcomeAsync(arg.Guild.Id);

            if (channelId == 0)
            {
                return;
            }

            var channel = arg.Guild.GetTextChannel(channelId);

            if (channel == null)
            {
                await _servers.ClearWelcomeAsync(arg.Guild.Id);

                return;
            }

            var background = await _servers.GetBackgroundAsync(arg.Guild.Id);

            string path = await _images.CreateImageAsync(arg, background);

            await channel.SendFileAsync(path, null);

            System.IO.File.Delete(path);
        }
コード例 #7
0
ファイル: Administration.cs プロジェクト: Pat-1337/DiscordBot
        public async Task Mute([Summary("User")] SocketGuildUser arg, [Summary("Time")] int minutes = 0, [Summary("Reason"), Remainder()] string reason = null)
        {
            if (BaseCommands.IsVip(Context.User as SocketUser) && !BaseCommands.IsVip(arg))
            {
                if (jSon._permWR(Context, BaseCommands.Commands.Mute).Result)
                {
                    await Context.Message.DeleteAsync();

                    var sw = Stopwatch.StartNew();
                    await arg.AddRolesAsync(arg.Guild.Roles.Where(y => y.Name.ToLower().Equals("muted")));

                    EmbedBuilder builder = new EmbedBuilder()
                    {
                        Title       = $"**{arg.Username} has been muted!**",
                        Description = $"{(string.IsNullOrEmpty(reason) ? string.Empty : $"**Reason: {reason}**")}{(minutes.Equals(0) ? string.Empty : $"\n**Minutes: {minutes}**")}",
                        Color       = new Color((byte)(_ran.Next(255)), (byte)(_ran.Next(255)), (byte)(_ran.Next(255))),
                    }.WithCurrentTimestamp();
                    sw.Stop();
                    await ReplyAsync(string.Empty, false, embed : builder.WithFooter(y => y.WithText($"{sw.ElapsedMilliseconds}ms | {Context.User}")).Build());

                    await BaseCommands.SendReasonEmbedToUserDM(arg, Context.Guild, reason, BaseCommands.Commands.Mute, minutes);

                    if (minutes <= 360 && minutes > 0)
                    {
                        await TimerClass._tMute(Context.Guild, arg.Id, TimeSpan.FromMinutes(minutes), new CancellationTokenSource().Token);
                    }
                    else
                    {
                        await TimerClass._tMute(Context.Guild, arg.Id, TimeSpan.FromMinutes(360), new CancellationTokenSource().Token);
                    }
                }
            }
        }
コード例 #8
0
ファイル: Administration.cs プロジェクト: Pat-1337/DiscordBot
        public async Task _fMute([Summary("User")] SocketGuildUser arg, [Summary("Reason"), Remainder()] string reason = null)
        {
            if (BaseCommands.IsVip(Context.User as SocketUser) && !BaseCommands.IsVip(arg))
            {
                if (jSon._permWR(Context, BaseCommands.Commands.Mute).Result)
                {
                    await Context.Message.DeleteAsync();

                    var sw = Stopwatch.StartNew();
                    await arg.RemoveRolesAsync(arg.Roles.Where(x => x.Id != Context.Guild.EveryoneRole.Id && x.Position < x.Guild.CurrentUser.Hierarchy));

                    await arg.AddRolesAsync(arg.Guild.Roles.Where(y => y.Name.ToLower().Equals("muted")));

                    EmbedBuilder builder = new EmbedBuilder()
                    {
                        Title       = $"**{arg.Username} has been muted!**",
                        Description = $"{(string.IsNullOrEmpty(reason) ? string.Empty : $"**Reason: {reason}**")}",
                        Color       = new Color((byte)(_ran.Next(255)), (byte)(_ran.Next(255)), (byte)(_ran.Next(255)))
                    }.WithCurrentTimestamp();
                    sw.Stop();
                    await ReplyAsync(string.Empty, false, embed : builder.WithFooter(y => y.WithText($"{sw.ElapsedMilliseconds}ms | {Context.User}")).Build());

                    await BaseCommands.SendReasonEmbedToUserDM(arg, Context.Guild, reason, BaseCommands.Commands.Mute);
                }
            }
        }
コード例 #9
0
        public async Task SelfassignMe([Summary("The code")] string code)
        {
            Dictionary <string, ulong> sassables = await GranularPermissionsStorage.GetSelfassignable(this.Context.Guild.Id);

            if (sassables != null && sassables.ContainsKey(code))
            {
                SocketGuildUser sgu = this.Context.User as SocketGuildUser;
                if (sgu != null)
                {
                    IEnumerable <SocketRole> rolesToAssign = sgu.Guild.Roles.Where(x => x.Id == sassables[code]);
                    await sgu.AddRolesAsync(rolesToAssign);

                    await this.Context.Message.AddReactionAsync(new Emoji("👌"));

                    return;
                }
                else
                {
                    await this.Context.Message.AddReactionAsync(new Emoji("👎"));
                }
            }
            else
            {
                await this.Context.Message.AddReactionAsync(new Emoji("👎"));
            }
        }
コード例 #10
0
        private async Task <(List <SocketRole>, OsuUserDetails)> GrantUserRolesAsync(SocketGuildUser user, OsuUser osuUser)
        {
            OsuUserDetails osuUserDetails = await osuUser.GetDetailsAsync();

            _logger.LogTrace("Details: {@details}", osuUserDetails);
            IReadOnlyCollection <SocketRole> guildRoles = user.Guild.Roles;
            // Find roles that user should have
            List <SocketRole> roles = OsuRoles.FindUserRoles(guildRoles, osuUserDetails);
            // Remove roles that user shouldn't have
            await user.RemoveRolesAsync(OsuRoles.FindAllRoles(guildRoles).Where(role => user.Roles.Contains(role) && !roles.Contains(role)));

            // Add roles that user should have
            await user.AddRolesAsync(roles.Where(role => !user.Roles.Contains(role)));

            // Change user nickname to that from game

            // Ignore if can't change nickname
            try
            {
                await user.ModifyAsync(properties => properties.Nickname = osuUserDetails.Username);
            }
            catch (HttpException)
            {
            }

            return(roles, osuUserDetails);
        }
コード例 #11
0
ファイル: Admin.cs プロジェクト: pipe01/DreamBot
        public async Task UnVerify([Remainder] SocketGuildUser user)
        {
            var config = GetServerConfig((SocketGuild)Context.Guild);

            if (config.Verifications == true)
            {
                var role1 = Context.Guild.Roles.First(f => f.Name == "unverified");
                var role2 = Context.Guild.Roles.First(f => f.Name == "verified");
                var roles = user.Roles;
                if (roles.Contains(role2))
                {
                    await user.RemoveRolesAsync(role2);

                    await user.AddRolesAsync(role1);

                    await Context.Channel.SendMessageAsync(msgConfig.UnverifySuc.Replace("{0}", user.Mention));
                }
                else
                {
                    await Context.Channel.SendMessageAsync(msgConfig.UnverifyErr.Replace("{0}", user.Mention));
                }
            }
            else
            {
                await Context.Channel.SendMessageAsync(msgConfig.VerificationsDisabled);
            }
        }
コード例 #12
0
ファイル: Greetings.cs プロジェクト: DaavidM/Discord-Bot
        public async Task UserJoined(SocketGuildUser recipient)
        {
            var role = recipient.Guild.Roles.Where(has => has.Name.ToUpper() == "muted".ToUpper());
            var user = Context.User as SocketGuildUser;
            await recipient.AddRolesAsync(role);

            await ReplyAsync($"{user.Mention} has muted you, {recipient}.");
        }
コード例 #13
0
        public async Task FreeAsync([RequireInvokerHierarchy("free")] SocketGuildUser user)
        {
            SocketRole role = await modRolesDatabase.PrisonerRole.GetPrisonerRoleAsync(Context.Guild);

            List <SocketRole> roles = await modRolesDatabase.UserRoles.GetUserRolesAsync(user);

            if ((role == null || !user.Roles.Contains(role)) && roles.Count == 0)
            {
                await Context.Channel.SendMessageAsync($"Our security team has informed us that {user.Nickname ?? user.Username} is not held captive.");

                return;
            }

            EmbedBuilder embed = new EmbedBuilder()
                                 .WithColor(new Color(12, 156, 24))
                                 .WithDescription($"{user.Mention} has been freed from Guantanamo Bay after a good amount of ~~torture~~ re-education.");

            List <Task> cmds = new()
            {
                modRolesDatabase.Prisoners.RemovePrisonerAsync(user),
                Context.Channel.SendMessageAsync(embed: embed.Build()),
                FreeModLog.SendToModLogAsync(Context.User as SocketGuildUser, user)
            };

            if (roles.Count > 0)
            {
                cmds.AddRange(new List <Task>()
                {
                    user.AddRolesAsync(roles),
                    modRolesDatabase.UserRoles.RemoveUserRolesAsync(user)
                });
            }
            if (role != null)
            {
                cmds.Add(user.RemoveRoleAsync(role));
            }
            await Task.WhenAll(cmds);

            if (!await modRolesDatabase.Prisoners.HasPrisoners(Context.Guild))
            {
                SocketTextChannel channel = await modRolesDatabase.PrisonerChannel.GetPrisonerChannelAsync(Context.Guild);

                cmds = new()
                {
                    modRolesDatabase.PrisonerChannel.RemovePrisonerChannelAsync(Context.Guild),
                    modRolesDatabase.PrisonerRole.RemovePrisonerRoleAsync(Context.Guild)
                };
                if (channel != null)
                {
                    cmds.Add(channel.DeleteAsync());
                }
                if (role != null)
                {
                    cmds.Add(role.DeleteAsync());
                }
                await Task.WhenAll(cmds);
            }
        }
コード例 #14
0
        /// <summary>
        /// When a user joins a server, check if they have an active role persist and if they do, reapply it
        /// </summary>
        private async Task OnUserJoin(SocketGuildUser user)
        {
            // Get a list of all the role persists on the user in this guild
            RolePersist[] rolePersists = await GetUserRolePersists(user.Guild, user);

            // Add all the active role persists back
            await user.AddRolesAsync(rolePersists.Where(x => x.Active)
                                     .Select(x => user.Guild.GetRole(x.RoleId)));
        }
コード例 #15
0
ファイル: RoleHandler.cs プロジェクト: SinSiXX/YunoBot
        private async Task AddRole(SocketGuildUser user)
        {
            if (user.Activity == null)
            {
                return;
            }
            if (user.Activity.Type != ActivityType.Playing)
            {
                return;
            }
            var autoRole = AutoRole.Load(user.Guild.Id);
            var game     = user.Activity.Name;

            var rolesA = user.Guild.Roles.Where(r => autoRole.IsAutoRole(r) && r.Name.ContainsIgnoreCase(game));
            await user.AddRolesAsync(rolesA);

            var rolesP = user.Guild.Roles.Where(r => autoRole.IsPermaRole(r) && r.Name.ContainsIgnoreCase(game));
            await user.AddRolesAsync(rolesP);
        }
コード例 #16
0
        /// <summary>
        /// Sends greetings and mod log messages, and sets an auto role, if configured.
        /// </summary>
        private async Task HandleUserJoinedAsync(SocketGuildUser guildUser)
        {
            var settings = SettingsConfig.GetSettings(guildUser.Guild.Id);

            if (!string.IsNullOrEmpty(settings.Greeting) && settings.GreetingId != 0)
            {
                var greeting = settings.Greeting.Replace("%user%", guildUser.Mention);
                greeting = greeting.Replace("%username%", $"{guildUser.Username}#{guildUser.Discriminator}");

                greeting = Consts.ChannelRegex.Replace(greeting, new MatchEvaluator((Match chanMatch) =>
                {
                    string channelName = chanMatch.Groups[1].Value;
                    var channel        = guildUser.Guild.Channels.Where(c => c is ITextChannel && c.Name.Equals(channelName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                    return((channel as ITextChannel)?.Mention ?? $"#{channelName}");
                }));

                var greetingChannel = this.Client.GetChannel(settings.GreetingId) as ITextChannel ?? guildUser.Guild.DefaultChannel;
                if (greetingChannel.GetCurrentUserPermissions().SendMessages)
                {
                    await greetingChannel.SendMessageAsync(greeting);
                }
            }

            if (settings.JoinRoleId != 0 && guildUser.Guild.CurrentUser.GuildPermissions.ManageRoles)
            {
                var role = guildUser.Guild.GetRole(settings.JoinRoleId);
                if (role != null)
                {
                    try
                    {
                        await guildUser.AddRolesAsync(new[] { role });
                    }
                    catch (HttpException ex) when(ex.HttpCode == HttpStatusCode.Forbidden)
                    {
                        await guildUser.Guild.SendOwnerDMAsync($"Permissions error detected for {guildUser.Guild.Name}: Auto role add on user joined failed, role `{role.Name}` is higher in order than my role");
                    }
                    catch (HttpException ex) when(ex.HttpCode == HttpStatusCode.NotFound)
                    {
                        await guildUser.Guild.SendOwnerDMAsync($"Error detected for {guildUser.Guild.Name}: Auto role add on user joined failed, role `{role.Name}` does not exist");
                    }
                }
            }

            // mod log
            if (settings.Mod_LogId != 0 && settings.HasFlag(ModOptions.Mod_LogUserJoin))
            {
                string joinText = $"{guildUser.Username}#{guildUser.Discriminator} joined.";
                if (this.Client.GetChannel(settings.Mod_LogId) is ITextChannel modLogChannel && modLogChannel.GetCurrentUserPermissions().SendMessages)
                {
                    this.BatchSendMessageAsync(modLogChannel, joinText);
                }
            }
        }
コード例 #17
0
        private async Task OnMemberUpdated(SocketGuildUser before, SocketGuildUser after)
        {
            // Find if any roles were removed
            IEnumerable <SocketRole> removedRoles = before.Roles.Except(after.Roles);

            // Find if any removed roles are active persists
            IEnumerable <SocketRole> activePersists = removedRoles.Intersect((await GetUserRolePersists(before.Guild, before))
                                                                             .Select(x => before.Guild.GetRole(x.RoleId)));

            // Add them back
            await after.AddRolesAsync(activePersists);
        }
コード例 #18
0
        internal static async Task AssignAutoRoles(IAutoRoleService autoRoleService, SocketGuildUser userJoining)
        {
            var roles = await autoRoleService.GetAutoRoles(userJoining.Guild);

            if (!roles.Any())
            {
                Log.Information("AutoRoleHelper: No auto roles to assign to {user} in {server}", userJoining.Username, userJoining.Guild.Name);
                return;
            }

            Log.Information("AutoRoleHelper: Assigning auto roles to {user}", userJoining.Username);
            await userJoining.AddRolesAsync(roles);
        }
コード例 #19
0
        private async Task SetRole(SocketMessage e)
        {
            SocketGuildChannel chan = (SocketGuildChannel)e.Channel;
            SocketGuildUser    user = (SocketGuildUser)e.Author;

            //check we're in the right server
            if (chan.Guild.Id == 467695581054107658)
            {
                ulong roleID = 0;
                //get the role to add
                string[] parts = e.Content.Split(' ');
                if (parts.Length > 1)
                {
                    switch (parts[1].ToLower())
                    {
                    case "watcher":
                        roleID = 471611370530406410;
                        break;

                    default:
                        break;
                    }

                    if (roleID != 0)
                    {
                        //assign role to user
                        List <SocketRole> roleList = new List <SocketRole>();
                        SocketRole        r        = chan.Guild.GetRole(roleID);
                        roleList.Add(r);
                        if (r != null)
                        {
                            await user.AddRolesAsync(roleList);

                            await e.Channel.SendMessageAsync("`" + r.Name + " has been added to " + e.Author.Username + "`");
                        }
                    }
                    else
                    {
                        await e.Channel.SendMessageAsync("**-Coral Bot looks at you confused-**");
                    }
                }
                else
                {
                    await e.Channel.SendMessageAsync("**-Coral Bot looks at you confused-**");
                }
            }
            else
            {
                await e.Channel.SendMessageAsync("<Whoops, this command doesn't work in this server!>");
            }
        }
コード例 #20
0
ファイル: RemModerationToolkit.cs プロジェクト: lofdat/Rem
        public async Task MuteCommand(SocketGuildUser TargetUser)
        {
            SocketRole MutedRole = TargetUser.Guild.Roles.First(x => x.Name == "Muted");

            if (TargetUser.RoleIds.Contains(MutedRole.Id))
            {
                await ReplyAsync($"{TargetUser.Mention} is already muted.");

                return;
            }
            await TargetUser.AddRolesAsync(MutedRole);

            await ReplyAsync($"{TargetUser.Mention} has been muted.");
        }
コード例 #21
0
        /// <summary>
        /// If a user had left and had sticky roles, readd the sticky roles
        /// </summary>
        private async Task UserJoined(SocketGuildUser user)
        {
            var guild = user.Guild;

            if (ConfigManager.IsGuildManaged(guild.Id))
            {
                GuildConfig config;
                if ((config = ConfigManager.GetManagedConfig(guild.Id)) == null)
                {
                    return;
                }
                await user.AddRolesAsync(config.GetStickyRoles(user.Id).Select(x => guild.GetRole(x)));
            }
        }
コード例 #22
0
        private Task HandleUserJoined(SocketGuildUser guildUser)
        {
            TaskHelper.FireForget(async() =>
            {
                try
                {
                    var settings = await _settings.Read <RolesSettings>(guildUser.Guild.Id, false);
                    if (settings == null)
                    {
                        return;
                    }

                    if (!settings.PersistentAssignableRoles && settings.AdditionalPersistentRoles.Count <= 0)
                    {
                        return;
                    }

                    List <ulong> roleIds;
                    if (!settings.PersistentRolesData.TryGetValue(guildUser.Id, out roleIds))
                    {
                        return;
                    }

                    // Intersect with current persistent roles
                    var intersected = roleIds.Where(x => settings.AdditionalPersistentRoles.Contains(x)).ToList();
                    if (settings.PersistentAssignableRoles)
                    {
                        intersected.AddRange(roleIds.Where(x => settings.AssignableRoles.Any(y => y.RoleId == x || y.SecondaryId == x)));
                    }

                    var roles = intersected.Select(x => guildUser.Guild.Roles.FirstOrDefault(y => x == y.Id)).Where(x => x != null).ToList();

                    _logger.WithScope(guildUser).LogInformation("Restoring {Count} roles", roles.Count);

                    if (roles.Count > 0)
                    {
                        await guildUser.AddRolesAsync(roles);
                    }

                    await _settings.Modify(guildUser.Guild.Id, (RolesSettings x) => x.PersistentRolesData.Remove(guildUser.Id));
                }
                catch (Exception ex)
                {
                    _logger.WithScope(guildUser).LogError(ex, "Failed to potentially restore persistent roles");
                }
            });

            return(Task.CompletedTask);
        }
コード例 #23
0
        public async Task TimeoutAsync(SocketGuildUser User, int Minutes)
        {
            if (Context.GuildHelper.HierarchyCheck(Context.Guild, User))
            {
                await ReplyAsync($"Can't mute someone whose highest role is higher than valerie's roles. "); return;
            }
            var Roles = User.Roles.Where(x => x.IsEveryone == false);
            await User.RemoveRolesAsync(Roles).ContinueWith(async _ => await MuteAsync(User));

            _ = Task.Delay(TimeSpan.FromMinutes(Minutes)).ContinueWith(async y =>
            {
                await UnMuteAsync(User);
                await User.AddRolesAsync(Roles);
            });
        }
コード例 #24
0
ファイル: RoleCommands.cs プロジェクト: djnorthlight/WhaleBot
        public async Task RoleCommand(SocketGuildUser user, params SocketRole[] roles)
        {
            var addRoles    = new List <SocketRole>();
            var removeRoles = new List <SocketRole>();

            foreach (SocketRole role in roles)
            {
                if (user.Roles.Contains(role))
                {
                    removeRoles.Add(role);
                }
                else
                {
                    addRoles.Add(role);
                }
            }

            await user.AddRolesAsync(addRoles, new RequestOptions { AuditLogReason = $"Added by {Context.User.ToString()}" });

            await user.RemoveRolesAsync(removeRoles, new RequestOptions { AuditLogReason = $"Removed by {Context.User.ToString()}" });

            List <string> addedRoles   = new List <string>();
            List <string> removedRoles = new List <string>();

            foreach (SocketRole role in addRoles)
            {
                addedRoles.Add(role.Name);
            }
            foreach (SocketRole role in removeRoles)
            {
                removedRoles.Add(role.Name);
            }

            var added   = addRoles.Count > 0 ? "Added: " : "";
            var space   = addRoles.Count > 0 && removeRoles.Count > 0 ? " " : "";
            var removed = removeRoles.Count > 0 ? "Removed: " : "";

            var reply = await ReplyAsync($"Done. {added}{string.Join(", ", addedRoles)}{space}{removed}{string.Join(", ", removedRoles)}");

            var t = Task.Run(async() =>
            {
                await Task.Delay(15000);
                await reply.DeleteAsync();
                await Context.Message.DeleteAsync();
            });
        }
コード例 #25
0
        private async Task UserJoined(SocketGuildUser user)
        {
            var userAccount = UserAccounts.GetAccount(user);

            UserAccounts.SaveAccounts();
            var r1 = user.Guild.Roles.FirstOrDefault(x => x.Name == "WERYFIKACJA 1/5");
            var r2 = user.Guild.Roles.FirstOrDefault(x => x.Id == 517062410050469898);
            var r3 = user.Guild.Roles.FirstOrDefault(x => x.Id == 548973612317671424);
            var r4 = user.Guild.Roles.FirstOrDefault(x => x.Id == 517063485364895783);
            var r5 = user.Guild.Roles.FirstOrDefault(x => x.Id == 517063595612307466);
            var r6 = user.Guild.Roles.FirstOrDefault(x => x.Id == 521721061008474113);
            var r7 = user.Guild.Roles.FirstOrDefault(x => x.Id == 521734161401249802);
            var r8 = user.Guild.Roles.FirstOrDefault(x => x.Id == 521734162437111821);
            var r9 = user.Guild.Roles.FirstOrDefault(x => x.Id == 556550338912452610);

            await user.AddRolesAsync(new[] { r1, r2, r3, r4, r5, r6, r7, r8, r9 });
        }
コード例 #26
0
        public void ChangeRolesToMute(SocketGuildUser user)
        {
            var    guildEntity     = _databaseHandler.Get <GuildEntity>(user.Guild.Id);
            string muteRolesSuffix = guildEntity.RoleForMutedSuffix;

            var userRoleNames = user.Roles.Select(r => r.Name).ToHashSet();
            var giveMuteRoles = user.Guild.Roles.Where(r =>
                                                       r.Id == guildEntity.MuteRoleId || // or it's the muteRole
                                                       (muteRolesSuffix != default &&
                                                        r.Name.EndsWith(muteRolesSuffix) &&                                                    // e.g. Rolename ends with "Muted" (muteRoleSuffix)
                                                        userRoleNames.Contains(r.Name.Substring(0, r.Name.Length - muteRolesSuffix.Length)))); // e.g. User got the same role without "Muted" (muteRoleSuffix)

            user.AddRolesAsync(giveMuteRoles);

            var giveMuteRoleNamesHashset = giveMuteRoles.Select(r => r.Name.Substring(0, r.Name.Length - muteRolesSuffix.Length)).ToHashSet();
            var removeNotMuteRoles       = user.Roles.Where(r => giveMuteRoleNamesHashset.Contains(r.Name));

            user.RemoveRolesAsync(removeNotMuteRoles);
        }
コード例 #27
0
ファイル: RestoreRoles.cs プロジェクト: GIRU-GIRU/GIRUBotV3
 public async Task RestoreUserRoles(SocketCommandContext context, SocketGuildUser target)
 {
     try
     {
         using (var db = new Restoreroles())
         {
             var IRoleCollection = new List <IRole>();
             foreach (var item in db.RoleModelRolesStore.AsQueryable().Where(x => x.UserID == target.Id))
             {
                 IRoleCollection.Add(context.Guild.GetRole(item.RoleID));
             }
             await target.AddRolesAsync(IRoleCollection);
         }
     }
     catch (Exception ex)
     {
         await context.Channel.SendMessageAsync($"restore user roles table is f****d atm sry kid {ex.Message}");
     }
 }
コード例 #28
0
        public void ChangeRolesToUnmute(SocketGuildUser user)
        {
            var    guildEntity     = _databaseHandler.Get <GuildEntity>(user.Guild.Id);
            string muteRolesSuffix = guildEntity.RoleForMutedSuffix;

            if (muteRolesSuffix == default)
            {
                return;
            }

            var removeMuteRoles = user.Roles.Where(r => r.Id == guildEntity.MuteRoleId || r.Name.EndsWith(muteRolesSuffix));

            user.RemoveRolesAsync(removeMuteRoles);

            var addNotMuteRoleNames = removeMuteRoles.Select(r => r.Name.Substring(0, r.Name.Length - muteRolesSuffix.Length));
            var addNotMuteRoles     = user.Guild.Roles.Where(r => addNotMuteRoleNames.Contains(r.Name));

            user.AddRolesAsync(addNotMuteRoles);
        }
コード例 #29
0
        private async Task SetRole(SocketGuildUser User, IDictionary <RoleLevel, IRole> RoleMap, RoleLevel DesiredRole, StringBuilder sb)
        {
            var ToAdd = RoleMap
                        //Find all roles less then or equal to current role.
                        .Where(o => o.Key <= DesiredRole)
                        //Filter by roles the user does not have.
                        .Where(o => !User.Roles.Any(z => z.Id == o.Value.Id))
                        //Select the Role
                        .Select(o => o.Value);

            var ToRemove = RoleMap
                           //Find all roles greater then current role.
                           .Where(o => o.Key > DesiredRole)
                           //Filter by roles the user does have.
                           .Where(o => User.Roles.Any(z => z.Id == o.Value.Id))
                           //Select the Role
                           .Select(o => o.Value);

            //Make a formatted message return.
            sb.AppendLine($"Setting {User.Mention} to role {DesiredRole.ToString()}");

            foreach (var remove in ToRemove)
            {
                sb.AppendLine($"\tRemoved Role {remove.Mention}");
            }
            foreach (var add in ToAdd)
            {
                sb.AppendLine($"\tAdded Role {add.Mention}");
            }

            //Remove applicable roles
            if (ToRemove.Count() > 0)
            {
                await User.RemoveRolesAsync(ToRemove);
            }

            //Add applicable roles
            if (ToAdd.Count() > 0)
            {
                await User.AddRolesAsync(ToAdd);
            }
        }
コード例 #30
0
ファイル: Responses.cs プロジェクト: Nolanlemahn/Facedesk_Bot
        public static async Task HandleUserJoinAsync(SocketGuildUser joiner)
        {
            var guild = joiner.Guild;

            bool authed = await Permissions.GranularPermissionsStorage.GetAuthStatusFor(guild.Id);

            if (authed)
            {
                List <ulong> roleIDs = await Permissions.GranularPermissionsStorage.GetDefaultRoles(guild.Id);

                if (roleIDs != null)
                {
                    foreach (ulong roleID in roleIDs)
                    {
                        IEnumerable <SocketRole> rolesToAssign = joiner.Guild.Roles.Where(x => roleIDs.Contains(x.Id));
                        await joiner.AddRolesAsync(rolesToAssign);
                    }
                }
            }
        }