Example #1
0
        public async Task Mute(SocketRole role)
        {
            var user = Context.User as SocketGuildUser;
            await role.DeleteAsync();

            await ReplyAsync($"{user.Mention} has deleted the role **{role}**.");

            string s    = ($"{role}");
            string line = null;

            // Keeps a list of deleted roles.  Simultaneously updates the role list, too.

            using (System.IO.StreamReader reader = new System.IO.StreamReader(@"C:\DeletedRoles.txt"))
            {
                using (System.IO.StreamWriter writer = new System.IO.StreamWriter(@"C:\RoleList.txt"))
                {
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (String.Compare(line, s) == 0)
                        {
                            continue;
                        }
                        writer.WriteLine(line);
                    }
                }
            }
        }
Example #2
0
        public async Task DeleteRole(SocketRole role)
        {
            string message = $"Attempting to delete `{role.Name}`, `{role.Id}`.";

            await this.Context.Channel.SendMessageAsync(message);

            await role.DeleteAsync();
        }
Example #3
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);
            }
        }
Example #4
0
        public static Task CheckVoiceChannelOnDelete(SocketChannel channel)
        {
            if (channel is SocketVoiceChannel voiceChannel)
            {
                DiscordServer    server = DiscordServer.GetServerFromID(voiceChannel.Guild.Id);
                VoiceChannelRole vcRole = server.voiceChannelRoles.Find(x => x.voiceChannelID == voiceChannel.Id);

                server.voiceChannelRoles.Remove(vcRole);

                SocketRole role = server.Guild.GetRole(vcRole.roleID);

                if (vcRole.voiceChannelID != 0)
                {
                    SocketTextChannel textChannelDeletion = server.Guild.GetTextChannel(vcRole.textChannelID);
                    if (textChannelDeletion != null)
                    {
                        textChannelDeletion.DeleteAsync();
                    }
                }

                if (role != null)
                {
                    role.DeleteAsync();
                }

                server.SaveData();
            }

            if (channel is SocketTextChannel textChannel)
            {
                DiscordServer    server = DiscordServer.GetServerFromID(textChannel.Guild.Id);
                VoiceChannelRole vcRole = server.voiceChannelRoles.Find(x => x.textChannelID == textChannel.Id);

                server.voiceChannelRoles.Remove(vcRole);

                SocketRole role = server.Guild.GetRole(vcRole.roleID);

                if (vcRole.voiceChannelID != 0)
                {
                    SocketVoiceChannel voiceChannelDeletion = server.Guild.GetVoiceChannel(vcRole.voiceChannelID);
                    if (voiceChannelDeletion != null)
                    {
                        voiceChannelDeletion.DeleteAsync();
                    }
                }

                if (role != null)
                {
                    role.DeleteAsync();
                }

                server.SaveData();
            }

            return(Task.CompletedTask);
        }
Example #5
0
 /// <summary>
 /// Clears values for a raid notification message.
 /// </summary>
 /// <param name="guild">Guild to clear notify message.</param>
 /// <param name="channel">Id of registered channel.</param>
 /// <param name="emotes">Emotes that represent roles.</param>
 /// <returns></returns>
 public static async Task ClearNotifyMessage(SocketGuild guild, ulong channel, Emote[] emotes)
 {
     foreach (GuildEmote emote in emotes)
     {
         SocketRole role = guild.Roles.FirstOrDefault(x => x.Name.Equals(emote.Name, StringComparison.OrdinalIgnoreCase));
         if (role != null)
         {
             await role.DeleteAsync();
         }
     }
     Instance().ClearNotificationMessage(guild.Id, channel);
 }
Example #6
0
        protected async Task <bool> RemoveRole(string givenserverid, string givenroleid)
        {
            DiscordSocketClient Discord = bot.getDiscordClient();

            if (ulong.TryParse(givenserverid, out ulong serverid) == false)
            {
                return(false);
            }
            if (ulong.TryParse(givenroleid, out ulong roleid) == false)
            {
                return(false);
            }
            SocketGuild server = Discord.GetGuild(serverid);
            SocketRole  role   = server.GetRole(roleid);
            await role.DeleteAsync().ConfigureAwait(true);

            return(true);
        }
        /// <summary>
        /// Deletes a guild both on server and in data
        /// </summary>
        /// <param name="minecraftGuild">Guild to remove</param>
        /// <returns>True, if operation completed</returns>
        public static async Task <bool> DeleteGuildAsync(SocketGuild discordGuild, MinecraftGuild minecraftGuild)
        {
            string errorhint = "Removing Guild Role";

            try
            {
                SocketRole guildRole   = discordGuild.GetRole(minecraftGuild.RoleId);
                SocketRole captainRole = discordGuild.GetRole(SettingsModel.GuildCaptainRole);
                if (guildRole != null)
                {
                    await guildRole.DeleteAsync();
                }
                errorhint = "Removing captain role from captain";
                SocketGuildUser captain = discordGuild.GetUser(minecraftGuild.CaptainId);
                if (captain != null && captainRole != null)
                {
                    if (captain.Roles.Any(item => { return(item.Id == captainRole.Id); }))
                    {
                        await captain.RemoveRoleAsync(captainRole);
                    }
                }
                errorhint = "Removing Guild Channel";
                if (GuildChannelHelper.TryGetChannel(minecraftGuild.ChannelId, out SocketTextChannel guildChannel))
                {
                    await guildChannel.DeleteAsync();
                }
                errorhint = "Removing Guild and Saving";
                await DeleteGuildDatasetAsync(minecraftGuild);

                errorhint = "Notify Admins";
                await AdminTaskInteractiveMessage.CreateAdminTaskMessage($"Remove ingame represantation of guild\"{minecraftGuild.Name}\"", string.Empty);

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

                return(false);
            }
        }
        public async Task RemoveColor()
        {
            SocketRole deletThis = null;

            //Loop over each role of the user (Get the color they have)
            foreach (SocketRole role in (Context.User as SocketGuildUser).Roles)
            {
                if (colors.Contains(role.Name))
                {
                    await(Context.User as IGuildUser).RemoveRoleAsync(role);
                }
                if (role.Name == Context.User.Id.ToString())
                {
                    deletThis = role;
                }
            }
            if (deletThis != null)
            {
                await deletThis.DeleteAsync();
            }
            await ReplyAsync(Context.User.Mention + " Your color was removed and now you're super boring");
        }
Example #9
0
        public async Task ConsumeMessageAsync(IGatewayMessage message, CancellationToken ct)
        {
            if (message is not DiscordMessage discordMessage)
            {
                return;
            }
            if (discordMessage.SocketMessage.Channel is not SocketGuildChannel)
            {
                return;
            }
            var         parts = message.Content.ToLower().Split();
            SocketGuild guild = (discordMessage.SocketMessage.Channel as SocketGuildChannel).Guild;

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

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

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

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

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

                        await user.AddRoleAsync(newrole);

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

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

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

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

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

                        return;
                    }
                    await guild.DownloadUsersAsync();

                    if (role != null)
                    {
                        await message.RespondToSenderAsync($"Users in `{target}`: {String.Join(", ", role.Members.Select(m => m.Username))}", ct);
                    }
                    else
                    {
                        await message.RespondToSenderAsync($"`{target}` doesn't exist.", ct);
                    }
                    return;
                }
                await message.RespondToSenderAsync(_invalid, ct);
            }
        }
    }
Example #10
0
 public async Task DeleteRoleAsync(SocketRole role) => await role.DeleteAsync();
Example #11
0
        public async Task RemoveRole([Remainder] string targetRole)
        {
            var roles = new List <SocketRole>();

            roles = Context.Guild.Roles.Where(r => r.Name.ToLower() == targetRole.ToLower()).ToList();

            if (roles.Count > 1)
            {
                var emojis = new Emoji[]
                {
                    new Emoji("1⃣"),
                    new Emoji("2⃣"),
                    new Emoji("3⃣"),
                    new Emoji("4⃣"),
                    new Emoji("5⃣"),
                    new Emoji("6⃣"),
                    new Emoji("7⃣"),
                    new Emoji("8⃣"),
                    new Emoji("9⃣")
                };

                var embed = new KaguyaEmbedBuilder
                {
                    Description = $"I found `{roles.Count.ToWords()}` roles that match this name. Please " +
                                  $"select the role that you want to delete, or use the ⛔ reaction " +
                                  $"to delete all roles with this name.",
                    Fields = new List <EmbedFieldBuilder>()
                };

                var callbacks = new List <(IEmote, Func <SocketCommandContext, SocketReaction, Task>)>();

                for (int i = 0; i < roles.Count; i++)
                {
                    int        roleIndex = i + 1;
                    SocketRole role      = roles.ElementAt(i);

                    embed.Fields.Add(new EmbedFieldBuilder
                    {
                        Name  = $"Role #{roleIndex}",
                        Value = $"Exact Name: `{role.Name}`\n" +
                                $"Number of users who have this role: " +
                                $"`{Context.Guild.Users.Count(x => x.Roles.Contains(role))}`\n" +
                                $"Permissions: `{roles.Count}`\n" +
                                $"Created: `{role.CreatedAt.Humanize()}`\n" +
                                $"Position in role list (higher number = higher position): `{role.Position}`"
                    });

                    callbacks.Add((emojis[i], async(c, r) =>
                    {
                        await role.DeleteAsync();
                        await ReplyAsync($"{Context.User.Mention} `Successfully deleted Role #{roleIndex}`");
                    }
                                   ));
                }

                callbacks.Add((new Emoji("⛔"), async(c, r) =>
                {
                    foreach (SocketRole role in roles)
                    {
                        await role.DeleteAsync();
                    }

                    await ReplyAsync($"{Context.User.Mention} Successfully deleted `{roles.Count.ToWords()}` roles.");
                }
                               ));

                var data = new ReactionCallbackData("", embed.Build(), false, false, TimeSpan.FromSeconds(120));
                data.SetCallbacks(callbacks);
                await InlineReactionReplyAsync(data);
            }
            else if (roles.Count == 1)
            {
                SocketRole role  = roles.First();
                var        embed = new KaguyaEmbedBuilder
                {
                    Description = $"{Context.User.Mention} Successfully deleted role `{role.Name}`"
                };

                await role.DeleteAsync();

                await ReplyAsync(embed : embed.Build());
            }
            else
            {
                var embed = new KaguyaEmbedBuilder
                {
                    Description = $"I could not find the specified role."
                };

                embed.SetColor(EmbedColor.RED);

                await ReplyAsync(embed : embed.Build());
            }
        }
Example #12
0
        private async Task MessageReceived(SocketMessage arg)
        {
            SocketRole infectedRole = null;

            if (arg is SocketUserMessage message && !message.Author.IsBot && !message.Author.IsWebhook && message.Author is SocketGuildUser user1 && message.Channel is SocketGuildChannel channel)
            {
                if (!configs.Guilds.ContainsKey(user1.Guild.Id.ToString()))
                {
                    return;
                }
                if (!databases.Guilds.ContainsKey(user1.Guild.Id.ToString()))
                {
                    databases.Guilds.Add(user1.Guild.Id.ToString(), new GuildDatabase());
                }
                GuildConfig config = (configs.Guilds[user1.Guild.Id.ToString()]);
                if (infectedRole == null)
                {
                    infectedRole = user1.Guild.GetRole(config.InfectedRoleId);
                }
                SocketGuild guild = user1.Guild;
                if (infectedRole != null && !config.SafeChannelIds.Contains(message.Channel.Id) && !config.SuperSafeChannelIds.Contains(message.Channel.Id) && message.Content.ToLower().Contains("*cough*") && user1.Roles.Contains(infectedRole))
                {
                    bool found = false;
                    foreach (var item in config.SafeChannelIds)
                    {
                        var cat = guild.GetCategoryChannel(item);
                        if (cat == null || !cat.Channels.Contains(channel))
                        {
                            continue;
                        }
                        found = true;
                        break;
                    }
                    if (!found)
                    {
                        foreach (var item in config.SuperSafeChannelIds)
                        {
                            var cat = guild.GetCategoryChannel(item);
                            if (cat == null || !cat.Channels.Contains(channel))
                            {
                                continue;
                            }
                            found = true;
                            break;
                        }
                    }
                    if (!found)
                    {
                        var msgsa = message.Channel.GetMessagesAsync(config.InfectMessageLimit);
                        var msgs  = await msgsa.FlattenAsync();

                        // if (msgs.Where(p => p.Content.Contains("*cough*") && p.Author.Id == user1.Id).Count() == 0)
                        {
                            IMessage[] array = msgs.Where(p => !p.Author.IsBot && !p.Author.IsWebhook && p.Author.Id != user1.Id && p.Timestamp.UtcDateTime.Add(TimeSpan.FromSeconds(config.SafeTimeSeconds)) >= DateTime.UtcNow && p.Author is SocketGuildUser user && !user.Roles.Contains(infectedRole)).ToArray();
                            if (array.Length != 0)
                            {
                                IMessage msg2 = array[rng.Next(array.Length)];
                                if (msg2 is RestUserMessage message2 && message2.Author is SocketGuildUser user2)
                                {
                                    await InfectUser(user2, infectedRole, user1);
                                    await SaveData();

                                    string name = string.IsNullOrWhiteSpace(user1.Nickname) ? user1.Username : user1.Nickname;
                                    await message2.ReplyAsync($"{name} infected you with {config.VirusName}!");
                                }
                            }
                        }
                    }
                }
                if (infectedRole != null && !user1.Roles.Contains(infectedRole) && !config.SuperSafeChannelIds.Contains(message.Channel.Id) && rng.Next(100) < config.AutoInfectPercent)
                {
                    bool found = false;
                    foreach (var item in config.SuperSafeChannelIds)
                    {
                        var cat = guild.GetCategoryChannel(item);
                        if (cat == null || !cat.Channels.Contains(channel))
                        {
                            continue;
                        }
                        found = true;
                        break;
                    }
                    if (!found)
                    {
                        await InfectUser(user1, infectedRole);
                        await SaveData();

                        await message.ReplyAsync($"Somehow, you were infected with {config.VirusName}!");
                    }
                }
                if (infectedRole != null && message.Content.ToLower().StartsWith(config.StatsCommand.ToLower()))
                {
                    string[] infected = infectedRole.Members.OrderByDescending(p =>
                    {
                        if (databases.Guilds[user1.Guild.Id.ToString()].InfectedTimestamps.ContainsKey(p.Id.ToString()))
                        {
                            return(databases.Guilds[user1.Guild.Id.ToString()].InfectedTimestamps[p.Id.ToString()]);
                        }
                        return(long.MinValue);
                    }).Select(p =>
                    {
                        string time = "N/A";
                        if (databases.Guilds[user1.Guild.Id.ToString()].InfectedTimestamps.ContainsKey(p.Id.ToString()))
                        {
                            time = DateTime.MinValue.AddTicks(databases.Guilds[user1.Guild.Id.ToString()].InfectedTimestamps[p.Id.ToString()]).ToString();
                        }
                        return($"{p.Username}#{p.Discriminator} was infected at {time}");
                    }).ToArray();
                    string output = "";
                    for (int i = 0; i < infected.Length && i < config.StatsMaxInfectedListings; i++)
                    {
                        if (i != 0)
                        {
                            output += "\n";
                        }
                        output += infected[i];
                    }
                    EmbedBuilder emb = new EmbedBuilder();
                    emb.WithColor(config.InfectedRoleColorRed, config.InfectedRoleColorGreen, config.InfectedRoleColorBlue);
                    emb.WithTitle(config.VirusName);
                    emb.WithDescription(output);
                    await message.ReplyAsync(embed : emb.Build());

                    // string path = Path.GetTempFileName();
                    string path = Path.GetRandomFileName() + ".png";
                    StatsDraw.Draw(path, user1.Guild, databases.Guilds[user1.Guild.Id.ToString()].InfectedWho, config.StatsMaxInfectedListings);
                    await message.Channel.SendFileAsync(path);

                    File.Delete(path);
                }
                if (user1.GuildPermissions.ManageRoles && message.Content.ToLower().StartsWith(config.ResetCommand.ToLower()))
                {
                    if (infectedRole != null)
                    {
                        await infectedRole.DeleteAsync();
                    }
                    RestRole role = await user1.Guild.CreateRoleAsync(config.InfectedRoleName, GuildPermissions.None, new Discord.Color(config.InfectedRoleColorRed, config.InfectedRoleColorGreen, config.InfectedRoleColorBlue), false, false);

                    configs.Guilds[user1.Guild.Id.ToString()].InfectedRoleId = role.Id;
                    databases.Guilds[user1.Guild.Id.ToString()].InfectedTimestamps.Clear();
                    databases.Guilds[user1.Guild.Id.ToString()].InfectedWho.Clear();
                    await SaveData();

                    await message.ReplyAsync($"{config.VirusName} has been contained.");
                }
            }
        }