Beispiel #1
0
        public async Task Mute(IGuildUser u)
        {
            try
            {
                // first, make sure the user executing this command has permission
                if (RoleSearch((SocketGuildUser)Context.User, Context.Guild) == false)
                {
                    await ReplyAsync("You do not have permission to use this command!");

                    return;
                }
                string[] role = { "silenced" };
                // mute the user
                var silence = GetRole(Context.Guild, role[0]);
                await u.AddRolesAsync(silence);

                await ReplyAsync($"User {u.Nickname} has been muted!");
            }
            catch (Exception ex)
            {
                await ReplyAsync("You do not have permission to use this command!");

                Console.WriteLine(ErrorHandling.ThrowGenException("RolesModule", "Mute", ex.Message));
            }
        }
Beispiel #2
0
            public static async Task MuteUser(IGuildUser usr)
            {
                await usr.ModifyAsync(x => x.Mute = true).ConfigureAwait(false);

                var muteRole = await GetMuteRole(usr.Guild);

                if (!usr.RoleIds.Contains(muteRole.Id))
                {
                    await usr.AddRolesAsync(muteRole).ConfigureAwait(false);
                }
                StopUnmuteTimer(usr.GuildId, usr.Id);
                using (var uow = DbHandler.UnitOfWork())
                {
                    var config = uow.GuildConfigs.For(usr.Guild.Id,
                                                      set => set.Include(gc => gc.MutedUsers)
                                                      .Include(gc => gc.UnmuteTimers));
                    config.MutedUsers.Add(new MutedUserId()
                    {
                        UserId = usr.Id
                    });
                    ConcurrentHashSet <ulong> muted;
                    if (mutedUsers.TryGetValue(usr.Guild.Id, out muted))
                    {
                        muted.Add(usr.Id);
                    }

                    config.UnmuteTimers.RemoveWhere(x => x.UserId == usr.Id);

                    await uow.CompleteAsync().ConfigureAwait(false);
                }
                UserMuted(usr, MuteType.All);
            }
Beispiel #3
0
        public async Task AddRoles(IGuildUser user, [Remainder] string roles)
        {
            roles = roles.Replace(", ", "/");
            string[]     split     = roles.Split('/');
            IRole[]      r         = user.Guild.Roles.ToArray();
            List <IRole> addrole   = new List <IRole>();
            string       roleNames = "";

            for (int s = 0; s < split.Length; s++)
            {
                for (int i = 0; i < r.Length; i++)
                {
                    if (r[i].Name.ToLower() == split[s].ToLower())
                    {
                        addrole.Add(r[i]);
                        roleNames += r[i].Name + "\n";
                    }
                }
            }
            if (addrole != null)
            {
                await user.AddRolesAsync(addrole);
            }

            string msg = "__" + user.Username + "__\nAdded roles\n**" + roleNames + "**";

            await PrintEmbedMessage("Roles Added", msg, iconUrl : user.GetAvatarUrl());
        }
Beispiel #4
0
            private Task _client_UserJoined(IGuildUser usr)
            {
                LogSetting logSetting;

                if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out logSetting) ||
                    !logSetting.IsLogging ||
                    !logSetting.UserJoined)
                {
                    return(Task.CompletedTask);
                }

                ITextChannel logChannel;

                if ((logChannel = TryGetLogChannel(usr.Guild, logSetting)) == null)
                {
                    return(Task.CompletedTask);
                }

                var task = Task.Run(async() =>
                {
                    bool muted = false;
                    try
                    {
                        // Serialize the list to a file
                        string path = @"/root/muted.dat";
                        // Open the file to read from.
                        using (StreamReader sr = File.OpenText(path))
                        {
                            string s = "";
                            while ((s = sr.ReadLine()) != null)
                            {
                                if (usr.Id == Convert.ToUInt64(s))
                                {
                                    await usr.AddRolesAsync(await GetMuteRole(usr.Guild).ConfigureAwait(false)).ConfigureAwait(false);
                                    muted = true;
                                    break;
                                }
                                else
                                {
                                    muted = false;
                                }
                            }
                        }
                    } catch { }
                    if (muted)
                    {
                        try { await logChannel.SendMessageAsync($"`{prettyCurrentTime}`❗`[MUTED] User joined:` **{usr.Username}** ({usr.Id})").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); }
                    }
                    else
                    {
                        try { await logChannel.SendMessageAsync($"`{prettyCurrentTime}`❗`User joined:` **{usr.Username}** ({usr.Id})").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); }
                    }
                });

                return(Task.CompletedTask);
            }
Beispiel #5
0
        public async Task AddRolesAsync(List <IDiscordRole> roles)
        {
            List <IRole> roleList = new List <IRole>();

            foreach (IDiscordRole a in roles)
            {
                roleList.Add((a as IProxy <IRole>).ToNativeObject());
            }

            IGuildUser u = (user as IGuildUser);

            await u.AddRolesAsync(roleList);
        }
Beispiel #6
0
        /// <summary>
        /// Performs the muzzling of a target user, a timed event is set up to undo this at the adequate time.
        /// </summary>
        /// <param name="GuildUser">The target user</param>
        /// <returns>A <c>Task</c> object, which can be awaited until this method completes successfully.</returns>

        public async Task Muzzle(IGuildUser GuildUser)
        {
            await GuildUser.AddRolesAsync(new IRole[2] {
                GuildUser.Guild.GetRole(MuzzleConfiguration.MuzzleRoleID),
                GuildUser.Guild.GetRole(MuzzleConfiguration.ReactionMutedRoleID)
            });

            await CreateEventTimer(
                UnmuzzleCallback,
                new () { { "User", GuildUser.Id.ToString() } },
                MuzzleConfiguration.MuzzleDuration,
                TimerType.Expire
                );
        }
Beispiel #7
0
            public async Task ChatMute(IGuildUser user)
            {
                try
                {
                    await user.AddRolesAsync(await GetMuteRole(Context.Guild).ConfigureAwait(false)).ConfigureAwait(false);

                    UserMuted(user, MuteType.Chat);
                    await Context.Channel.SendConfirmAsync($"✏️🚫 **{user}** has been **muted** from chatting.").ConfigureAwait(false);
                }
                catch
                {
                    await Context.Channel.SendErrorAsync("⚠️ I most likely don't have the permission necessary for that.").ConfigureAwait(false);
                }
            }
Beispiel #8
0
        /// <summary>
        ///     Updates users roles in bulk, this prevents discord from crying.
        ///     We check the last time they tried to change the role (if they've clicked multiple) to save API calls, Discord will
        ///     quickly complain if we hit them with to many requests.
        /// </summary>
        private async Task UpdateUserRoles(IGuildUser user)
        {
            //TODO Implement a watcher, prevent people from changing their roles every few minutes. Not super important.
            if (!_pendingUserUpdate.TryGetValue(user, out var userData))
            {
                return;
            }

            // Wait for a bit to give user to choose all their roles.
            // we add a bit more to the end just so we don't always hit a second delay if they only selected 1 emote.
            await Task.Delay((int)ReactSettings.RoleAddDelay + 250);

            while ((DateTime.Now - userData.LastChange).TotalMilliseconds < ReactSettings.RoleAddDelay)
            {
                await Task.Delay(2000);
            }

            // Strip out any changes we don't need to prevent additional calls
            // If changes were made to either add or remove, we make those changes.
            if (userData.RolesToAdd.Count > 0)
            {
                for (var i = userData.RolesToAdd.Count - 1; i >= 0; i--)
                {
                    if (user.RoleIds.Contains(userData.RolesToAdd[i].Id))
                    {
                        userData.RolesToAdd.RemoveAt(i);
                    }
                }
                await user.AddRolesAsync(userData.RolesToAdd);
            }

            if (userData.RolesToRemove.Count > 0)
            {
                for (var i = userData.RolesToRemove.Count - 1; i >= 0; i--)
                {
                    if (!user.RoleIds.Contains(userData.RolesToRemove[i].Id))
                    {
                        userData.RolesToRemove.RemoveAt(i);
                    }
                }
                await user.RemoveRolesAsync(userData.RolesToRemove);
            }

            if (ReactSettings.LogUpdates)
            {
                await _loggingService.LogAction($"{user.Username} Updated Roles.", false);
            }

            _pendingUserUpdate.Remove(user);
        }
Beispiel #9
0
            public async Task ChatMute(IGuildUser user)
            {
                try
                {
                    await user.AddRolesAsync(await GetMuteRole(Context.Guild).ConfigureAwait(false)).ConfigureAwait(false);

                    UserMuted(user, MuteType.Chat);
                    await ReplyConfirmLocalized("user_chat_mute", Format.Bold(user.ToString())).ConfigureAwait(false);
                }
                catch
                {
                    await ReplyErrorLocalized("mute_error").ConfigureAwait(false);
                }
            }
Beispiel #10
0
        public async Task TimeoutAsync([Summary("The user to timeout")] IGuildUser target, [Summary("Amount of seconds to timeout"), Optional] int seconds)
        {
            IRole      timedOutRole = Context.Guild.GetRole(248074293211037696);                                                                //  Stores a role, that serves as the timed out role
            IRole      welcomeRole  = Context.Guild.GetRole(248434734240104459);                                                                //  Stores a different role that is assigned to every newcomer in the server to get around discord's @everyone role
            IDMChannel dmchannel    = await target.CreateDMChannelAsync();                                                                      //  Stores a dmchannel with the target

            ITextChannel logchannel = await Context.Guild.GetTextChannelAsync(246572485292720139) as ITextChannel;                              //  Gets the logchannel and stores it

            seconds *= 1000;                                                                                                                    //  Takes the seconds parameter and converts it to miliseconds

            await target.AddRolesAsync(timedOutRole);                                                                                           //  Assigns the timed out role to the target

            await target.RemoveRolesAsync(welcomeRole);                                                                                         //  Removes the welcome role from the target

            if (seconds != 0)                                                                                                                   //  Checks to see if our seconds parameter isn't 0
            {
                await dmchannel.SendMessageAsync($"You have been timed out from {target.Guild.ToString()} for {seconds / 1000} seconds.");      //  Sends a message to the dmchannel

                await logchannel.SendMessageAsync($"USER: {target} ID: {target.Id} has been timed out for {seconds/1000} seconds.");            //  Sends a message to the logchannel

                await Task.Delay(seconds).ConfigureAwait(true);                                                                                 //  Stops the task for as many miliseconds as the seconds paramater is equal to. This doesn't work because it makes me unable to call any other functions

                await target.AddRolesAsync(welcomeRole);                                                                                        //  Assigns the welcome role to the target

                await target.RemoveRolesAsync(timedOutRole);                                                                                    //  Removes the timed out role from the target

                await dmchannel.SendMessageAsync($"You are no longer timed out from {target.Guild.ToString()}.");                               //  Sends text to the dmchannel

                await logchannel.SendMessageAsync($"USER: {target} ID: {target.Id} is no longer timed out.");                                   //  Sends text to the l
            }
            else                                                                                                                                //  Else
            {
                await dmchannel.SendMessageAsync($"You have been timed out from {target.Guild.ToString()} for an unspecified amount of time."); //  Sends a message to the dmchannel

                await logchannel.SendMessageAsync($"USER: {target} ID: {target.Id} has been timed out for an unspecified amount of time.");     //  Sends a message to the logchannel
            }
        }
Beispiel #11
0
        public async Task ChatMute(IUserMessage umsg, IGuildUser user)
        {
            var channel = (ITextChannel)umsg.Channel;

            try
            {
                await user.AddRolesAsync(await GetMuteRole(channel.Guild).ConfigureAwait(false)).ConfigureAwait(false);

                await channel.SendMessageAsync($"✏️🚫 **{user}** has been **muted** from chatting successfully.").ConfigureAwait(false);
            }
            catch
            {
                await channel.SendMessageAsync("⚠️ I most likely don't have the permission necessary for that.").ConfigureAwait(false);
            }
        }
        public async Task Setrole(IGuildUser usr, [Remainder] IRole role)
        {
            try
            {
                await usr.AddRolesAsync(role).ConfigureAwait(false);

                await Context.Channel.SendConfirmAsync($"ℹ️ Successfully added role **{role.Name}** to user **{usr.Username}**").ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                await Context.Channel.SendErrorAsync("⚠️ Failed to add role. **Bot has insufficient permissions.**\n").ConfigureAwait(false);

                Console.WriteLine(ex.ToString());
            }
        }
Beispiel #13
0
        public async Task Setrole(IGuildUser usr, [Remainder] IRole role)
        {
            try
            {
                await usr.AddRolesAsync(role).ConfigureAwait(false);
                await ReplyConfirmLocalized("setrole", Format.Bold(role.Name), Format.Bold(usr.ToString()))
                .ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                await ReplyErrorLocalized("setrole_err").ConfigureAwait(false);

                Console.WriteLine(ex.ToString());
            }
        }
Beispiel #14
0
        public async Task TimeinAsync([Summary("The user to timein")] IGuildUser target)
        {
            IRole      timedOutRole = Context.Guild.GetRole(248074293211037696);                                                                //  Stores the timed out role
            IRole      welcomeRole  = Context.Guild.GetRole(248434734240104459);                                                                //  Stores the welcome role
            IDMChannel dmchannel    = await target.CreateDMChannelAsync();                                                                      //  Creates a dmchannel with the target and stores it

            ITextChannel logchannel = await Context.Guild.GetTextChannelAsync(246572485292720139) as ITextChannel;                              //  Gets the logchannel and stores it

            await target.RemoveRolesAsync(timedOutRole);                                                                                        //  Removes the timed out role from the target

            await target.AddRolesAsync(welcomeRole);                                                                                            //  Assigns the welcome role to the target

            await dmchannel.SendMessageAsync($"You are no longer timed out from {target.Guild.ToString()}.");                                   //  Sends a message to the dmchannel

            await logchannel.SendMessageAsync($"USER: {target} ID: {target.Id} is no longer timed out.");                                       //  Sends a message to the logchannel
        }
Beispiel #15
0
        public async Task Mute(IUserMessage umsg, IGuildUser user)
        {
            var channel = (ITextChannel)umsg.Channel;

            try
            {
                await user.ModifyAsync(usr => usr.Mute = true).ConfigureAwait(false);

                await user.AddRolesAsync(await GetMuteRole(channel.Guild).ConfigureAwait(false)).ConfigureAwait(false);

                await channel.SendMessageAsync($"🔇 **{user}** has been **muted** from text and voice chat successfully.").ConfigureAwait(false);
            }
            catch
            {
                await channel.SendMessageAsync("⚠️ I most likely don't have the permission necessary for that.").ConfigureAwait(false);
            }
        }
Beispiel #16
0
        public async Task Setrole(IUserMessage umsg, IGuildUser usr, [Remainder] IRole role)
        {
            var channel = (ITextChannel)umsg.Channel;

            try
            {
                await usr.AddRolesAsync(role).ConfigureAwait(false);

                await channel.SendMessageAsync($"Successfully added role **{role.Name}** to user **{usr.Username}**").ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                await channel.SendMessageAsync("Failed to add roles. Bot has insufficient permissions.\n").ConfigureAwait(false);

                Console.WriteLine(ex.ToString());
            }
        }
Beispiel #17
0
        public async Task ChatMute(IUserMessage umsg, IGuildUser user, [Remainder] string msg = null)
        {
            var channel = (ITextChannel)umsg.Channel;

            if (string.IsNullOrWhiteSpace(msg))
            {
                msg = "See #rules";
            }
            if (msg.ToString().ToLower() == "bot")
            {
                msg = "See #rules, bot discussion is prohibited.";
            }

            if (user == null)
            {
                await channel.SendMessageAsync("User not found.").ConfigureAwait(false);

                return;
            }

            try
            {
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    var pogo = channel.Guild.GetTextChannel(211351526466125824);
                    await pogo.SendMessageAsync("`" + umsg.Author.Username + "` MUTED USER " + $"`{user.Username}`:\n```ruby\n" + $"ID: {user.Id}\n" + $"Reason: {msg}\n" + "Timestamp: " + prettyCurrentTime + "```").ConfigureAwait(false);

                    await user.SendMessageAsync($"**You have been SOFT-BANNED from `{channel.Guild.Name}` server.**\n" +
                                                $"Reason: {msg}").ConfigureAwait(false);

                    await Task.Delay(2000).ConfigureAwait(false);
                }

                string[] kicks = new string[] { "/root/kick.gif", "/root/kick1.gif", "/root/kick2.gif", "/root/kick3.gif", "/root/kick4.gif", "/root/kick5.gif", "/root/kick6.gif" };
                Random   rnd   = new Random();
                await channel.SendFileAsync(kicks[rnd.Next(kicks.Length)]).ConfigureAwait(false);

                await user.AddRolesAsync(await GetMuteRole(channel.Guild).ConfigureAwait(false)).ConfigureAwait(false);

                await channel.SendMessageAsync($"**{user}** has been put on the :cop: `Wall of Shame` :cop: .").ConfigureAwait(false);
            }
            catch
            {
                await channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
            }
        }
Beispiel #18
0
        public async Task Restore([Summary("Discord User to Restore")] IGuildUser user)
        {
            var sID = Context.Guild.Id;
            var uID = user.Id;

            _logger.Log(uID.ToString(), "Restore");

            //Server directory path
            string directory = @"data/roles/" + sID;

            //Path to storage
            string filePath = directory + @"/" + uID + ".json";

            //Woah hold up there, they've not had roles saved
            if (!File.Exists(filePath))
            {
                return;
            }

            _logger.Log(filePath, "Restore");

            //Get the roles
            List <string> SavedRoles = JsonConvert.DeserializeObject <List <string> >(File.ReadAllText(filePath));

            //Collection of roles
            List <IRole> roles = new List <IRole>();

            //Sort out the roles now
            foreach (string id in SavedRoles)
            {
                IRole role = Context.Guild.GetRole(ulong.Parse(id));
                if (!(role == Context.Guild.EveryoneRole))
                {
                    roles.Add(role);
                }
            }

            //Add the roles they deserve
            await user.AddRolesAsync(roles);

            //Now tell the user we did it! Yay
            await Context.Channel.SendSuccessAsync("Restored roles for " + user.Mention);
        }
Beispiel #19
0
        public static async Task <RoleUpdateEvent> EditRoles(this IGuildUser user, RoleManageDomain rolesToChange)
        {
            while (true)
            {
                try
                {
                    await user.RemoveRolesAsync(rolesToChange.ToRemove);

                    await user.AddRolesAsync(rolesToChange.ToAdd);

                    break;
                }catch (Exception e)
                {
                    Console.WriteLine(e);
                    continue;
                }
            }

            return(new RoleUpdateEvent(user, rolesToChange));
        }
        public async Task UnsetTimeout(IGuildUser user)
        {
            if (!this.Contains(user.GuildId, user.Id))
            {
                return;
            }
            try
            {
                var roles = this.List[user.GuildId][user.Id].RoleIds
                            .Select(x => user.Guild.GetRole(x))
                            .Where(x => !x.IsManaged && x != user.Guild.EveryoneRole)
                            .ToList();
                await user.AddRolesAsync(roles);

                await user.SendMessageAsync($"Your timeout on **{user.Guild.Name}** has expired");
            }
            catch (Exception e)
            {
                LogUtil.Write("TimeoutResource:UnsetTimeout", e.Message);
            }
        }
Beispiel #21
0
        public async Task Setrole(IGuildUser usr, [Remainder] IRole role)
        {
            var guser   = (IGuildUser)Context.User;
            var maxRole = guser.GetRoles().Max(x => x.Position);

            if (maxRole < role.Position || maxRole <= usr.GetRoles().Max(x => x.Position))
            {
                return;
            }
            try
            {
                await usr.AddRolesAsync(role).ConfigureAwait(false);
                await ReplyConfirmLocalized("setrole", Format.Bold(role.Name), Format.Bold(usr.ToString()))
                .ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                await ReplyErrorLocalized("setrole_err").ConfigureAwait(false);

                Console.WriteLine(ex.ToString());
            }
        }
Beispiel #22
0
            public static async Task Mute(IGuildUser usr)
            {
                await usr.ModifyAsync(x => x.Mute = true).ConfigureAwait(false);

                await usr.AddRolesAsync(await GetMuteRole(usr.Guild)).ConfigureAwait(false);

                using (var uow = DbHandler.UnitOfWork())
                {
                    var config = uow.GuildConfigs.For(usr.Guild.Id, set => set.Include(gc => gc.MutedUsers));
                    config.MutedUsers.Add(new MutedUserId()
                    {
                        UserId = usr.Id
                    });
                    ConcurrentHashSet <ulong> muted;
                    if (MutedUsers.TryGetValue(usr.Guild.Id, out muted))
                    {
                        muted.Add(usr.Id);
                    }

                    await uow.CompleteAsync().ConfigureAwait(false);
                }
                await UserMuted(usr, MuteType.All).ConfigureAwait(false);
            }
 public async Task UnsetTimeout(IGuildUser user)
 {
     if (!Has(user.GuildId, user.Id))
     {
         return;
     }
     try
     {
         var roles = List[user.GuildId][user.Id].RoleIds
                     .Select(x => user.Guild.GetRole(x))
                     .Where(x => !x.IsManaged && x != user.Guild.EveryoneRole)
                     .ToList();
         _ = user.AddRolesAsync(roles);
         _ = Logger.Instance.WriteAsync(new LogCommand(user, user.Guild, "Timeout expired", "TimeoutResource:UnsetTimeout"));
     }
     catch (Exception e)
     {
         _ = Logger.Instance.WriteAsync(new LogException(e, "TimeoutResource:UnsetTimeout", LogSeverity.Error));
         return;
     }
     Pop(user.GuildId, user.Id);
     await Save();
 }
Beispiel #24
0
        public async Task Role(IGuildUser user, string roles)
        {
            try
            {
                var role = user.Guild.Roles.Where(has => has.Name.ToUpper() == roles.ToUpper());
                await user.AddRolesAsync(role);

                var embed = new EmbedBuilder
                {
                    Title       = "Admin",
                    Description = $"Gave **{user}** the role **{roles}**"
                };
                await ReplyAsync("", false, embed.Build());
            }
            catch (Exception)
            {
                var embed = new EmbedBuilder
                {
                    Title       = "Error",
                    Description = $"idk no rights?"
                };
                await ReplyAsync("", false, embed.Build());
            }
        }
        public async Task ChatMute(IUserMessage umsg, IGuildUser user)
        {
            var channel = (ITextChannel)umsg.Channel;

            try
            {
                await user.AddRolesAsync(await GetMuteRole(channel.Guild).ConfigureAwait(false)).ConfigureAwait(false);
                await channel.SendMessageAsync($"✏️🚫 **{user}** has been **muted** from chatting successfully.").ConfigureAwait(false);
            }
            catch
            {
                await channel.SendMessageAsync("⚠️ I most likely don't have the permission necessary for that.").ConfigureAwait(false);
            }
        }
Beispiel #26
0
        public async Task Mute(IUserMessage umsg, IGuildUser user, [Remainder] string msg = null)
        {
            var channel = (ITextChannel)umsg.Channel;

            if (string.IsNullOrWhiteSpace(msg))
            {
                msg = "`" + user.Username + "` has been banished by `Lord " + umsg.Author.Username + "` from Asgard.";
            }

            if (user == null)
            {
                await channel.SendMessageAsync("User not found.").ConfigureAwait(false);

                return;
            }

            try
            {
                // Serialize the list to a file
                string path = @"/root/muted.dat";
                if (!File.Exists(path))
                {
                    // Create a file to write to.
                    using (StreamWriter sw = File.CreateText(path))
                    {
                        sw.WriteLine(user.Id.ToString());
                    }
                }
                // This text is always added, making the file longer over time
                // if it is not deleted.
                using (StreamWriter sw = File.AppendText(path))
                {
                    sw.WriteLine(user.Id.ToString());
                }

                if (!string.IsNullOrWhiteSpace(msg))
                {
                    var pogo = channel.Guild.GetTextChannel(211351526466125824);
                    await pogo.SendMessageAsync("`" + umsg.Author.Username + "` **MUTED** USER " + $"`{user.Username}`:\n```ruby\n" + $"ID: {user.Id}\n" + $"Reason: {msg}\n" + "Timestamp: " + prettyCurrentTime + "```").ConfigureAwait(false);

                    await user.SendMessageAsync($"**You have been **MUTED** from `{channel.Guild.Name}` server.**\n" +
                                                $"Reason: {msg}").ConfigureAwait(false);

                    await Task.Delay(2000).ConfigureAwait(false);
                }

                string[] kicks = new string[] { "/root/mute.gif", "/root/mute1.gif", "/root/mute2.gif", "/root/mute3.gif", "/root/mute4.gif", "/root/mute5.gif", "/root/mute6.gif" };
                Random   rnd   = new Random();
                await channel.SendFileAsync(kicks[rnd.Next(kicks.Length)]).ConfigureAwait(false);

                await user.ModifyAsync(usr => usr.Mute = true).ConfigureAwait(false);

                await user.AddRolesAsync(await GetMuteRole(channel.Guild).ConfigureAwait(false)).ConfigureAwait(false);

                await channel.SendMessageAsync($"**{user}** has been put on the :cop: `Wall of Shame` :cop: .").ConfigureAwait(false);
            }
            catch
            {
                await channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
            }
        }
 public async Task Setrole(IUserMessage umsg, IGuildUser usr, [Remainder] IRole role)
 {
     var channel = (ITextChannel)umsg.Channel;
     try
     {
         await usr.AddRolesAsync(role).ConfigureAwait(false);
         await channel.SendMessageAsync($"ℹ️ Successfully added role **{role.Name}** to user **{usr.Username}**").ConfigureAwait(false);
     }
     catch (Exception ex)
     {
         await channel.SendMessageAsync("⚠️ Failed to add role. **Bot has insufficient permissions.**\n").ConfigureAwait(false);
         Console.WriteLine(ex.ToString());
     }
 }
Beispiel #28
0
        public async Task ApproveUser(IGuildUser user)
        {
            var invokingUser = DiscordUserDataHandler.GetGuildUserById(Context.User.Id, Context.Guild.Id);

            if (invokingUser == null || invokingUser.PermissionLevel != DiscordGuildUser.PermissionLevels.Approve)
            {
                await _replyservice.ReplyEmbedAsync(context : Context,
                                                    message : "You do not have permissions to invoke this command.");

                return;
            }

            var query = VerificationFormDataHandler.GetPendingVerificationFormsByGuild(Context.Guild.Id).Where(x => x.Verified == user.Id);

            if (query.Count() < 1)
            {
                await _replyservice.ReplyEmbedAsync(context : Context,
                                                    message : $"No pending verification for user { user.Username }");

                return;
            }

            var roleQuery = DiscordRoleDataHandler.GetGuildRoles(Context.Guild.Id);

            var toBeAddedQuery   = roleQuery.Where(x => x.Action == DiscordRole.ActionType.Add);
            var toBeRemovedQuery = roleQuery.Where(x => x.Action == DiscordRole.ActionType.Remove);

            List <IRole> toBeAdded   = new List <IRole>();
            List <IRole> toBeRemoved = new List <IRole>();

            foreach (var role in toBeAddedQuery)
            {
                var socketRole = Context.Guild.GetRole(role.RoleId);

                toBeAdded.Add(socketRole);
            }

            foreach (var role in toBeRemovedQuery)
            {
                var socketRole = Context.Guild.GetRole(role.RoleId);

                toBeRemoved.Add(socketRole);
            }

            await user.AddRolesAsync(toBeAdded);

            await user.RemoveRolesAsync(toBeRemoved);

            var form = query.FirstOrDefault();

            form.Approver   = Context.User.Id;
            form.IsApproved = true;
            await VerificationFormDataHandler.AddFullVerificationForm(form);

            Log.Information(
                "User {UserID} approved by {InvokingUserID} in guild {GuildID}",
                user.Id, Context.User.Id, Context.Guild.Id
                );

            await _replyservice.ReplyEmbedAsync(context : Context,
                                                message : $"User {user.Username} has been approved.");
        }
Beispiel #29
0
        public async Task Verify(IGuildUser user)
        {
            var invokingUser = DiscordUserDataHandler.GetGuildUserById(Context.User.Id, Context.Guild.Id);

            if (invokingUser == null)
            {
                await _replyservice.ReplyEmbedAsync(context : Context,
                                                    message : "You do not have permissions to invoke this command.");

                return;
            }

            var form = new VerificationForm
            {
                GuildId   = Context.Guild.Id,
                Verified  = user.Id,
                Verifier  = Context.User.Id,
                IssuedUtc = DateTime.UtcNow
            };

            if (invokingUser.PermissionLevel == DiscordGuildUser.PermissionLevels.Approve)
            {
                form.Approver   = Context.User.Id;
                form.IsApproved = true;

                var query = DiscordRoleDataHandler.GetGuildRoles(Context.Guild.Id);

                var toBeAddedQuery   = query.Where(x => x.Action == DiscordRole.ActionType.Add);
                var toBeRemovedQuery = query.Where(x => x.Action == DiscordRole.ActionType.Remove);

                List <IRole> toBeAdded   = new List <IRole>();
                List <IRole> toBeRemoved = new List <IRole>();

                foreach (var role in toBeAddedQuery)
                {
                    var socketRole = Context.Guild.GetRole(role.RoleId);

                    toBeAdded.Add(socketRole);
                }

                foreach (var role in toBeRemovedQuery)
                {
                    var socketRole = Context.Guild.GetRole(role.RoleId);

                    toBeRemoved.Add(socketRole);
                }

                await user.AddRolesAsync(toBeAdded);

                await user.RemoveRolesAsync(toBeRemoved);

                await VerificationFormDataHandler.AddFullVerificationForm(form);

                var message = $"User {user.Username} has been verified ";
                if (form.Verifier != Context.User.Id)
                {
                    message += $"by { Context.Guild.GetUser(form.Verifier).Username } ";
                }
                message += "and approved.";

                Log.Information(
                    "User {UserID} verified and approved by {InvokingUserID} in guild {GuildID}",
                    user.Id, Context.User.Id, Context.Guild.Id
                    );

                await _replyservice.ReplyEmbedAsync(context : Context,
                                                    message : message);
            }
            else
            {
                try
                {
                    await VerificationFormDataHandler.AddPendingVerificationForm(form);

                    Log.Information(
                        "Verification form for user {UserID} submitted by {InvokingUserID} in guild {GuildID}",
                        user.Id, Context.User.Id, Context.Guild.Id
                        );

                    await _replyservice.ReplyEmbedAsync(context : Context,
                                                        message : $"Verification form for user {user.Username} has been submitted by {Context.User.Username}.");
                }
                catch (VerificationFormExistsException)
                {
                    await _replyservice.ReplyEmbedAsync(context : Context,
                                                        message : $"User {user.Username} already has a pending verification form");
                }
            }
        }
        public async Task Mute(IUserMessage umsg, IGuildUser user)
        {
            var channel = (ITextChannel)umsg.Channel;

            try
            {
                await user.ModifyAsync(usr => usr.Mute = true).ConfigureAwait(false);
                await user.AddRolesAsync(await GetMuteRole(channel.Guild).ConfigureAwait(false)).ConfigureAwait(false);
                await channel.SendMessageAsync($"🔇 **{user}** has been **muted** from text and voice chat successfully.").ConfigureAwait(false);
            }
            catch
            {
                await channel.SendMessageAsync("⚠️ I most likely don't have the permission necessary for that.").ConfigureAwait(false);
            }
        }
        // Returns name of the roles
        public async Task <List <string> > AssignRoleAsync(ulong userId, string groups)
        {
            var roleNames  = new List <string>();
            var rolesToAdd = new List <IRole>();

            bool isRedhat      = groups.Contains("Redhat");
            bool isContributor = groups.Contains("cla/done");
            bool isDotnet      = groups.Contains("dotnet-team");

            foreach (var guild in _client.Guilds)
            {
                IGuildUser user = guild.GetUser(userId);
                if (user == null)
                {
                    user = await _client.Rest.GetGuildUserAsync(guild.Id, userId);

                    if (user == null)
                    {
                        continue;
                    }
                }

                if (isRedhat)
                {
                    foreach (var roleId in Config.RedhatRoles)
                    {
                        var newRole = guild.GetRole(roleId);
                        if (newRole != null)
                        {
                            rolesToAdd.Add(newRole);
                            roleNames.Add($"{guild.Name} - {newRole.Name}");
                            // Only 1 Redhat role per guild? Or is there reason for more roles to exist?
                            break;
                        }
                    }
                }
                else
                {
                    if (isContributor)
                    {
                        foreach (var roleId in Config.ContributorRoles)
                        {
                            var newRole = guild.GetRole(roleId);
                            if (newRole != null)
                            {
                                rolesToAdd.Add(newRole);
                                roleNames.Add($"{guild.Name} - {newRole.Name}");
                                break;
                            }
                        }
                    }

                    if (isDotnet)
                    {
                        foreach (var roleId in Config.DotnetRoles)
                        {
                            var newRole = guild.GetRole(roleId);
                            if (newRole != null)
                            {
                                rolesToAdd.Add(newRole);
                                roleNames.Add($"{guild.Name} - {newRole.Name}");
                                break;
                            }
                        }
                    }
                }

                await user.AddRolesAsync(rolesToAdd);

                rolesToAdd.Clear();
            }

            return(roleNames);
        }