public IEnumerable <IUserMessage> GetMessages(IMessageChannel channel, TimeSpan period) { var timestamp = DateTime.UtcNow; ulong lastId = 0; var messages = channel.GetMessagesAsync().Flatten(); var enumerator = messages.GetAsyncEnumerator(); var isEmpty = true; do { while (enumerator.MoveNextAsync().Result) { isEmpty = false; lastId = enumerator.Current.Id; if (enumerator.Current.Timestamp.UtcDateTime < timestamp) { timestamp = enumerator.Current.Timestamp.UtcDateTime; } if (enumerator.Current is IUserMessage userMessage) { yield return(userMessage); } } Console.WriteLine(timestamp); enumerator = channel.GetMessagesAsync(lastId, Direction.Before).Flatten().GetAsyncEnumerator(); } while (!isEmpty && timestamp.Add(period) > DateTime.UtcNow); }
private async Task PurgeUserMessages(SocketUser user, IMessageChannel channel, int limit = -1) { List <IMessage> to_delete = new List <IMessage>(); List <IMessage> messages = new List <IMessage>(await channel.GetMessagesAsync(50).FlattenAsync()); while (messages.Count != 0 && (limit == -1 || to_delete.Count < limit)) { foreach (IMessage message in messages) { if (message.Author.Id == user.Id) { to_delete.Add(message); if (to_delete.Count >= limit) { break; } } } messages = new List <IMessage>(await channel.GetMessagesAsync(messages[messages.Count - 1], Direction.Before, 50).FlattenAsync()); } foreach (IMessage message in to_delete) { await channel.DeleteMessageAsync(message.Id); } }
public static async Task <IMessage[]> DownloadAllMessagesAsync(IMessageChannel channel, int limit = 0) { List <IMessage> messages = new List <IMessage>(); if (channel is null) { return(messages.ToArray()); } IEnumerable <IMessage> next_messages = await channel.GetMessagesAsync().FlattenAsync(); while (next_messages.Count() > 0 && (limit <= 0 || messages.Count() < limit)) { if (next_messages.Count() > 0) { messages.AddRange(next_messages); } if (messages.Count() > 0) { next_messages = await channel.GetMessagesAsync(messages.Last(), Direction.Before).FlattenAsync(); } } messages.Reverse(); if (limit <= 0) { return(messages.ToArray()); } else { return(messages.Take(limit).ToArray()); } }
private static async Task <IAsyncEnumerable <IMessage> > ScrapeChannel([NotNull] IMessageChannel channel, IMessage start = null) { //If start message is not set then get the latest message in the channel now if (start == null) { start = (await channel.GetMessagesAsync(1).FlattenAsync()).SingleOrDefault(); } //If message is still null that means we failed to get a start message (no messages in channel?) if (start == null) { return(new EmptyAsyncEnumerable <IMessage>()); } return(new PagedAsyncEnumerable <IReadOnlyList <IMessage>, IMessage>( async page => { //Add a slight delay between fetching pages so we don't hammer discord too hard await Task.Delay(150); var startMessage = start; if (page != null) { startMessage = page.LastOrDefault(); } if (startMessage == null) { return Array.Empty <IMessage>(); } return (await channel.GetMessagesAsync(startMessage, Direction.Before, 99).FlattenAsync()).OrderByDescending(a => a.CreatedAt).ToArray(); }, page => page.GetEnumerator() )); }
private async Task <RetrieveEntityResult <Task <long> > > CountUserMessagesAsync(IMessageChannel channel, IUser user) { long sum = 0; try { var latestMessage = (await channel.GetMessagesAsync(1).FlattenAsync()).FirstOrDefault(); if (latestMessage is null) { return(RetrieveEntityResult <Task <long> > .FromError("No messages in channel.")); } // We'll explicitly include the latest message, since it'd get ignored otherwise if (latestMessage.Author.Id == user.Id) { sum += 1; } while (true) { var channelMessages = channel.GetMessagesAsync(latestMessage, Direction.Before); var processedBatches = 0; await foreach (var channelMessageBatch in channelMessages) { if (channelMessageBatch.Count == 0) { continue; } foreach (var channelMessage in channelMessageBatch) { latestMessage = channelMessage; if (latestMessage.Author.Id == user.Id) { sum += 1; } } processedBatches += 1; } if (processedBatches == 0) { break; } } } catch (HttpException hex) when(hex.WasCausedByMissingPermission()) { return(RetrieveEntityResult <Task <long> > .FromError("No permissions to read the channel.")); } catch (Exception ex) { return(RetrieveEntityResult <Task <long> > .FromError(ex)); } return(Task.FromResult(sum)); }
public async Task AppendAroundAsync(IMessageChannel channel, ulong messageID, int limit = 50) { limit /= 2; var messages = (await channel.GetMessagesAsync(messageID, Direction.After, limit).FlattenAsync()).ToList(); messages.AddRange(await channel.GetMessagesAsync(messageID, Direction.Before, limit).FlattenAsync()); foreach (var message in messages) { Data.TryAdd(message.Id, message); } }
public async Task <List <IBufferedMessage> > GetLatestMessagesAsync(int limit = 100) { List <IBufferedMessage> result = new List <IBufferedMessage>(); var enumerator = _channel.GetMessagesAsync(limit); await enumerator.ForEachAsync(messages => { foreach (var message in messages) { result.Add(new DiscordMessage(message)); } }); return(result); }
/** * ClearMessages * Clears [num] number of messages from the current text channel. * * @param guild * @param channel * @param num */ public async Task ClearMessagesAsync(IGuild guild, IMessageChannel channel, IUser user, int num) { // Check usage case. if (num == 0) // Check if Delete is 0, int cannot be null. { Log("You need to specify the amount | !clear (amount) | Replace (amount) with anything", (int)E_LogOutput.Reply); return; } // Check permissions. var GuildUser = await guild.GetUserAsync(user.Id); if (!GuildUser.GetPermissions(channel as ITextChannel).ManageMessages) { Log("You do not have enough permissions to manage messages", (int)E_LogOutput.Reply); return; } // Delete. var messages = await channel.GetMessagesAsync((int)num + 1).Flatten(); await channel.DeleteMessagesAsync(messages); // Reply with status. Log($"{user.Username} deleted {num} messages", (int)E_LogOutput.Reply); }
/// <summary> /// Méthode de prise en charge de la commande clear /// </summary> /// <param name="guild"></param> /// <param name="channel"></param> /// <param name="n"></param> /// <returns></returns> public async void ClearMessagesAsync(IGuild guild, IMessageChannel channel, IUser user, int n) { var eb = new EmbedBuilder(); eb.WithTitle("Clear command") .WithDescription("Supprime [n] messages du channel courrant") .AddField("Usage", "!clear [n]") .AddField("Require", "Permission de gestion des messages"); // Vérification des paramètres if (n == 0) { Reply("", eb); return; } // Vérifications des permissions var guildUser = await guild.GetUserAsync(user.Id); if (!guildUser.GetPermissions(channel as ITextChannel).ManageChannel) { Reply($"{user.Mention} Vous n'avez pas les permissions pour la gestion des messages"); Reply("", eb); return; } // Suppression var messages = await channel.GetMessagesAsync(n + 1).FlattenAsync(); await(channel as SocketTextChannel).DeleteMessagesAsync(messages); Reply($"{user.Mention} Suppression des messages ..."); }
public async Task DeleteMessages(IGuildUser user, IMessageChannel channel = null) { System.Collections.Generic.IEnumerable <IMessage> msgs = null; List <IMessage> deleteMsgs = new List <IMessage>(); if (channel == null) { channel = Context.Channel; msgs = await Context.Channel.GetMessagesAsync().Flatten(); } else { msgs = await channel.GetMessagesAsync().Flatten(); } foreach (var msg in msgs) { if (msg.Author == user) { deleteMsgs.Add(msg); } } await channel.DeleteMessagesAsync(deleteMsgs); await new ChangeLog().LogChange($"[{Context.Message.Timestamp}]: {Context.Message.Author.Mention} deleted messages from {user.Nickname} in {MentionUtils.MentionChannel(channel.Id)}.", Context); }
private static async Task ClearChannelAsync(IMessageChannel messageChannel, ulong botId) { await Utility.DeleteMessagesAsync( messageChannel.GetMessagesAsync( ), m => m.Author.Id == botId ); }
private async Task Find(IMessageChannel channel, CommandArguments commandArgs) { string response = "meep"; bool found = false; int count = 0; guid lastMessageId = 0; while (true) { IEnumerable <IMessage> batch = await channel.GetMessagesAsync(lastMessageId + 1, Direction.After, 100, CacheMode.AllowDownload).FlattenAsync(); if (batch == null || !batch.Any()) { break; } lastMessageId = batch.Last().Id; count++; if (batch.FirstOrDefault(m => m?.Content != null && guid.TryParse(this.UserIdRegex.Match(m.Content).Value, out guid id) && guid.TryParse(commandArgs.TrimmedMessage, out guid argId) && id == argId) is IUserMessage message) { found = true; response = $"Found message `{message.Id}` at position `{count}`\n{message.Content}"; break; } } if (!found) { response = $"Not found after {count} messages."; } await commandArgs.SendReplySafe(response); }
private async Task <string> Bump(IMessageChannel channel, guid authorId) { guid lastMessageId = 0; while (true) { IEnumerable <IMessage> batch = await channel.GetMessagesAsync(lastMessageId + 1, Direction.After, 100, CacheMode.AllowDownload).FlattenAsync(); if (batch == null || !batch.Any()) { break; } lastMessageId = batch.Last().Id; IMessage message = batch.FirstOrDefault(m => m.Content != null && guid.TryParse(this.UserIdRegex.Match(m.Content).Value, out guid id) && id == authorId); if (message != null) { TimeSpan diff = DateTime.UtcNow - Utils.GetTimeFromId(message.Id); if (diff < TimeSpan.FromDays(this.BumpDays)) { return($"Gotta wait {Utils.GetDurationString(TimeSpan.FromDays(this.BumpDays) - diff).Replace("for", "another")}"); } await channel.SendMessageAsync(message.Content, embed : message.Embeds.First() as Embed); await message.DeleteAsync(); return("Bump'd!"); } } return("Nothing to bump into..."); }
private static async Task CleanChannel(IMessageChannel channel, TimeSpan limit) { await foreach (var page in channel.GetMessagesAsync()) { foreach (var message in page) { if (message.Id == 835621994753294456) { continue; } if (DateTimeOffset.UtcNow - message.Timestamp <= limit) { continue; } try { await message.DeleteAsync(); Log.Information("Message deleted in channel {ChannelId}", channel.Id); } catch (Exception e) { Log.Error(e, "Failed to delete message from channel {ChannelId} in KeepClean!", channel.Id); } await Task.Delay(1000); } } }
public async Task ArchiveCommand(IMessageChannel Channel, int Amount = 9000) { if (Amount >= 10000) { await ReplyAsync("Amount must by less than 9000!"); return; } var listOfMessages = new List <IMessage>(await Channel.GetMessagesAsync(Amount).Flatten()); List <ArchiveModel> list = new List <ArchiveModel>(listOfMessages.Capacity); foreach (var message in listOfMessages) { list.Add(new ArchiveModel { Author = message.Author.Username, Message = message.Content, Timestamp = message.Timestamp, }); } var jsonSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; var json = JsonConvert.SerializeObject(list, Formatting.Indented, jsonSettings); await(await Context.User.GetOrCreateDMChannelAsync()).SendFileAsync(GenerateStreamFromString(json), $"{Channel.Name}.json"); await ReplyAsync($"{Channel.Name}'s Archive has been sent to your DM."); }
private static async Task <(IUserMessage, IEmbed)> FindAnnouncement(IMessageChannel channel, ulong eventId) { await foreach (var page in channel.GetMessagesAsync()) { foreach (var message in page) { var restMessage = (IUserMessage)message; var embed = restMessage.Embeds.FirstOrDefault(); if (embed?.Footer == null) { continue; } if (embed.Footer?.Text != eventId.ToString()) { continue; } return(restMessage, embed); } } return(null, null); }
public async Task UpdateRaidMessages(SocketGuild guild, IMessageChannel channel, int count = 10) { try { var channelBinding = raidChannelService.TryGetRaidChannelBindingTo(guild.Id, channel.Id); var mayContainScheduledRaids = channelBinding != null && channelBinding.AllowScheduledRaids; var dateTimeFrom = !mayContainScheduledRaids ? DateTime.UtcNow.Date : DateTime.UtcNow.AddDays(-14); var batchMessages = await channel.GetMessagesAsync(count, options : retryOptions) .ToList(); var latestMessages = batchMessages.SelectMany(t => t.Where(m => m.CreatedAt.UtcDateTime > dateTimeFrom)) .ToList(); if (!latestMessages.Any()) { return; } logger.LogInformation($"start updating raid messages for channel '{channel.Name}'"); foreach (var message in latestMessages) { if (message is IUserMessage userMessage) { await FixRaidMessageAfterLoad(guild, userMessage); } } logger.LogInformation($"end updating raid messages for channel '{channel.Name}'"); } catch (Exception ex) { logger.LogError($"Failed to update {guild.Name}/{channel.Name} ({ex.Message})"); } }
private async Task DeleteMessagesInDirectonAsync(IMessageChannel channel, ulong messageReferenceID, int limit, Direction direction, bool isFast) { var messages = await channel.GetMessagesAsync(messageReferenceID, direction, limit).FlattenAsync(); var builder = new EmbedBuilder() .WithColor(0xC75B39) .WithDescription($"Видалення {messages.Count()} повідомлень…"); var notification = await channel.SendMessageAsync(embed : builder.Build()); if (isFast) { try { await((ITextChannel)channel).DeleteMessagesAsync(messages); } catch { } } else { foreach (var msg in messages) { await DeleteMessageAsync(msg); } } await DeleteMessageAsync(notification); }
public async Task <List <Message> > GetChatMessages(string id) { IMessageChannel channel = await GetChannel(id); var messages = await channel.GetMessagesAsync(999999).FlattenAsync(); return(messages.Select(m => ConvertMessage(m)).ToList <Message>()); }
public async Task Clear(ulong id) { await Context.Message.DeleteAsync(); IMessageChannel channel = Context.Channel; List <IMessage> messages = (await channel.GetMessagesAsync(id, Direction.After).Flatten()).ToList(); await channel.DeleteMessagesAsync(messages); await ReplyAsync($"{messages.Count} messages deleted."); }
public async Task <bool> CanBotReadTheChannelAsync(IMessageChannel textChannel) { try { return(await textChannel.GetMessagesAsync(limit : 1).Flatten().AnyAsync()); } catch { return(false); } }
public bool CanBotReadTheChannel(IMessageChannel textChannel) { try { textChannel.GetMessagesAsync(limit: 1).FlattenAsync().Wait(); return(true); } catch { return(false); } }
public async Task ClearMessagesAsync(IGuild guild, IMessageChannel channel, IUser agent, int num) { if (num == 0) { DiscordReply("You need to specify the amount | !clear (amount) | Replace (amount) with any number above 0"); return; } var GuildUser = await guild.GetUserAsync(agent.Id); if (!GuildUser.GetPermissions(channel as ITextChannel).ManageMessages) { return; } var messages = await channel.GetMessagesAsync(num + 1).FlattenAsync(); await(channel as ITextChannel).DeleteMessagesAsync(messages); var ebl = new EmbedBuilder() { Description = $"Cleared {num} messages!", Author = new EmbedAuthorBuilder() { IconUrl = $"{agent.GetAvatarUrl()}", Name = "Messages deleted", }, Fields = { new EmbedFieldBuilder() { Name = "Perpetrator", Value = $"• **Agent:** {agent.Username}#{agent.Discriminator}\n• **Agent ID:** {agent.Id}", IsInline = false }, new EmbedFieldBuilder() { Name = "Source", Value = $"• **Server:** {guild.Name}\n• **Channel:** <#{channel.Id}>", IsInline = false } }, Footer = new EmbedFooterBuilder() { Text = $"{DateTime.Now}", }, }; ebl.WithColor(Color.Blue); await Utils.LogChannel.SendMessageAsync("", false, ebl.Build()); DiscordReply("", ebl); }
private bool LastMsgIsMine(IMessageChannel channel) { var msg = channel.GetMessagesAsync(1); if (msg.ElementAtAsync(0).Result.ToString().Contains("Now playing")) { return(true); } else { return(false); } }
public async Task <bool> CanBotReadTheChannel(IMessageChannel textChannel) { try { await textChannel.GetMessagesAsync(limit : 1).FlattenAsync(); return(true); } catch { return(false); } }
public async Task AppendAroundAsync(IMessageChannel channel, ulong messageID, int limit = 50) { try { var messages = await channel.GetMessagesAsync(messageID, Direction.Around, limit).FlattenAsync(); foreach (var message in messages) { Data.TryAdd(message.Id, message); } } catch (HttpException ex) when(ex.HttpCode == HttpStatusCode.InternalServerError) /* Internal server error can ignore. */ } { }
private static async Task <bool> ShouldSkipReaction(IMessageChannel channel, IMessage message) { var messageTimeSpan = DateTime.UtcNow - message.Timestamp.UtcDateTime; if (messageTimeSpan.TotalHours < MinReactionMessageHours) { return(true); } var messages = await channel.GetMessagesAsync(message, Direction.After, MessagesAfterCurrentLimit + 1).ToArray(); bool shouldSkip = messages.SelectMany(x => x).Count() < MessagesAfterCurrentLimit; return(shouldSkip); }
public static IEnumerable <IMessage> EnumerateMessages(IMessageChannel channel) { ulong lastMessageID = 0; IEnumerable <IMessage> messages; while (true) { try { if (lastMessageID == 0) { messages = channel.GetMessagesAsync().FlattenAsync().Result.OfType <IMessage>(); } else { messages = channel.GetMessagesAsync(lastMessageID, Direction.Before, 100).FlattenAsync().Result.OfType <IMessage>(); } } catch { break; } if (messages.Count() == 0) { break; } foreach (var message in messages) { yield return(message); } lastMessageID = messages.Last().Id; } }
private static async IAsyncEnumerable <IMessage> ScrapeChannel(IMessageChannel channel, IMessage?start = null) { //If start message is not set then get the latest message in the channel now start ??= (await channel.GetMessagesAsync(1).FlattenAsync()).SingleOrDefault(); // Keep loading pages until the start message is null while (start != null) { // Add a slight delay between fetching pages so we don't hammer discord too hard await Task.Delay(150); // Get the next page of messages var page = (await channel.GetMessagesAsync(start, Direction.Before, 99).FlattenAsync()).OrderByDescending(a => a.CreatedAt).ToArray(); // Set the start of the next page to the end of this page start = page.LastOrDefault(); // yield every message in page foreach (var message in page) { yield return(message); } } }
public async Task Clear(int amount) { if (amount < 1) { await ReplyAsync("cant delete less than one message").DeleteAfterSeconds(15); return; } await Context.Message.DeleteAsync(); IMessageChannel channel = Context.Channel; List <IMessage> messages = (await channel.GetMessagesAsync(amount).Flatten()).ToList(); messages.RemoveAll(x => x.Timestamp.Day > 14); await channel.DeleteMessagesAsync(messages); await ReplyAsync($"{messages.Count} messages deleted."); }