Exemple #1
0
        public async Task CreatePrivateLobby(CommandContext ctx, string lobbyName, params DiscordMember[] allowedUsers)
        {
            try
            {
                await ctx.Channel.DeleteMessageAsync(ctx.Message);

                DiscordChannel parentCategory = await ctx.Client.GetChannelAsync(ParentCategoryId);

                DiscordChannel waitChannel = await ctx.Client.GetChannelAsync(WaitChannelId);

                if (!waitChannel.Users.Contains(ctx.User))
                {
                    throw new NBWaitRoomException();
                }

                DiscordRole createdRole = await ctx.Guild.CreateRoleAsync(lobbyName);

                DiscordChannel createdLobby = await ctx.Guild.CreateVoiceChannelAsync(
                    lobbyName == "_"?$"Lobby - {ctx.Member.DisplayName}" : lobbyName,
                    parent : parentCategory);

                await createdLobby.PlaceMemberAsync(ctx.Member);

                await createdLobby.AddOverwriteAsync(ctx.Guild.GetRole(DefaultRole), deny : Permissions.AccessChannels);

                await createdLobby.AddOverwriteAsync(createdRole, allow : Permissions.AccessChannels);

                await createdLobby.AddOverwriteAsync(ctx.Member, allow : Permissions.MuteMembers | Permissions.DeafenMembers);

                IReadOnlyCollection <DiscordMember> allMembers = await ctx.Guild.GetAllMembersAsync();

                await ctx.Member.GrantRoleAsync(createdRole);

                foreach (DiscordMember member in allowedUsers)
                {
                    await member.GrantRoleAsync(createdRole);
                }

                while (true)
                {
                    await Task.Delay(5000);

                    if (createdLobby.Users.Count() <= 0)
                    {
                        await createdLobby.DeleteAsync();

                        await createdRole.DeleteAsync();

                        return;
                    }
                }
            }
            catch (NBException ex)
            {
                await ex.SendException(ctx);
            }
        }
        public async Task LockSalasync(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();

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

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

                if (resultadoSalas[0].salaTrancada)
                {
                    embed.WithAuthor($"❎ - Esta sala já está trancada!", null, Values.logoUBGE);
                    embed.WithColor(Program.Bot.Utilities.RandomColorEmbed());

                    await ctx.RespondAsync(embed : embed.Build());
                }
                else if (!resultadoSalas[0].salaTrancada)
                {
                    await salasCollection.UpdateOneAsync(filtroSalas, Builders <Salas> .Update.Set(s => s.salaTrancada, true));

                    DiscordMember m = null;

                    foreach (ulong u in resultadoSalas[0].idsPermitidos)
                    {
                        m = await ctx.Guild.GetMemberAsync(u);

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

                    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 travada!", 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 #3
0
            public async Task AddApproval(CommandContext e, [Description("Mention the user you will be approving.")] DiscordMember m)
            {
                Regex          rgx  = new Regex("[^a-zA-Z0-9-]");
                string         name = rgx.Replace(m.DisplayName, "");
                DiscordChannel c    = await e.Guild.CreateChannelAsync(name, ChannelType.Text, parent : RPClass.ApprovalsCategory);

                await c.AddOverwriteAsync(m, Permissions.SendMessages, Permissions.None);

                await c.AddOverwriteAsync(e.Guild.EveryoneRole, Permissions.ReadMessageHistory, Permissions.SendMessages);

                await e.RespondAsync("Channel created!\n" + c.Mention);
            }
Exemple #4
0
 public static async Task GrantPermissions(this DiscordChannel channel, DiscordRole role, Permissions allow, Permissions deny)
 {
     if (role.CheckPermission(allow) != PermissionLevel.Allowed)
     {
         await channel.AddOverwriteAsync(role, allow, deny, $"Setting @{role.Name} role permissions for channel #team_{role.Name}.");
     }
 }
Exemple #5
0
        internal async Task OnMemberAdded(DiscordClient client, GuildMemberAddEventArgs e)
        {
            if (!Database.TryGetOpenTickets(e.Member.Id, out List <Database.Ticket> ownTickets))
            {
                return;
            }

            foreach (Database.Ticket ticket in ownTickets)
            {
                try
                {
                    DiscordChannel channel = await client.GetChannelAsync(ticket.channelID);

                    if (channel?.GuildId == e.Guild.Id)
                    {
                        await channel.AddOverwriteAsync(e.Member, Permissions.AccessChannels, Permissions.None);

                        DiscordEmbed message = new DiscordEmbedBuilder()
                                               .WithColor(DiscordColor.Green)
                                               .WithDescription("User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has rejoined the server, and has been re-added to the ticket.");
                        await channel.SendMessageAsync(message);
                    }
                }
                catch (Exception) { }
            }
        }
Exemple #6
0
        public static async Task MoveChat(DiscordGuild guild, DiscordChannel channel, int limit, DiscordChannel target)
        {
            var lastMessages = await channel.GetMessagesAsync(limit);

            // check if everyone has access
            var permSend          = true;
            var channelOverwrites = channel.PermissionOverwrites.ToList();

            channelOverwrites.ForEach(o => {
                if (o.Id == guild.EveryoneRole.Id)
                {
                    permSend = !o.Denied.HasPermission(Permissions.SendMessages) && !o.Denied.HasPermission(Permissions.AccessChannels);
                }
            });
            await channel.SendMessageAsync("This conversation belongs to " + target.Mention + " and was moved there! \n" + (permSend ? channel.Mention + " is now closed for 2 mins to cool things down.\n" : "") + "\n*Remember to avoid offtopic chats!*");

            if (permSend)
            {
                await channel.AddOverwriteAsync(guild.EveryoneRole, DSharpPlus.Permissions.None, DSharpPlus.Permissions.SendMessages, "Temp timeout start");
            }
            // build embed with recent chat
            var embedChat = new DiscordEmbedBuilder
            {
                Title       = "**Moved chat from *#" + channel.Name + "* **",
                Description = "This conversation didn't meet the channel topic and should be continued here.\n\n\n<a:typing:745068588909592737>"
            };

            embedChat.Color = new DiscordColor("#ff1744");
            lastMessages.Reverse().ToList().ForEach(
                (m) => {
                if (m.Author != Client.CurrentUser)
                {
                    embedChat.AddField("**" + m.Author.Username + "**", m.Content);
                }
            }
                );
            await target.SendMessageAsync(embed : embedChat);

            if (permSend)
            {
                await Task.Delay(120000);

                // release channel
                await channel.AddOverwriteAsync(guild.EveryoneRole, DSharpPlus.Permissions.SendMessages, DSharpPlus.Permissions.None, "Temp timeout stop");
            }
        }
Exemple #7
0
        public async Task SyncPermissions(CommandContext ctx, DiscordChannel channel)
        {
            foreach (var ow in channel.Parent.PermissionOverwrites)
            {
                var role = await ow.GetRoleAsync();

                await channel.AddOverwriteAsync(role, ow.Allowed, ow.Denied, $"Syncing with Parent per request from {ctx.User}");
            }
        }
            static async Task AddOverwrite(DiscordChannel channel, DiscordRole muteRole)
            {
                await channel.AddOverwriteAsync(
                    muteRole,
                    deny : Permissions.SendMessages
                    | Permissions.SendTtsMessages
                    | Permissions.AddReactions
                    | Permissions.Speak
                    );

                await Task.Delay(10);
            }
Exemple #9
0
        public virtual async Task CloseMeeting()
        {
            //Move text meeting to archive.
            DiscordChannel archiveChannel = await GetArchiveChannel(guild);

            DateTimeOffset dateTimeOffset = meetingTextChannel.CreationTimestamp;

            //Check to see if meeting text channel still exists.
            if (guild.GetChannel(meetingTextChannel.Id) != null)
            {
                //Change the name to 'meeting-hhmm-dd-mm'
                await meetingTextChannel.ModifyAsync(async x => {
                    x.Name   = $"meeting-{dateTimeOffset.Hour.ToString("D2")}{dateTimeOffset.Minute.ToString("D2")}-{dateTimeOffset.Day}-{dateTimeOffset.Month}";
                    x.Parent = archiveChannel;
                    x.Topic  = "Archived meeting.";
                });

                //Create a archived meeting message.
                await new DiscordMessageBuilder()
                .WithContent(
                    $"**End of archived messages.** ( ̄o ̄) . z Z\n" +
                    $"*Meeting created on **{dateTimeOffset.Day}-{dateTimeOffset.Month}-{dateTimeOffset.Year}** at **{dateTimeOffset.Hour}:{dateTimeOffset.Minute}:{dateTimeOffset.Second.ToString("D2")}**.\n\n" +
                    $"This is an archived channel and can no longer be messaged by users with the 'everyone' permission.\n" +
                    $"Please contact a server administrator for further assistance.* :crab:")
                .SendAsync(meetingTextChannel);

                //Send the message to the channel.
                await meetingTextChannel.AddOverwriteAsync(guild.EveryoneRole, DSharpPlus.Permissions.None, DSharpPlus.Permissions.SendMessages);
            }

            //Delete channels.
            foreach (DiscordChannel channel in channels)
            {
                //Check channel still exists.
                if (guild.GetChannel(channel.Id) != null)
                {
                    await channel.DeleteAsync();
                }
            }

            //Remove meeting from registry.
            GuildMeetings[guild.Id].Remove(hostMember.Id, out _);

            //Remove the guild from the list completely if it's empty.
            if (GuildMeetings[guild.Id].IsEmpty)
            {
                GuildMeetings.Remove(guild.Id, out _);
            }

            meetingClosed = true;
        }
        async Task <(bool, string)> CreateClass(CommandContext context)
        {
            string errorMessage = string.Empty;
            bool   success      = true;

            DiscordChannel categoryChannel = await _channel.Guild.CreateChannelAsync($"{_courseCategory} {_courseNumber} {_courseTitle}", ChannelType.Category);

            DiscordRole categoryRole = await _channel.Guild.CreateRoleAsync($"{_courseCategory} {_courseNumber}", ALLOWED);

            // if you do not modify the position - it will end up at the bottom of the channel list
            await categoryChannel.ModifyPositionAsync(await GetSortPosition());

            await categoryChannel.AddOverwriteAsync(categoryRole, ALLOWED, Permissions.Administrator);

            await categoryChannel.AddOverwriteAsync(everyone, Permissions.None, DENIED);

            // Apply all roles that were found in the config (to our category)
            foreach (DiscordRole role in this.additionalRoles)
            {
                await categoryChannel.AddOverwriteAsync(role, ALLOWED, Permissions.None);
            }

            // Create each specified channel within the config
            foreach (string channelName in _options.ChannelNames)
            {
                await CreateTextChannel(categoryChannel, $"{_courseCategory} {_courseNumber}", channelName);
            }

            // Create voice channels based on config
            for (int i = 0; i < _options.NumberOfVoiceChannels; i++)
            {
                _ = await _channel.Guild.CreateChannelAsync($"{_courseCategory} {_courseNumber} - {i + 1}", ChannelType.Voice, parent : categoryChannel);
            }

            return(success, errorMessage);
        }
Exemple #11
0
        public async Task End(CommandContext e, [Description("Quote the ID at the beginning of the channel name.")] int rpID)
        {
            InstanceObject.RootObject instance = RPClass.InstanceList.FirstOrDefault(x => x.Id == rpID);
            if (instance != null)
            {
                DiscordChannel c = e.Guild.GetChannel(instance.ChannelID);
                await c.AddOverwriteAsync(e.Guild.EveryoneRole, Permissions.ReadMessageHistory, Permissions.SendMessages);

                instance.Active = false;

                RPClass.SaveData(7);
                await e.RespondAsync("Instance closed.");
            }
            else
            {
                await e.RespondAsync("Use the ID at the beginning of the channel name.");
            }
        }
Exemple #12
0
        public async Task SyncPermissions(CommandContext ctx, DiscordChannel channel,
                                          DiscordChannel category = null)
        {
            var parent = category ?? channel.Parent;

            if (parent.Type != ChannelType.Category)
            {
                //TODO Throw custom exception
            }

            foreach (var ow in channel.Parent.PermissionOverwrites)
            {
                var role = await ow.GetRoleAsync();

                await channel.AddOverwriteAsync(role, ow.Allowed, ow.Denied,
                                                $"Syncing with Parent per request from {ctx.User}");
            }
        }
Exemple #13
0
        public async Task CreateLobby(CommandContext ctx, string lobbyName, int userLimit = 20)
        {
            try
            {
                await ctx.Channel.DeleteMessageAsync(ctx.Message);

                DiscordChannel parentCategory = await ctx.Client.GetChannelAsync(ParentCategoryId);

                DiscordChannel waitChannel = await ctx.Client.GetChannelAsync(WaitChannelId);

                if (!waitChannel.Users.Contains(ctx.User))
                {
                    throw new NBWaitRoomException();
                }

                DiscordChannel createdLobby = await ctx.Guild.CreateChannelAsync(
                    lobbyName == "_"?$"Lobby - {ctx.Member.DisplayName}" : lobbyName,
                    ChannelType.Voice,
                    parent : parentCategory,
                    userLimit : userLimit);

                await createdLobby.PlaceMemberAsync(ctx.Member);

                await createdLobby.AddOverwriteAsync(ctx.Member, allow : Permissions.MuteMembers | Permissions.DeafenMembers);

                while (true)
                {
                    await Task.Delay(5000);

                    if (createdLobby.Users.Count() <= 0)
                    {
                        await createdLobby.DeleteAsync();

                        return;
                    }
                }
            }
            catch (NBException ex)
            {
                await ex.SendException(ctx);
            }
        }
        public void Start()
        {
            Task.Run(async() =>
            {
                await _ch.AddOverwriteAsync(_ch.Guild.EveryoneRole, Permissions.SendMessages, Permissions.None).ConfigureAwait(false);

                var initMsg = $"An Old Maid game has started between {Players[0].Player.DisplayName} and {Players[1].Player.DisplayName}!\n";
                initMsg    += $"{Players[Players.Count - 1].Player.DisplayName} goes first!\n";
                try
                {
                    await _ch.SendMessageAsync(initMsg).ConfigureAwait(false);
                    await Players[0].Start().ConfigureAwait(false);
                    await Players[1].Start().ConfigureAwait(false);
                    await ShowAll().ConfigureAwait(false);
                } catch (Exception e)
                {
                    await _ch.SendMessageAsync(e.Message).ConfigureAwait(false);
                    await Dispose().ConfigureAwait(false);
                }
            });
        }
Exemple #15
0
        public void BeginTimeboxMeeting()
        {
            Task.Run(async() => {
                DiscordChannel statsChannel = await CreateTimeboxStatsChannel();
                DiscordMessage statsMessage = null;

                while (currentTimeboxTime > 0 && !meetingClosed)
                {
                    //Refresh the channel.
                    statsChannel = guild.GetChannel(statsChannel.Id);

                    //Make sure stats channel exists.
                    if (statsChannel == null)
                    {
                        statsChannel = await CreateTimeboxStatsChannel();
                    }


                    //Handle message deletions.
                    if (statsMessage != null)
                    {
                        try {
                            statsMessage = await statsChannel.GetMessageAsync(statsMessage.Id);
                        }
                        catch (Exception) {
                            await statsChannel.AddOverwriteAsync(guild.EveryoneRole, DSharpPlus.Permissions.SendMessages, DSharpPlus.Permissions.None);
                            statsMessage = null;
                        }
                    }

                    if (statsMessage == null)
                    {
                        try {
                            statsMessage = await new DiscordMessageBuilder()
                                           .WithContent(getTimeboxStatsMessage())
                                           .SendAsync(statsChannel);
                        }
                        catch (Exception) {
                            //Cry me a f*****g river.
                        }
                        await statsChannel.AddOverwriteAsync(guild.EveryoneRole, DSharpPlus.Permissions.None, DSharpPlus.Permissions.SendMessages);
                    }
                    else
                    {
                        try {
                            await statsMessage.ModifyAsync(getTimeboxStatsMessage());
                        }
                        catch (Exception) {
                            //Again, just throwing random ass exceptions for no apparent reason.
                            //Thanks DSharpPlus, you're my favourite API :D
                        }
                    }

                    //10 second update.
                    await Task.Delay(1000 * 10);
                    currentTimeboxTime -= 10;
                }

                await CloseMeeting();
            });
        }
Exemple #16
0
        internal async Task OnReactionAdded(DiscordClient client, MessageReactionAddEventArgs e)
        {
            if (e.Message.Id != Config.reactionMessage)
            {
                return;
            }

            DiscordGuild  guild  = e.Message.Channel.Guild;
            DiscordMember member = await guild.GetMemberAsync(e.User.Id);

            if (!Config.HasPermission(member, "new") || Database.IsBlacklisted(member.Id))
            {
                return;
            }
            if (reactionTicketCooldowns.ContainsKey(member.Id))
            {
                if (reactionTicketCooldowns[member.Id] > DateTime.Now)
                {
                    return;                                                                    // cooldown has not expired
                }
                else
                {
                    reactionTicketCooldowns.Remove(member.Id);                  // cooldown exists but has expired, delete it
                }
            }


            DiscordChannel category      = guild.GetChannel(Config.ticketCategory);
            DiscordChannel ticketChannel = await guild.CreateChannelAsync("ticket", ChannelType.Text, category);

            if (ticketChannel == null)
            {
                return;
            }

            ulong staffID = 0;

            if (Config.randomAssignment)
            {
                staffID = Database.GetRandomActiveStaff(0)?.userID ?? 0;
            }

            long id = Database.NewTicket(member.Id, staffID, ticketChannel.Id);

            reactionTicketCooldowns.Add(member.Id, DateTime.Now.AddSeconds(10));             // add a cooldown which expires in 10 seconds
            string ticketID = id.ToString("00000");

            await ticketChannel.ModifyAsync(model => model.Name = "ticket-" + ticketID);

            await ticketChannel.AddOverwriteAsync(member, Permissions.AccessChannels, Permissions.None);

            await ticketChannel.SendMessageAsync("Hello, " + member.Mention + "!\n" + Config.welcomeMessage);

            // Remove user's reaction
            await e.Message.DeleteReactionAsync(e.Emoji, e.User);

            // Refreshes the channel as changes were made to it above
            ticketChannel = await SupportBoi.GetClient().GetChannelAsync(ticketChannel.Id);

            if (staffID != 0)
            {
                DiscordEmbed assignmentMessage = new DiscordEmbedBuilder
                {
                    Color       = DiscordColor.Green,
                    Description = "Ticket was randomly assigned to <@" + staffID + ">."
                };
                await ticketChannel.SendMessageAsync(assignmentMessage);

                if (Config.assignmentNotifications)
                {
                    DiscordEmbed message = new DiscordEmbedBuilder
                    {
                        Color       = DiscordColor.Green,
                        Description = "You have been randomly assigned to a newly opened support ticket: " +
                                      ticketChannel.Mention
                    };

                    try
                    {
                        DiscordMember staffMember = await guild.GetMemberAsync(staffID);

                        await staffMember.SendMessageAsync(message);
                    }
                    catch (NotFoundException)
                    {
                    }
                    catch (UnauthorizedException)
                    {
                    }
                }
            }

            // Log it if the log channel exists
            DiscordChannel logChannel = guild.GetChannel(Config.logChannel);

            if (logChannel != null)
            {
                DiscordEmbed logMessage = new DiscordEmbedBuilder
                {
                    Color       = DiscordColor.Green,
                    Description = "Ticket " + ticketChannel.Mention + " opened by " + member.Mention + ".\n",
                    Footer      = new DiscordEmbedBuilder.EmbedFooter {
                        Text = "Ticket " + ticketID
                    }
                };
                await logChannel.SendMessageAsync(logMessage);
            }
        }
Exemple #17
0
        internal async Task OnReactionAdded(MessageReactionAddEventArgs e)
        {
            if (e.Message.Id != Config.reactionMessage)
            {
                return;
            }

            DiscordGuild  guild  = e.Message.Channel.Guild;
            DiscordMember member = await guild.GetMemberAsync(e.User.Id);

            if (!Config.HasPermission(member, "new") || Database.IsBlacklisted(member.Id))
            {
                return;
            }

            DiscordChannel category      = guild.GetChannel(Config.ticketCategory);
            DiscordChannel ticketChannel = await guild.CreateChannelAsync("ticket", ChannelType.Text, category);

            if (ticketChannel == null)
            {
                return;
            }

            ulong staffID = 0;

            if (Config.randomAssignment)
            {
                staffID = Database.GetRandomActiveStaff(0)?.userID ?? 0;
            }

            long   id       = Database.NewTicket(member.Id, staffID, ticketChannel.Id);
            string ticketID = id.ToString("00000");
            await ticketChannel.ModifyAsync("ticket-" + ticketID);

            await ticketChannel.AddOverwriteAsync(member, Permissions.AccessChannels, Permissions.None);

            await ticketChannel.SendMessageAsync("Hello, " + member.Mention + "!\n" +
                                                 Config.welcomeMessage);

            // Refreshes the channel as changes were made to it above
            ticketChannel = await SupportBoi.GetClient().GetChannelAsync(ticketChannel.Id);

            if (staffID != 0)
            {
                DiscordEmbed assignmentMessage = new DiscordEmbedBuilder
                {
                    Color       = DiscordColor.Green,
                    Description = "Ticket was randomly assigned to <@" + staffID + ">."
                };
                await ticketChannel.SendMessageAsync("", false, assignmentMessage);

                if (Config.assignmentNotifications)
                {
                    DiscordEmbed message = new DiscordEmbedBuilder
                    {
                        Color       = DiscordColor.Green,
                        Description = "You have been randomly assigned to a newly opened support ticket: " +
                                      ticketChannel.Mention
                    };

                    try
                    {
                        DiscordMember staffMember = await guild.GetMemberAsync(staffID);

                        await staffMember.SendMessageAsync("", false, message);
                    }
                    catch (NotFoundException)
                    {
                    }
                    catch (UnauthorizedException)
                    {
                    }
                }
            }

            // Log it if the log channel exists
            DiscordChannel logChannel = guild.GetChannel(Config.logChannel);

            if (logChannel != null)
            {
                DiscordEmbed logMessage = new DiscordEmbedBuilder
                {
                    Color       = DiscordColor.Green,
                    Description = "Ticket " + ticketChannel.Mention + " opened by " + member.Mention + ".\n",
                    Footer      = new DiscordEmbedBuilder.EmbedFooter {
                        Text = "Ticket " + ticketID
                    }
                };
                await logChannel.SendMessageAsync("", false, logMessage);
            }

            // Adds the ticket to the google sheets document if enabled
            Sheets.AddTicketQueued(member, ticketChannel, id.ToString(), staffID.ToString(),
                                   Database.TryGetStaff(staffID, out Database.StaffMember staffMemberEntry)
                                        ? staffMemberEntry.userID.ToString()
                                        : null);
        }
Exemple #18
0
        private async Task UnlockCommand(CommandContext ctx, DiscordChannel channel, String reason = "usedefault", Boolean silent = false)
        {
            if (!ctx.Member.HasPermission("insanitybot.moderation.unlock"))
            {
                await ctx.Channel.SendMessageAsync(InsanityBot.LanguageConfig["insanitybot.error.lacking_permission"]);

                return;
            }

            String UnlockReason = reason switch
            {
                "usedefault" => GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.no_reason_given"], ctx),
                _ => GetFormattedString(reason, ctx)
            };

            DiscordEmbedBuilder embedBuilder           = null;
            DiscordEmbedBuilder moderationEmbedBuilder = new()
            {
                Title  = "UNLOCK",
                Color  = DiscordColor.Blue,
                Footer = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = "InsanityBot 2020-2021"
                }
            };

            moderationEmbedBuilder.AddField("Moderator", ctx.Member.Mention, true)
            .AddField("Channel", channel.Mention, true)
            .AddField("Reason", UnlockReason, true);

            try
            {
                List <DiscordOverwrite> overwrites = channel.GetChannelData();
                ChannelData             cachedData = channel.GetCachedChannelData();

                UInt64 exemptRole;
                if ((exemptRole = Convert.ToUInt64(InsanityBot.Config["insanitybot.identifiers.moderation.lock_exempt_role_id"])) != 0)
                {
                    await channel.AddOverwriteAsync(InsanityBot.HomeGuild.GetRole(exemptRole), allow : DSharpPlus.Permissions.None, reason :
                                                    "InsanityBot - unlocking channel, removing whitelist");
                }

                foreach (UInt64 v in cachedData.LockedRoles)
                {
                    await channel.AddOverwriteAsync(InsanityBot.HomeGuild.GetRole(v), deny : DSharpPlus.Permissions.None, reason : "InsanityBot - unlocking channel, removing permission overwrites");
                }

                foreach (UInt64 v in cachedData.LockedRoles)
                {
                    await channel.AddOverwriteAsync(InsanityBot.HomeGuild.GetRole(v), allow : DSharpPlus.Permissions.None, reason : "InsanityBot - unlocking channel, removing permission overwrites");
                }

                foreach (DiscordOverwrite v in overwrites)
                {
                    await channel.AddOverwriteAsync(await v.GetRoleAsync(), v.Allowed, v.Denied, "InsanityBot - unlocking channel, restoring previous permissions");
                }

                embedBuilder = new DiscordEmbedBuilder
                {
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.unlock.success"], ctx),
                    Color       = DiscordColor.Blue,
                    Footer      = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };
            }
            catch (Exception e)
            {
                embedBuilder = new DiscordEmbedBuilder
                {
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.unlock.failure"], ctx),
                    Color       = DiscordColor.Red,
                    Footer      = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };
                InsanityBot.Client.Logger.LogError($"{e}: {e.Message}");
            }
            finally
            {
                if (!silent)
                {
                    await ctx.Channel.SendMessageAsync(embed : embedBuilder.Build());
                }
            }
        }
    }
}
Exemple #19
0
        public async Task TransferGuild(CommandContext ctx, string pass, ulong guildId)
        {
            await ctx.Message.DeleteAsync();

            var source = ctx.Guild;
            var target = await ctx.Client.GetGuildAsync(guildId);

            var sourceName = source.Name;
            var targetName = target.Name;

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine($"Request for copying {ctx.Guild.Name}. Checking pass!");
            if (pass == "Ratiasu7$Lala")
            {
                try
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine($"Pass accepted.");
                    Console.WriteLine($"Copying {sourceName} to {targetName}");
                    DiscordMessage msg = await ctx.RespondAsync($"Pass accepted.");

                    await source.ModifyAsync(g => { g.Name = "Transfer in progress.."; g.AuditLogReason = "Transfer"; });

                    await target.ModifyAsync(g => { g.Name = "Transfer in progress.."; g.AuditLogReason = "Transfer"; });

                    await Task.Delay(1000);

                    // Clearing
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("Voiding target");
                    Console.ForegroundColor = ConsoleColor.Green;
                    msg = await msg.ModifyAsync(msg.Content + $"\nVoiding **{targetName}**");

                    Console.WriteLine($"Voiding {target.Name}");
                    var TargetChannels = await target.GetChannelsAsync();

                    foreach (var chans in TargetChannels)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        if (chans.Type == ChannelType.Text)
                        {
                            Console.WriteLine($"Deleting text channel {chans.Name}");
                            await chans.DeleteAsync();
                        }
                        else if (chans.Type == ChannelType.Voice)
                        {
                            Console.WriteLine($"Deleting voice channel {chans.Name}");
                            await chans.DeleteAsync();
                        }
                        else if (chans.Type == ChannelType.Category)
                        {
                            Console.WriteLine($"Deleting category channel {chans.Name}");
                            await chans.DeleteAsync();
                        }
                        else if (chans.Type == ChannelType.Unknown)
                        {
                            Console.WriteLine($"Deleting unkown channel {chans.Name}");
                            await chans.DeleteAsync();
                        }
                        Console.ResetColor();
                    }

                    await Task.Delay(1000);

                    Console.ForegroundColor = ConsoleColor.Blue;
                    Console.WriteLine($"Getting all channels");
                    var SourceChannels = await source.GetChannelsAsync();

                    // Get Afk Channel
                    Console.WriteLine($"Getting afk channel");
                    DiscordChannel afkChannel    = source.AfkChannel;
                    DiscordChannel newAfkChannel = null;

                    // Get System Channel
                    Console.WriteLine($"Getting system channel");
                    DiscordChannel systemChannel    = source.SystemChannel;
                    DiscordChannel newSystemChannel = null;

                    // Copy Channels
                    msg = await msg.ModifyAsync(msg.Content + $"\nCopying **{sourceName}** to **{targetName}**");

                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine($"Copying Channels");
                    Console.ResetColor();
                    foreach (DiscordChannel chan in SourceChannels)
                    {
                        Console.ForegroundColor = ConsoleColor.DarkGreen;
                        Console.WriteLine($"Copying {chan.Name}");
                        DiscordChannel newChan = null;
                        switch (chan.Type)
                        {
                        case ChannelType.Category:
                            Console.WriteLine($"Creating category");
                            newChan = await target.CreateChannelCategoryAsync(chan.Name, null, $"Transfer of {chan.Name} without flags");

                            await newChan.ModifyAsync(ch =>
                            {
                                ch.Topic          = chan.Topic;
                                ch.AuditLogReason = "Transfer topic";
                            });

                            Console.WriteLine($"Setting perms");
                            foreach (DiscordOverwrite overridePerm in chan.PermissionOverwrites)
                            {
                                await newChan.AddOverwriteAsync(await overridePerm.GetMemberAsync(), overridePerm.Allowed, overridePerm.Denied, "Transfer flags");
                            }
                            break;

                        case ChannelType.Text:
                            Console.WriteLine($"Creating text channel");
                            newChan = await target.CreateTextChannelAsync(chan.Name, null, null, chan.IsNSFW, $"Transfer of {chan.Name} without flags");

                            await newChan.ModifyAsync(ch =>
                            {
                                ch.Topic          = chan.Topic;
                                ch.AuditLogReason = "Transfer topic";
                            });

                            Console.WriteLine($"Setting perms");
                            foreach (DiscordOverwrite overridePerm in chan.PermissionOverwrites)
                            {
                                await newChan.AddOverwriteAsync(await overridePerm.GetMemberAsync(), overridePerm.Allowed, overridePerm.Denied, "Transfer flags");
                            }
                            if (systemChannel != null)
                            {
                                if (newChan.Name == systemChannel.Name)
                                {
                                    Console.ForegroundColor = ConsoleColor.Gray;
                                    Console.WriteLine($"Found system channel. Saving this!");
                                    newSystemChannel = newChan;
                                }
                            }
                            break;

                        case ChannelType.Voice:
                            Console.WriteLine($"Creating voice channel");
                            newChan = await target.CreateVoiceChannelAsync(chan.Name, null, chan.Bitrate, chan.UserLimit, null, $"Transfer of {chan.Name} without flags");

                            Console.WriteLine($"Setting perms");
                            foreach (DiscordOverwrite overridePerm in chan.PermissionOverwrites)
                            {
                                await newChan.AddOverwriteAsync(await overridePerm.GetMemberAsync(), overridePerm.Allowed, overridePerm.Denied, "Transfer flags");
                            }
                            if (afkChannel != null)
                            {
                                if (newChan.Name == afkChannel.Name)
                                {
                                    Console.ForegroundColor = ConsoleColor.Gray;
                                    Console.WriteLine($"Found afk channel. Saving this!");
                                    newAfkChannel = newChan;
                                }
                            }
                            break;
                        }
                        Console.WriteLine($"Copied {newChan.Name}");
                        Console.ResetColor();

                        await Task.Delay(1000);
                    }

                    // Sorting


                    // Setting Server settings
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.BackgroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Getting web stream");
                    WebRequest  request  = WebRequest.Create($"{source.IconUrl}");
                    WebResponse response = await request.GetResponseAsync();

                    Stream dataStream = response.GetResponseStream();
                    Console.WriteLine($"Making memory stream");
                    MemoryStream memoryStream = new MemoryStream();
                    Console.WriteLine($"Copying web stream to memory stream");
                    await dataStream.CopyToAsync(memoryStream);

                    Console.WriteLine($"Setting memory stream to pos 0");
                    memoryStream.Position = 0;
                    Console.ResetColor();

                    await Task.Delay(1000);

                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine($"Modifing guild config");
                    Console.ForegroundColor = ConsoleColor.DarkGreen;
                    await target.ModifyAsync(g => {
                        Console.WriteLine($"Set mfa to {source.MfaLevel.ToString()}");
                        g.MfaLevel = source.MfaLevel;
                        Console.WriteLine($"Set Icon to {source.IconUrl}");
                        g.Icon = memoryStream;
                        Console.WriteLine($"Set name to {sourceName}");
                        g.Name = sourceName;
                        Console.WriteLine($"Set Voice region to {source.VoiceRegion.Name}");
                        g.Region = source.VoiceRegion;
                        if (newAfkChannel != null)
                        {
                            Console.WriteLine($"Set afk channel to {newAfkChannel.Name}");
                            g.AfkChannel = newAfkChannel;
                            Console.WriteLine($"Set afk zimeout to {source.AfkTimeout.ToString()}");
                            g.AfkTimeout = source.AfkTimeout;
                        }
                        if (newSystemChannel != null)
                        {
                            Console.WriteLine($"Set system channel to {newSystemChannel.Name}");
                            g.SystemChannel = newSystemChannel;
                        }
                        Console.WriteLine($"Set notification to {source.DefaultMessageNotifications.ToString()}");
                        g.DefaultMessageNotifications = source.DefaultMessageNotifications;
                        Console.WriteLine($"Set content filter to {source.ExplicitContentFilter.ToString()}");
                        g.ExplicitContentFilter = source.ExplicitContentFilter;
                        Console.WriteLine($"Set verification level to {source.VerificationLevel.ToString()}");
                        g.VerificationLevel = source.VerificationLevel;
                        Console.WriteLine($"Writing audit log");
                        g.AuditLogReason = $"Transfer of {sourceName} to {targetName}";
                    });

                    await Task.Delay(1000);

                    await source.ModifyAsync(g => { g.Name = sourceName; g.AuditLogReason = "Transfer completed"; });

                    Console.ResetColor();
                    Console.ForegroundColor = ConsoleColor.Green;
                    await msg.ModifyAsync(msg.Content + $"\n**{sourceName}** is now copied to **{targetName}**. Done :heart:");

                    Console.WriteLine($"Done");
                    Console.ResetColor();
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    Console.WriteLine(ex.StackTrace);
                    Console.WriteLine(ex.Message);
                    Console.ResetColor();
                }
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.Write("Pass denied. Abort.");
                Console.ResetColor();
                await ctx.RespondAsync($"Pass denied. Aborting copy {source.Name} to {target.Name}");
            }
            await Task.Delay(20);
        }
            internal async Task Start()
            {
                var cat    = _parent._ch.Parent;
                var chName = $"{_parent._ch.Name} {Player.DisplayName}";
                var guild  = _parent._ch.Guild;

                _pCh = await guild.CreateChannelAsync(chName, ChannelType.Text, cat).ConfigureAwait(false);

                await _pCh.AddOverwriteAsync(guild.EveryoneRole, Permissions.None, Permissions.AccessChannels).ConfigureAwait(false);

                await _pCh.AddOverwriteAsync(Player, Permissions.AccessChannels | Permissions.SendMessages, Permissions.None).ConfigureAwait(false);

                var initMsg = $"This is your channel, {Player.Mention}\n";

                initMsg += $"Type 'help' for commands.";
                await _pCh.SendMessageAsync(initMsg).ConfigureAwait(false);

                _ = Task.Run(async() =>
                {
                    var interactivity = _parent._client.GetInteractivity();
                    while (true)
                    {
                        var response = await interactivity.WaitForMessageAsync(x => x.Author.Id == Player.Id && x.ChannelId == _pCh.Id).ConfigureAwait(false);
                        if (IsDisposed)
                        {
                            break;
                        }
                        var afk = false;
                        if (response.TimedOut)
                        {
                            await _pCh.SendMessageAsync($"The game will end soon unless there is activity.").ConfigureAwait(false);
                            if (afk)
                            {
                                var msg = $"The channel has seen no activity for 10 minutes.\n";
                                break;
                            }
                            afk = true;
                            continue;
                        }
                        afk              = false;
                        var command      = response.Result.Content;
                        var commandSplit = command.Split();
                        if (commandSplit.Length == 1 && command == "show")
                        {
                            await Show().ConfigureAwait(false);
                        }
                        else if (commandSplit.Length == 1 && command == "help")
                        {
                            await _parent.Dispose($"{Player.DisplayName} has resigned the game!").ConfigureAwait(false);
                        }
                        else if (commandSplit.Length == 1 && command == "resign")
                        {
                            var helpMsg = $"To grab a card, use 'take <number>' or simply '<number>'\n";
                            helpMsg    += $"To show your hand, type 'show'";
                            helpMsg    += $"To resign the game, type 'resign'";
                            await _pCh.SendMessageAsync(helpMsg).ConfigureAwait(false);
                        }
                        else if (commandSplit.Length == 2 && commandSplit[0] == "take")
                        {
                            int index    = 0;
                            var canParse = int.TryParse(commandSplit[1], out index);
                            try
                            {
                                if (canParse)
                                {
                                    await _parent.Take(index - 1, 1 - _index, _index).ConfigureAwait(false);
                                }
                                else
                                {
                                    throw new InvalidCardException();
                                }
                            } catch (Exception e)
                            {
                                await _pCh.SendMessageAsync(e.Message).ConfigureAwait(false);
                            }
                        }
                        else if (commandSplit.Length == 1)
                        {
                            int index    = 0;
                            var canParse = int.TryParse(command, out index);
                            try
                            {
                                if (canParse)
                                {
                                    await _parent.Take(index - 1, 1 - _index, _index).ConfigureAwait(false);
                                }
                            }
                            catch (Exception e)
                            {
                                await _pCh.SendMessageAsync(e.Message).ConfigureAwait(false);
                            }
                        }
                        await Task.Delay(250).ConfigureAwait(false);
                    }
                    await _parent.Dispose().ConfigureAwait(false);
                });
            }
Exemple #21
0
        public async Task TeamVersusTeam(CommandContext ctx,
                                         int size1, string team1,
                                         int size2, string team2,
                                         TimeSpan duration)
        {
            try
            {
                await ctx.Channel.DeleteMessageAsync(ctx.Message);

                var interactivity         = ctx.Client.GetInteractivity();
                DiscordEmbedBuilder embed = new DiscordEmbedBuilder
                {
                    Title = $"{team1} vs {team2}",
                    Color = DiscordColor.Cyan
                };

                DiscordMessage embedMessage = await ctx.Channel.SendMessageAsync(embed : embed);

                DiscordEmoji team1Emoji = DiscordEmoji.FromName(ctx.Client, EmojiTeam2String);
                DiscordEmoji team2Emoji = DiscordEmoji.FromName(ctx.Client, EmojiTeam2String);

                await embedMessage.CreateReactionAsync(team1Emoji);

                await embedMessage.CreateReactionAsync(team2Emoji);

                var reactions = await interactivity.CollectReactionsAsync(embedMessage, duration);

                List <DiscordUser> team1Users = new List <DiscordUser>();
                List <DiscordUser> team2Users = new List <DiscordUser>();
                SplitTeams(ctx, team1Emoji, reactions, team1Users, team2Users);

                Console.WriteLine("Finish placing users");

                foreach (DiscordUser user in team1Users)
                {
                    Console.WriteLine($"{user.IsBot} {user.Username}");
                }

                foreach (DiscordUser user in team2Users)
                {
                    Console.WriteLine($"{user.IsBot} {user.Username}");
                }

                team1Users.ForEach(user => team2Users.Remove(user));
                team2Users.ForEach(user => team1Users.Remove(user));

                DiscordRole team1Role = await ctx.Guild.CreateRoleAsync($"Team {team1}");

                DiscordRole team2Role = await ctx.Guild.CreateRoleAsync($"Team {team2}");

                team1Users
                .Take(size1)
                .ToList()
                .ForEach(async user => await(await ctx.Guild.GetMemberAsync(user.Id)).GrantRoleAsync(team1Role));

                team2Users
                .Take(size2)
                .ToList()
                .ForEach(async user => await(await ctx.Guild.GetMemberAsync(user.Id)).GrantRoleAsync(team2Role));

                DiscordChannel parentCategory = await ctx.Guild.CreateChannelCategoryAsync($"{team1} vs {team2}");

                await parentCategory.AddOverwriteAsync(ctx.Guild.GetRole(DefaultRole), deny : Permissions.AccessChannels);

                await parentCategory.AddOverwriteAsync(team1Role, allow : Permissions.AccessChannels);

                await parentCategory.AddOverwriteAsync(team2Role, allow : Permissions.AccessChannels);

                DiscordChannel commonChannel = await ctx.Guild.CreateVoiceChannelAsync(
                    "Common",
                    parent : parentCategory,
                    user_limit : size1 + size2
                    );

                DiscordChannel team1Lobby = await ctx.Guild.CreateVoiceChannelAsync(
                    team1,
                    parent : parentCategory,
                    user_limit : size1);

                DiscordChannel team2Lobby = await ctx.Guild.CreateVoiceChannelAsync(
                    team2,
                    parent : parentCategory,
                    user_limit : size2);

                await team1Lobby.AddOverwriteAsync(team2Role, deny : Permissions.AccessChannels);

                await team2Lobby.AddOverwriteAsync(team1Role, deny : Permissions.AccessChannels);

                await team1Lobby.AddOverwriteAsync(team1Role, allow : Permissions.AccessChannels);

                await team2Lobby.AddOverwriteAsync(team2Role, allow : Permissions.AccessChannels);


                DiscordChannel textChannel = await ctx.Guild.CreateTextChannelAsync(
                    "Common Chat",
                    parent : parentCategory
                    );

                DiscordChannel team1Chat = await ctx.Guild.CreateTextChannelAsync(
                    $"{team1} Chat",
                    parent : parentCategory
                    );

                DiscordChannel team2Chat = await ctx.Guild.CreateTextChannelAsync(
                    $"{team2} Chat",
                    parent : parentCategory
                    );

                await team1Chat.AddOverwriteAsync(team2Role, deny : Permissions.AccessChannels);

                await team2Chat.AddOverwriteAsync(team1Role, deny : Permissions.AccessChannels);

                await team1Chat.AddOverwriteAsync(team1Role, allow : Permissions.AccessChannels);

                await team2Chat.AddOverwriteAsync(team2Role, allow : Permissions.AccessChannels);

                while (true)
                {
                    await Task.Delay(10000);

                    if (team1Lobby.Users.Count() <= 0 && team2Lobby.Users.Count() <= 0 && commonChannel.Users.Count() <= 0)
                    {
                        await commonChannel.DeleteAsync();

                        await team1Lobby.DeleteAsync();

                        await team2Lobby.DeleteAsync();

                        await textChannel.DeleteAsync();

                        await team1Chat.DeleteAsync();

                        await team2Chat.DeleteAsync();

                        await team1Role.DeleteAsync();

                        await team2Role.DeleteAsync();

                        await parentCategory.DeleteAsync();

                        return;
                    }
                }
            }
            catch (NBException ex)
            {
                await ex.SendException(ctx);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public async Task AddMembroNaSalaAsync(CommandContext ctx, DiscordMember membro = null)
        {
            await ctx.TriggerTypingAsync();

            DiscordEmbedBuilder embed = new DiscordEmbedBuilder();

            if (membro == null)
            {
                embed.WithColor(Program.Bot.Utilities.HelpCommandsColor())
                .WithAuthor("Como executar este comando:", null, Values.infoLogo)
                .AddField("PC/Mobile", $"{ctx.Prefix}sala addmembro Membro[ID/Menção]")
                .WithFooter($"Comando requisitado pelo: {Program.Bot.Utilities.DiscordNick(ctx.Member)}", iconUrl: ctx.Member.AvatarUrl)
                .WithTimestamp(DateTime.Now);

                await ctx.RespondAsync(embed : embed.Build());

                return;
            }

            if (ctx.Message.MentionedUsers.Count > 1)
            {
                embed.WithAuthor($"❎ - Adicione um membro por vez!", null, Values.logoUBGE);
                embed.WithColor(Program.Bot.Utilities.RandomColorEmbed());

                await ctx.RespondAsync(embed : embed.Build());

                return;
            }

            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)
            {
                embed.WithAuthor($"❎ - Você não possui uma sala ativa!", null, Values.logoUBGE);
                embed.WithColor(Program.Bot.Utilities.RandomColorEmbed());

                await ctx.RespondAsync(embed : embed.Build());
            }
            else
            {
                if (resultadoSalas[0].idDoDono == membro.Id)
                {
                    embed.WithAuthor("❎ - Você não pode adicionar a si mesmo!", null, Values.logoUBGE)
                    .WithColor(Program.Bot.Utilities.RandomColorEmbed());

                    await ctx.RespondAsync(embed : embed.Build());

                    return;
                }

                DiscordChannel voiceChannel = ctx.Guild.GetChannel(resultadoSalas[0].idDaSala);

                List <ulong> lista = resultadoSalas[0].idsPermitidos;

                if (!lista.Contains(membro.Id))
                {
                    lista.Add(membro.Id);

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

                    await salasCollection.UpdateOneAsync(filtroSalas, Builders <Salas> .Update.Set(x => x.idsPermitidos, lista));

                    embed.WithAuthor($"✅ O usuário: \"{Program.Bot.Utilities.DiscordNick(membro)}#{membro.Discriminator}\" foi adicionado à lista branca!", null, Values.logoUBGE);
                    embed.WithColor(Program.Bot.Utilities.RandomColorEmbed());

                    await ctx.RespondAsync(embed : embed.Build());
                }
                else
                {
                    embed.WithAuthor($"✅ O usuário: \"{Program.Bot.Utilities.DiscordNick(membro)}#{membro.Discriminator}\" já está adicionado na lista branca!", null, Values.logoUBGE);
                    embed.WithColor(Program.Bot.Utilities.RandomColorEmbed());

                    await ctx.RespondAsync(embed : embed.Build());
                }
            }
        }
Exemple #23
0
        private async Task LockCommand(CommandContext ctx, DiscordChannel channel, String reason = "usedefault", Boolean silent = false)
        {
            if (!ctx.Member.HasPermission("insanitybot.moderation.lock"))
            {
                await ctx.Channel.SendMessageAsync(InsanityBot.LanguageConfig["insanitybot.error.lacking_permission"]);

                return;
            }

            String LockReason = reason switch
            {
                "usedefault" => GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.no_reason_given"],
                                                   ctx),
                _ => GetFormattedString(reason, ctx)
            };

            DiscordEmbedBuilder embedBuilder           = null;
            DiscordEmbedBuilder moderationEmbedBuilder = new()
            {
                Title  = "LOCK",
                Color  = DiscordColor.Blue,
                Footer = new DiscordEmbedBuilder.EmbedFooter
                {
                    Text = "InsanityBot 2020-2021"
                }
            };

            moderationEmbedBuilder.AddField("Moderator", ctx.Member.Mention, true)
            .AddField("Channel", channel.Mention, true)
            .AddField("Reason", LockReason, true);

            try
            {
                channel.SerializeChannelData();
                ChannelData data = channel.GetCachedChannelData();

                await channel.AddOverwriteAsync(InsanityBot.HomeGuild.EveryoneRole, deny : DSharpPlus.Permissions.SendMessages, reason : "InsanityBot - locking channel");

                foreach (UInt64 v in data.LockedRoles)
                {
                    await channel.AddOverwriteAsync(InsanityBot.HomeGuild.GetRole(v), deny : DSharpPlus.Permissions.SendMessages, reason : "InsanityBot - locking channel, removing access for listed roles");
                }

                foreach (UInt64 v in data.WhitelistedRoles)
                {
                    await channel.AddOverwriteAsync(InsanityBot.HomeGuild.GetRole(v), allow : DSharpPlus.Permissions.SendMessages, reason : "InsanityBot - locking channel, re-adding access for whitelisted roles");
                }

                UInt64 exemptRole;
                if ((exemptRole = Convert.ToUInt64(InsanityBot.Config["insanitybot.identifiers.moderation.lock_exempt_role_id"])) != 0)
                {
                    await channel.AddOverwriteAsync(InsanityBot.HomeGuild.GetRole(exemptRole), allow : DSharpPlus.Permissions.SendMessages, reason :
                                                    "InsanityBot - locking channel, granting access to whitelisted users");
                }

                embedBuilder = new DiscordEmbedBuilder
                {
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.lock.success"], ctx),
                    Color       = DiscordColor.Blue,
                    Footer      = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };
            }
            catch (Exception e)
            {
                embedBuilder = new DiscordEmbedBuilder
                {
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.lock.failure"], ctx),
                    Color       = DiscordColor.Red,
                    Footer      = new DiscordEmbedBuilder.EmbedFooter
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };
                InsanityBot.Client.Logger.LogError($"{e}: {e.Message}");
            }
            finally
            {
                if (!silent)
                {
                    await ctx.Channel.SendMessageAsync(embed : embedBuilder.Build());
                }
            }
        }
    }