예제 #1
0
        public Task SaveChangesAsync()
        {
            Analytics.TrackEvent("ChannelEditViewModel_SaveChanges");

            if (IsText)
            {
                return(_channel.ModifyAsync(m =>
                {
                    m.Name = Name;
                    m.Topic = Topic;
                    m.Nsfw = NSFW;
                }));
            }
            if (IsVoice)
            {
                return(_channel.ModifyAsync(m =>
                {
                    m.Name = Name;
                    m.Userlimit = (int)Userlimit;
                    m.Bitrate = (int)Bitrate * 1000;
                }));
            }

            return(Task.CompletedTask);
        }
예제 #2
0
        public async Task ModifyAsync(CommandContext ctx,
                                      [Description("Voice channel to edit")] DiscordChannel channel,
                                      [Description("User limit.")] int limit = 0,
                                      [Description("Bitrate.")] int bitrate  = 0,
                                      [RemainingText, Description("Reason.")] string reason = null)
        {
            if (channel.Type != ChannelType.Voice)
            {
                throw new InvalidCommandUsageException("You can only modify voice channels!");
            }

            if (limit == 0 && bitrate == 0)
            {
                throw new InvalidCommandUsageException("You need to specify atleast one change for either bitrate or user limit.");
            }

            await channel.ModifyAsync(new Action <ChannelEditModel>(m =>
            {
                if (limit > 0)
                {
                    m.Userlimit = limit;
                }
                if (bitrate > 0)
                {
                    m.Bitrate = bitrate;
                }
                m.AuditLogReason = ctx.BuildInvocationDetailsString(reason);
            })).ConfigureAwait(false);

            await this.InformAsync(ctx, $"Successfully modified voice channel {Formatter.Bold(channel.Name)}:\n\nUser limit: {(limit > 0 ? limit.ToString() : "Not changed")}\nBitrate: {(bitrate > 0 ? bitrate.ToString() : "Not changed")}", important : false);
        }
예제 #3
0
        public async Task CreateCategoryAsync(CommandContext ctx,
                                              [Description("Channel to clone.")] DiscordChannel channel,
                                              [RemainingText, Description("Name for the cloned channel.")] string name = null)
        {
            DiscordChannel cloned = await channel.CloneAsync(ctx.BuildInvocationDetailsString());

            if (!string.IsNullOrWhiteSpace(name))
            {
                if (name.Length > 100)
                {
                    throw new InvalidCommandUsageException("Channel name must be shorter than 100 characters.");
                }

                if (channel.Type == ChannelType.Text && name.Contains(' '))
                {
                    throw new CommandFailedException("Text channel name cannot contain spaces!");
                }

                if (ctx.Guild.Channels.Values.Any(chn => chn.Name == name.ToLowerInvariant()))
                {
                    if (!await ctx.WaitForBoolReplyAsync("Another channel with that name already exists. Continue?"))
                    {
                        return;
                    }
                }

                await cloned.ModifyAsync(new Action <ChannelEditModel>(m => m.Name = name));
            }

            await this.InformAsync(ctx, $"Successfully created clone of channel {Formatter.Bold(channel.Name)} with name {Formatter.Bold(cloned.Name)}.", important : false);
        }
예제 #4
0
        public async Task SetRatelimitAsync(CommandContext ctx,
                                            [Description("Channel to affect.")] DiscordChannel channel,
                                            [Description("New ratelimit.")] int ratelimit,
                                            [RemainingText, Description("Reason.")] string reason = null)
        {
            if (ratelimit < 0)
            {
                throw new InvalidCommandUsageException("Ratelimit value cannot be negative.");
            }

            if (!_ratelimitValues.Contains(ratelimit))
            {
                throw new InvalidCommandUsageException($"Ratelimit value must be one of the following: {Formatter.InlineCode(string.Join(", ", _ratelimitValues))}");
            }

            channel = channel ?? ctx.Channel;

            await channel.ModifyAsync(new Action <ChannelEditModel>(m =>
            {
                m.PerUserRateLimit = ratelimit;
                m.AuditLogReason = ctx.BuildInvocationDetailsString(reason);
            }));

            await this.InformAsync(ctx, $"Changed the ratemilit setting of channel {Formatter.Bold(channel.Name)} to {Formatter.Bold(ratelimit.ToString())}", important : false);
        }
예제 #5
0
        public async Task RenameAsync(CommandContext ctx,
                                      [Description("Reason.")] string reason,
                                      [Description("Channel to rename.")] DiscordChannel channel,
                                      [RemainingText, Description("New name.")] string newname)
        {
            if (string.IsNullOrWhiteSpace(newname))
            {
                throw new InvalidCommandUsageException("Missing new channel name.");
            }

            if (newname.Length < 2 || newname.Length > 100)
            {
                throw new InvalidCommandUsageException("Channel name must be longer than 2 and shorter than 100 characters.");
            }

            channel = channel ?? ctx.Channel;

            if (channel.Type == ChannelType.Text && newname.Contains(' '))
            {
                throw new InvalidCommandUsageException("Text channel name cannot contain spaces.");
            }

            string name = channel.Name;
            await channel.ModifyAsync(new Action <ChannelEditModel>(m =>
            {
                m.Name = newname;
                m.AuditLogReason = ctx.BuildInvocationDetailsString(reason);
            }));

            await this.InformAsync(ctx, $"Successfully renamed channel {Formatter.Bold(name)} to {Formatter.Bold(channel.Name)}", important : false);
        }
예제 #6
0
        public async Task SetChannelTopicAsync(CommandContext ctx,
                                               [Description("Reason.")] string reason,
                                               [Description("Channel.")] DiscordChannel channel,
                                               [RemainingText, Description("New topic.")] string topic)
        {
            if (string.IsNullOrWhiteSpace(topic))
            {
                throw new InvalidCommandUsageException("Missing topic.");
            }

            if (topic.Length > 1024)
            {
                throw new InvalidCommandUsageException("Topic cannot exceed 1024 characters!");
            }

            channel = channel ?? ctx.Channel;

            await channel.ModifyAsync(new Action <ChannelEditModel>(m =>
            {
                m.Topic = topic;
                m.AuditLogReason = ctx.BuildInvocationDetailsString(reason);
            }));

            await this.InformAsync(ctx, $"Successfully changed the topic for channel {Formatter.Bold(channel.Name)}", important : false);
        }
 private void HandleLeaveVoiceChat(DiscordGuild guild, DiscordChannel channel)
 {
     Task.Run(async() => {
         var guildConfig = this._config.GuildConfigs[guild.Id];
         if (guildConfig.VoiceChannelNames?.ContainsKey(channel.Id) == true)
         {
             await channel.ModifyAsync(model => model.Name = guildConfig.VoiceChannelNames[channel.Id]);
         }
     });
 }
예제 #8
0
 public async Task SaveChangesAsync()
 {
     if (IsText)
     {
         await _channel.ModifyAsync(m =>
         {
             m.Name  = Name;
             m.Topic = Topic;
             m.Nsfw  = NSFW;
         });
     }
     if (IsVoice)
     {
         await _channel.ModifyAsync(m =>
         {
             m.Name      = Name;
             m.Userlimit = (int)Userlimit;
             m.Bitrate   = (int)Bitrate * 1000;
         });
     }
 }
예제 #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;
        }
예제 #10
0
                public async Task UpdateChannelStats(CommandContext ctx, bool force = false)
                {
                    if (!updateNeeded.ContainsKey(ctx.Guild.Id))
                    {
                        ctx.Client.DebugLogger.LogMessage(LogLevel.Debug, ctx.Client.CurrentApplication.Name, $"{ctx.Guild.Name} not found in updateNeeded dictionary creating new instance.", DateTime.Now);
                        updateNeeded.Add(ctx.Guild.Id, true);
                    }

                    if (!updateNeeded[ctx.Guild.Id] && !force)
                    {
                        ctx.Client.DebugLogger.LogMessage(LogLevel.Debug, ctx.Client.CurrentApplication.Name, $"{ctx.Guild.Name} Does not need to update stats.", DateTime.Now);
                        return;
                    }

                    ctx.Client.DebugLogger.LogMessage(LogLevel.Debug, ctx.Client.CurrentApplication.Name, $"{ctx.Guild.Name} needs stats to be updating, updating now...", DateTime.Now);

                    updateNeeded[ctx.Guild.Id] = false;


                    using var context = new RPGContext(_options);

                    var guildPrefs = await _guildPreferences.GetOrCreateGuildPreferences(ctx.Guild.Id);

                    guildPrefs.TotalCommandsExecuted++;
                    context.Update(guildPrefs);
                    await context.SaveChangesAsync();

                    if (guildPrefs.StatChannels.Count == 0)
                    {
                        ctx.Client.DebugLogger.LogMessage(DSharpPlus.LogLevel.Debug, ctx.Client.CurrentApplication.Name, "This guild is not configured to update a stat channel, updating other stats and returning.", DateTime.Now);
                        return;
                    }

                    foreach (var statChannel in guildPrefs.StatChannels)
                    {
                        DiscordChannel channel = null;

                        channel = ctx.Guild.GetChannel(statChannel.ChannelId);

                        if (channel == null)
                        {
                            ctx.Client.DebugLogger.LogMessage(LogLevel.Warning, ctx.Client.CurrentApplication.Name, $"The stat channel for stat option {statChannel.StatOption} in the guild '{ctx.Guild.Name}' no longer exists and the data base entry will be removed.", DateTime.Now);
                            await _statChannelService.DeleteStatChannel(ctx.Guild.Id, statChannel.StatOption);

                            break;
                        }

                        await channel.ModifyAsync(x => x.Name = $"{statChannel.StatMessage}: { GetStat(ctx, statChannel.StatOption) }").ConfigureAwait(false);
                    }
                }
예제 #11
0
        public Task SaveChangesAsync()
        {
            if (IsText)
            {
                return(_channel.ModifyAsync(m =>
                {
                    m.Name = Name;
                    m.Topic = Topic;
                    m.Nsfw = NSFW;
                }));
            }
            if (IsVoice)
            {
                return(_channel.ModifyAsync(m =>
                {
                    m.Name = Name;
                    m.Userlimit = (int)Userlimit;
                    m.Bitrate = (int)Bitrate * 1000;
                }));
            }

            return(Task.CompletedTask);
        }
예제 #12
0
        public async Task SetChannelName(CommandContext ctx,
                                         [Description("Channel to rename")] DiscordChannel channel,
                                         [Description("New channel name")][RemainingText] string name)
        {
            if (!BotServices.CheckChannelName(name))
            {
                await BotServices.SendEmbedAsync(ctx, Resources.ERR_CHANNEL_NAME, EmbedType.Warning).ConfigureAwait(false);
            }
            else
            {
                var old_name = channel.Name;
                await channel.ModifyAsync(new Action <ChannelEditModel>(m => m.Name = name.Trim().Replace(" ", "-"))).ConfigureAwait(false);

                await BotServices.SendEmbedAsync(ctx, $"Successfully renamed the channel " + Formatter.Bold(old_name) + " to " + Formatter.Bold(name), EmbedType.Good).ConfigureAwait(false);
            }
        }
예제 #13
0
        public async Task ChangeParentAsync(CommandContext ctx,
                                            [Description("Child channel.")] DiscordChannel channel,
                                            [Description("Parent category.")] DiscordChannel parent,
                                            [RemainingText, Description("Reason.")] string reason = null)
        {
            if (parent.Type != ChannelType.Category)
            {
                throw new CommandFailedException("Parent must be a category.");
            }

            channel = channel ?? ctx.Channel;

            await channel.ModifyAsync(new Action <ChannelEditModel>(m => {
                m.Parent = parent;
                m.AuditLogReason = ctx.BuildInvocationDetailsString(reason);
            }));

            await this.InformAsync(ctx, $"Successfully set the parent of channel {Formatter.Bold(channel.Name)} to {Formatter.Bold(parent.Name)}", important : false);
        }
예제 #14
0
        public async Task SetChannelName(CommandContext ctx,
                                         [Description("Channel to rename.")] DiscordChannel channel,
                                         [Description("New channel name.")][RemainingText]
                                         string name)
        {
            if (!BotServices.CheckChannelName(name))
            {
                await BotServices.SendResponseAsync(ctx, Resources.ERR_CHANNEL_NAME, ResponseType.Warning)
                .ConfigureAwait(false);

                return;
            }

            var oldName = channel.Name;
            await channel.ModifyAsync(m => m.Name = name.Trim().Replace(" ", "-")).ConfigureAwait(false);

            await ctx.RespondAsync("Successfully renamed the channel " + Formatter.Bold(oldName) + " to " +
                                   Formatter.Bold(name)).ConfigureAwait(false);
        }
예제 #15
0
        public async Task ChangeNsfwAsync(CommandContext ctx,
                                          [Description("Set NSFW?")] bool nsfw,
                                          [Description("Channel.")] DiscordChannel channel      = null,
                                          [RemainingText, Description("Reason.")] string reason = null)
        {
            channel = channel ?? ctx.Channel;

            if (channel.Type != ChannelType.Text)
            {
                throw new CommandFailedException("Only text channels can be flagged as NSFW.");
            }

            await channel.ModifyAsync(new Action <ChannelEditModel>(m => {
                m.Nsfw = nsfw;
                m.AuditLogReason = ctx.BuildInvocationDetailsString(reason);
            }));

            await this.InformAsync(ctx, $"Successfully set the NSFW var of channel {Formatter.Bold(channel.Name)} to {Formatter.Bold(nsfw.ToString())}", important : false);
        }
예제 #16
0
        public static async void SetTopic(string topic)
        {
            DiscordChannel chan = await Program._client.GetChannelAsync(channelID);

            if (UpdateBot == false)
            {
                try
                {
                    await chan.ModifyAsync(chan.Name, chan.Position, topic, chan.Parent);
                }
                catch
                {
                    Console.WriteLine("Exception: Failed to set topic (Permission?)");
                }
            }
            else
            {
                Console.WriteLine("Bot Refreshing| Can't set topic");
            }
        }
예제 #17
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);
            }
        }
예제 #18
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);
        }
예제 #19
0
 private async Task UpdateLobbyChannelName(Lobby lobby, DiscordChannel lobbyChannel)
 {
     await lobbyChannel.ModifyAsync(lobby.ChannelName);
 }
예제 #20
0
        public async Task MaxSalaAsync(CommandContext ctx, int maxJoin)
        {
            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)
            {
                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
            {
                DiscordChannel voiceChannel = ctx.Guild.GetChannel(resultadoSalas[0].idDaSala);

                int oldmaxJoin = resultadoSalas[0].limiteDeUsuarios;

                if (oldmaxJoin != maxJoin && maxJoin != 0 && maxJoin < 101)
                {
                    await voiceChannel.ModifyAsync(x => x.Userlimit = maxJoin);

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

                    embed.WithAuthor($"✅ - O número máximo de usuários da sala foi atualizado!", null, Values.logoUBGE);
                    embed.WithDescription($"De: **{oldmaxJoin}**\n" +
                                          $"Para: **{maxJoin}**");
                    embed.WithColor(Program.Bot.Utilities.RandomColorEmbed());

                    await ctx.RespondAsync(embed : embed.Build());
                }
                else if (oldmaxJoin == maxJoin)
                {
                    embed.WithAuthor($"✅ - O número máximo de usuários se manteve em: {oldmaxJoin}.", null, Values.logoUBGE);
                    embed.WithColor(Program.Bot.Utilities.RandomColorEmbed());

                    await ctx.RespondAsync(embed : embed.Build());
                }
                else if (maxJoin == 0)
                {
                    await voiceChannel.ModifyAsync(x => x.Userlimit = maxJoin);

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

                    embed.WithAuthor($"✅ - O limite de usuários foi removido!", null, Values.logoUBGE);
                    embed.WithColor(Program.Bot.Utilities.RandomColorEmbed());

                    await ctx.RespondAsync(embed : embed.Build());
                }
                else if (maxJoin > 100)
                {
                    maxJoin = 0;

                    await voiceChannel.ModifyAsync(x => x.Userlimit = maxJoin);

                    UpdateDefinition <Salas> Update = Builders <Salas> .Update.Set(x => x.limiteDeUsuarios, maxJoin);

                    await salasCollection.UpdateOneAsync(filtroSalas, Update);

                    embed.WithAuthor($"❎ - Você colocou um número maior que 100, então o limite de usuários foi retirado.", null, Values.logoUBGE);
                    embed.WithColor(Program.Bot.Utilities.RandomColorEmbed());

                    await ctx.RespondAsync(embed : embed.Build());
                }
                else if (maxJoin < 0)
                {
                    maxJoin = 0;

                    await voiceChannel.ModifyAsync(x => x.Userlimit = maxJoin);

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

                    embed.WithAuthor($"❎ - Você colocou um número menor que 0, então o limite de usuários foi retirado.", null, Values.logoUBGE);
                    embed.WithColor(Program.Bot.Utilities.RandomColorEmbed());

                    await ctx.RespondAsync(embed : embed.Build());
                }
            }
        }
예제 #21
0
        public async Task NomeSalaAsync(CommandContext ctx, [RemainingText] string nome = null)
        {
            try
            {
                await ctx.TriggerTypingAsync();

                DiscordEmbedBuilder embed = new DiscordEmbedBuilder();

                if (string.IsNullOrWhiteSpace(nome))
                {
                    embed.WithColor(Program.Bot.Utilities.HelpCommandsColor())
                    .WithAuthor("Como executar este comando:", null, Values.logoUBGE)
                    .AddField("PC/Mobile", $"{ctx.Prefix}sala nome Nome[Novo nome da sala]")
                    .WithFooter($"Comando requisitado pelo: {Program.Bot.Utilities.DiscordNick(ctx.Member)}", iconUrl: ctx.Member.AvatarUrl)
                    .WithTimestamp(DateTime.Now);

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

                    return;
                }
                else if (nome.Length > 40 || ctx.Message.MentionedUsers.Count != 0 || ctx.Message.MentionedRoles.Count != 0 ||
                         ctx.Message.MentionedChannels.Count != 0 || ctx.Message.MentionEveryone ||
                         Uri.IsWellFormedUriString(ctx.Message.Content.ToLower(), UriKind.RelativeOrAbsolute) ||
                         ctx.Message.Attachments.Count != 0 || ctx.Message.Content.ToLower().Contains("https") ||
                         ctx.Message.Content.ToLower().Contains("http") || ctx.Message.Content.ToLower().Contains("https:") ||
                         ctx.Message.Content.ToLower().Contains("http:") || ctx.Message.Content.ToLower().Contains("https:/") ||
                         ctx.Message.Content.ToLower().Contains("http:/") || ctx.Message.Content.ToLower().Contains("https://") ||
                         ctx.Message.Content.ToLower().Contains("http://") || ctx.Message.Content.ToLower().Contains(".com"))
                {
                    embed.WithColor(Program.Bot.Utilities.RandomColorEmbed())
                    .WithAuthor("Erro!", null, Values.logoUBGE)
                    .WithDescription($"Regras para a criação de nome de canais de voz:\n" +
                                     $"- O nome do canal deve ter menos de **40** caracteres\n" +
                                     $"- **Não** deve conter **menções** de **membros**\n" +
                                     $"- **Não** deve conter **menções** de **cargos**\n" +
                                     $"- **Não** deve conter **menções** de **canais**\n" +
                                     $"- **Não** deve conter a **menção** do @everyone\n" +
                                     $"- **Não** deve conter **links**")
                    .WithThumbnailUrl(ctx.Member.AvatarUrl)
                    .WithFooter($"Comando requisitado pelo: {Program.Bot.Utilities.DiscordNick(ctx.Member)}", iconUrl: ctx.Member.AvatarUrl)
                    .WithTimestamp(DateTime.Now);

                    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();

                DiscordChannel voiceChannel = null;

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

                    await salasCollection.UpdateOneAsync(filtroSalas, Builders <Salas> .Update.Set(s => s.nomeDaSala, nome));

                    await voiceChannel.ModifyAsync(x => x.Name = nome);

                    embed.WithAuthor($"✅ - Sala renomeada para: \"{nome}\".", 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());
                }
            }
            catch (Exception exception)
            {
                await Program.Bot.Logger.Error(Log.TypeError.Commands, exception);
            }
        }
예제 #22
0
        private async Task ExecuteSlowmodeCommand(CommandContext ctx, DiscordChannel channel, TimeSpan slowmodeTime, Boolean silent)
        {
            if (!ctx.Member.HasPermission("insanitybot.moderation.slowmode"))
            {
                await ctx.Channel.SendMessageAsync(InsanityBot.LanguageConfig["insanitybot.error.lacking_permission"]);

                return;
            }

            if (silent)
            {
                await ctx.Message.DeleteAsync();
            }

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

            moderationEmbedBuilder.AddField("Moderator", ctx.Member.Mention, true)
            .AddField("Channel", channel.Mention, true)
            .AddField("Time", slowmodeTime.ToString(), true);

            try
            {
                await channel.ModifyAsync(xm =>
                {
                    xm.PerUserRateLimit = slowmodeTime.Seconds;
                });

                embedBuilder = new()
                {
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.slowmode.success"],
                                                     ctx).Replace("{TIME}", slowmodeTime.ToString()),
                    Color  = DiscordColor.Blue,
                    Footer = new()
                    {
                        Text = "InsanityBot 2020-2021"
                    }
                };

                _ = InsanityBot.ModlogQueue.QueueMessage(ModlogMessageType.Moderation, new DiscordMessageBuilder
                {
                    Embed = moderationEmbedBuilder
                });
            }
            catch (Exception e)
            {
                embedBuilder = new()
                {
                    Description = GetFormattedString(InsanityBot.LanguageConfig["insanitybot.moderation.slowmode.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(embedBuilder.Build());
                }
            }
        }
예제 #23
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);
        }
예제 #24
0
        private async void DragonGift()
        {
            nextDragonFly = DateTimeOffset.Now.AddHours(botConfig.DragonCooldown);
            while (true)
            {
                if (!IsConnected)
                {
                    continue;
                }
                try
                {
                    if ((nextDragonFly - DateTimeOffset.Now).TotalMinutes < 1)
                    {
                        nextDragonFly = DateTimeOffset.Now.AddHours(botConfig.DragonCooldown);
                        Dictionary <ulong, uint> dragonUsers = default;
                        using (var db = new LiteDatabase($"filename={Bot.botConfig.GuildID}_voiceStat.db; journal=false;"))
                        {
                            var col     = db.GetCollection <UserModel>("Users");
                            var dbUsers = col.Find(x => x.DragonCount > 0);
                            if (dbUsers != null && dbUsers.Any())
                            {
                                var dbDragonUsers = dbUsers.ToArray();
                                dragonUsers = new Dictionary <ulong, uint>(dbDragonUsers.Length);
                                for (int i = 0; i < dbDragonUsers.Length; i++)
                                {
                                    dragonUsers.Add(dbDragonUsers[i].Id, dbDragonUsers[i].DragonCount);
                                }
                            }
                        }
                        var embed = new DiscordEmbedBuilder
                        {
                            Author = new DiscordEmbedBuilder.EmbedAuthor
                            {
                                Name = "🐲 Бесконечный Дракон"
                            },
                            Color = DiscordColor.Blurple
                        };
                        if (dragonUsers.Count == 0)
                        {
                            embed.Description = "Дракон не нашел достойных его подарка";
                            await dragonGiftsChannel.SendMessageAsync(embed : embed);
                        }
                        else
                        {
                            var giftSize = 0;
                            var chance   = random.Next(0, 100);
                            switch (chance)
                            {
                            case var _ when chance < 10:
                                giftSize = 0;
                                break;

                            case var _ when chance < 20:
                                giftSize = random.Next(90, 180);
                                break;

                            case var _ when chance < 50:
                                giftSize = random.Next(50, 90);
                                break;

                            default:
                                giftSize = random.Next(20, 50);
                                break;
                            }
                            if (giftSize == 0)
                            {
                                embed.Description = "Сегодня был сильный туман. Дракон не смог разглядеть поклонителей. Награда на сегодня: 0 🔑";
                            }
                            else
                            {
                                foreach (var dragonUser in dragonUsers)
                                {
                                    await NadekoDbExtension.SetCurrencyValue(dragonUser.Key, giftSize *(int)dragonUser.Value);
                                }
                                embed.Description = $"Дракон наградил {dragonUsers.Count} верных поданных. Каждый получил сегодня: {giftSize} 🔑";
                            }
                            await dragonGiftsChannel.SendMessageAsync(embed : embed);
                        }
                    }
                    var channelName = $"🐲 Дракон через {(nextDragonFly - DateTimeOffset.Now).Hours}:{(nextDragonFly - DateTimeOffset.Now).Minutes}​​";
                    await dragonCategory.ModifyAsync(name : channelName);

                    await Task.Delay(TimeSpan.FromMinutes(1));
                }
                catch (Exception ex)
                {
                    Log.Error(ex.ToString());
                    continue;
                }
            }
        }