コード例 #1
0
ファイル: DiscordBot.cs プロジェクト: codacy-badger/SecondBot
        protected async static Task CleanDiscordChannel(ITextChannel chan, int HistoryHours, bool forceempty)
        {
            DateTimeOffset         Now = new DateTimeOffset(new DateTime());
            IEnumerable <IMessage> messages;
            bool empty = false;

            while (empty == false)
            {
                empty    = true;
                messages = await chan.GetMessagesAsync(50).FlattenAsync();

                List <ulong> deleteMessages = new List <ulong>();
                foreach (IMessage mess in messages)
                {
                    var hours = ((Now.ToUnixTimeSeconds() - mess.Timestamp.ToUnixTimeSeconds()) / 60) / 60;
                    if ((hours > HistoryHours) || (forceempty == true))
                    {
                        empty = false;
                        deleteMessages.Add(mess.Id);
                    }
                }
                if (deleteMessages.Count > 0)
                {
                    await chan.DeleteMessagesAsync(deleteMessages);
                }
            }
        }
コード例 #2
0
        public async Task DeleteMessage(ITextChannel chan, uint count)
        {
            chan = chan as SocketTextChannel;
            var messages = await chan.GetMessagesAsync((int)count).FlattenAsync();

            await chan.DeleteMessagesAsync(messages);
        }
コード例 #3
0
        public async Task Delete(int n)
        {
            ITextChannel           channel  = Context.Channel as ITextChannel;
            IEnumerable <IMessage> messages = channel.GetMessagesAsync(n) as IEnumerable <Discord.IMessage>;

            await channel.DeleteMessagesAsync(messages);
        }
コード例 #4
0
        private async Task DoDeleteMessagesAsync(ITextChannel channel, IGuildChannel guildChannel, IEnumerable <IMessage> messages)
        {
            await channel.DeleteMessagesAsync(messages);

            using (var transaction = await DeletedMessageBatchRepository.BeginCreateTransactionAsync())
            {
                await ChannelService.TrackChannelAsync(guildChannel);

                await DeletedMessageBatchRepository.CreateAsync(new DeletedMessageBatchCreationData()
                {
                    CreatedById = AuthorizationService.CurrentUserId.Value,
                    GuildId     = AuthorizationService.CurrentGuildId.Value,
                    Data        = messages.Select(
                        x => new DeletedMessageCreationData()
                    {
                        AuthorId  = x.Author.Id,
                        ChannelId = x.Channel.Id,
                        Content   = x.Content,
                        GuildId   = AuthorizationService.CurrentGuildId.Value,
                        MessageId = x.Id,
                        Reason    = "Mass-deleted.",
                    }),
                });

                transaction.Commit();
            }
        }
コード例 #5
0
        public async Task <long> PickAsync(ulong gid, ITextChannel ch, ulong uid, string pass)
        {
            long amount;

            ulong[] ids;
            using (var uow = _db.UnitOfWork)
            {
                // this method will sum all plants with that password,
                // remove them, and get messageids of the removed plants
                (amount, ids) = uow.PlantedCurrency.RemoveSumAndGetMessageIdsFor(ch.Id, pass);
                if (amount > 0)
                {
                    // give the picked currency to the user
                    await _cs.AddAsync(uid, "Picked currency", amount, gamble : false);
                }
                uow.Complete();
            }

            try
            {
                // delete all of the plant messages which have just been picked
                var _ = ch.DeleteMessagesAsync(ids);
            }
            catch { }

            // return the amount of currency the user picked
            return(amount);
        }
コード例 #6
0
        public static async Task BulkDeleteAndTrackAsync(this IEnumerable <IMessage> messages, ITextChannel channel, string reason, RequestOptions options = null)
        {
            var ids = messages.Select(x => x.Id);

            foreach (var id in ids)
            {
                LoggingService.MessagesDeletedByBot[id] = reason;
            }
            try
            {
                if (options == null)
                {
                    options = new RequestOptions()
                    {
                        AuditLogReason = reason
                    }
                }
                ;
                await channel.DeleteMessagesAsync(ids, options);
            } catch
            {
                foreach (var id in ids) // atomic
                {
                    LoggingService.MessagesDeletedByBot.Remove(id);
                }
                throw;
            }
        }
コード例 #7
0
ファイル: DeleteMessageTimer.cs プロジェクト: Oxidda/Kamina
        private static async Task DeleteMessage(DeleteMessageTimerArgs deleteArgs, ITextChannel textChannel)
        {
            IMessage message = await textChannel.GetMessageAsync(deleteArgs.MessageId);

            if (message != null)
            {
                await textChannel.DeleteMessagesAsync(new[] { message });
            }
        }
コード例 #8
0
        protected static async Task DeleteAllMessagesAsync(ITextChannel channel)
        {
            try
            {
                var messages = await channel.GetMessagesAsync().FlattenAsync();

                await channel.DeleteMessagesAsync(messages);
            }
            catch (Exception e)
            {
                await channel.SendMessageAsync(embed : Logger.LogException(e));
            }
        }
コード例 #9
0
ファイル: Utility.cs プロジェクト: kvietcong/SharpBot
        private async Task <int> PurgeBase(int limit)
        {
            limit = limit > 10000 ? 10000 : limit;
            ITextChannel           channel  = (ITextChannel)Context.Channel;
            IEnumerable <IMessage> messages = (await channel
                                               .GetMessagesAsync(Context.Message, Direction.Before, limit)
                                               .FlattenAsync())
                                              .Where(message =>
                                                     (DateTimeOffset.UtcNow - message.Timestamp).TotalDays <= 14);
            await channel.DeleteMessagesAsync(messages);

            return(limit - messages.Count());
        }
コード例 #10
0
        internal async Task ClearChannel(ITextChannel c)
        {
            var messages = await c.GetMessagesAsync().FlattenAsync();

            List <IMessage> messagesToDelete = new List <IMessage>();

            foreach (var message in messages)
            {
                if (message.Id != _message.Id && message.Id != _hoursMessage.Id && message.Id != _deathCountMessage.Id)
                {
                    messagesToDelete.Add(message);
                }
            }
            await c.DeleteMessagesAsync(messagesToDelete).ConfigureAwait(false);
        }
コード例 #11
0
        async Task ClearMessages(ulong messageId)
        {
            ITextChannel channel = Context.Channel as ITextChannel;

            var messages = await channel.GetMessagesAsync(messageId, Direction.After).FlattenAsync();

            await channel.DeleteMessagesAsync(messages);

            var m = await ReplyAsync("Messages deleted.");

            Task.Delay(5000).ContinueWith(t =>
            {
                m.DeleteAsync();
                _logging.LogAction($"{Context.User.Username} has removed {messages.Count()} messages from {Context.Channel.Name}");
            });
        }
コード例 #12
0
        /// <summary>
        /// Deletes messages in specified <see cref="ITextChannel"/>
        /// </summary>
        /// <param name="textChannel"><see cref="ITextChannel"/> where messages will be deleted</param>
        /// <param name="messageCount">Amount of messages that will be deleted</param>
        /// <exception cref="NullReferenceException">Thrown when <paramref name="textChannel"/> is <see cref="null"/></exception>
        public static async Task DeleteMessagesAsync(ITextChannel textChannel, int messageCount)
        {
            if (textChannel is null)
            {
                throw new NullReferenceException();
            }

            var messages = await textChannel.GetMessagesAsync(messageCount).FlattenAsync();

            if (messages is null || !messages.Any())
            {
                return;
            }

            await textChannel.DeleteMessagesAsync(messages);
        }
コード例 #13
0
ファイル: ModerationModule.cs プロジェクト: SimplyJpk/UDC-Bot
        public async Task ClearMessages(int count)
        {
            ITextChannel channel = Context.Channel as ITextChannel;

            var messages = await channel.GetMessagesAsync(count + 1).FlattenAsync();

            await channel.DeleteMessagesAsync(messages);

            var m = await ReplyAsync("Messages deleted.");

            Task.Delay(5000).ContinueWith(t =>
            {
                m.DeleteAsync();
                _logging.LogAction($"{Context.User.Username} has removed {count} messages from {Context.Channel.Name}");
            });
        }
コード例 #14
0
        public async Task Deleteasync(string count = null)
        {
            try
            {
                if (count == null)
                {
                    List <IMessage> messageList = await Context.Channel.GetMessagesAsync().Flatten().ToList();

                    int          num     = messageList.Count();
                    ITextChannel channel = Context.Channel as ITextChannel;
                    await channel.DeleteMessagesAsync(messageList);

                    Services.CommandUsed.ClearAdd(num + 1);
                    var message = await ReplyAsync($"Deleted the last {num} messages.");

                    _ = await Task.Delay(TimeSpan.FromSeconds(1)).ContinueWith(_ => message.DeleteAsync());
                }
                else if (int.Parse(count) < 101)
                {
                    List <IMessage> messageList = await Context.Channel.GetMessagesAsync(int.Parse(count)).Flatten().ToList();

                    int          num     = messageList.Count();
                    ITextChannel channel = Context.Channel as ITextChannel;
                    await channel.DeleteMessagesAsync(messageList);

                    Services.CommandUsed.ClearAdd(num + 1);
                    var message = await ReplyAsync($"Deleted the last {num} messages.");

                    _ = await Task.Delay(TimeSpan.FromSeconds(1)).ContinueWith(_ => message.DeleteAsync());
                }
                else
                {
                    await ReplyAsync("Sorry, but 100 is the maximum");
                }
            }
            catch
            {
                await ReplyAsync("Couldn't delete messages: Insufficient role");
            }
        }
コード例 #15
0
        public async Task CleanAsync(string all = null)
        {
            //sends a message acknowledgling the request
            RestUserMessage cleanMessage = await Context.Channel.SendMessageAsync("Cleaning...");

            //gets the last 100 messages. (this is the maximum) <- not really but whatever
            var messages = await Context.Channel.GetMessagesAsync(100).FlattenAsync();

            //creates a list that will contain messages to be cleaned
            List <IMessage> messagesToClean = new List <IMessage>();

            //required ref for hascharprefix() and hasmentionprefix()
            int argPos = 0;

            //loops through all messages collected
            foreach (IMessage message in messages)
            {
                //checks if the message starts with the prefix, or mention, if the message's author is the bot or if the "all" flag was set
                //also ensures the message is younger than 14 days
                //if it passes the checks the message is added to the list
                if (message is IUserMessage userMessage)
                {
                    if ((userMessage.HasCharPrefix('!', ref argPos) || userMessage.HasMentionPrefix(Context.Client.CurrentUser, ref argPos) ||
                         message.Author.Id == cleanMessage.Author.Id || all != null) &&
                        !(message.Timestamp - DateTimeOffset.Now <= new TimeSpan(-14, 0, 0, 0)))
                    {
                        messagesToClean.Add(message);
                    }
                }
            }
            //casts the channel to get DeleteMessagesAsync
            ITextChannel channel = (ITextChannel)Context.Channel;

            //does some funky shit because this method wont accept a list
            await channel.DeleteMessagesAsync(messagesToClean.ToAsyncEnumerable().ToEnumerable());

            //deletes orignal acknowledgement message (should get deleted by the bulk delete)
            //await cleanMessage.DeleteAsync();
        }
コード例 #16
0
ファイル: AdminCmds.cs プロジェクト: Bourne-ID/BluBotCore
        public async Task PurgeMsgAsync(int num)
        {
            if (num > 0 && num < 100) // Limit 100 - Minus 1 for your command to purge.
            {
                try
                {
                    var          messages = Context.Channel.GetCachedMessages(num + 1);
                    ITextChannel chan     = Context.Channel as ITextChannel;
                    await chan.DeleteMessagesAsync(messages);
                    await ReplyAsync($"{Context.User} has purged {messages.Count} messages!");

                    if (messages.Count < num)
                    {
                        await ReplyAsync("`Only cached messages can be removed.`");
                    }
                }
                catch { }
            }
            else
            {
                await ReplyAsync($"Purge 99 messages max. [Cached ONLY].");
            }
        }
コード例 #17
0
        public async Task PurgeCmd(int input)
        {
            if (input > 100)
            {
                await ReplyAsync("You can not delete more than 100 messages at once.");

                return;
            }
            if (input <= 0)
            {
                await ReplyAsync("What? No.");

                return;
            }

            try
            {
                IEnumerable <IMessage> messages = await Context.Channel.GetMessagesAsync(input + 1).FlattenAsync();

                ITextChannel       channel            = (ITextChannel)Context.Channel;
                ChannelPermissions channelPermissions = Context.Guild.CurrentUser.GetPermissions(channel);

                if (channelPermissions.ManageMessages)
                {
                    await channel.DeleteMessagesAsync(messages);
                    await ReplyAsync("", embed : _lib.CreateEmbedWithText("Purge", "Successfully deleted " + (input + 1) + " messages! :ok_hand:"));
                }
                else
                {
                    await ReplyAsync("", embed : _lib.CreateEmbedWithError("Purge Error", "I don't seem to have permissions to delete messages.\nTo Delete messages, i must have the **Manage Messages** permission."));
                }
            } catch (Exception e)
            {
                Embed err = _lib.CreateEmbedWithError("Purge Error", $"**Error**: {e.Message}");
                await ReplyAsync("", embed : err);
            }
        }
コード例 #18
0
        public async Task PruneWhere(ITextChannel channel, int amount, Func <IMessage, bool> predicate)
        {
            channel.ThrowIfNull(nameof(channel));
            if (amount <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(amount));
            }

            if (!_pruningGuilds.Add(channel.GuildId))
            {
                return;
            }

            try
            {
                IMessage[] msgs;
                IMessage   lastMessage = null;
                msgs = (await channel.GetMessagesAsync(50).Flatten()).Where(predicate).Take(amount).ToArray();
                while (amount > 0 && msgs.Any())
                {
                    lastMessage = msgs[msgs.Length - 1];

                    var bulkDeletable   = new List <IMessage>();
                    var singleDeletable = new List <IMessage>();
                    foreach (var x in msgs)
                    {
                        if (DateTime.UtcNow - x.CreatedAt < twoWeeks)
                        {
                            bulkDeletable.Add(x);
                        }
                        else
                        {
                            singleDeletable.Add(x);
                        }
                    }

                    if (bulkDeletable.Count > 0)
                    {
                        await Task.WhenAll(Task.Delay(1000), channel.DeleteMessagesAsync(bulkDeletable)).ConfigureAwait(false);
                    }

                    var i = 0;
                    foreach (var group in singleDeletable.GroupBy(x => ++ i / (singleDeletable.Count / 5)))
                    {
                        await Task.WhenAll(Task.Delay(1000), Task.WhenAll(group.Select(x => x.DeleteAsync()))).ConfigureAwait(false);
                    }

                    //this isn't good, because this still work as if i want to remove only specific user's messages from the last
                    //100 messages, Maybe this needs to be reduced by msgs.Length instead of 100
                    amount -= 50;
                    if (amount > 0)
                    {
                        msgs = (await channel.GetMessagesAsync(lastMessage, Direction.Before, 50).Flatten()).Where(predicate).Take(amount).ToArray();
                    }
                }
            }
            catch
            {
                //ignore
            }
            finally
            {
                _pruningGuilds.TryRemove(channel.GuildId);
            }
        }
コード例 #19
0
        public async Task DeleteOtherChannelMessages
        (
            [Summary("The channel on which the the messages to delete are contained.")]
            ITextChannel textChannel,
            [Summary("The ID of the first message that will be deleted, **inclusive**.")]
            ulong firstMessageID,
            [Summary("The ID of the last message that will be deleted, **inclusive**.")]
            ulong lastMessageID
        )
        {
            var contextChannel = Context.Channel;

            if (firstMessageID == 0 || lastMessageID == 0)
            {
                await contextChannel.SendMessageAsync("The provided message IDs are invalid.");

                return;
            }

            var originalProgressMessage = await contextChannel.SendMessageAsync($"Discovering messages to delete... 0 messages have been found so far.");

            var progressMessageTimestamp = originalProgressMessage.Timestamp;

            var persistentProgressMessage = new PersistentMessage(originalProgressMessage);

            var foundMessages = await textChannel.GetMessageRangeAsync(firstMessageID, lastMessageID, UpdateMessage);

            async Task UpdateMessage(int messages)
            {
                await persistentProgressMessage.SetContentAsync($"Discovering users to delete... {messages} messages have been found so far.");
            }

            // The progress message's timestamp is being used because it was used with Discord's clock
            // Avoiding clock difference issues
            var threshold = progressMessageTimestamp.UtcDateTime - TimeSpan.FromDays(14);

            foundMessages.Dissect(m => m.Timestamp.UtcDateTime < threshold, out var olderMessages, out var newerMessages);

            var newerMessageIDs = newerMessages.Select(m => m.Id).ToArray();

            int  currentlyDeletedMessages = 0;
            bool deletionComplete         = false;

            await persistentProgressMessage.SetContentAsync($"{foundMessages.Count} messages are being deleted...");

            await textChannel.DeleteMessagesAsync(newerMessageIDs);

            currentlyDeletedMessages += newerMessageIDs.Length;
            deletionComplete          = foundMessages.Count == newerMessageIDs.Length;

            if (!deletionComplete)
            {
                var progressMessageUpdatingTask = UpdateProgressMessage();

                foreach (var message in olderMessages)
                {
                    await textChannel.DeleteMessageAsync(message);

                    currentlyDeletedMessages++;
                }

                deletionComplete = true;

                await progressMessageUpdatingTask;

                async Task UpdateProgressMessage()
                {
                    while (!deletionComplete)
                    {
                        var progressMessageContent = $"{foundMessages.Count} messages are being deleted... {currentlyDeletedMessages} messages have been deleted.";

                        await persistentProgressMessage.SetContentAsync(progressMessageContent);

                        await Task.Delay(1000);
                    }
                }
            }

            await persistentProgressMessage.SetContentAsync($"{foundMessages.Count} messages have been deleted.");

            await Task.Delay(5000);

            await persistentProgressMessage.DeleteAsync();
        }
コード例 #20
0
        private async Task <int> IterateAndDeleteChannels(ITextChannel channel, int limit, Func <IMessage, bool> predicate, IUser currentActor, IUser filterUser = null)
        {
            ulong           lastId   = 0;
            int             deleted  = 0;
            List <IMessage> toDelete = new ();
            var             messages = channel.GetMessagesAsync(Math.Min(limit, 100));

            if (await messages.CountAsync() < Math.Min(limit, 100))
            {
                limit = 0;  // ignore while loop since channel will be empty soon
            }
            foreach (IMessage message in await messages.FlattenAsync())
            {
                lastId = message.Id;
                limit--;
                if (filterUser != null && message.Author.Id != filterUser.Id)
                {
                    continue;
                }
                if (predicate(message))
                {
                    deleted++;
                    if (message.CreatedAt.UtcDateTime.AddDays(14) > DateTime.UtcNow)
                    {
                        toDelete.Add(message);
                    }
                    else
                    {
                        await message.DeleteAsync();
                    }
                }
            }
            while (limit > 0)
            {
                if (toDelete.Count >= 2)
                {
                    RequestOptions options = new();
                    options.AuditLogReason = $"Bulkdelete by {currentActor.Username}#{currentActor.Discriminator} ({currentActor.Id}).";

                    await channel.DeleteMessagesAsync(toDelete, options);

                    toDelete.Clear();
                }
                else if (toDelete.Count > 0)
                {
                    await toDelete[0].DeleteAsync();
                    toDelete.Clear();
                }

                messages = channel.GetMessagesAsync(lastId, Direction.Before, Math.Min(limit, 100));
                bool breakAfterDeleteIteration = false;

                if (await messages.CountAsync() == 0)
                {
                    break;
                }
                if (await messages.CountAsync() < Math.Min(limit, 100))
                {
                    breakAfterDeleteIteration = true;
                }
                foreach (IMessage message in await messages.FlattenAsync())
                {
                    lastId = message.Id;
                    limit--;
                    if (filterUser != null && message.Author.Id != filterUser.Id)
                    {
                        continue;
                    }
                    if (predicate(message))
                    {
                        deleted++;
                        if (message.CreatedAt.UtcDateTime.AddDays(14) > DateTime.UtcNow)
                        {
                            toDelete.Add(message);
                        }
                        else
                        {
                            await message.DeleteAsync();
                        }
                    }
                }
                if (breakAfterDeleteIteration)
                {
                    break;
                }
            }
            if (toDelete.Count >= 2)
            {
                RequestOptions options = new();
                options.AuditLogReason = $"Bulkdelete by {currentActor.Username}#{currentActor.Discriminator} ({currentActor.Id}).";

                await channel.DeleteMessagesAsync(toDelete, options);

                toDelete.Clear();
            }
            else if (toDelete.Count > 0)
            {
                await toDelete[0].DeleteAsync();
                toDelete.Clear();
            }
            return(deleted);
        }
コード例 #21
0
 // DeleteMessageAsync / DeleteMessagesAsync
 public static Task DeleteMessagesAsync(this ITextChannel channel, IEnumerable <IMessage> messages, CancellationToken cancellationToken)
 => channel.DeleteMessagesAsync(messages, new RequestOptions {
     CancelToken = cancellationToken
 });
コード例 #22
0
ファイル: Moderation.cs プロジェクト: jpmac26/JackFrost-Bot
        public static async void DeleteMessages(ITextChannel channel, int amount)
        {
            var msgs = await channel.GetMessagesAsync(amount).FlattenAsync();

            await channel.DeleteMessagesAsync(msgs);
        }
コード例 #23
0
        protected async static Task CleanDiscordChannel(ITextChannel chan, int HistoryHours, bool forceempty)
        {
            long nowunix = DateTimeOffset.Now.ToUnixTimeSeconds();
            IEnumerable <IMessage> messages;
            bool empty = false;

            while (empty == false)
            {
                empty    = true;
                messages = await chan.GetMessagesAsync(50).FlattenAsync();

                List <ulong>    deleteMessages     = new List <ulong>();
                List <IMessage> slowDeleteMessages = new List <IMessage>();

                foreach (IMessage mess in messages)
                {
                    long messageunix = mess.Timestamp.ToUnixTimeSeconds();
                    long dif         = nowunix - messageunix;
                    var  hours       = (dif / 60) / 60;
                    bool slowdel     = false;

                    if (hours > (24 * 13))
                    {
                        slowdel = true;
                    }
                    if ((hours > HistoryHours) || (forceempty == true))
                    {
                        empty = false;
                        if (slowdel == false)
                        {
                            deleteMessages.Add(mess.Id);
                        }
                        else
                        {
                            slowDeleteMessages.Add(mess);
                        }
                    }
                }
                if ((deleteMessages.Count > 0) || (slowDeleteMessages.Count > 0))
                {
                    try
                    {
                        if (deleteMessages.Count > 0)
                        {
                            await chan.DeleteMessagesAsync(deleteMessages).ConfigureAwait(true);
                        }
                        if (slowDeleteMessages.Count > 0)
                        {
                            foreach (IMessage slowdelmessage in slowDeleteMessages)
                            {
                                await chan.DeleteMessageAsync(slowdelmessage).ConfigureAwait(true);
                            }
                        }
                    }
                    catch
                    {
                    }
                    empty = false;
                }
            }
        }
コード例 #24
0
        public async Task Purge(string text = " ")
        {
            int             count        = 0;
            string          s            = "s";
            bool            admin        = true;                                                                                                                         //stay true for normal bot purging, change if admin permission is required
            ITextChannel    channel      = Context.Channel as ITextChannel;                                                                                              //Sets a variable up with info on the channel its called from
            ulong           BotID        = Context.Client.CurrentUser.Id;                                                                                                //Gets the ID of the bot
            DateTimeOffset  twoweeks     = Context.Message.Timestamp.AddDays(-14);                                                                                       //time from two weeks ago (Bots can't touch posts older than two weeks apparently)
            int             dumpAmount   = 100;
            List <IMessage> MsgsToDelete = new List <IMessage>();                                                                                                        //Creates a new IMessage List for storing the messages to delete

            if (text.Contains("@all"))
            {
                dumpAmount = 20;
            }
            var dump = await channel.GetMessagesAsync(dumpAmount, CacheMode.AllowDownload, null).FlattenAsync();                                                //Gets the last bunch of messages from the channel (limit 50)

            if (string.IsNullOrWhiteSpace(text))
            {
                foreach (var content in dump)                                                                                                               //for every message in the message dump...
                {
                    if ((content.Author.Id == BotID || content.Content.StartsWith(Config.Load().Prefix)) && content.Timestamp > twoweeks)                   //if the message has the bot's ID or the message starts with the command prefix...
                    {
                        MsgsToDelete.Add(content);                                                                                                          //add it to the IMessage List
                    }
                }
            }
            else if (text.Contains("@users"))
            {
                foreach (var content in dump)                                                                                                               //for every message in the message dump...
                {
                    if (content.Content.StartsWith(Config.Load().Prefix) && content.Timestamp > twoweeks)                                                   //if the message starts with the command prefix...
                    {
                        MsgsToDelete.Add(content);                                                                                                          //add it to the IMessage List
                    }
                }
            }
            else
            {
                admin = Config.Load().IsAdmin(Context.User.Id);                                                                                             //check if they're an admin
                if (!admin)                                                                                                                                 //if not then they can't do this
                {
                    await Context.Message.DeleteAsync();
                    await ReplyAsync($"`Only admins can do this.`");

                    return;
                }

                if (text.Contains("@all"))
                {
                    foreach (var content in dump)                                                                                               //for every message in the message dump...
                    {
                        if (content.Timestamp > twoweeks)                                                                                       //if the message is young enough...
                        {
                            MsgsToDelete.Add(content);                                                                                          //add it to the IMessage List
                        }
                    }
                }
                else
                {
                    foreach (var content in dump)                                                                                                               //for every message in the message dump...
                    {
                        foreach (var person in Context.Message.MentionedUsers)
                        {
                            if (content.Author.Id == person.Id && content.Timestamp > twoweeks)                                                                         //if the message has the user's ID and is young enough...
                            {
                                MsgsToDelete.Add(content);                                                                                                              //add it to the IMessage List
                            }
                        }
                    }
                }
            }

            if (MsgsToDelete.Count - 1 == 1)
            {
                s = "";
            }                                                                                                                               //This is just for formatting if it only deletes one message
            //It's Count - 1 because we don't count the message that invoked the command
            if (MsgsToDelete.Count - 1 < 1)                                                                                                 //If the list is less or equal to one... (the command call will always be in the list, honestly)
            {
                await channel.DeleteMessagesAsync(MsgsToDelete);

                var message = await ReplyAsync($"`I couldn't find anything to delete within 50 posts.`");

                await Task.Delay(1500);

                await message.DeleteAsync();                                                                                                //Erase that message to keep tidy
            }
            else                                                                                                                            //If the list is bigger than one...
            {
                await channel.DeleteMessagesAsync(MsgsToDelete);

                count = MsgsToDelete.Count - 1;
                var message = await ReplyAsync($"`Deleted {count} message{s}.`");

                await Task.Delay(1500);

                await message.DeleteAsync();                                                                                                //Erase that message to keep tidy
            }
        }
コード例 #25
0
ファイル: BotActions.cs プロジェクト: sephirothx/JigsawBot
        public async Task PurgeChannel(ITextChannel channel)
        {
            var messages = await channel.GetMessagesAsync().FlattenAsync();

            await channel.DeleteMessagesAsync(messages);
        }