Esempio n. 1
0
        internal async Task <List <IMessage> > GetAllChannelMessages(ISocketMessageChannel channel, int limit = 100)
        {
            var msgs     = new List <IMessage>();
            var messages = await channel.GetMessagesAsync().FlattenAsync();

            while (messages.Count() > 0 && msgs.Count() < limit)
            {
                msgs.AddRange(messages);
                messages = await channel.GetMessagesAsync(messages.Last(), Direction.Before).FlattenAsync();
            }

            return(msgs);
        }
Esempio n. 2
0
        public async Task Del(IUser user, int input = 10)
        {
            var User = user ?? Context.Message.Author;
            ISocketMessageChannel channel = Context.Channel as ISocketMessageChannel;
            var messages = await channel.GetMessagesAsync(input + 1).FlattenAsync();

            var messages2 = new List <IUserMessage>();

            foreach (var item in messages)
            {
                messages2.Add(item as IUserMessage);
            }
            var delete = messages2.Where(x => x.Author.Id == User.Id);

            await ReplyAndDeleteAsync("", false, Embed.GetEmbed($"**Delete Summary**", $"I have deleted {input} of {User.Username}'s messages, as requested by {Context.Message.Author}"), new TimeSpan(0, 0, 30));

            foreach (var item in delete)
            {
                try
                {
                    await item.DeleteAsync();
                }
                catch { }
            }

            try { await Context.Message.DeleteAsync(); }
            catch { }
        }
Esempio n. 3
0
        public static async void CleanChannel(ISocketMessageChannel channel)
        {
            string PostTitle = "Crafting Requests Listing";
            var    items     = await channel.GetMessagesAsync().Flatten();

            foreach (var item in items)
            {
                if (item.Author.Username == "Jasper")
                {
                    if (item.Embeds.Count > 0)
                    {
                        var enumerator = item.Embeds.GetEnumerator();
                        enumerator.MoveNext();
                        string title = enumerator.Current.Title;
                        if (title == PostTitle)
                        {
                            continue;
                        }
                    }
                }

                var local = item.CreatedAt.ToLocalTime().AddMinutes(5);
                if (DateTime.Now > local && Program.Requests.Find(r => r.messageId == item.Id) == null)
                {
                    await item.DeleteAsync();
                }
            }
        }
Esempio n. 4
0
 /// <summary>
 /// Saves all the messages in a channel.
 /// This saves about 300-700 messages per second, which means it can take minutes for larger channels.
 /// </summary>
 public async Task SaveAllChannelMessagesAsync(ISocketMessageChannel channel)
 {
     IsSavingMessages             = true;
     _channelMessages[channel.Id] = (await channel.GetMessagesAsync(int.MaxValue).FlattenAsync())
                                    .Where(x => !x.Author.IsBot)
                                    .ToList();
     IsSavingMessages = false;
 }
Esempio n. 5
0
        public async Task <IEnumerable <IMessage> > GetLatestNewsAsync(int count)
        {
            if (_channel == null)
            {
                return(Enumerable.Empty <IMessage>());
            }

            return(await _channel.GetMessagesAsync(count).FlattenAsync());
        }
Esempio n. 6
0
        public static async void DeleteCMD(ISocketMessageChannel channel)
        {
            try
            {
                var items = await channel.GetMessagesAsync(1).Flatten();

                await channel.DeleteMessagesAsync(items);
            }
            catch { }
        }
Esempio n. 7
0
        public async Task ArchiveChannel(ISocketMessageChannel channel, [Remainder] string title)
        {
            var messages = await channel.GetMessagesAsync().Flatten();

            using (ChannelArchive archive = new ChannelArchive(title))
            {
                string voteEmote = _settings.Has("brackeys-emote") ? _settings.Get("brackeys-emote").Split(':').First() : string.Empty;

                foreach (IMessage msg in messages)
                {
                    ArchiveMessage             archiveMessage = new ArchiveEventSubmission(msg, voteEmote);
                    IEnumerable <ArchiveImage> archiveImages  = archiveMessage.GetMessageImages();

                    archive.AddMessage(archiveMessage);
                    foreach (ArchiveImage image in archiveImages)
                    {
                        archive.AddImage(image);
                    }
                }

                archive.CloseArchive();
                string zippedArchive = archive.ZipArchive();

                WeTransferClient wt = new WeTransferClient(BrackeysBot.Configuration["wetransfer-api-key"]);
                // Make sure we are authorized
                await wt.Authorize();

                var fileInfo = new System.IO.FileInfo(zippedArchive);
                // Create Partial File Information so WeTransfer knows how many files
                // you're going to upload, the names of those files and their sizes
                PartialFileInfo[] partialFileInfos = new PartialFileInfo[]
                {
                    new PartialFileInfo
                    {
                        Name = fileInfo.Name,
                        Path = fileInfo.FullName,
                        Size = (int)fileInfo.Length
                    }
                };

                // Create a File Transfer which informs WeTransfer that you're about to upload files
                // The second parameter is the transfer message which will show on the download page
                FileTransferResponse response = await wt.CreateTransfer(partialFileInfos, $"Download the archived channel #{channel.Name}!");

                // Now you can upload the files!
                // The first parameter is the transfer's ID
                await wt.Upload(response.ID, response.Files);

                // Now you need to tell WeTransfer that your files have been uploaded
                FileUploadResult result = await wt.FinalizeUpload(response.ID, response.Files);

                // FileUploadResult contains the url to the download page and the date of the expiry

                StringBuilder reply = new StringBuilder()
                                      .AppendLine($"I archived the channel <#{channel.Id}> for you{(title == channel.Name ? "!" : $", under the name **{title}**!")}")
Esempio n. 8
0
        internal static async Task <EmbedInfo> GetEmbedInfo(ISocketMessageChannel textChannel)
        {
            var messagesList = await textChannel.GetMessagesAsync(1).FlattenAsync();

            var message = messagesList.FirstOrDefault();
            var embed   = message?.Embeds.FirstOrDefault();

            var info = new EmbedInfo(textChannel, embed as Embed, message);

            return(info);
        }
Esempio n. 9
0
 async Task DeleteMessagesAsync(ISocketMessageChannel channel)
 {
     var tmp = channel.GetMessagesAsync().Flatten();
     await tmp.ForEachAsync(async x =>
     {
         var admin = baseService.Guild.Users.FirstOrDefault(y => y.Id == x.Author.Id).GuildPermissions.Administrator;
         if (!admin)
         {
             await x.DeleteAsync();
         }
     });
 }
Esempio n. 10
0
        public async static Task <List <DateTimeOffset> > indexChannel(ISocketMessageChannel channel)
        {
            Console.WriteLine("Starting " + channel.Name + " collection");
            var messages = channel.GetMessagesAsync(int.MaxValue).ToEnumerable().ToList();
            //Console.WriteLine("Got messages for " + channel.Name);
            List <DateTimeOffset> l = new List <DateTimeOffset>();

            foreach (IMessage m in messages)
            {
                l.Add(m.Timestamp);
            }
            return(l);
        }
        private async Task <(IEnumerable <IUserMessage> messages, IUserMessage logMessage)> GetMessagesInChannelAsync(ISocketMessageChannel collectionChannel, ISocketMessageChannel logChannel)
        {
            if (!(collectionChannel is IGuildChannel guildChannel))
            {
                throw new ArgumentException("Collection channel must be a guild channel");
            }

            //We send a message at the start of the process and reuse it to update progress, and display the final results
            var logMessage = await logChannel.SendMessageAsync("", embed : GetProgressEmbed(0, null, guildChannel));

            IMessage offset = null;
            var      ret    = new List <IMessage>();

            IEnumerable <IMessage> lastBatch;

            do
            {
                if (offset != null)
                {
                    lastBatch = await collectionChannel.GetMessagesAsync(offset, Direction.Before).FlattenAsync();
                }
                else
                {
                    lastBatch = await collectionChannel.GetMessagesAsync().FlattenAsync();
                }

                ret.AddRange(lastBatch);
                offset = ret.Last();

                if (ret.Count % 500 == 0)
                {
                    await logMessage.ModifyAsync(prop => prop.Embed = GetProgressEmbed(ret.Count, offset, guildChannel));
                }
            }while (lastBatch.Count() > 0);

            await logMessage.ModifyAsync(prop => prop.Embed = GetProgressEmbed(ret.Count, offset, guildChannel, true));

            return(ret.OfType <IUserMessage>(), logMessage);
        }
Esempio n. 12
0
        private static async Task ArchiveChannel(ISocketMessageChannel channel,
                                                 Func <string, IUserMessage, Task> callback)
        {
            var history  = new StringBuilder();
            var messages = (await channel.GetMessagesAsync(5000).FlattenAsync()).ToList();

            foreach (var message in Enumerable.Reverse(messages))
            {
                history.Append('[').Append(message.Timestamp.ToUniversalTime().ToString("MM/dd/yyyy HH:mm:ss"))
                .Append(" UTC] ");
                history.Append(message.Author.Username.DiscordEscape()).Append('#')
                .Append(message.Author.Discriminator ?? "@" + message.Author.Id);
                history.Append(": ");

                if (message is IUserMessage userMsg)
                {
                    history.Append(userMsg.Resolve());

                    if (userMsg.Reactions.Count > 0)
                    {
                        history.Append(" (").Append(string.Join(", ",
                                                                userMsg.Reactions.Select(r => r.Key.Name + ": " + r.Value.ReactionCount))).Append(')');
                    }
                }

                if (message.Author.IsBot)
                {
                    foreach (var embed in message.Embeds)
                    {
                        history.Append(' ').Append(embed.Author?.Name).Append(' ').Append(embed.Description);
                    }
                }

                foreach (var attachment in message.Attachments)
                {
                    history.Append(" (Attachment: ").Append(attachment.Url).Append(')');
                }

                if (message.EditedTimestamp.HasValue)
                {
                    history.Append(" (Edited: ")
                    .Append(message.EditedTimestamp.Value.ToUniversalTime().ToString("MM/dd/yyyy HH:mm:ss"))
                    .Append(" UTC)");
                }

                history.AppendLine();
            }

            await callback(history.ToString(), (IUserMessage)messages.Last(m => m.Author.IsBot && m.Embeds.Any()));
        }
Esempio n. 13
0
        /// <summary>
        /// Saves the messages that were sent after the previous save.
        /// Please check that <see cref="ChannelHasMessagesSaved(ulong)"/> is true first.
        /// </summary>
        public async Task SaveNewChannelMessagesAsync(ISocketMessageChannel channel)
        {
            var channelMessages    = _channelMessages[channel.Id];
            var latestMessageSaved = channelMessages[0];

            IsSavingMessages = true;
            var newMessages = (await channel.GetMessagesAsync(latestMessageSaved.Id, Direction.After, int.MaxValue).FlattenAsync())
                              .Where(x => !x.Author.IsBot)
                              .Reverse()
                              .ToList();

            IsSavingMessages = false;

            _channelMessages[channel.Id].InsertRange(0, newMessages);
        }
Esempio n. 14
0
        public async Task <string> GenerateChannelSentence(ISocketMessageChannel channel)
        {
            var messages = await channel.GetMessagesAsync(2000, CacheMode.AllowDownload).FlattenAsync();

            List <string> messagesContent = new List <string>();

            foreach (var message in messages)
            {
                messagesContent.Add(message.Content);
            }

            MarkovHelper markov = new MarkovHelper(messagesContent);

            return(markov.GenerateSentence());
        }
Esempio n. 15
0
    public async Task <IEnumerable <IMessage> > Print(ISocketMessageChannel Channel = null)
    {
        if (Channel == null)
        {
            Channel = Context.Channel;
        }
        Puzzle puzzle = Load();

        if (puzzle.IsOver)
        {
            var embed = new EmbedBuilder
            {
                Description = $"*{ MentionUtils.MentionUser(puzzle.PlayerId) }* đã kết thúc trò chơi trong ***{puzzle.MoveCount}*** bước! :partying_face::tada::confetti_ball:",
                Color       = Color.Red
            };
            await DiscordWrapper.SendMessage(Context, embed : embed.Build(), Channel : Channel);
        }
        else
        {
            var embed = new EmbedBuilder
            {
                Description = $"*Người chơi: { MentionUtils.MentionUser(puzzle.PlayerId) }*\nSố bước đã đi: {puzzle.MoveCount}.",
                Color       = Color.Magenta
            };
            await DiscordWrapper.SendMessage(Context, embed : embed.Build(), Channel : Channel);
        }

        string output = "";

        for (var i = 0; i < Puzzle.Size; i++)
        {
            for (var j = 0; j < Puzzle.Size; j++)
            {
                output += $"{puzzle.Board[i, j]} ";
            }
            if (i == 0)
            {
                output += $"{Puzzle.IconFull}\n";
            }
            else
            {
                output += ":black_large_square:\n";
            }
        }
        await Channel.SendMessageAsync(output);

        return(await Channel.GetMessagesAsync(2).FlattenAsync());
    }
        public async Task Clear(byte ilosc, ISocketMessageChannel channel = null)
        {
            if (channel == null)
            {
                channel = Context.Channel;
            }

            IEnumerable <IMessage> messages = await channel.GetMessagesAsync(ilosc).FlattenAsync();

            foreach (IMessage msg in messages)
            {
                await msg.DeleteAsync();

                await Task.Delay(200);
            }
        }
Esempio n. 17
0
        public async Task AddFromChannel()
        {
            SocketCommandContext  last    = CommandHandlingService.LastCommandContext;
            ISocketMessageChannel channel = last.Channel;

            var t = await channel.GetMessagesAsync(1000).Flatten().ToArray();

            foreach (IMessage message in t)
            {
                Program.table.Add(message.Id, message.Author.Username, message.Timestamp.Date, message.Content);
            }

            Program.table.PrintTableNoPadding();
            FileInteraction.ConvertDatabaseToFile(Program.db);
            Program.table.DumpData(25);
        }
Esempio n. 18
0
        private async Task <IUserMessage> RetrieveApplicationMessageAsync(string applicationId)
        {
            ISocketMessageChannel       channel  = GetNotificationChannel();
            IAsyncEnumerable <IMessage> messages = channel.GetMessagesAsync(100).Flatten();
            IUserMessage applicationEmbedMessage = null;

            await messages.ForEachAsync((msg) =>
            {
                var embed = msg.Embeds.FirstOrDefault();
                if (embed != null && embed.Author != null && embed.Author.Value.Url.Contains($"id={applicationId}"))
                {
                    applicationEmbedMessage = msg as IUserMessage;
                }
            });

            return(applicationEmbedMessage);
        }
Esempio n. 19
0
        public static async Task DeleteMessages(ISocketMessageChannel channel, int count) //! Delete N messages in a ISocketMessageChannel
        {
            IAsyncEnumerable <IReadOnlyCollection <IMessage> > messages   = channel.GetMessagesAsync(count + 1);
            IAsyncEnumerator <IReadOnlyCollection <IMessage> > enumerator = messages.GetEnumerator();

            while (await enumerator.MoveNext())
            {
                foreach (IMessage msg in enumerator.Current)
                {
                    if (msg.IsPinned)
                    {
                        continue;
                    }
                    await msg.DeleteAsync();
                }
            }
        }
Esempio n. 20
0
        public static async Task <IMessage> LastMessage(ISocketMessageChannel channel, SocketUser user)
        {
            IEnumerable <IMessage> hismessages = await channel.GetMessagesAsync(20).FlattenAsync();

            var lastmessage = hismessages
                              .Where(u => u.Author.Id == user.Id)
                              .OrderByDescending(m => m.CreatedAt)
                              .Skip(1)
                              .FirstOrDefault(m => !containsEmoji(m));

            if (lastmessage == null)
            {
                return(null);
            }

            return(lastmessage);
        }
Esempio n. 21
0
        public async Task <IMessage> LastUserMessage(ISocketMessageChannel channel, SocketUser user, int messagecount = 20)
        {
            IEnumerable <IMessage> hismessages = await channel.GetMessagesAsync(messagecount).FlattenAsync();

            IMessage lastmessage = hismessages
                                   .Where(u => u.Author.Id == user.Id)
                                   .OrderByDescending(m => m.CreatedAt)
                                   .Skip(1)
                                   .FirstOrDefault();

            if (lastmessage == null)
            {
                return(null);
            }

            return(lastmessage);
        }
Esempio n. 22
0
        public async Task DistributePointsPerRatings(ISocketMessageChannel channel)
        {
            string emoteName = _settings.Get("brackeys-emote").Split(':').First();

            Dictionary <IUser, int> userScoreLookup = new Dictionary <IUser, int>();

            var messages = await channel.GetMessagesAsync().Flatten();

            foreach (IMessage msg in messages)
            {
                var kvp   = (msg as IUserMessage).Reactions.FirstOrDefault(r => r.Key.Name == emoteName);
                int score = kvp.Value.ReactionCount;

                if (userScoreLookup.ContainsKey(msg.Author))
                {
                    if (userScoreLookup[msg.Author] < score)
                    {
                        userScoreLookup[msg.Author] = score;
                    }
                }
                else
                {
                    userScoreLookup.Add(msg.Author, score);
                }
            }

            var sortedPlaces = userScoreLookup.OrderByDescending(k => k.Value).ToArray();

            for (int i = 0; i < sortedPlaces.Length; i++)
            {
                var place = sortedPlaces[i];

                int points = 3;
                if (i < 3)
                {
                    points += (3 - i) * 3;
                }

                _pointTable.AddPoints(place.Key, points);
            }

            await UpdateTopUsersWithRoles(true);
        }
        private async Task OnMessageUpdate(Cacheable <IMessage, ulong> original, SocketMessage edit, ISocketMessageChannel channel)
        {
            if (edit == null)
            {
                return;
            }
            var msg = await original.DownloadAsync() as SocketUserMessage;

            var msg2   = edit as SocketUserMessage;
            int argPos = 0;

            if (msg2.HasStringPrefix(_config["prefix"], ref argPos))
            {
                var messages = await channel.GetMessagesAsync(msg, Direction.After, 2, CacheMode.AllowDownload).FlattenAsync();

                var lastreply = messages.Where(x => x.Author.Id == _discord.CurrentUser.Id).FirstOrDefault();
                await lastreply.DeleteAsync();
                await MessageReceived(edit);
            }
        }
Esempio n. 24
0
        public async Task PurgeAsync([Remainder] string name = "")
        {
            if (!ServerData.HasPermissionLevel(BotUtils.GetGUser(Context), ServerData.PermissionLevel.MODERATOR))
            {
                return;
            }

            ISocketMessageChannel channel = Context.Channel;

            List <IMessage> messages = await channel.GetMessagesAsync(99999, CacheMode.AllowDownload).Flatten().ToList();

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

            for (int i = 0; i < messages.Count; i++)
            {
                // Check if message can be deleted and record it
                if (messages[i].Timestamp.AddDays(14) > DateTimeOffset.Now)
                {
                    messagesToDelete.Add(messages[i]);
                }
                else
                {
                    break; // Cannot get any more messages
                }
            }

            StreamWriter sw = new StreamWriter("Admin/PurgeLog.txt");

            // Delete Messages
            for (int i = messagesToDelete.Count - 1; i >= 0; i--)
            {
                sw.WriteLine($"[{messagesToDelete[i].Timestamp.DateTime.ToLongTimeString()}] {messagesToDelete[i].Author.Username}#{messagesToDelete[i].Author.Discriminator}: {messagesToDelete[i].Content}");
                await messagesToDelete[i].DeleteAsync();
            }

            sw.Close();

            await ServerData.AdminChannel.SendMessageAsync(BotUtils.KamtroText($"{messagesToDelete.Count} messages were deleted in {channel.Name}."));

            await ServerData.AdminChannel.SendFileAsync("Admin/PurgeLog.txt", "");
        }
Esempio n. 25
0
        public async Task Delete25Messages(ISocketMessageChannel chan)
        {
            try
            {
                if (chan == null)
                {
                    var messages = await Context.Channel.GetMessagesAsync(25).FlattenAsync();

                    List <IMessage> toDelete = new List <IMessage>();
                    foreach (var message in messages)
                    {
                        if (message.Author.IsBot)
                        {
                            toDelete.Add(message);
                        }
                    }
                    await(Context.Channel as SocketTextChannel).DeleteMessagesAsync(toDelete);
                }
                else
                {
                    var messages = await chan.GetMessagesAsync(25).FlattenAsync();

                    List <IMessage> toDelete = new List <IMessage>();
                    foreach (var message in messages)
                    {
                        if (message.Author.IsBot)
                        {
                            toDelete.Add(message);
                        }
                    }
                    await(chan as SocketTextChannel).DeleteMessagesAsync(toDelete);
                }
            }
            catch (Exception e)
            {
                await ReplyAsync($"{Context.Guild.GetUser(269643701888745474).Mention} I broke the broom..\n{e.Message}");

                return;
            }
            await ReplyAndDeleteAsync("Sweep, sweep, I cleanded up some of my messages :recycle:");
        }
Esempio n. 26
0
        public async Task DeleteOldBotMessages(ISocketMessageChannel chan, int getOld)
        {
            /*List<IMessage> messages = (List<IMessage>)chan.GetMessagesAsync(getOld);
             * foreach (var m in messages)
             * {
             *  if (m.Author.IsBot) await m.DeleteAsync();
             * }*/

            var messages = await chan.GetMessagesAsync(25).FlattenAsync();

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

            foreach (var message in messages)
            {
                if (message.Author.IsBot)
                {
                    toDelete.Add(message);
                }
            }
            await(chan as SocketTextChannel).DeleteMessagesAsync(toDelete);
        }
Esempio n. 27
0
        public async Task <string> GenerateUserSentence(IUser user, ISocketMessageChannel channel)
        {
            var messages = await channel.GetMessagesAsync(2000, CacheMode.AllowDownload).FlattenAsync();

            var           userMessages        = messages.Where(msg => msg.Author == user);
            List <string> userMessagesContent = new List <string>();

            foreach (var message in userMessages)
            {
                //ignore commands
                if (message.Author == user && !Regex.IsMatch(message.Content, @"\!\w"))
                {
                    //strip emotes
                    userMessagesContent.Add(message.Content);
                }
            }

            MarkovHelper userMarkov = new MarkovHelper(userMessagesContent);

            return(userMarkov.GenerateSentence());
        }
Esempio n. 28
0
        public async Task <IMessage> FindAsync(ISocketMessageChannel Channel)
        {
            var allMessages = Channel.GetMessagesAsync(50)
                              .SelectMany(xs => xs.ToAsyncEnumerable());

            IMessage refMessage = null;
            int      i          = 0;
            await allMessages.ForEachAsync(msg =>
            {
                if (msg.Author.Username.Equals(Author, StringComparison.OrdinalIgnoreCase))
                {
                    if (i == MessageIndex)
                    {
                        refMessage = msg;
                    }
                    i++;
                }
            });

            return(refMessage);
        }
        public async Task <bool> DeleteMesseges(byte quantity, ISocketMessageChannel channel)
        {
            byte min = 1, max = 20 + 1;

            if (Validator.IsInRange(quantity, min, max) == false)
            {
                await channel.SendMessageAsync($"Wrong quantity number, range {min}-{max-1}");

                return(false);
            }

            //command msg
            ++quantity;

            //limit numbers of message
            var messages = await channel.GetMessagesAsync(limit : quantity).FlattenAsync();

            foreach (var msg in messages)
            {
                await msg.DeleteAsync();
            }

            return(true);
        }
Esempio n. 30
0
        private async Task DeleteOldMessages()
        {
            if (_announcementChannel == null)
            {
                return;
            }

            try
            {
                var messages = await _announcementChannel.GetMessagesAsync(1000).Flatten().ToListAsync();

                foreach (var message in messages)
                {
                    if (message.Timestamp < DateTimeOffset.UtcNow.AddHours(-3))
                    {
                        await message.DeleteAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, ex);
            }
        }