コード例 #1
0
ファイル: ReactionHandler.cs プロジェクト: scp-cs/Thorn
        private async Task AssignRole(Cacheable <IUserMessage, ulong> cacheable, SocketReaction reaction,
                                      IGuildUser user, UserActions action)
        {
            string message;

            switch (action)
            {
            case UserActions.ClassC:
                await user.AddRoleAsync(user.Guild.GetRole(_classCRoleId));

                message = $"**Přijat nový člen {user.Mention}!** [{user.Id}]\n" +
                          $"```{cacheable.Value.Content}```";
                break;

            case UserActions.Int:
                await user.AddRoleAsync(user.Guild.GetRole(_intRoleId));

                message = $"**Přijat nový *INT* člen {user.Mention}!** [{user.Id}]\n" +
                          $"```{cacheable.Value.Content}```";
                break;

            case UserActions.Underage:
                message = $"**Uživatel {user.Mention} pod věkovou hranicí!** [{user.Id}]\n" +
                          $"```{cacheable.Value.Content}```";
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(action), action, null);
            }

            await reaction.Message.Value.DeleteAsync();

            await((ISocketMessageChannel)_client.GetChannel(_loggingChannelId)).SendMessageAsync(message);
            Logger.LogInformation("{ReactionUser} made action in #welcome: {Message}", reaction.User, message);
        }
コード例 #2
0
ファイル: reactionRoles.cs プロジェクト: Hoovier/WagglesBot
        public async Task addRole(Discord.IRole role, string emoji, ulong messageID)
        {
            //try to give user role in order to test if perms are present
            IGuildUser user = (IGuildUser)Context.Message.Author;

            try
            {
                //if user has it, remove then add back, this prevents removal of roles from people who already had a role
                if (user.RoleIds.Contains(role.Id))
                {
                    await user.RemoveRoleAsync(role);

                    await user.AddRoleAsync(role);
                }
                //if they dont, add it and then remove again
                else
                {
                    await user.AddRoleAsync(role);

                    await user.RemoveRoleAsync(role);
                }
                Console.WriteLine("Successful Role addition test. Permissions ok.");
                //add a task to list
                DBTransaction.setReactionRole(role.Id, Context.Guild.Id, emoji, messageID);
                await ReplyAsync("Success! Reacting with ``" + emoji + "`` will give the user the ``" + role.Name + "`` role!");
            }
            catch
            {
                await ReplyAsync("Sorry! Something went wrong! Make sure that I have permission to modify roles and that my role is higher than the selected one!");
            }
        }
コード例 #3
0
        public async Task CustomAward([Summary("The amount of points to be awarded.")] int points, [Summary("The user to award points to")][Remainder] IGuildUser user = null)
        {
            if (!Context.DbGuild.OverhaulEnabled)
            {
                await ReplyErrorAsync("all Overhaul related commands are disabled on this server.");

                return;
            }

            if (user == null)
            {
                await _guildRepository.ModifyAsync(Context.DbGuild, x => x.Points += points);

                await ReplyAsync($"you have successfully added **{points}** points to this server's total.");

                return;
            }

            var dbUser = await _userRepository.GetUserAsync(user.Id, user.GuildId);

            await _userRepository.ModifyAsync(dbUser, x => x.Points += points);

            await _guildRepository.ModifyAsync(Context.DbGuild, x => x.Points += points);

            await _pointService.HandleRanksAsync(user, Context.DbGuild, dbUser);

            var dmMessage     = $"**{Context.User.Mention}** has awarded you **{points}** points in **{Context.Guild.Name}**.";
            var adminResponse = $"you have successfully added **{points}** points to {user.Mention}.";

            await DmAsync(user, dmMessage);
            await ReplyAsync(adminResponse);

            if (Context.DbGuild.TopThreeRole != 0)
            {
                var thirdPlaceDbUser  = (await _userRepository.AllAsync(x => x.GuildId == Context.Guild.Id)).OrderByDescending(x => x.Points).ElementAtOrDefault(2);
                var fourthPlaceDbUser = (await _userRepository.AllAsync(x => x.GuildId == Context.Guild.Id)).OrderByDescending(x => x.Points).ElementAtOrDefault(3);

                if (thirdPlaceDbUser == default)
                {
                    await user.AddRoleAsync(Context.Guild.GetRole(Context.DbGuild.TopThreeRole));

                    return;
                }

                if (dbUser.Points >= thirdPlaceDbUser.Points)
                {
                    await user.AddRoleAsync(Context.Guild.GetRole(Context.DbGuild.TopThreeRole));

                    if (fourthPlaceDbUser == default || thirdPlaceDbUser.Points <= fourthPlaceDbUser.Points)
                    {
                        var thirdPlaceGuildUser = (IGuildUser)Context.Guild.GetUser(thirdPlaceDbUser.UserId);

                        await thirdPlaceGuildUser.AddRoleAsync(Context.Guild.GetRole(Context.DbGuild.TopThreeRole));
                    }
                }
            }
        }
コード例 #4
0
ファイル: RoleCommands.cs プロジェクト: otooleam/Nona
        public async Task Role([Summary("Set nickname and role for this user.")] IGuildUser user,
                               [Summary("User\'s nickname.")] string nickname,
                               [Summary("User\'s team (Valor, Mystic, or Instinct).")] string teamName)
        {
            if (!Connections.Instance().GetSetupComplete(Context.Guild.Id))
            {
                await ResponseMessage.SendErrorMessage(Context.Channel, "role", "Roles not setup. Please run the setup command");
            }
            else if (((SocketGuildUser)Context.User).Roles.FirstOrDefault(x => x.Name.ToString().Equals(Global.ROLE_TRAINER, StringComparison.OrdinalIgnoreCase)) == null)
            {
                await ResponseMessage.SendErrorMessage(Context.Channel, "role", "Error: You are not authorized to run this command.");
            }
            else
            {
                SocketRole team = Context.Guild.Roles.FirstOrDefault(x => x.Name.ToString().Equals(teamName, StringComparison.OrdinalIgnoreCase));
                if (team == null)
                {
                    await ResponseMessage.SendErrorMessage(Context.Channel, "role", $"{teamName} is not a valid role");
                }
                else
                {
                    try
                    {
                        await user.ModifyAsync(x => { x.Nickname = nickname; });
                    }
                    catch (Discord.Net.HttpException e)
                    {
                        Console.WriteLine(e.Message);
                        await ResponseMessage.SendWarningMessage(Context.Channel, "role", $"Unable to set nickname for {user.Username}.\nPlease set your server nickname to match your Pokémon Go trainer name.");
                    }

                    SocketRole valor    = Context.Guild.Roles.FirstOrDefault(x => x.Name.ToString().Equals(Global.ROLE_VALOR, StringComparison.OrdinalIgnoreCase));
                    SocketRole mystic   = Context.Guild.Roles.FirstOrDefault(x => x.Name.ToString().Equals(Global.ROLE_MYSTIC, StringComparison.OrdinalIgnoreCase));
                    SocketRole instinct = Context.Guild.Roles.FirstOrDefault(x => x.Name.ToString().Equals(Global.ROLE_INSTINCT, StringComparison.OrdinalIgnoreCase));
                    if (user.RoleIds.Contains(valor.Id))
                    {
                        await user.RemoveRoleAsync(valor);
                    }
                    else if (user.RoleIds.Contains(mystic.Id))
                    {
                        await user.RemoveRoleAsync(mystic);
                    }
                    else if (user.RoleIds.Contains(instinct.Id))
                    {
                        await user.RemoveRoleAsync(instinct);
                    }
                    await user.AddRoleAsync(team);

                    SocketRole role = Context.Guild.Roles.FirstOrDefault(x => x.Name.ToString().Equals(Global.ROLE_TRAINER, StringComparison.OrdinalIgnoreCase));
                    await user.AddRoleAsync(role);

                    await ResponseMessage.SendInfoMessage(Context.Channel, $"{user.Username} nickname set to {nickname} and now has the \'Trainer\' and \'{teamName}\' roles");
                }
            }
        }
コード例 #5
0
ファイル: PromoteAndDemote.cs プロジェクト: Phytal/Wsashi
        public async Task Demote(string rank, IGuildUser user = null)
        {
            var config = GlobalGuildAccounts.GetGuildAccount(Context.Guild.Id);
            var guser  = Context.User as SocketGuildUser;

            if (guser.GuildPermissions.ManageRoles)
            {
                try
                {
                    var role1 = Context.Guild.Roles.FirstOrDefault(x => x.Name == config.HelperRoleName);
                    var role2 = Context.Guild.Roles.FirstOrDefault(x => x.Name == config.ModRoleName);
                    var role3 = Context.Guild.Roles.FirstOrDefault(x => x.Name == config.AdminRoleName);
                    if (rank == "mod" || rank == "moderator")
                    {
                        await user.AddRoleAsync(role2);

                        await user.RemoveRoleAsync(role3);
                        await ReplyAsync(":exclamation:  | " + Context.User.Mention + " demoted " + user.Mention + " to the " + config.ModRoleName + " rank.");
                    }
                    if (rank == "helper")
                    {
                        await user.AddRoleAsync(role1);

                        await user.RemoveRoleAsync(role2);

                        await user.RemoveRoleAsync(role3);
                        await ReplyAsync(":exclamation:  | " + Context.User.Mention + " demoted " + user.Mention + " to the " + config.HelperRoleName + " rank.");
                    }
                    if (rank == "member")
                    {
                        await user.RemoveRoleAsync(role1);

                        await user.RemoveRoleAsync(role2);

                        await user.RemoveRoleAsync(role3);
                        await ReplyAsync(":exclamation:  | " + Context.User.Mention + " demoted " + user.Mention);
                    }
                }
                catch
                {
                    var embed = new EmbedBuilder();
                    embed.WithColor(37, 152, 255);
                    embed.WithTitle(":hand_splayed:  | Please say who and what you want to demote the user to. Ex: w!demote <@username> <rank>");
                    await ReplyAndDeleteAsync("", embed : embed.Build(), timeout : TimeSpan.FromSeconds(5));
                }
            }
            else
            {
                var embed = new EmbedBuilder();
                embed.WithColor(37, 152, 255);
                embed.Title = $":x:  | You need the Manange Roles Permission to do that {Context.User.Username}";
                await ReplyAndDeleteAsync("", embed : embed.Build(), timeout : TimeSpan.FromSeconds(5));
            }
        }
コード例 #6
0
        public static async Task Promote(IGuild guild, IMessage message, IRole role, IGuildUser promoteuser, IGuildUser administrator, [Remainder] string reason)
        {
            await message.DeleteAsync();

            //Variables
            string TimeDate         = Global.TimeDate;
            var    UserAccount      = UserAccounts.GetAccount((SocketUser)promoteuser);
            var    GuildAccount     = GuildAccounts.GetAccount(guild);
            var    ContextGuild     = guild as SocketGuild;
            ulong  PenaltyChannelID = GuildAccount.PenaltyChannelID;
            var    PenaltyChannel   = ContextGuild.GetChannel(PenaltyChannelID) as IMessageChannel;

            var RoleAdm           = guild.Roles.FirstOrDefault(x => x.Id == 517062140612313089);
            var RoleStazysta      = guild.Roles.FirstOrDefault(x => x.Name == "STAŻYSTA");
            var RolePomocnik      = guild.Roles.FirstOrDefault(x => x.Name == "POMOCNIK");
            var RolePomocnikPlus  = guild.Roles.FirstOrDefault(x => x.Name == "POMOCNIK+");
            var RoleModerator     = guild.Roles.FirstOrDefault(x => x.Name == "MODERATOR");
            var RoleAdministrator = guild.Roles.FirstOrDefault(x => x.Name == "ADMIN");
            var RoleOwner         = guild.Roles.FirstOrDefault(x => x.Name == "WŁAŚCICIEL");

            var SocketGuildAdministrator = (SocketGuildUser)administrator;

            //pomocnik
            if (SocketGuildAdministrator.Roles.Contains(RolePomocnik) && (role == RoleStazysta || role == RolePomocnik || role == RolePomocnikPlus || role == RoleModerator || role == RoleAdministrator || role == RoleOwner))
            {
                return;
            }
            //pomocnik plus
            if (SocketGuildAdministrator.Roles.Contains(RolePomocnikPlus) && (role == RolePomocnik || role == RolePomocnikPlus || role == RoleModerator || role == RoleAdministrator || role == RoleOwner))
            {
                return;
            }
            //moderator
            if (SocketGuildAdministrator.Roles.Contains(RoleModerator) && (role == RoleModerator || role == RoleAdministrator || role == RoleOwner))
            {
                return;
            }
            //administrator
            if (SocketGuildAdministrator.Roles.Contains(RoleAdministrator) && (role == RoleAdministrator || role == RoleOwner))
            {
                return;
            }

            //Promote user
            await promoteuser.AddRoleAsync(role);

            if (role == RoleStazysta || role == RolePomocnik || role == RolePomocnikPlus || role == RoleModerator || role == RoleAdministrator)
            {
                await promoteuser.AddRoleAsync(RoleAdm);
            }
            //Send message
            await PenaltyChannel.SendMessageAsync("", false, Messages.GeneratePromoteEmbed(promoteuser, administrator, role, TimeDate, reason));
        }
コード例 #7
0
        public async Task MuteAsync(IGuildUser User)
        {
            if (User.RoleIds.Contains(Context.Server.Mod.MuteRole))
            {
                await ReplyAsync($"{User} is already muted.");

                return;
            }
            if (Context.GuildHelper.HierarchyCheck(Context.Guild, User))
            {
                await ReplyAsync($"Can't mute someone whose highest role is higher than valerie's roles. "); return;
            }
            if (Context.Guild.Roles.Contains(Context.Guild.Roles.FirstOrDefault(x => x.Name == "Muted")))
            {
                Context.Server.Mod.MuteRole = Context.Guild.Roles.FirstOrDefault(x => x.Name == "Muted").Id;
                await User.AddRoleAsync(Context.Guild.Roles.FirstOrDefault(x => x.Name == "Muted"));

                await Context.GuildHelper.LogAsync(Context, User, CaseType.Mute, string.Empty);
                await ReplyAsync($"{User} has been muted {Emotes.ThumbDown}", Document : DocumentType.Server);

                return;
            }
            var Permissions = new OverwritePermissions(addReactions: PermValue.Deny, sendMessages: PermValue.Deny, attachFiles: PermValue.Deny);

            if (Context.Guild.GetRole(Context.Server.Mod.MuteRole) == null)
            {
                var Role = await Context.Guild.CreateRoleAsync("Muted", GuildPermissions.None, Color.DarkerGrey);

                foreach (var Channel in (Context.Guild as SocketGuild).TextChannels)
                {
                    if (!Channel.PermissionOverwrites.Select(x => x.Permissions).Contains(Permissions))
                    {
                        await Channel.AddPermissionOverwriteAsync(Role, Permissions).ConfigureAwait(false);
                    }
                }
                Context.Server.Mod.MuteRole = Role.Id;
                await User.AddRoleAsync(Role);

                await Context.GuildHelper.LogAsync(Context, User, CaseType.Mute, string.Empty);
                await ReplyAsync($"{User} has been muted {Emotes.ThumbDown}", Document : DocumentType.Server);

                return;
            }

            await User.AddRoleAsync(Context.Guild.GetRole(Context.Server.Mod.MuteRole));

            await Context.GuildHelper.LogAsync(Context, User, CaseType.Mute, string.Empty);

            await ReplyAsync($"{User} has been muted {Emotes.ThumbDown}", Document : DocumentType.Server);
        }
コード例 #8
0
        public static async Task <CustomResult> MuteUser(IGuildUser user)
        {
            // will be replaced with a better handling in the future
            if (!Global.Roles.ContainsKey("voicemuted") || !Global.Roles.ContainsKey("textmuted"))
            {
                return(CustomResult.FromError("Configure the voicemuted and textmuted roles correctly. Check your Db!"));
            }
            var muteRole = user.Guild.GetRole(Global.Roles["voicemuted"]);
            await user.AddRoleAsync(muteRole);

            muteRole = user.Guild.GetRole(Global.Roles["textmuted"]);
            await user.AddRoleAsync(muteRole);

            return(CustomResult.FromSuccess());
        }
コード例 #9
0
        public async Task Mute(IGuildUser user, int amount = 0, string unitName = "")
        {
            var gagString = Context.Message.Content.Contains("gag") && !user.Nickname.Contains("gag")
                ? "gagged"
                : "muted";

            var delTask = Context.Message.DeleteAsync();

            IRole mutedRole = Context.Guild.Roles.FirstOrDefault(role => role.Name.ToLower().Contains("muted"));
            var   duration  = 0;

            try
            {
                duration = amount * TimeUnits[unitName];
            }
            catch (KeyNotFoundException)
            {
            }

            if (duration == 0)
            {
                await user.AddRoleAsync(mutedRole);

                await delTask;
                await ReplyAsync($"User {user.Mention} has been {gagString} by {Context.User.Mention}.");

                return;
            }

            if (duration < 0)
            {
                await ReplyAsync($"User <@{user.Id}> has not been {gagString}, since the duration of the {(gagString == "gagged" ? "gag" : "mute")} was negative.");

                return;
            }

            await user.AddRoleAsync(mutedRole);

            await delTask;

            await ReplyAsync($"User {user.Mention} has been {gagString} by {Context.User.Mention} for {amount} {unitName}.");

            await Task.Delay(duration);

            await user.RemoveRoleAsync(mutedRole);

            await ReplyAsync($"User <@{user.Id}> has been un{gagString} automatically.");
        }
コード例 #10
0
ファイル: ModToolModule.cs プロジェクト: crewszk/Sub-Bot
        public async Task MuteAsync(IGuildUser user = null, uint time = 1)
        {
            var guildUser = Context.Guild.GetUser(Context.User.Id);

            if (!CheckPermissions(guildUser, "role"))
            {
                return;
            }

            if (user == null)
            {
                await ReplyAsync("I need to know who you're trying to mute, try `s@help mute` for help");

                return;
            }

            var targetUser = (user as SocketGuildUser).Nickname ?? (user as SocketGuildUser).Username;
            var role       = Context.Guild.Roles.FirstOrDefault(x => x.Name == "Muted");
            await user.AddRoleAsync(role);

            await BotLogAsync(guildUser, "s@mute",
                              $"decided to mute **{targetUser}** in {(Context.Channel as SocketTextChannel).Mention}.\n" +
                              $"They have been muted for {time} minute(s)");

            Task.Delay(TimeSpan.FromMinutes(time)).ContinueWith(t =>
                                                                RemoveMuteSend(user, Context.Guild.GetTextChannel(CommandHandler.ClientToken.GuildChannels.BotLog), role));
        }
コード例 #11
0
        public async Task Mute(IGuildUser userToMute, [Remainder] string reason = "No reason.")
        {
            var guild = await GuildRepository.FetchGuildAsync(Context.Guild.Id);

            var mutedRole = Context.Guild.GetRole((ulong)guild.MutedRoleId);

            if (mutedRole == null)
            {
                throw new Exception($"You may not mute users if the muted role is not valid.\nPlease use the " +
                                    $"`{guild.Prefix}SetMutedRole` command to change that.");
            }
            if (await IsModAsync(userToMute))
            {
                throw new Exception("You cannot mute another mod!");
            }
            await InformSubjectAsync(Context.User, "Mute", userToMute, reason);

            await userToMute.AddRoleAsync(mutedRole);

            await MuteRepository.AddMuteAsync(userToMute.Id, Context.Guild.Id, Config.DEFAULT_MUTE_TIME);

            await Logger.ModLog(Context, "Mute", new Color(255, 114, 14), reason, userToMute, $"\n**Length:** {Config.DEFAULT_MUTE_TIME.TotalHours} hours");

            await ReplyAsync($"{Context.User.Mention} has successfully muted {userToMute.Mention}!");
        }
コード例 #12
0
        /// <summary>
        ///     Mutes specified user.
        ///     <para>Prevents the user from sending chat messages.</para>
        /// </summary>
        public async Task <Embed> MuteAsync(SocketCommandContext context, IGuildUser user, string reason)
        {
            //Get Muted role if it exists or create it if it doesn't exist
            var muteRole = Helper.DoesRoleExist(context.Guild, "Muted") ??
                           await context.Guild.CreateRoleAsync("Muted", GuildPermissions.None, Color.DarkGrey, false,
                                                               null);

            if (user.RoleIds.Any(role => role == muteRole.Id))
            {
                return(CustomFormats.CreateErrorEmbed($"{user} is already muted!"));
            }

            //Add muted role to the user
            await user.AddRoleAsync(muteRole);

            //Loop through every channel in the guild and deny the user from sending messages
            foreach (var channel in context.Guild.TextChannels)
            {
                await channel.AddPermissionOverwriteAsync(user, new OverwritePermissions(sendMessages : PermValue.Deny));
            }

            var caseId = await GenerateModCaseId(context.Guild.Id);

            //Create modCase
            var modCase = new ModCase(context, user, caseId, PunishmentType.Mute, reason);
            await _botContext.ModCases.AddAsync(modCase);

            await _botContext.SaveChangesAsync();

            await SendModLog(context.Guild, modCase);

            return(ModerationFormats.CreateModerationEmbed(user, $"{user} muted",
                                                           $"{user} has been muted for: {reason ?? "_No reason_"}.", Color.DarkGrey));
        }
コード例 #13
0
        public async Task GiveMarietta()
        {
            ulong roleid = 613097920777945091;

            IUser user = Context.User;
            IRole role = Context.Guild.GetRole(roleid);

            IGuildUser   guildUser = user as IGuildUser;
            List <ulong> userRoles = new List <ulong>(guildUser.RoleIds);
            bool         hasRole   = false;

            foreach (ulong x in userRoles)
            {
                if (x == roleid)
                {
                    hasRole = true;
                }
            }

            if (!hasRole)
            {
                await guildUser.AddRoleAsync(role);

                var check = new Emoji("\u2705");
                await Context.Message.AddReactionAsync(check);

                Console.WriteLine($"{DateTime.Now} at Commands] {role.Name} given to {user.Username}.");
            }
            else
            {
                await Context.Channel.SendMessageAsync("" + user.Username + ", you already have that role!");

                Console.WriteLine($"{DateTime.Now} at Commands] {user.Username} already has {role.Name}.");
            }
        }
コード例 #14
0
        public async Task RestoreUserRoles(IGuildUser user)
        {
            var oldUserRoles = GetUserRoles(user);

            if (oldUserRoles != null) // user actually had old roles
            {
                var oldUserRolesList = oldUserRoles.Split(",");

                // restore each role 1 by 1
                foreach (string roleId in oldUserRolesList)
                {
                    IRole role = user.Guild.GetRole(Convert.ToUInt64(roleId));

                    if (role == null) // role does not exist
                    {
                        Log.Error("Unable to return role ID " + roleId + " to user ID " + user.Id + " as it does not exist anymore!");
                        continue;
                    }
                    else
                    {
                        try
                        {
                            await user.AddRoleAsync(role);
                        }
                        catch (Exception ex)
                        {
                            Log.Information("Cannot return the role ID " + role.Id + " to user ID " + user.Id + ". Error: " + ex.ToString());
                            continue; // try add next role
                        }
                    }
                }
            }
        }
コード例 #15
0
        private async Task OnMessage(SocketMessage message)
        {
            IGuildUser user = (IGuildUser)message.Author;

            if (!user.IsBot && !user.RoleIds.Any((id) => id == APPROVED_ROLE))
            {
                if (message.Content.Equals(code))
                {
                    await user.AddRoleAsync(user.Guild.Roles.First((role) => role.Id == APPROVED_ROLE));
                    await UpdateMessage();

                    try
                    {
                        await(await user.GetOrCreateDMChannelAsync())
                        .SendMessageAsync(strings.AgreementSuccess);
                    }
                    catch
                    {
                    }
                }
                await message.DeleteAsync(new RequestOptions()
                {
                    RetryMode = RetryMode.AlwaysRetry
                });
            }
        }
コード例 #16
0
        public async Task AddRole(IRole role)
        {
            if ((role.Permissions.BanMembers || role.Permissions.KickMembers))
            {
                await ReplyAsync("I'm sorry, you can't make yourself a mod...");
            }
            else if (!role.Permissions.SendMessages)
            {
                await ReplyAsync("You probably don't really want to do that.");
            }
            else
            {
                IGuildUser user = await Context.Guild.GetUserAsync(Context.User.Id);

                if (user.RoleIds.Contains(role.Id))
                {
                    await ReplyAsync("You already had that role");
                }
                else
                {
                    await user.AddRoleAsync(role);
                    await ReplyAsync($"You now have the {role.Name} role");
                }
            }
        }
コード例 #17
0
        public async Task mute(IGuildUser user)
        {
            var role = Context.Guild.GetRole(310741004305170433);
            await user.AddRoleAsync(role);

            await ReplyAsync($"{user.Username} Has been muted");
        }
コード例 #18
0
        /// <summary>
        /// Adds the given role to the given user.
        /// </summary>
        /// <param name="context">The command context.</param>
        /// <param name="guildUser">The user.</param>
        /// <param name="role">The role.</param>
        /// <returns>A modification result which may or may not have succeeded.</returns>
        public async Task <ModifyEntityResult> AddUserRoleAsync
        (
            [NotNull] ICommandContext context,
            [NotNull] IGuildUser guildUser,
            [NotNull] IRole role
        )
        {
            if (!await HasPermissionAsync(context, GuildPermission.ManageRoles))
            {
                return(ModifyEntityResult.FromError
                       (
                           "I'm not allowed to manage roles on this server."
                       ));
            }

            if (guildUser.RoleIds.Contains(role.Id))
            {
                return(ModifyEntityResult.FromSuccess(ModifyEntityAction.None));
            }

            try
            {
                await guildUser.AddRoleAsync(role);
            }
            catch (HttpException hex) when(hex.HttpCode == HttpStatusCode.Forbidden)
            {
                return(ModifyEntityResult.FromError
                       (
                           "I couldn't modify the roles due to a priority issue."
                       ));
            }

            return(ModifyEntityResult.FromSuccess());
        }
コード例 #19
0
 private async Task AddNewMoonRoleAsync(IGuildUser caller, SocketRole role)
 {
     if (caller.RoleIds.Contains(role.Id) == false)
     {
         await caller.AddRoleAsync(role);
     }
 }
コード例 #20
0
        public async Task Mute([Remainder] string a)
        {
            GuildPermissions perms = GuildPermissions.None;

            perms = Context.Guild.EveryoneRole.Permissions.Modify(sendMessages: false);
            var        mutedUserId = Context.Message.MentionedUserIds.First();
            var        guild       = Context.Guild;
            IGuildUser user        = await guild.GetUserAsync(mutedUserId);

            Dictionary <string, ulong> roledict = guild.Roles.ToDictionary(x => { return(x.Name); }, y => { return(y.Id); });
            IRole muteRole = null;

            if (roledict.ContainsKey("Muted") == false)
            {
                muteRole = await guild.CreateRoleAsync("Muted", perms);
            }
            else
            {
                roledict.TryGetValue("Muted", out ulong id);
                muteRole = Context.Guild.GetRole(id);
            }
            await user.AddRoleAsync(muteRole);

            await ReplyAsync($"Muted {user}!");
        }
コード例 #21
0
        public async Task Role(IGuildUser user, string roles)
        {
            try
            {
                var GuildUser = await Context.Guild.GetUserAsync(Context.User.Id);

                if (GuildUser.Id != 185402901236154368)
                {
                    await Context.Channel.SendMessageAsync("No rights");
                }
                else
                {
                    var role = Context.Guild.Roles.FirstOrDefault(x => x.Name == roles);
                    await user.AddRoleAsync(role);

                    var embed = new EmbedBuilder
                    {
                        Title       = "Admin",
                        Description = $"Gave **{user}** the role **{roles}**"
                    };
                    await ReplyAsync("", false, embed.Build());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
コード例 #22
0
ファイル: AddRole.cs プロジェクト: mmattbtw/Kaguya
        public async Task GiveRole(IGuildUser user, params string[] args)
        {
            int i = 0;

            foreach (string roleName in args)
            {
                SocketRole role = roleName.AsUlong(false) != 0
                    ? Context.Guild.GetRole(roleName.AsUlong())
                    : Context.Guild.Roles.FirstOrDefault(x => x.Name.ToLower() == roleName.ToLower());

                try
                {
                    await user.AddRoleAsync(role);

                    i++;
                }
                catch (Exception ex)
                {
                    await ConsoleLogger.LogAsync($"Exception thrown when adding role to user through command addrole: {ex.Message}", LogLvl.WARN);
                }
            }

            var embed = new KaguyaEmbedBuilder
            {
                Description = $"`{user.Username}` has been given `{i.ToWords()}` roles."
            };

            await ReplyAsync(embed : embed.Build());
        }
コード例 #23
0
ファイル: StreamerModule.cs プロジェクト: PezeM/Volvox.Helios
        /// <summary>
        ///     Add the specified user to the specified streaming role.
        /// </summary>
        /// <param name="guildUser">User to add to role.</param>
        /// <param name="streamingRole">Role to add the user to.</param>
        private async Task AddUserToStreamingRole(IGuildUser guildUser, IRole streamingRole)
        {
            await guildUser.AddRoleAsync(streamingRole);

            Logger.LogDebug($"Streamer Module: Adding {guildUser.Username} to role {streamingRole.Name}. " +
                            $"Guild ID: {guildUser.GuildId}, User ID: {guildUser.Id}.");
        }
コード例 #24
0
ファイル: AnnounceMonitor.cs プロジェクト: rreminy/Prima2
        private async Task AssignExecutorRole(SocketGuild guild, IGuildUser host)
        {
            var executor = guild.GetRole(DelubrumProgressionRoles.Executor);
            await host.AddRoleAsync(executor);

            await _db.AddTimedRole(executor.Id, guild.Id, host.Id, DateTime.UtcNow.AddHours(4.5));
        }
コード例 #25
0
ファイル: InfoModule.cs プロジェクト: Eforen/Town-Crier
		public async Task OptIn()
		{
			if (Context.Guild == null)
			{
				await ReplyAsync("You must call this from within a server channel.");
				return;
			}

			IGuildUser user = Context.User as IGuildUser;
			IRole role = Context.Guild.Roles.FirstOrDefault(test => test.Name == "followers");

			if (role == null)
			{
				await ReplyAsync("Role not found");
				return;
			}

			if (user.RoleIds.Contains(role.Id))
			{
				await ReplyAsync("You are already a follower!\nUse !unfollow to stop following.");
				return;
			}

			await user.AddRoleAsync(role);
			await ReplyAsync("You are now a follower!");
		}
コード例 #26
0
        public async Task Silence(IUser userToSilence)
        {
            var application = await Context.Client.GetApplicationInfoAsync();

            IGuildUser user       = userToSilence as IGuildUser;
            var        activeuser = Context.User as IGuildUser;
            var        silent     = Justibot.Loader.LoadPerm(user, "SILENCE");

            if (silent.Item1 == true)
            {
                if ((activeuser.GuildPermissions.Has(GuildPermission.MuteMembers) && activeuser.GuildPermissions.Has(GuildPermission.ManageMessages)) || activeuser.Id == application.Owner.Id)
                {
                    bool isStaff = Justibot.Loader.isStaff(userToSilence as IGuildUser);
                    if (isStaff == false)
                    {
                        IRole joinerRole = user.Guild.GetRole(silent.Item2) as IRole;
                        await user.AddRoleAsync(joinerRole);
                        await ReplyAsync($"{activeuser.Mention} has silenced {userToSilence.Mention}, please appeal to a staff member via voice chat or DM to be allowed to talk again.");
                    }
                    else
                    {
                        await ReplyAsync("Cannot silence a staff member");
                    }
                }
                else
                {
                    await ReplyAsync("You do not have permission to use this command");
                }
            }
        }
コード例 #27
0
        public async Task Void(IGuildUser member, ulong moderator, string?reason)
        {
            var moderation = member.Guild.Roles.Where(x => x.Name.StartsWith("moderat", StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); // Moderation, moderator. Yes, it's shit.
            var voided     = member.Guild.Roles.Where(x => x.Name.StartsWith("void", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();    // Void, voided

            if (moderation == null)
            {
                throw new MissingRoleException("No moderation/moderator role exists.");
            }
            if (voided == null)
            {
                throw new MissingRoleException("No void role exists.");
            }
            using var db = data.GetContext();
            var channel = await member.Guild.CreateTextChannelAsync("void-" + member.Id);

            await Task.WhenAll(
                channel.AddPermissionOverwriteAsync(member, new OverwritePermissions(68608, 0)),
                channel.AddPermissionOverwriteAsync(member.Guild.EveryoneRole, new OverwritePermissions(0, 68608)),
                channel.AddPermissionOverwriteAsync(moderation, new OverwritePermissions(68608, 0)),
                member.AddRoleAsync(voided),
                db.AddModerationAction(
                    guild: member.GuildId,
                    member: member.Id,
                    moderator: moderator,
                    since: DateTime.Now,
                    type: (byte)ModerationType.Void,
                    reason: reason
                    )
                );
        }
コード例 #28
0
        public async Task SBanAsync(IGuildUser user, [Remainder] string reason = "No reason specified.")
        {
            var victim = user as SocketGuildUser;
            var author = Context.User as SocketGuildUser;

            if (Context.User.Id == user.Id)
            {
                await ReplyAsync("Just leave");

                return;
            }

            if (victim.Hierarchy >= author.Hierarchy)
            {
                await ReplyAsync("You are not high enough in the Role Hierarchy to do that");
            }
            else
            {
                await user.AddRoleAsync(Context.Client.GetGuild(Context.Guild.Id).GetRole(Config.SoftbanRoleId));

                UserSoftBanned?.Invoke(this, new ModEventArgs()
                {
                    OffendingUser = user, ResponsibleModerator = Context.User, Reason = reason
                });
                await ReplyAsync("User " + user.Username + " was banished to the Shadow Realm. Reason: " + reason);
            }
        }
コード例 #29
0
        public async Task joinRole([Remainder] string roleName)
        {
            IRole role = Utilities.RoleHelper.getRole(roleName, Context);



            string[] whiteList = { "Students", "Guests", "Alumni" };

            if (!whiteList.Contains(role.Name))
            {
                await ReplyAsync($"That role is not availible with that command. Please try a different role.");

                return;
            }

            if (role == null)
            {
                await ReplyAsync($"{Context.User.Mention} The role could not be found. You have not been added to the role ***{role.Name}***.");

                return;
            }

            IGuildUser user = (IGuildUser)Context.User;

            await leaveRole();

            await user.AddRoleAsync(Utilities.RoleHelper.getRole(roleName, Context));

            await ReplyAsync($"{Context.User.Mention} You have successfully been added to the role ***{role.Name}!***");
        }
コード例 #30
0
ファイル: EventModule.cs プロジェクト: Zulleyy3/ColonelBot-v4
        public async Task <Embed> ToggleRole(IGuildUser caller, SocketRole role)
        {
            string RoleResponseText = "";

            if (caller.RoleIds.Contains(role.Id))
            {//The caller already has the role, remove it.
                await caller.RemoveRoleAsync(role, null);

                RoleResponseText = "The " + role.Name + " role has been removed.";
            }
            else
            {//The caller does not have the role, add it.
                await caller.AddRoleAsync(role, null);

                RoleResponseText = "The " + role.Name + " role has been added.";
            }
            var embed = new EmbedBuilder
            {
                Color = new Color(0xffcf39)
            };

            embed.AddField("Role Updated", RoleResponseText);
            await ReplyAsync("", embed : embed.Build());

            return(embed.Build());
        }