public static async Task MemberJoinEventHandlerAsync(TheGodfatherShard shard, GuildMemberAddEventArgs e)
        {
            DatabaseGuildConfig gcfg = e.Guild.GetGuildSettings(shard.Database);
            await Task.Delay(TimeSpan.FromSeconds(gcfg.AntiInstantLeaveSettings.Cooldown + 1));

            if (e.Member.Guild is null)
            {
                return;
            }

            DiscordChannel wchn = e.Guild.GetChannel(gcfg.WelcomeChannelId);

            if (!(wchn is null))
            {
                if (string.IsNullOrWhiteSpace(gcfg.WelcomeMessage))
                {
                    await wchn.EmbedAsync($"Welcome to {Formatter.Bold(e.Guild.Name)}, {e.Member.Mention}!", StaticDiscordEmoji.Wave);
                }
                else
                {
                    await wchn.EmbedAsync(gcfg.WelcomeMessage.Replace("%user%", e.Member.Mention), StaticDiscordEmoji.Wave);
                }
            }

            try {
                using (DatabaseContext db = shard.Database.CreateContext()) {
                    IQueryable <ulong> rids = db.AutoAssignableRoles
                                              .Where(dbr => dbr.GuildId == e.Guild.Id)
                                              .Select(dbr => dbr.RoleId);
                    foreach (ulong rid in rids.ToList())
                    {
                        try {
                            DiscordRole role = e.Guild.GetRole(rid);
                            if (!(role is null))
                            {
                                await e.Member.GrantRoleAsync(role);
                            }
                            else
                            {
                                db.AutoAssignableRoles.Remove(db.AutoAssignableRoles.Single(r => r.GuildId == e.Guild.Id && r.RoleId == rid));
                            }
                        } catch (Exception exc) {
                            shard.Log(LogLevel.Debug,
                                      $"| Failed to assign an automatic role to a new member!\n" +
                                      $"| {e.Guild.ToString()}\n" +
                                      $"| Exception: {exc.GetType()}\n" +
                                      $"| Message: {exc.Message}"
                                      );
                        }
                    }
Exemple #2
0
        private async Task <bool> RemoveFeedRole(DiscordMember member, DiscordRole city)
        {
            var reason = "Default city role/raid role removal.";

            if (city == null)
            {
                _logger.Error($"Failed to find city role {city?.Name}, please make sure it exists.");
                return(false);
            }

            await member.RevokeRoleAsync(city, reason);

            return(true);
        }
Exemple #3
0
        public async Task RenameAsync(CommandContext ctx,
                                      [Description("Role.")] DiscordRole role,
                                      [RemainingText, Description("New name.")] string newname)
        {
            if (string.IsNullOrWhiteSpace(newname))
            {
                throw new ArgumentException("I need a new name for the role.");
            }

            string name = role.Name;
            await role.ModifyAsync(name : newname, reason : ctx.BuildInvocationDetailsString());

            await this.InformAsync(ctx, $"Successfully renamed role {Formatter.Bold(name)} to {Formatter.Bold(role.Name)}", important : false);
        }
Exemple #4
0
        internal override async Task Execute(CommandObjects CommandObject)
        {
            try {
                string[] msgs = CommandObject.CommandArgs.Remove(0);
                if (msgs.Length == 0)
                {
                    await CommandObject.Message.Channel.SendMessageAsync(CommandObject.Language.EmptyText);

                    return;
                }

                if (string.IsNullOrWhiteSpace(msgs[0]))
                {
                    await CommandObject.Message.Channel.SendMessageAsync(CommandObject.Language.EmptyId);

                    return;
                }
                if (!ulong.TryParse(msgs[0], out ulong msgs_ID))
                {
                    await CommandObject.Message.Channel.SendMessageAsync(CommandObject.Language.IdCouldntParse);

                    return;
                }

                if (!Database.DatabaseMethods.RolesMethods.RoleFind(CommandObject.Guild.Id, msgs_ID, out Roles DBRolesID))
                {
                    await CommandObject.Message.Channel.SendMessageAsync(CommandObject.Language.IdNotRegisted);

                    return;
                }
                // if DBRolesID is null, processes will not be executed from here.

                if (!await Authentication.Confirmation(CommandObject))
                {
                    await CommandObject.Channel.SendMessageAsync(CommandObject.Language.AuthFailure);

                    return;
                }

                Database.DatabaseMethods.RolesMethods.RoleDelete(DBRolesID);

                DiscordRole GuildRole  = CommandObject.Guild.GetRole(DBRolesID.Uuid);
                string      ResultText = string.Format(CommandObject.Language.DBRoleDeleteSuccess, GuildRole.Name, DBRolesID.Uuid);
                await CommandObject.Message.Channel.SendMessageAsync(ResultText);
            }
            catch (IndexOutOfRangeException) {
                await CommandObject.Message.Channel.SendMessageAsync(CommandObject.Language.TypingMissed);
            }
        }
Exemple #5
0
        public List <DiscordMember> AddRoleAsActive(DiscordGuild guild, DiscordRole role)
        {
            var result = new List <DiscordMember>();

            foreach (var user in guild.GetAllMembersAsync().Result)
            {
                if (user.Roles.Contains(role))
                {
                    SetActive(user);
                    result.Add(user);
                }
            }

            return(result);
        }
Exemple #6
0
            public async Task Disallowed(CommandContext ctx, [Description("Role that will be disallowed from pinning")] DiscordRole role)
            {
                if (!ctx.Guild.Roles.Any(r => r.Value.Id == role.Id))
                {
                    return;
                }
                if (context.Pinners.Any(c => c.Roleid == role.Id.ToString()))
                {
                    throw new UserError("That role is already disallowed");
                }
                context.Remove(context.Pinners.Single(c => c.Roleid == role.Id.ToString()));
                await context.SaveChangesAsync();

                await ctx.RespondAsync(embed : Embeds.Success.WithDescription($"Disallowed {role.Mention} from pinning messages with the 📌 react!"));
            }
Exemple #7
0
            public async Task AutoRole(CommandContext ctx, DiscordRole role)
            {
                var GuildSettings = await this.discordUrie.Config.FindGuildSettings(ctx.Guild);

                if (GuildSettings.AutoRole == role.Id)
                {
                    return;
                }
                this.discordUrie.Config.GuildSettings.Remove(GuildSettings);
                GuildSettings.AutoRole = role.Id;
                this.discordUrie.Config.GuildSettings.Add(GuildSettings);
                await GuildSettings.SaveGuild(this.discordUrie.SQLConn);

                await ctx.RespondAsync($"Autorole set to {role.Mention}");
            }
        public async Task DeleteRole(CommandContext ctx, [RemainingText] DiscordRole role)
        {
            if (role == null)
            {
                await BotServices.SendErrorEmbedAsync(ctx, ":mag: Role not found in this server!");
            }
            else
            {
                await ctx.TriggerTypingAsync();

                await role.DeleteAsync();

                await ctx.RespondAsync($"Role **{role.Name}** has been **removed**");
            }
        }
Exemple #9
0
        public async Task GetMembersWithRoleAsync(CommandContext context, DiscordRole role)
        {
            var(_, guildRole) = context.Guild.Roles.FirstOrDefault(x => x.Key == role.Id);

            if (guildRole != null)
            {
                var membersWithRole = context.Guild.Members.Values.Count(x => x.Roles.Contains(guildRole));
                await ReplyNewEmbedAsync(context, $"{membersWithRole} users have {guildRole.Mention}",
                                         MomentumColor.Blue);
            }
            else
            {
                await ReplyNewEmbedAsync(context, "That role does not exist in this server", DiscordColor.Orange);
            }
        }
 public async Task RemoveRoleFromEmoji(CommandContext ctx, DiscordRole role)
 {
     if (role == null)
     {
         await ctx.Channel.SendMessageAsync("Неверное форматирование !RGremoveRole {Упоминание роли через @}(Без фигурных скобок)");
     }
     if (await RGranter.TryRemoveRoleAsync(ctx.Client, role))
     {
         await ctx.Channel.SendTempMessageAsync("Роль успешно удалена");
     }
     else
     {
         await ctx.Channel.SendTempMessageAsync("Такой роли нет в списке");
     }
 }
Exemple #11
0
 private IEnumerable <DiscordOverwriteBuilder> GetDMNotesOverwriteBuilders(DiscordRole everyone, DiscordMember dm, DiscordRole role)
 {
     return(new DiscordOverwriteBuilder[]
     {
         new DiscordOverwriteBuilder()
         .Deny(DSharpPlus.Permissions.AccessChannels)
         .For(everyone),
         new DiscordOverwriteBuilder()
         .Deny(DSharpPlus.Permissions.AccessChannels)
         .For(role),
         new DiscordOverwriteBuilder()
         .Allow(DSharpPlus.Permissions.AccessChannels)
         .For(dm)
     });
 }
Exemple #12
0
        public async Task RevokeRole(CommandContext ctx,
                                     [Description("Server user to get revoked.")]
                                     DiscordMember member,
                                     [Description("Server role name.")][RemainingText]
                                     DiscordRole role)
        {
            if (role != null)
            {
                member ??= ctx.Member;
                await member.RevokeRoleAsync(role).ConfigureAwait(false);

                await ctx.RespondAsync(Formatter.Bold(member.DisplayName) + " has been removed from the role " +
                                       Formatter.Bold(role.Name)).ConfigureAwait(false);
            }
        }
Exemple #13
0
        private async Task Deregister(CommandArgs <RoleBotConfig> args)
        {
            string emojiName = args["emojiName"];

            if (args.Config.EmojiRoles.TryGetValue(emojiName, out ulong roleID))
            {
                args.Config.EmojiRoles.Remove(emojiName);
                DiscordRole role = args.Guild.GetRole(roleID);
                await args.Channel.SendMessageAsync($"*{role.Name}* is no longer associated with {emojiName}");
            }
            else
            {
                await args.Channel.SendMessageAsync($"No role is mapped to {emojiName}");
            }
        }
        public async Task SairDoEsquadrãoFoxholeUBGE(CommandContext ctx, [RemainingText] string squad = "listar")
        {
            Dictionary <string, ulong> dicionariofoxhole = JsonConvert.DeserializeObject <Dictionary <string, ulong> >(File.ReadAllText(Directory.GetCurrentDirectory() + @"\FoxholeEsquadroes.json"));

            dicionariofoxhole.Values.Distinct().ToList().ForEach(u => {
                DiscordRole r = ctx.Guild.GetRole(u);
            });

            var embedesquadraosaiu = new DiscordEmbedBuilder();
            var semmembrodocla     = new DiscordEmbedBuilder();
            var naotemocargo       = new DiscordEmbedBuilder();
            var emojo = DiscordEmoji.FromName(ctx.Client, ":thinking:");

            var Formigas      = ctx.Guild.GetRole(valores.IdFormigas);
            var Canivetes     = ctx.Guild.GetRole(valores.IdCanivetes);
            var Tuiti         = ctx.Guild.GetRole(valores.IdTuiti);
            var DivisaoTatica = ctx.Guild.GetRole(valores.IdDivisaoTatica);

            DiscordColor cor;

            cor = new Utilidades.Utilidades().randomColor();
            DiscordUser self      = ctx.Member;
            DiscordRole MembroCla = ctx.Guild.GetRole(352296287493947402);

            embedesquadraosaiu.WithColor(cor)
            .WithAuthor($"Tag do esquadrão foi removida com sucesso.", null, "https://cdn.discordapp.com/emojis/450829956063166474.png?v=1")
            .WithDescription($"Removi a tag do esquadrão `{ctx.Guild.GetRole(dicionariofoxhole[squad]).Name}` para você, se quiser entrar em outro esquadrão, digite /fox-entrar `(squad)`.\n\n**Esquadrões:**\n/fox-entrar `Formigas`\n/fox-entrar `Canivete`\n/fox-entrar `DivisãoTática`\n/fox-entrar `Tuiti`\n/fox-entrar `BlackDragon`")
            .WithFooter("Comando requisitado pelo: " + ctx.Member.Username, iconUrl: self.AvatarUrl);
            semmembrodocla.WithColor(cor)
            .WithAuthor("Erro!", null, "https://cdn.discordapp.com/attachments/452508980896333825/468940279068491777/Alert-icon.png")
            .WithDescription($"Como isso é possível? Você não tem a tag <@&352296287493947402> e está em um esquadrão e quer sair dele... {emojo}\n\nConsiga a tag <@&352296287493947402> depois tente novamente dar o comando.")
            .WithFooter("Comando requisitado pelo: " + ctx.Member.Username, iconUrl: self.AvatarUrl);
            naotemocargo.WithColor(cor)
            .WithAuthor("Erro!", null, "https://cdn.discordapp.com/attachments/452508980896333825/468940279068491777/Alert-icon.png")
            .WithDescription("Você não tem a tag: <@&352296287493947402> ou você não está em nenhum esquadrão. Ou você tem a tag de algum esquadrão, mas não tem a tag de membro do clã.\n\nPeça para alguém da <@&316723010818277376> verificar seus cargos e ver o que está acontecendo.")
            .WithFooter("Comando requisitado pelo: " + ctx.Member.Username, iconUrl: self.AvatarUrl);

            if (!(ctx.Member.Roles.Contains(MembroCla)))
            {
                await ctx.RespondAsync(embed : naotemocargo);
            }
            else if (ctx.Member.Roles.Contains(MembroCla))
            {
                await ctx.Member.RevokeRoleAsync(ctx.Guild.GetRole(dicionariofoxhole[squad]));

                await ctx.RespondAsync(embed : embedesquadraosaiu);
            }
        }
Exemple #15
0
        public async Task BanAsync(CommandContext ctx, DiscordMember membro = null, [RemainingText] string razao = "")
        {
            if (ctx.Guild.Id == 732102804654522470)
            {
                // Verify if the member has "Moderator" role.
                ulong modRole = 775094267831255110;
                var   isMod   = ctx.Member.Roles.FirstOrDefault(x => x.Id == modRole);
                if (isMod != null)
                {
                    if (membro == null)
                    {
                        await ctx.RespondAsync($"{ctx.User.Mention}, você precisa informar um membro válido!");

                        return;
                    }

                    isMod = membro.Roles.FirstOrDefault(x => x.Id == modRole);
                    if (isMod == null)
                    {
                        DiscordEmbedBuilder embed = new DiscordEmbedBuilder().Inicializar(ctx);
                        embed.WithTitle("Ban");
                        embed.WithTimestamp(DateTime.Now);
                        if (string.IsNullOrWhiteSpace(razao))
                        {
                            embed.WithDescription($"{membro.Mention}, foi banido sem nenhuma razão especifica.");
                        }
                        else
                        {
                            embed.WithDescription($"{membro.Mention}, foi banido.\n{razao}");
                        }
                        // Role banido.
                        DiscordRole banido = ctx.Guild.GetRole(775098106823704617);
                        await membro.GrantRoleAsync(banido);

                        var channel = ctx.Guild.GetChannel(775099480928026656);
                        await channel.SendMessageAsync(embed : embed.Build());
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }
            }
        }
Exemple #16
0
        public static DiscordEmbed GenerateWelcomeMessage(DiscordMember newMember)
        {
            MessageConfig  config         = Core.Util.ConfigHandler.ViewWelcomeConfig();
            DiscordGuild   guild          = Bot.Discord.Guilds.FirstOrDefault(x => x.Value.Name.ToLower().Contains("devry")).Value;
            DiscordChannel welcomeChannel = guild.Channels
                                            .FirstOrDefault(x => x.Value.Name.ToLower().Contains("welcome"))
                                            .Value;

            string[] words = config.Contents.Split(" ");

            for (int i = 0; i < words.Length; i++)
            {
                if (words[i].StartsWith('#'))
                {
                    DiscordChannel channel = guild.Channels.FirstOrDefault(x => x.Value.Name.ToLower()
                                                                           .Contains(words[i].ToLower()
                                                                                     .Substring(1)))
                                             .Value;
                    if (channel != null)
                    {
                        words[i] = channel.Mention;
                    }
                }
                else if (words[i].StartsWith("@"))
                {
                    DiscordRole role = guild.Roles
                                       .Where(x => x.Value.Name.ToLower().Contains(words[i].Substring(1).ToLower()))
                                       .FirstOrDefault().Value;

                    if (role != null)
                    {
                        words[i] = role.Mention;
                    }
                }
                else if (words[i].Contains("[USER]"))
                {
                    words[i] = words[i].Replace("[USER]", newMember.Mention);
                }
            }

            DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
                                          .WithAuthor("Devry IT")
                                          .WithTitle("Welcome!")
                                          .WithDescription(string.Join(" ", words))
                                          .WithColor(DiscordColor.Cyan);

            return(builder.Build());
        }
        public async Task TempmuteCommand(CommandContext ctx, [Description("The Member to mute (ID, Mention, Username)")] DiscordMember member, [RemainingText, Description("Length (d/h/m/s) Ex. 7d for 7 Days")] string time)
        {
            double      Time      = JokinsCommon.Methods.TimeConverter(time);
            DateTime    dateTime  = DateTime.Now.AddMilliseconds(Time);
            DiscordRole MutedRole = ctx.Guild.GetRole(Program.MutedRole);

            var PS = await Program.SQLC.GetPlayer(member.Id);

            if (PS.Muted)
            {
                await ctx.RespondAsync("That Member is already muted");

                return;
            }

            PS.Muted = true;
            await PS.Save();

            await member.GrantRoleAsync(MutedRole);

            await Program.SQLC.AddTempmute((long)member.Id, dateTime.ToBinary());

            DiscordEmbedBuilder TempMute = new DiscordEmbedBuilder {
                Title       = $"TempMute | {member.Username}",
                Description = $"**{member.Mention} has been muted for {time}**",
                Color       = Program.EmbedColor,
                Footer      = new DiscordEmbedBuilder.EmbedFooter {
                    Text = "Unmuted on"
                },
                Timestamp = dateTime
            };
            await ctx.RespondAsync(embed : TempMute);

            _ = Task.Run(async() => {
                try {
                    await Task.Delay((int)Time);

                    var PS   = await Program.SQLC.GetPlayer(member.Id);
                    PS.Muted = false;

                    await PS.Save();
                    await Program.SQLC.DeleteTempmutesWithID((long)member.Id);
                    await member.RevokeRoleAsync(MutedRole);
                } catch (Exception) {
                    ctx.Client.Logger.LogInformation($"Failed the Tempmute process for {ctx.Member.Username + ctx.Member.Discriminator}");
                }
            });
        }
        public async Task MentionAllFromRoleAsync(CommandContext ctx,
                                                  [Description("Role.")] DiscordRole role)
        {
            if (role.IsMentionable)
            {
                await ctx.RespondAsync(role.Mention);

                return;
            }

            await role.ModifyAsync(mentionable : true);

            await ctx.RespondAsync(role.Mention);

            await role.ModifyAsync(mentionable : false);
        }
        public async Task SetBlackBacon(CommandContext ctx, DiscordRole role)
        {
            if (role == null)
            {
                throw new ArgumentNullException("role", "Role cannot be null!");
            }

            //Fetch the settings, update its prefix then save again
            var settings = await GuildSettings.GetGuildSettingsAsync(ctx.Guild);

            settings.BlackBaconId = role.Id;
            await settings.SaveAsync();

            //Respond that we did that.
            await ctx.ReplyReactionAsync(true);
        }
Exemple #20
0
        public async Task Edit(CommandContext ctx, DiscordRole role)
        {
            if (!ctx.Message.Attachments.Any())
            {
                await ctx.RespondAsync("Provide an image please");

                return;
            }

            new WebClient().DownloadFile(ctx.Message.Attachments.First().Url, "./icon.png");

            var stream = File.OpenRead("./icon.png");
            await role.ModifyAsync(icon : stream);

            await ctx.RespondAsync($"Edited role! {role.Mention}");
        }
Exemple #21
0
        public async Task CheckMute(CommandContext ctx)
        {
            DiscordRole muted = await GetMutedRole(ctx.Guild);

            foreach (DiscordChannel channel in ctx.Guild.Channels.Values)
            {
                if (channel.Type != ChannelType.Text)
                {
                    continue;
                }

                await channel.AddOverwriteAsync(muted, deny : Permissions.SendMessages);
            }

            await ctx.Message.RespondAsync($"{ctx.Member.Mention}, done!");
        }
            public async Task CountAll(CommandContext ctx)
            {
                int         authenticatedCount = 0;
                DiscordRole authenticatedRole  = ctx.Guild.GetRole(_commonCommandOptions.AuthenticatedRoleId);

                foreach ((_, DiscordMember member) in ctx.Guild.Members)
                {
                    if (member.Roles.Contains(authenticatedRole))
                    {
                        authenticatedCount++;
                    }
                }

                await ctx.Channel.SendMessageAsync(
                    $"Authenticated: {authenticatedCount}, All: {ctx.Guild.Members.Count.ToString()}");
            }
Exemple #23
0
            public async Task Allowed(CommandContext ctx, [Description("Role that will be allowed to pin")] DiscordRole role)
            {
                if (!ctx.Guild.Roles.Any(r => r.Value.Id == role.Id))
                {
                    return;
                }
                if (context.Pinners.Any(c => c.Roleid == role.Id.ToString()))
                {
                    throw new UserError("That role is already allowed");
                }
                await context.AddAsync(new Pinner { Roleid = role.Id.ToString(), Guild = ctx.Guild.Id.ToString() });

                await context.SaveChangesAsync();

                await ctx.RespondAsync(embed : Embeds.Success.WithDescription($"Allowed {role.Mention} to pin messages with the 📌 react!"));
            }
Exemple #24
0
            public async Task TicketFrom(CommandContext ctx,

                                         [Description("The role to move the ticket away from")]
                                         DiscordRole role)
            {
                if (!ctx.Channel.Name.StartsWith("ticket-"))
                {
                    await ctx.RespondAsync("This is no ticket channel! You can only move ticket channels away from a certain role!");

                    return;
                }

                await ctx.Channel.AddOverwriteAsync(role, Permissions.None, Permissions.AccessChannels);

                await ctx.RespondAsync($"This ticket was successfully moved away from {role.Name}.");
            }
Exemple #25
0
 public Task InfoAsync(CommandContext ctx,
                       [Description("desc-role")] DiscordRole role)
 {
     return(ctx.RespondWithLocalizedEmbedAsync(emb => {
         emb.WithTitle(role.Name);
         emb.WithColor(this.ModuleColor);
         emb.AddLocalizedTitleField("str-pos", role.Position, inline: true);
         emb.AddLocalizedTitleField("str-color", role.Color, inline: true);
         emb.AddLocalizedTitleField("str-id", role.Id, inline: true);
         emb.AddLocalizedTitleField("str-mention", role.IsMentionable, inline: true);
         emb.AddLocalizedTitleField("str-hoist", role.IsHoisted, inline: true);
         emb.AddLocalizedTitleField("str-managed", role.IsManaged, inline: true);
         emb.AddLocalizedTimestampField("str-created-at", role.CreationTimestamp, inline: true);
         emb.AddLocalizedTitleField("str-perms", role.Permissions.ToPermissionString(), inline: true);
     }));
 }
Exemple #26
0
        public async Task RemoveHumans(CommandContext ctx, [Description("The role to modify")] DiscordRole role, [Description("Reason for the action"), RemainingText] string reason)
        {
            if (ctx.Channel.Get(ConfigManager.Enabled)
                .And(ctx.Channel.GetMethodEnabled()))
            {
                await ctx.TriggerTypingAsync();

                DiscordMember member = await ctx.Guild.GetMemberAsync(ctx.Message.Author.Id);

                foreach (DiscordMember human in ctx.Guild.Members.Select(s => s.Value).Where(s => !s.IsBot && s.Roles.Contains(role)))
                {
                    await human.RevokeRoleAsync(role, reason);
                }
                await ctx.RespondAsync("Done!");
            }
        }
Exemple #27
0
        private async Task RemoveDiscordRole(CommandContext ctx, DiscordRole existingDiscordRole, string userRoleName)
        {
            var member = ctx.Member;
            var guild  = ctx.Guild;

            if (member == null)
            {
                throw new ArgumentNullException(nameof(member));
            }

            await member.RevokeRoleAsync(existingDiscordRole);

            await ctx.Message.CreateReactionAsync(DiscordEmoji.FromUnicode(EmojiMap.WhiteCheckmark));

            await LogRoleRemoved(guild, userRoleName, member);
        }
        public async Task UnlockSalaAsync(CommandContext ctx)
        {
            await ctx.TriggerTypingAsync();

            DiscordEmbedBuilder embed = new DiscordEmbedBuilder();

            IMongoCollection <Salas> salasCollection = Program.Bot.LocalDB.GetCollection <Salas>(Values.Mongo.salas);

            FilterDefinition <Salas> filtroSalas = Builders <Salas> .Filter.Eq(x => x.idDoDono, ctx.Member.Id);

            List <Salas> resultadoSalas = await(await salasCollection.FindAsync(filtroSalas)).ToListAsync();

            if (resultadoSalas.Count != 0 && ctx.Guild.GetChannel(resultadoSalas[0].idDaSala) != null)
            {
                DiscordChannel voiceChannel = ctx.Guild.GetChannel(resultadoSalas[0].idDaSala);

                DiscordRole moderadorDiscordCargo = ctx.Guild.GetRole(Values.Roles.roleModeradorDiscord);

                if (resultadoSalas[0].salaTrancada)
                {
                    await salasCollection.UpdateOneAsync(filtroSalas, Builders <Salas> .Update.Set(s => s.salaTrancada, false));

                    await voiceChannel.AddOverwriteAsync(ctx.Guild.EveryoneRole, Permissions.AccessChannels | Permissions.UseVoice | Permissions.Speak);

                    await voiceChannel.AddOverwriteAsync(moderadorDiscordCargo, Permissions.AccessChannels | Permissions.UseVoice | Permissions.Speak);

                    embed.WithAuthor($"✅ - Sala destravada!", null, Values.logoUBGE);
                    embed.WithColor(Program.Bot.Utilities.RandomColorEmbed());

                    await ctx.RespondAsync(embed : embed.Build());
                }
                else if (!resultadoSalas[0].salaTrancada)
                {
                    embed.WithAuthor($"❎ - Esta sala já está destrancada!", null, Values.logoUBGE);
                    embed.WithColor(Program.Bot.Utilities.RandomColorEmbed());

                    await ctx.RespondAsync(embed : embed.Build());
                }
            }
            else
            {
                embed.WithAuthor($"❎ - Você não possui uma sala ativa!", null, Values.logoUBGE);
                embed.WithColor(Program.Bot.Utilities.RandomColorEmbed());

                await ctx.RespondAsync(embed : embed.Build());
            }
        }
Exemple #29
0
        public async Task AddCommand(CommandContext ctx, DiscordRole role, [RemainingText] string name)
        {
            using (var db = new RolesContext())
            {
                var dbRole = new AssignableRole
                {
                    Name     = name,
                    RoleId   = role.Id.ToString(),
                    ServerId = ctx.Guild.Id.ToString()
                };

                db.AssignableRoles.Add(dbRole);
                await db.SaveChangesAsync();

                await ctx.RespondAsync("Role added successfully.");
            }
        }
        private async Task NewsRoleAssignment(DiscordClient dClient, MessageReactionAddEventArgs args)
        {
            if (args.User.Id == dClient.CurrentUser.Id || (args.Message?.Id != SBGMessages.TheOnlyMessageIDWeCurrentlyCareAboutAtleastInAPublicFacingPerspective && !args.Emoji.Equals(DiscordEmoji.FromGuildEmote(this.dClient, ManageRoleEmojis.BloonMoji))))
            {
                return;
            }

            DiscordMember discordUser = await args.Guild.GetMemberAsync(args.User.Id);

            DiscordRole newsRole = args.Guild.GetRole(SBGRoles.News);

            if (args.Message.Id == SBGMessages.TheOnlyMessageIDWeCurrentlyCareAboutAtleastInAPublicFacingPerspective && !discordUser.Roles.Contains(newsRole))
            {
                await discordUser.GrantRoleAsync(newsRole);
            }
            return;
        }
        private void GuildUpdateEvents(JObject message)
        {
            DiscordServer oldServer = ServersList.Find(x => x.ID == message["d"]["id"].ToString());
            DiscordServer newServer = oldServer.ShallowCopy();

            newServer.Name = message["d"]["name"].ToString();
            newServer.ID = message["d"]["id"].ToString();
            newServer.parentclient = this;
            newServer.Roles = new List<DiscordRole>();
            newServer.Region = message["d"]["region"].ToString();
            if (!message["d"]["icon"].IsNullOrEmpty())
            {
                newServer.icon = message["d"]["icon"].ToString();
            }
            if (!message["d"]["roles"].IsNullOrEmpty())
            {
                foreach (var roll in message["d"]["roles"])
                {
                    DiscordRole t = new DiscordRole
                    {
                        Color = new DiscordSharp.Color(roll["color"].ToObject<int>().ToString("x")),
                        Name = roll["name"].ToString(),
                        Permissions = new DiscordPermission(roll["permissions"].ToObject<uint>()),
                        Position = roll["position"].ToObject<int>(),
                        Managed = roll["managed"].ToObject<bool>(),
                        ID = roll["id"].ToString(),
                        Hoist = roll["hoist"].ToObject<bool>()
                    };
                    newServer.Roles.Add(t);
                }
            }
            else
            {
                newServer.Roles = oldServer.Roles;
            }
            newServer.Channels = new List<DiscordChannel>();
            if (!message["d"]["channels"].IsNullOrEmpty())
            {
                foreach (var u in message["d"]["channels"])
                {
                    DiscordChannel tempSub = new DiscordChannel();
                    tempSub.Client = this;
                    tempSub.ID = u["id"].ToString();
                    tempSub.Name = u["name"].ToString();
                    tempSub.Type = u["type"].ToObject<ChannelType>();

                    if (!u["topic"].IsNullOrEmpty())
                        tempSub.Topic = u["topic"].ToString();
                    if (tempSub.Type == ChannelType.Voice && !u["bitrate"].IsNullOrEmpty())
                        tempSub.Bitrate = u["bitrate"].ToObject<int>();

                    tempSub.Parent = newServer;
                    List<DiscordPermissionOverride> permissionoverrides = new List<DiscordPermissionOverride>();
                    foreach (var o in u["permission_overwrites"])
                    {
                        DiscordPermissionOverride dpo = new DiscordPermissionOverride(o["allow"].ToObject<uint>(), o["deny"].ToObject<uint>());
                        dpo.type = o["type"].ToObject<DiscordPermissionOverride.OverrideType>();
                        dpo.id = o["id"].ToString();

                        permissionoverrides.Add(dpo);
                    }
                    tempSub.PermissionOverrides = permissionoverrides;

                    newServer.Channels.Add(tempSub);
                }
            }
            else
            {
                newServer.Channels = oldServer.Channels;
            }
            if (!message["d"]["members"].IsNullOrEmpty())
            {
                foreach (var mm in message["d"]["members"])
                {
                    DiscordMember member = JsonConvert.DeserializeObject<DiscordMember>(mm["user"].ToString());
                    member.parentclient = this;
                    member.Parent = newServer;

                    JArray rawRoles = JArray.Parse(mm["roles"].ToString());
                    if (rawRoles.Count > 0)
                    {
                        foreach (var role in rawRoles.Children())
                        {
                            member.Roles.Add(newServer.Roles.Find(x => x.ID == role.Value<string>()));
                        }
                    }
                    else
                    {
                        member.Roles.Add(newServer.Roles.Find(x => x.Name == "@everyone"));
                    }

                    newServer.AddMember(member);
                }
            }
            else
            {
                newServer.Members = oldServer.Members;
            }
            if (!message["d"]["owner_id"].IsNullOrEmpty())
            {
                newServer.Owner = newServer.GetMemberByKey(message["d"]["owner_id"].ToString());
                DebugLogger.Log($"Transferred ownership from user '{oldServer.Owner.Username}' to {newServer.Owner.Username}.");
            }
            ServersList.Remove(oldServer);
            ServersList.Add(newServer);
            DiscordServerUpdateEventArgs dsuea = new DiscordServerUpdateEventArgs { NewServer = newServer, OldServer = oldServer };
            GuildUpdated?.Invoke(this, dsuea);
        }
Exemple #32
0
        //eh
        private void GetChannelsList(JObject m)
        {
            if (ServersList == null)
                ServersList = new List<DiscordServer>();
            foreach(var j in m["d"]["guilds"])
            {
                DiscordServer temp = new DiscordServer();
                temp.parentclient = this;
                temp.id = j["id"].ToString();
                temp.name = j["name"].ToString();
                if (!j["icon"].IsNullOrEmpty())
                    temp.icon = j["icon"].ToString();
                else
                    temp.icon = null;

                //temp.owner_id = j["owner_id"].ToString();
                List<DiscordChannel> tempSubs = new List<DiscordChannel>();

                List<DiscordRole> tempRoles = new List<DiscordRole>();
                foreach(var u in j["roles"])
                {
                    DiscordRole t = new DiscordRole
                    {
                        color = new DiscordSharp.Color(u["color"].ToObject<int>().ToString("x")),
                        name = u["name"].ToString(),
                        permissions = new DiscordPermission(u["permissions"].ToObject<uint>()),
                        position = u["position"].ToObject<int>(),
                        managed = u["managed"].ToObject<bool>(),
                        id = u["id"].ToString(),
                        hoist = u["hoist"].ToObject<bool>()
                    };
                    tempRoles.Add(t);
                }
                temp.roles = tempRoles;
                foreach(var u in j["channels"])
                {
                    DiscordChannel tempSub = new DiscordChannel();
                    tempSub.ID = u["id"].ToString();
                    tempSub.Name = u["name"].ToString();
                    tempSub.Type = u["type"].ToObject<ChannelType>();
                    tempSub.Topic = u["topic"].ToString();
                    tempSub.parent = temp;
                    List<DiscordPermissionOverride> permissionoverrides = new List<DiscordPermissionOverride>();
                    foreach(var o in u["permission_overwrites"])
                    {
                        DiscordPermissionOverride dpo = new DiscordPermissionOverride(o["allow"].ToObject<uint>(), o["deny"].ToObject<uint>());
                        dpo.id = o["id"].ToString();

                        if (o["type"].ToString() == "member")
                            dpo.type = DiscordPermissionOverride.OverrideType.member;
                        else
                            dpo.type = DiscordPermissionOverride.OverrideType.role;

                        permissionoverrides.Add(dpo);
                    }
                    tempSub.PermissionOverrides = permissionoverrides;

                    tempSubs.Add(tempSub);
                }
                temp.channels = tempSubs;
                foreach(var mm in j["members"])
                {
                    DiscordMember member = JsonConvert.DeserializeObject<DiscordMember>(mm["user"].ToString());
                    member.parentclient = this;
                    //member.ID = mm["user"]["id"].ToString();
                    //member.Username = mm["user"]["username"].ToString();
                    //member.Avatar = mm["user"]["avatar"].ToString();
                    //member.Discriminator = mm["user"]["discriminator"].ToString();
                    member.Roles = new List<DiscordRole>();
                    JArray rawRoles = JArray.Parse(mm["roles"].ToString());
                    if(rawRoles.Count > 0)
                    {
                        foreach(var role in rawRoles.Children())
                        {
                            member.Roles.Add(temp.roles.Find(x => x.id == role.Value<string>()));
                        }
                    }
                    else
                    {
                        member.Roles.Add(temp.roles.Find(x => x.name == "@everyone"));
                    }
                    member.Parent = temp;

                    temp.members.Add(member);
                }
                foreach(var presence in j["presence"])
                {
                    DiscordMember member = temp.members.Find(x => x.ID == presence["user"]["id"].ToString());
                    member.SetPresence(presence["status"].ToString());
                    if (!presence["game"].IsNullOrEmpty())
                        member.CurrentGame = presence["game"]["name"].ToString();
                }
                temp.region = j["region"].ToString();
                temp.owner = temp.members.Find(x => x.ID == j["owner_id"].ToString());
                ServersList.Add(temp);
            }
            if (PrivateChannels == null)
                PrivateChannels = new List<DiscordPrivateChannel>();
            foreach(var privateChannel in m["d"]["private_channels"])
            {
                DiscordPrivateChannel tempPrivate = JsonConvert.DeserializeObject<DiscordPrivateChannel>(privateChannel.ToString());
                DiscordServer potentialServer = new DiscordServer();
                ServersList.ForEach(x =>
                {
                    x.members.ForEach(y =>
                    {
                        if (y.ID == privateChannel["recipient"]["id"].ToString())
                            potentialServer = x;
                    });
                });
                if(potentialServer.owner != null) //should be a safe test..i hope
                {
                    DiscordMember recipient = potentialServer.members.Find(x => x.ID == privateChannel["recipient"]["id"].ToString());
                    if (recipient != null)
                    {
                        tempPrivate.recipient = recipient;
                        PrivateChannels.Add(tempPrivate);
                    }
                    else
                    {
                        DebugLogger.Log("Recipient was null!!!!", MessageLevel.Critical);
                    }
                }
                else
                {
                    DebugLogger.Log("No potential server found for user's private channel null!!!!", MessageLevel.Critical);
                }
            }
        }
 /// <summary>
 /// Assigns a specified role to a member, given you have the permission.
 /// </summary>
 /// <param name="guild">The guild you and the user are in.</param>
 /// <param name="role">The role you wish to assign them.</param>
 /// <param name="member">The member you wish to assign the role to.</param>
 public void AssignRoleToMember(DiscordServer guild, DiscordRole role, DiscordMember member)
 {
     string url = Endpoints.BaseAPI + Endpoints.Guilds + $"/{guild.ID}" + Endpoints.Members + $"/{member.ID}";
     string message = JsonConvert.SerializeObject(new { roles = new string[] { role.ID } });
     try
     {
         WebWrapper.Patch(url, token, message);
     }
     catch (Exception ex)
     {
         DebugLogger.Log($"Exception ocurred while assigning role ({role.Name}) to member ({member.Username}): "
             + ex.Message, MessageLevel.Error);
     }
 }
Exemple #34
0
        private void GuildRoleUpdateEvents(JObject message)
        {
            DiscordServer inServer = ServersList.Find(x => x.id == message["d"]["guild_id"].ToString());
            DiscordRole roleUpdated = new DiscordRole
            {
                name = message["d"]["role"]["name"].ToString(),
                position = message["d"]["role"]["position"].ToObject<int>(),
                permissions = new DiscordPermission(message["d"]["role"]["permissions"].ToObject<uint>()),
                managed = message["d"]["role"]["managed"].ToObject<bool>(),
                hoist = message["d"]["role"]["hoist"].ToObject<bool>(),
                color = new Color(message["d"]["role"]["color"].ToObject<int>().ToString("x")),
                id = message["d"]["role"]["id"].ToString(),
            };

            ServersList.Find(x => x.id == inServer.id).roles.Remove(ServersList.Find(x => x.id == inServer.id).roles.Find(y => y.id == roleUpdated.id));
            ServersList.Find(x => x.id == inServer.id).roles.Add(roleUpdated);

            if (RoleUpdated != null)
                RoleUpdated(this, new DiscordGuildRoleUpdateEventArgs { RawJson = message, RoleUpdated = roleUpdated, InServer = inServer });
        }
        private void GuildRoleUpdateEvents(JObject message)
        {
            DiscordServer inServer = ServersList.Find(x => x.ID == message["d"]["guild_id"].ToString());
            DiscordRole roleUpdated = new DiscordRole
            {
                Name = message["d"]["role"]["name"].ToString(),
                Position = message["d"]["role"]["position"].ToObject<int>(),
                Permissions = new DiscordPermission(message["d"]["role"]["permissions"].ToObject<uint>()),
                Managed = message["d"]["role"]["managed"].ToObject<bool>(),
                Hoist = message["d"]["role"]["hoist"].ToObject<bool>(),
                Color = new Color(message["d"]["role"]["color"].ToObject<int>().ToString("x")),
                ID = message["d"]["role"]["id"].ToString(),
            };

            ServersList.Find(x => x.ID == inServer.ID).Roles.Remove(ServersList.Find(x => x.ID == inServer.ID).Roles.Find(y => y.ID == roleUpdated.ID));
            ServersList.Find(x => x.ID == inServer.ID).Roles.Add(roleUpdated);

            RoleUpdated?.Invoke(this, new DiscordGuildRoleUpdateEventArgs { RawJson = message, RoleUpdated = roleUpdated, InServer = inServer });
        }
Exemple #36
0
        private void GuildCreateEvents(JObject message)
        {
            DiscordGuildCreateEventArgs e = new DiscordGuildCreateEventArgs();
            e.RawJson = message;
            DiscordServer server = new DiscordServer();
            server.parentclient = this;
            server.id = message["d"]["id"].ToString();
            server.name = message["d"]["name"].ToString();
            server.members = new List<DiscordMember>();
            server.channels = new List<DiscordChannel>();
            server.roles = new List<DiscordRole>();
            foreach (var roll in message["d"]["roles"])
            {
                DiscordRole t = new DiscordRole
                {
                    color = new DiscordSharp.Color(roll["color"].ToObject<int>().ToString("x")),
                    name = roll["name"].ToString(),
                    permissions = new DiscordPermission(roll["permissions"].ToObject<uint>()),
                    position = roll["position"].ToObject<int>(),
                    managed = roll["managed"].ToObject<bool>(),
                    id = roll["id"].ToString(),
                    hoist = roll["hoist"].ToObject<bool>()
                };
                server.roles.Add(t);
            }
            foreach (var chn in message["d"]["channels"])
            {
                DiscordChannel tempChannel = new DiscordChannel();
                tempChannel.ID = chn["id"].ToString();
                tempChannel.Type = chn["type"].ToObject<ChannelType>();
                tempChannel.Topic = chn["topic"].ToString();
                tempChannel.Name = chn["name"].ToString();
                tempChannel.Private = false;
                tempChannel.PermissionOverrides = new List<DiscordPermissionOverride>();
                tempChannel.parent = server;
                foreach (var o in chn["permission_overwrites"])
                {
                    if (tempChannel.Type == ChannelType.Voice)
                        continue;
                    DiscordPermissionOverride dpo = new DiscordPermissionOverride(o["allow"].ToObject<uint>(), o["deny"].ToObject<uint>());
                    dpo.id = o["id"].ToString();

                    if (o["type"].ToString() == "member")
                        dpo.type = DiscordPermissionOverride.OverrideType.member;
                    else
                        dpo.type = DiscordPermissionOverride.OverrideType.role;

                    tempChannel.PermissionOverrides.Add(dpo);
                }
                server.channels.Add(tempChannel);
            }
            foreach(var mbr in message["d"]["members"])
            {
                DiscordMember member = JsonConvert.DeserializeObject<DiscordMember>(mbr["user"].ToString());
                member.parentclient = this;
                member.Parent = server;
                
                foreach(var rollid in mbr["roles"])
                {
                    member.Roles.Add(server.roles.Find(x => x.id == rollid.ToString()));
                }
                if (member.Roles.Count == 0)
                    member.Roles.Add(server.roles.Find(x => x.name == "@everyone"));
                server.members.Add(member);
            }
            server.owner = server.members.Find(x => x.ID == message["d"]["owner_id"].ToString());

            ServersList.Add(server);
            e.server = server;
            if (GuildCreated != null)
                GuildCreated(this, e);
        }
        /// <summary>
        /// Creates a default role in the specified guild.
        /// </summary>
        /// <param name="guild">The guild to make the role in.</param>
        /// <returns>The newly created role.</returns>
        public DiscordRole CreateRole(DiscordServer guild)
        {
            string url = Endpoints.BaseAPI + Endpoints.Guilds + $"/{guild.ID}" + Endpoints.Roles;

            try
            {
                var result = JObject.Parse(WebWrapper.Post(url, token, ""));

                if (result != null)
                {
                    DiscordRole d = new DiscordRole
                    {
                        Color = new Color(result["color"].ToObject<int>().ToString("x")),
                        Hoist = result["hoist"].ToObject<bool>(),
                        ID = result["id"].ToString(),
                        Managed = result["managed"].ToObject<bool>(),
                        Name = result["name"].ToString(),
                        Permissions = new DiscordPermission(result["permissions"].ToObject<uint>()),
                        Position = result["position"].ToObject<int>()
                    };

                    ServersList.Find(x => x.ID == guild.ID).Roles.Add(d);
                    return d;
                }
            }
            catch (Exception ex)
            {
                DebugLogger.Log($"Error ocurred while creating role in guild {guild.Name}: {ex.Message}", MessageLevel.Error);
            }
            return null;
        }
        /// <summary>
        /// Edits a role with the new role information.
        /// </summary>
        /// <param name="guild">The guild the role is in.</param>
        /// <param name="newRole">the new role.</param>
        /// <returns>The newly edited role returned from Discord.</returns>
        public DiscordRole EditRole(DiscordServer guild, DiscordRole newRole)
        {
            string url = Endpoints.BaseAPI + Endpoints.Guilds + $"/{guild.ID}" + Endpoints.Roles + $"/{newRole.ID}";
            string request = JsonConvert.SerializeObject(
                new
                {
                    color = decimal.Parse(newRole.Color.ToDecimal().ToString()),
                    hoist = newRole.Hoist,
                    name = newRole.Name,
                    permissions = newRole.Permissions.GetRawPermissions()
                }
            );

            try
            {
                var result = JObject.Parse(WebWrapper.Patch(url, token, request));
                if (result != null)
                {
                    DiscordRole d = new DiscordRole
                    {
                        Color = new Color(result["color"].ToObject<int>().ToString("x")),
                        Hoist = result["hoist"].ToObject<bool>(),
                        ID = result["id"].ToString(),
                        Managed = result["managed"].ToObject<bool>(),
                        Name = result["name"].ToString(),
                        Permissions = new DiscordPermission(result["permissions"].ToObject<uint>()),
                        Position = result["position"].ToObject<int>()
                    };

                    ServersList.Find(x => x.ID == guild.ID).Roles.Remove(d);
                    ServersList.Find(x => x.ID == guild.ID).Roles.Add(d);
                    return d;
                }
            }
            catch (Exception ex)
            {
                DebugLogger.Log($"Error ocurred while editing role ({newRole.Name}): {ex.Message}", MessageLevel.Error);
            }

            return null;
        }
 /// <summary>
 /// Deletes a specified role.
 /// </summary>
 /// <param name="guild">The guild the role is in.</param>
 /// <param name="role">The role to delete.</param>
 public void DeleteRole(DiscordServer guild, DiscordRole role)
 {
     string url = Endpoints.BaseAPI + Endpoints.Guilds + $"/{guild.ID}" + Endpoints.Roles + $"/{role.ID}";
     try
     {
         WebWrapper.Delete(url, token);
     }
     catch (Exception ex)
     {
         DebugLogger.Log($"Error ocurred while deleting role ({role.Name}): {ex.Message}", MessageLevel.Error);
     }
 }
        //eh
        private void GetChannelsList(JObject m)
        {
            if (ServersList == null)
                ServersList = new List<DiscordServer>();
            foreach (var j in m["d"]["guilds"])
            {
                if (!j["unavailable"].IsNullOrEmpty() && j["unavailable"].ToObject<bool>() == true)
                    continue; //unavailable server
                DiscordServer temp = new DiscordServer();
                temp.parentclient = this;
                temp.JoinedAt = j["joined_at"].ToObject<DateTime>();
                temp.ID = j["id"].ToString();
                temp.Name = j["name"].ToString();
                if (!j["icon"].IsNullOrEmpty())
                    temp.icon = j["icon"].ToString();
                else
                    temp.icon = null;

                //temp.owner_id = j["owner_id"].ToString();
                List<DiscordChannel> tempSubs = new List<DiscordChannel>();

                List<DiscordRole> tempRoles = new List<DiscordRole>();
                foreach (var u in j["roles"])
                {
                    DiscordRole t = new DiscordRole
                    {
                        Color = new DiscordSharp.Color(u["color"].ToObject<int>().ToString("x")),
                        Name = u["name"].ToString(),
                        Permissions = new DiscordPermission(u["permissions"].ToObject<uint>()),
                        Position = u["position"].ToObject<int>(),
                        Managed = u["managed"].ToObject<bool>(),
                        ID = u["id"].ToString(),
                        Hoist = u["hoist"].ToObject<bool>()
                    };
                    tempRoles.Add(t);
                }
                temp.Roles = tempRoles;
                foreach (var u in j["channels"])
                {
                    DiscordChannel tempSub = new DiscordChannel();
                    tempSub.Client = this;
                    tempSub.ID = u["id"].ToString();
                    tempSub.Name = u["name"].ToString();
                    tempSub.Type = u["type"].ToObject<ChannelType>();
                    if (!u["topic"].IsNullOrEmpty())
                        tempSub.Topic = u["topic"].ToString();
                    if (tempSub.Type == ChannelType.Voice && !u["bitrate"].IsNullOrEmpty())
                        tempSub.Bitrate = u["bitrate"].ToObject<int>();
                    tempSub.Parent = temp;
                    List<DiscordPermissionOverride> permissionoverrides = new List<DiscordPermissionOverride>();
                    foreach (var o in u["permission_overwrites"])
                    {
                        DiscordPermissionOverride dpo = new DiscordPermissionOverride(o["allow"].ToObject<uint>(), o["deny"].ToObject<uint>());
                        dpo.id = o["id"].ToString();

                        if (o["type"].ToString() == "member")
                            dpo.type = DiscordPermissionOverride.OverrideType.member;
                        else
                            dpo.type = DiscordPermissionOverride.OverrideType.role;

                        permissionoverrides.Add(dpo);
                    }
                    tempSub.PermissionOverrides = permissionoverrides;

                    tempSubs.Add(tempSub);
                }
                temp.Channels = tempSubs;
                foreach (var mm in j["members"])
                {
                    DiscordMember member = JsonConvert.DeserializeObject<DiscordMember>(mm["user"].ToString());
                    member.parentclient = this;
                    member.Roles = new List<DiscordRole>();
                    JArray rawRoles = JArray.Parse(mm["roles"].ToString());
                    if (rawRoles.Count > 0)
                    {
                        foreach (var role in rawRoles.Children())
                        {
                            member.Roles.Add(temp.Roles.Find(x => x.ID == role.Value<string>()));
                        }
                    }
                    else
                    {
                        member.Roles.Add(temp.Roles.Find(x => x.Name == "@everyone"));
                    }
                    temp.AddMember(member);
                }
                if (!j["presences"].IsNullOrEmpty())
                {
                    foreach (var presence in j["presences"])
                    {
                        DiscordMember member = temp.GetMemberByKey(presence["user"]["id"].ToString());
                        if (member != null)
                        {
                            member.SetPresence(presence["status"].ToString());
                            if (!presence["game"].IsNullOrEmpty())
                            {
                                member.CurrentGame = presence["game"]["name"].ToString();
                                if (presence["d"]["game"]["type"].ToObject<int>() == 1)
                                {
                                    member.Streaming = true;
                                    if (presence["d"]["game"]["url"].ToString() != null)
                                        member.StreamURL = presence["d"]["game"]["url"].ToString();
                                }
                            }
                        }
                    }
                }
                temp.Region = j["region"].ToString();
                temp.Owner = temp.GetMemberByKey(j["owner_id"].ToString());
                ServersList.Add(temp);
            }
            if (PrivateChannels == null)
                PrivateChannels = new List<DiscordPrivateChannel>();
            foreach (var privateChannel in m["d"]["private_channels"])
            {
                DiscordPrivateChannel tempPrivate = JsonConvert.DeserializeObject<DiscordPrivateChannel>(privateChannel.ToString());
                tempPrivate.Client = this;
                tempPrivate.user_id = privateChannel["recipient"]["id"].ToString();
                DiscordServer potentialServer = new DiscordServer();
                ServersList.ForEach(x =>
                {
                    if (x.GetMemberByKey(privateChannel["recipient"]["id"].ToString()) != null)
                    {
                        potentialServer = x;
                    }
                });
                if (potentialServer.Owner != null) //should be a safe test..i hope
                {
                    DiscordMember recipient = potentialServer.GetMemberByKey(privateChannel["recipient"]["id"].ToString());
                    if (recipient != null)
                    {
                        tempPrivate.Recipient = recipient;
                    }
                    else
                    {
                        DebugLogger.Log("Recipient was null!!!!", MessageLevel.Critical);
                    }
                }
                else
                {
                    DebugLogger.Log("No potential server found for user's private channel null! This will probably fix itself.", MessageLevel.Debug);
                }
                PrivateChannels.Add(tempPrivate);
            }

        }
        private void GuildCreateEvents(JObject message)
        {
            DiscordGuildCreateEventArgs e = new DiscordGuildCreateEventArgs();
            e.RawJson = message;
            DiscordServer server = new DiscordServer();
            server.JoinedAt = message["d"]["joined_at"].ToObject<DateTime>();
            server.parentclient = this;
            server.ID = message["d"]["id"].ToString();
            server.Name = message["d"]["name"].ToString();
            server.Members = new Dictionary<ID, DiscordMember>();
            server.Channels = new List<DiscordChannel>();
            server.Roles = new List<DiscordRole>();
            foreach (var roll in message["d"]["roles"])
            {
                DiscordRole t = new DiscordRole
                {
                    Color = new DiscordSharp.Color(roll["color"].ToObject<int>().ToString("x")),
                    Name = roll["name"].ToString(),
                    Permissions = new DiscordPermission(roll["permissions"].ToObject<uint>()),
                    Position = roll["position"].ToObject<int>(),
                    Managed = roll["managed"].ToObject<bool>(),
                    ID = roll["id"].ToString(),
                    Hoist = roll["hoist"].ToObject<bool>()
                };
                server.Roles.Add(t);
            }
            foreach (var chn in message["d"]["channels"])
            {
                DiscordChannel tempChannel = new DiscordChannel();
                tempChannel.Client = this;
                tempChannel.ID = chn["id"].ToString();
                tempChannel.Type = chn["type"].ToObject<ChannelType>();

                if (!chn["topic"].IsNullOrEmpty())
                    tempChannel.Topic = chn["topic"].ToString();
                if (tempChannel.Type == ChannelType.Voice && !chn["bitrate"].IsNullOrEmpty())
                    tempChannel.Bitrate = chn["bitrate"].ToObject<int>();

                tempChannel.Name = chn["name"].ToString();
                tempChannel.Private = false;
                tempChannel.PermissionOverrides = new List<DiscordPermissionOverride>();
                tempChannel.Parent = server;
                foreach (var o in chn["permission_overwrites"])
                {
                    if (tempChannel.Type == ChannelType.Voice)
                        continue;
                    DiscordPermissionOverride dpo = new DiscordPermissionOverride(o["allow"].ToObject<uint>(), o["deny"].ToObject<uint>());
                    dpo.id = o["id"].ToString();

                    if (o["type"].ToString() == "member")
                        dpo.type = DiscordPermissionOverride.OverrideType.member;
                    else
                        dpo.type = DiscordPermissionOverride.OverrideType.role;

                    tempChannel.PermissionOverrides.Add(dpo);
                }
                server.Channels.Add(tempChannel);
            }
            foreach (var mbr in message["d"]["members"])
            {
                DiscordMember member = JsonConvert.DeserializeObject<DiscordMember>(mbr["user"].ToString());
                if(mbr["nick"] != null)
                    member.Nickname = mbr["nick"].ToString();

                member.parentclient = this;
                member.Parent = server;

                foreach (var rollid in mbr["roles"])
                {
                    member.Roles.Add(server.Roles.Find(x => x.ID == rollid.ToString()));
                }
                if (member.Roles.Count == 0)
                    member.Roles.Add(server.Roles.Find(x => x.Name == "@everyone"));
                server.AddMember(member);
            }
            foreach (var voiceStateJSON in message["d"]["voice_states"]) {
                DiscordVoiceState voiceState = JsonConvert.DeserializeObject<DiscordVoiceState>(voiceStateJSON.ToString());
                DiscordMember member = server.GetMemberByKey(voiceState.UserID);

                member.CurrentVoiceChannel = server.Channels.Find(x => x.ID == voiceState.ChannelID);
                member.VoiceState = voiceState;
            }
            server.Owner = server.GetMemberByKey(message["d"]["owner_id"].ToString());
            e.Server = server;

            if (!message["d"]["unavailable"].IsNullOrEmpty() && message["d"]["unavailable"].ToObject<bool>() == false)
            {
                var oldServer = ServersList.Find(x => x.ID == server.ID);
                if (oldServer != null && oldServer.Unavailable)
                    ServersList.Remove(oldServer);

                ServersList.Add(server);

                DebugLogger.Log($"Guild with ID {server.ID} ({server.Name}) became available.");
                GuildAvailable?.Invoke(this, e);
                return;
            }

            ServersList.Add(server);
            GuildCreated?.Invoke(this, e);
        }