Beispiel #1
0
 public static EmbedAuthorBuilder ToBuilder(this EmbedAuthor author)
 => new EmbedAuthorBuilder()
 {
     Name    = author.Name,
     Url     = author.Url,
     IconUrl = author.IconUrl
 };
Beispiel #2
0
        public static async Task FilterBotMessages(SocketUserMessage message,
                                                   SocketCommandContext context,
                                                   SocketGuildChannel channel)
        {
            // A list of channels to monitor
            List <string> channelfilter = new List <string>()
            {
                "github", "circleci", "netlify"
            };

            if (null == channel || !channelfilter.Contains(channel.Name) || message.Embeds.Count <= 0)
            {
                return;
            }

            // A list of bots to monitor
            List <string> botfilter = new List <string>()
            {
                "houndci-bot"
            };

            // check if the sender is a known bot before deleting.
            foreach (Embed e in message.Embeds)
            {
                EmbedAuthor author = (EmbedAuthor)e.Author;
                if (botfilter.Contains(author.ToString()) || author.ToString().EndsWith("[bot]"))
                {
                    await context.Message.DeleteAsync();
                }
            }
        }
Beispiel #3
0
        private Embed ParseEmbed(JToken json)
        {
            // Get basic data
            string         title       = json["title"]?.Value <string>();
            string         description = json["description"]?.Value <string>();
            string         url         = json["url"]?.Value <string>();
            DateTimeOffset?timestamp   = json["timestamp"]?.Value <DateTime>().ToDateTimeOffset();

            // Get color
            Color color = json["color"] != null
                ? Color.FromArgb(json["color"].Value <int>()).ResetAlpha()
                : Color.FromArgb(79, 84, 92); // default color

            // Get author
            EmbedAuthor author = json["author"] != null?ParseEmbedAuthor(json["author"]) : null;

            // Get fields
            EmbedField[] fields = json["fields"].EmptyIfNull().Select(ParseEmbedField).ToArray();

            // Get thumbnail
            EmbedImage thumbnail = json["thumbnail"] != null?ParseEmbedImage(json["thumbnail"]) : null;

            // Get image
            EmbedImage image = json["image"] != null?ParseEmbedImage(json["image"]) : null;

            // Get footer
            EmbedFooter footer = json["footer"] != null?ParseEmbedFooter(json["footer"]) : null;

            return(new Embed(title, url, timestamp, color, author, description, fields, thumbnail, image, footer));
        }
Beispiel #4
0
 public static EmbedAuthorModel ToModel(this EmbedAuthor author)
 => author == null ? null : new EmbedAuthorModel
 {
     Name    = author.Name,
     Url     = author.Url,
     IconUrl = author.IconUrl
 };
Beispiel #5
0
        public static async Task HandleHoundCIMessages(SocketUserMessage message,
                                                       SocketCommandContext context,
                                                       SocketGuildChannel channel)
        {
            if (null == channel || channel.Name != "github" || message.Embeds.Count <= 0)
            {
                return;
            }

            bool purgeHoundBotMsgs = AppSettingsUtil.AppSettingsBool("deleteHoundBotMsgs",
                                                                     false, false);

            if (!purgeHoundBotMsgs)
            {
                return;
            }

            // #github channel contains messages from many different sources.
            // check if the sender is 'houndci-bot' before deleting.
            foreach (Embed e in message.Embeds)
            {
                EmbedAuthor author = (EmbedAuthor)e.Author;
                if (author.ToString() == "houndci-bot")
                {
                    //logger.InfoFormat("Deleting the houndci-bot message: {0} => {1}: {2}",
                    //                   e.Url, e.Title, e.Description);
                    await context.Message.DeleteAsync();
                }
            }
        }
    /// <summary>
    /// Adds meta information about the quote to the embed.
    /// </summary>
    /// <param name="message">The quoted message.</param>
    /// <param name="quotingUser">The quoting user.</param>
    /// <param name="embed">The embed to add the information to.</param>
    private static Embed AddMeta
    (
        IMessage message,
        Snowflake quotingUser,
        Embed embed
    )
    {
        var getUserAvatar = CDN.GetUserAvatarUrl(message.Author);

        var author = new EmbedAuthor($"{message.Author.Username}#{message.Author.Discriminator}")
        {
            IconUrl = getUserAvatar.IsSuccess
                ? getUserAvatar.Entity.ToString()
                : default(Optional <string>)
        };

        return(embed with
        {
            Author = author,
            Footer = new EmbedFooter(GetPostedTimeInfo(message)),
            Colour = Color.FromArgb(95, 186, 125),
            Fields = new[]
            {
                CreateQuoteMarkerField(message, quotingUser)
            }
        });
    }
        private void WriteEmbedAuthor(EmbedAuthor embedAuthor)
        {
            _writer.WriteStartObject("author");

            _writer.WriteString("name", embedAuthor.Name);
            _writer.WriteString("url", embedAuthor.Url);
            _writer.WriteString("iconUrl", embedAuthor.IconUrl);

            _writer.WriteEndObject();
        }
        public Embed BuildEmbed(UpdatesPage pageInfo)
        {
            EmbedAuthor author = new EmbedAuthor()
            {
                Name = pageInfo.Author.Name, Url = pageInfo.Author.Url
            };
            Embed embed = new Embed()
            {
                AuthorName = author.Name, AuthorUrl = author.Url, Title = pageInfo.Title, Url = pageInfo.PageUrl, TimeStamp = pageInfo.UpdateTime
            };

            return(embed);
        }
        /// <summary>
        ///     Constructs a new embed builder using another embed as prototype.
        /// </summary>
        /// <param name="original">Embed to use as prototype.</param>
        public DiscordEmbedBuilder(DiscordEmbed original)
            : this()
        {
            Title       = original.Title;
            Description = original.Description;
            Url         = original.Url?.ToString();
            Color       = original.Color;
            Timestamp   = original.Timestamp;

            if (original.Thumbnail != null)
            {
                Thumbnail = new EmbedThumbnail
                {
                    Url    = original.Thumbnail.Url?.ToString(),
                    Height = original.Thumbnail.Height,
                    Width  = original.Thumbnail.Width
                }
            }
            ;

            if (original.Author != null)
            {
                Author = new EmbedAuthor
                {
                    IconUrl = original.Author.IconUrl?.ToString(),
                    Name    = original.Author.Name,
                    Url     = original.Author.Url?.ToString()
                }
            }
            ;

            if (original.Footer != null)
            {
                Footer = new EmbedFooter
                {
                    IconUrl = original.Footer.IconUrl?.ToString(),
                    Text    = original.Footer.Text
                }
            }
            ;

            if (original.Fields?.Any() == true)
            {
                _fields.AddRange(original.Fields);
            }

            while (_fields.Count > 25)
            {
                _fields.RemoveAt(_fields.Count - 1);
            }
        }
        private async ValueTask WriteEmbedAuthorAsync(EmbedAuthor embedAuthor)
        {
            _writer.WriteStartObject("author");

            _writer.WriteString("name", embedAuthor.Name);
            _writer.WriteString("url", embedAuthor.Url);

            if (!string.IsNullOrWhiteSpace(embedAuthor.IconUrl))
            {
                _writer.WriteString("iconUrl", await Context.ResolveMediaUrlAsync(embedAuthor.IconUrl));
            }

            _writer.WriteEndObject();
            await _writer.FlushAsync();
        }
        internal async Task <string> UpdateSuggestion(GuildSettings gset, ulong id, string status)
        {
            var suggestionChannel = gset.GetChannel(GuildSettings.AssignedChannels.Suggestion);

            if (suggestionChannel == null)
            {
                throw NeitsilliaError.ReplyError("Suggestions are currently deactivated.");
            }
            IUserMessage msg = (IUserMessage)await suggestionChannel.GetMessageAsync(id);

            if (msg == null)
            {
                throw NeitsilliaError.ReplyError("Message not found.");
            }
            else if (msg.Author.Id != Program.clientCopy.CurrentUser.Id)
            {
                throw NeitsilliaError.ReplyError("Message not sent by this bot.");
            }

            IEmbed[] embeds = Enumerable.ToArray(msg.Embeds);
            if (embeds.Length < 1)
            {
                await msg.DeleteAsync();

                throw NeitsilliaError.ReplyError("Message had no embeds and was deleted.");
            }
            EmbedAuthor  a      = (EmbedAuthor)embeds[0].Author;
            string       footer = ((EmbedFooter)embeds[0].Footer).Text;
            EmbedBuilder embed  = DUtils.BuildEmbed(null,
                                                    embeds[0].Description, footer, embeds[0].Color ?? new Color(),
                                                    DUtils.NewField("Reply", status));

            embed.WithAuthor(a.Name, a.IconUrl, a.Url);

            await msg.ModifyAsync(x =>
            {
                x.Embed = embed.Build();
            });

            if (ulong.TryParse(footer, out ulong userId))
            {
                Program.clientCopy.GetUser(userId)?.SendMessageAsync("Your suggestion has a new response.", embed: embed.Build());
            }

            return(msg.GetJumpUrl());
        }
Beispiel #12
0
        public Embed(Model model)
        {
            Url         = model.Url;
            Type        = model.Type;
            Title       = model.Title;
            Description = model.Description;
            Color       = model.Color.Value;
            Timestamp   = model.Timestamp.Value;

            if (model.Provider.IsSpecified)
            {
                Provider = new EmbedProvider(model.Provider.Value);
            }
            if (model.Provider.IsSpecified)
            {
                Provider = new EmbedProvider(model.Provider.Value);
            }
            if (model.Thumbnail.IsSpecified)
            {
                Thumbnail = new EmbedThumbnail(model.Thumbnail.Value);
            }
            if (model.Author.IsSpecified)
            {
                Author = new EmbedAuthor(model.Author.Value);
            }
            if (model.Image.IsSpecified)
            {
                Image = EmbedImage.Create(model.Image.Value);
            }
            if (model.Video.IsSpecified)
            {
                Video = EmbedVideo.Create(model.Video.Value);
            }
            if (model.Footer.IsSpecified)
            {
                Footer = new EmbedFooter(model.Footer.Value);
            }
            if (model.Fields.IsSpecified)
            {
                Fields = model.Fields.Value.Select(EmbedField.Create).ToImmutableArray();
            }
            else
            {
                Fields = ImmutableArray.Create <EmbedField>();
            }
        }
    private async ValueTask WriteEmbedAuthorAsync(
        EmbedAuthor embedAuthor,
        CancellationToken cancellationToken = default)
    {
        _writer.WriteStartObject("author");

        _writer.WriteString("name", embedAuthor.Name);
        _writer.WriteString("url", embedAuthor.Url);

        if (!string.IsNullOrWhiteSpace(embedAuthor.IconUrl))
        {
            _writer.WriteString("iconUrl", await Context.ResolveMediaUrlAsync(embedAuthor.IconProxyUrl ?? embedAuthor.IconUrl, cancellationToken));
        }

        _writer.WriteEndObject();
        await _writer.FlushAsync(cancellationToken);
    }
        private static JSONContainer getAuthor(IEmbed embed)
        {
            EmbedAuthor   author     = embed.Author.Value;
            JSONContainer authorJSON = JSONContainer.NewObject();

            if (!string.IsNullOrEmpty(author.Name))
            {
                authorJSON.TryAddField(NAME, author.Name);
            }
            if (!string.IsNullOrEmpty(author.IconUrl))
            {
                authorJSON.TryAddField(ICON_URL, author.IconUrl);
            }
            if (!string.IsNullOrEmpty(author.Url))
            {
                authorJSON.TryAddField(URL, author.Url);
            }

            return(authorJSON);
        }
Beispiel #15
0
        public static Discord.Embed New(EmbedAuthor author, List<EmbedFieldBuilder> fields, Color color, string title = "", string description = "", string imgURL = "", string thumbnailUrl = "", string footer = "")
        {
            EmbedBuilder embed = new EmbedBuilder();

            embed.WithAuthor(author.Name, author.IconUrl, author.Url);
            embed.WithTitle(title);
            embed.WithDescription(description);
            embed.WithImageUrl(imgURL);
            embed.WithThumbnailUrl(thumbnailUrl);

            foreach (var field in fields)
            {
                embed.AddField(field);
            }

            embed.WithColor(color);
            embed.WithFooter(f => f.Text = footer);
            embed.WithTimestamp(DateTimeOffset.Now);

            return embed.Build();
        }
Beispiel #16
0
        public static void GetJSONFromMessageContentAndEmbed(string messageContent, IEmbed embed, out JSONContainer json)
        {
            json = JSONContainer.NewObject();

            if (messageContent != null)
            {
                json.TryAddField(MESSAGECONTENT, messageContent);
            }

            if (embed != null)
            {
                JSONContainer embedJSON = JSONContainer.NewObject();

                // Insert TITLE, DESCRIPTION, TITLE_URL, TIMESTAMP

                if (!string.IsNullOrEmpty(embed.Title))
                {
                    embedJSON.TryAddField(TITLE, embed.Title);
                }
                if (!string.IsNullOrEmpty(embed.Description))
                {
                    embedJSON.TryAddField(DESCRIPTION, embed.Description);
                }
                if (!string.IsNullOrEmpty(embed.Url))
                {
                    embedJSON.TryAddField(URL, embed.Url);
                }
                if (embed.Timestamp != null)
                {
                    embedJSON.TryAddField(TIMESTAMP, embed.Timestamp?.ToString("u"));
                }

                // Insert AUTHOR

                if (embed.Author != null)
                {
                    EmbedAuthor   author     = embed.Author.Value;
                    JSONContainer authorJSON = JSONContainer.NewObject();

                    if (!string.IsNullOrEmpty(author.Name))
                    {
                        authorJSON.TryAddField(NAME, author.Name);
                    }
                    if (!string.IsNullOrEmpty(author.IconUrl))
                    {
                        authorJSON.TryAddField(ICON_URL, author.IconUrl);
                    }
                    if (!string.IsNullOrEmpty(author.Url))
                    {
                        authorJSON.TryAddField(URL, author.Url);
                    }

                    embedJSON.TryAddField(AUTHOR, authorJSON);
                }

                // Insert THUMBNAIL, IMAGE

                if (embed.Thumbnail != null)
                {
                    if (!string.IsNullOrEmpty(embed.Thumbnail.Value.Url))
                    {
                        JSONContainer thumbnailJSON = JSONContainer.NewObject();
                        thumbnailJSON.TryAddField(URL, embed.Thumbnail.Value.Url);
                        embedJSON.TryAddField(THUMBNAIL, thumbnailJSON);
                    }
                }
                if (embed.Image != null)
                {
                    if (!string.IsNullOrEmpty(embed.Image.Value.Url))
                    {
                        JSONContainer imagJSON = JSONContainer.NewObject();
                        imagJSON.TryAddField(URL, embed.Image.Value.Url);
                        embedJSON.TryAddField(IMAGE, imagJSON);
                    }
                }

                // Insert Color

                if (embed.Color != null)
                {
                    if (embed.Color.Value.RawValue != 0)
                    {
                        embedJSON.TryAddField(COLOR, embed.Color.Value.RawValue);
                    }
                }

                // Insert Footer

                if (embed.Footer != null)
                {
                    EmbedFooter   footer     = embed.Footer.Value;
                    JSONContainer footerJSON = JSONContainer.NewObject();

                    if (!string.IsNullOrEmpty(footer.Text))
                    {
                        footerJSON.TryAddField(TEXT, footer.Text);
                    }
                    if (!string.IsNullOrEmpty(footer.IconUrl))
                    {
                        footerJSON.TryAddField(ICON_URL, footer.IconUrl);
                    }

                    embedJSON.TryAddField(FOOTER, footerJSON);
                }

                // Insert Fields

                if ((embed.Fields != null) && embed.Fields.Length > 0)
                {
                    JSONContainer fieldsJSON = JSONContainer.NewArray();

                    foreach (Discord.EmbedField embedField in embed.Fields)
                    {
                        JSONContainer fieldJSON = JSONContainer.NewObject();
                        fieldJSON.TryAddField(NAME, embedField.Name);
                        fieldJSON.TryAddField(VALUE, embedField.Value);
                        fieldJSON.TryAddField(INLINE, embedField.Inline);
                        fieldsJSON.Add(fieldJSON);
                    }

                    embedJSON.TryAddField(FIELDS, fieldsJSON);
                }

                json.TryAddField(EMBED, embedJSON);
            }
        }
Beispiel #17
0
        private async Task WhoIsPreset(CommandContext context, ulong userId)
        {
            await redis.InitUser(userId);

            var member = await context.Guild.GetMemberAsync(userId);

            var nickname = string.IsNullOrWhiteSpace(member.Nickname) ? string.Empty : $"({member.Nickname})";
            var owners   = context.Client.CurrentApplication.Owners;

            var author = new EmbedAuthor {
                Name = $"{member.GetUsertag()} {nickname}", Icon = member.AvatarUrl
            };

            var description = new StringBuilder();

            if (member.IsOwner)
            {
                description.AppendLine(owners.Any(x => x.Id == member.Id)
                                           ? $"{DiscordEmoji.FromGuildEmote(context.Client, EmojiLibrary.Verified)} {Formatter.InlineCode("Guild and Bot Owner")}"
                                           : $"{DiscordEmoji.FromGuildEmote(context.Client, EmojiLibrary.Verified)} {Formatter.InlineCode("Guild Owner")}");
            }
            else if (owners.Any(x => x.Id == member.Id))
            {
                description.AppendLine($"{DiscordEmoji.FromGuildEmote(context.Client, EmojiLibrary.Verified)} {Formatter.InlineCode("Bot Owner")}");
            }
            else if (member.IsBot)
            {
                description.AppendLine(Formatter.InlineCode("`[BOT]`"));
            }

            var userDays = await member.GetDaysExisting();

            var userSinceDays = userDays == 1 ? $"yesterday" : userDays == 0 ? "today" : $"{Formatter.Bold($"{userDays}")} days";

            var memberDays = await member.GetMemberDays();

            var memberSinceDays = memberDays == 1 ? $"yesterday" : memberDays == 0 ? "today" : $"{Formatter.Bold($"{memberDays}")} days ago";

            description.AppendLine($"Identity: `{member.Id}`")
            .AppendLine($"Registered: {await member.CreatedAtLongDateTimeString()} ({userSinceDays})")
            .AppendLine($"Joined: {await member.JoinedAtLongDateTimeString()} ({memberSinceDays})")
            .AppendLine($"Join Position: #{await JoinPosition(member, context.Guild)}");


            var roles = string.Empty;

            if (member.Roles.Any())
            {
                var rolesOrdered = member.Roles.ToList().OrderByDescending(x => x.Position);
                roles = rolesOrdered.Aggregate(roles, (current, role) => current + $"<@&{role.Id}> ");
            }
            else
            {
                roles = "None";
            }

            var userInfractions = redis.GetAsync <Defcon.Data.Users.User>(RedisKeyNaming.User(userId)).GetAwaiter().GetResult().Infractions;

            var userGuildInfractions = userInfractions.Where(x => x.GuildId == context.Guild.Id)
                                       .ToList();

            var infractions = new StringBuilder().AppendLine($"Warnings: {userGuildInfractions.Count(x => x.InfractionType == InfractionType.Warning)}")
                              .AppendLine($"Mutes: {userGuildInfractions.Count(x => x.InfractionType == InfractionType.Mute)}")
                              .AppendLine($"Kicks: {userGuildInfractions.Count(x => x.InfractionType == InfractionType.Kick)}").ToString();

            var keys = await UserKeyPermissions(member);

            var fields = new List <EmbedField>
            {
                new EmbedField {
                    Inline = true, Name = "Boosting since", Value = await member.PremiumSinceLongDateTimeString()
                },
                new EmbedField {
                    Inline = true, Name = "Server Infractions", Value = infractions
                },
                new EmbedField {
                    Inline = false, Name = "Roles", Value = roles
                }
            };

            if (!string.IsNullOrWhiteSpace(keys[0]))
            {
                fields.Add(new EmbedField()
                {
                    Name   = "Key Permissions",
                    Value  = keys[0],
                    Inline = false
                });
            }

            if (!string.IsNullOrWhiteSpace(keys[1]))
            {
                fields.Add(new EmbedField()
                {
                    Name   = "Acknowledgement",
                    Value  = keys[1],
                    Inline = false
                });
            }

            var embed = new Embed
            {
                Description = description.ToString(),
                Thumbnail   = member.AvatarUrl,
                Author      = author,
                Fields      = fields
            };

            await context.SendEmbedMessageAsync(embed);
        }
Beispiel #18
0
        public async Task Copy(CommandContext ctx,
                               [Description("The source guild ID. (Right click / three-dot menu of guild >> Copy ID)")] ulong guildId,
                               [Description("The source element ID. (Right click / long press channel or category >> Copy ID)")] ulong elementId,
                               [Description("\"True\" if user wishes to keep original channel or category name, \"False\" otherwise")] bool keepName
                               )
        {
            DiscordGuild guild;

            try
            {
                guild = await ctx.Client.GetGuildAsync(guildId);
            }
            catch (DSharpPlus.Exceptions.NotFoundException)
            {
                await ctx.RespondAsync("Guild not found.");

                return;
            }

            if (isMemberDisallowed(ctx.Member) || isMemberDisallowed(await guild.GetMemberAsync(ctx.Member.Id)))
            {
                return;                 // User isn't an administrator or doesn't have the "Archivist" role in any server. Aborting
            }
            DiscordChannel selectedElement;

            try
            {
                selectedElement = guild.GetChannel(elementId);
            }
            catch (DSharpPlus.Exceptions.NotFoundException)
            {
                await ctx.RespondAsync("Channel not found.");

                return;
            }

            string elementName;
            bool   elementIsCategory = selectedElement.Type == ChannelType.Category;
            string elementType       = elementIsCategory ? "category" : "channel";

            if (keepName)               // If user wishes to keep original element name
            {
                elementName = selectedElement.Name;
            }
            else
            {
                await ctx.RespondAsync($"What do you want the new {elementType} to be named?");

                var response = await ctx.Message.GetNextMessageAsync(
                    c => c.Author.Id == ctx.Message.Author.Id,
                    TimeSpan.FromSeconds(60)
                    );

                if (response.TimedOut)
                {
                    await ctx.Channel.SendMessageAsync("No input given. Aborting.");

                    return;
                }

                if (string.IsNullOrEmpty(response.Result.Content))
                {
                    await ctx.Channel.SendMessageAsync("Name cannot be empty.");

                    return;
                }

                elementName = response.Result.Content;
            }

            await ctx.Channel.SendMessageAsync("**Starting copy**");

            string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            Directory.CreateDirectory(tempDirectory);

            DiscordChannel newCategory = null;

            if (elementIsCategory)
            {
                newCategory = await ctx.Guild.CreateChannelAsync(elementName, ChannelType.Category);
            }

            await ctx.Channel.SendMessageAsync("Collecting messages...");

            foreach (var channel in (elementIsCategory ? onlySupported(selectedElement).OrderBy(c => c.Position).ToArray() : new DiscordChannel[] { selectedElement }))
            {
                await ctx.Channel.SendMessageAsync($"Creating channel {channel.Name}...");

                var newChannel = await ctx.Guild.CreateChannelAsync((elementIsCategory ? channel.Name : elementName), channel.Type);

                await newChannel.ModifyAsync(c => c.Topic = channel.Topic);

                if (channel.IsNSFW)
                {
                    await newChannel.ModifyAsync(c => c.Nsfw = true);
                }
                foreach (DiscordOverwrite overwrite in channel.PermissionOverwrites)
                {
                    try
                    {
                        if (overwrite.Type == OverwriteType.Member)
                        {
                            DiscordMember overwriteMember = await overwrite.GetMemberAsync();

                            if (ctx.Guild.Members.Where(r => r.Value.Id == overwriteMember.Id).Count() > 0)
                            {
                                await newChannel.AddOverwriteAsync((await ctx.Guild.GetMemberAsync(overwriteMember.Id)), overwrite.Allowed, overwrite.Denied);
                            }
                        }
                        else
                        {
                            DiscordRole overwriteRole = await overwrite.GetRoleAsync();

                            var matchingRole = ctx.Guild.Roles.Where(r => r.Value.Name == overwriteRole.Name);
                            if (matchingRole.Count() > 0)
                            {
                                await newChannel.AddOverwriteAsync(ctx.Guild.GetRole(matchingRole.First().Value.Id), overwrite.Allowed, overwrite.Denied);
                            }
                        }
                    }
                    catch (DSharpPlus.Exceptions.NotFoundException)
                    {
                    }
                }

                var firstFetchedMessages = await channel.GetMessagesAsync();

                if (firstFetchedMessages.Count == 0)
                {
                    if (elementIsCategory)
                    {
                        await newChannel.ModifyAsync(c => c.Parent = newCategory);
                    }
                    continue;                     // Empty channel - skip
                }

                List <DiscordMessage> bufferedMessagesList = firstFetchedMessages.ToList();

                var more = await channel.GetMessagesBeforeAsync(firstFetchedMessages.Last().Id, 100);

                int messageCount = firstFetchedMessages.Count();

                while (more.Count > 0)
                {
                    messageCount        += more.Count();
                    bufferedMessagesList = more.ToList();
                    more = await channel.GetMessagesBeforeAsync(more.First().Id, 100);                     // "Scrolling" to the first message
                }
                await ctx.Channel.SendMessageAsync($"Posting {messageCount} messages in {channel.Name}... (this might take a while)");

                do
                {
                    bufferedMessagesList.AddRange(more);
                    bufferedMessagesList.Reverse();
                    foreach (var mes in bufferedMessagesList)
                    {
                        if (mes.MessageType != MessageType.Default)
                        {
                            switch (mes.MessageType)
                            {
                            case MessageType.ChannelPinnedMessage:
                                var time = new DiscordEmbedBuilder {
                                    Description = $":pushpin: {mes.Author.Username} has pinned a message in this channel", Timestamp = mes.Timestamp
                                };
                                await newChannel.SendMessageAsync(null, time);

                                break;
                            }
                            continue;
                        }

                        EmbedAuthor         embedAuthor = null;
                        DiscordEmbedBuilder embed       = null;
                        DiscordMessage      newMessage  = null;
                        if (mes.Embeds.Count > 0)
                        {
                            if (mes.Author == ctx.Client.CurrentUser && mes.Embeds.First().Type == "rich")
                            {
                                DiscordEmbed CCEmbed = mes.Embeds.First();
                                embedAuthor = new EmbedAuthor {
                                    Name = CCEmbed.Author.Name, IconUrl = CCEmbed.Author.IconUrl.ToString()
                                };
                                embed = new DiscordEmbedBuilder {
                                    Description = CCEmbed.Description, Author = embedAuthor, Timestamp = CCEmbed.Timestamp
                                };
                                newMessage = await newChannel.SendMessageAsync(null, embed);
                            }
                            else
                            {
                                newMessage = await newChannel.SendMessageAsync($"{mes.Author.Username}'s attached embed(s):");

                                foreach (DiscordEmbed userEmbed in mes.Embeds)
                                {
                                    if (new String[] { "image", "gifv" }.Contains(userEmbed.Type))
                                    {
                                        await newChannel.SendMessageAsync(userEmbed.Url.ToString());
                                    }
                                    else
                                    {
                                        await newChannel.SendMessageAsync(null, userEmbed);
                                    }
                                }
                            }
                        }
                        else
                        {
                            embedAuthor = new EmbedAuthor {
                                Name = mes.Author.Username, IconUrl = mes.Author.AvatarUrl
                            };
                            embed = new DiscordEmbedBuilder {
                                Description = mes.Content, Author = embedAuthor, Timestamp = mes.Timestamp
                            };
                            newMessage = await newChannel.SendMessageAsync(null, embed);
                        }

                        if (mes.Pinned)
                        {
                            await newMessage.PinAsync();

                            var lastMessage = (await newChannel.GetMessagesAsync(1)).First();
                            if (lastMessage.MessageType == MessageType.ChannelPinnedMessage)
                            {
                                await newChannel.DeleteMessageAsync(lastMessage);
                            }
                        }

                        if (mes.Attachments.Count > 0)
                        {
                            foreach (var att in mes.Attachments)
                            {
                                {
                                    using (WebClient wc = new WebClient())
                                    {
                                        wc.DownloadFile(new System.Uri(att.Url), $"{tempDirectory}/{att.FileName}");
                                    }
                                    using (FileStream fs = File.OpenRead($"{tempDirectory}/{att.FileName}"))
                                    {
                                        await newChannel.SendMessageAsync((new DiscordMessageBuilder()).WithFile(att.FileName, fs));
                                    }
                                    File.Delete($"{tempDirectory}/{att.FileName}");
                                }
                            }
                        }
                    }

                    more = await channel.GetMessagesAfterAsync(bufferedMessagesList.Last().Id);

                    bufferedMessagesList.Clear();
                }while (more.Count > 0);

                if (elementIsCategory)
                {
                    await newChannel.ModifyAsync(c => c.Parent = newCategory);
                }
            }

            await ctx.Channel.SendMessageAsync($"Copy of {elementType} {elementName} complete!");
        }
Beispiel #19
0
 public DiscordEmbed AddAuthor(EmbedAuthor author)
 {
     this.Author = author;
     return(this);
 }
Beispiel #20
0
 /// <summary>
 /// Sets the author of the embed.
 /// </summary>
 /// <param name="iconUrl">
 /// The URL of the author's icon.
 /// <para>To use attachments uploaded alongside the embed, use the format: attachment://FILENAME_WITH_EXT</para>
 /// </param>
 public EmbedOptions SetAuthor(string name, string url = null, string iconUrl = null)
 {
     Author = new EmbedAuthor(name, url, iconUrl);
     return(this);
 }
Beispiel #21
0
        public async Task Info(CommandContext context)
        {
            var guild    = context.Guild;
            var channels = guild.GetChannelsAsync().ConfigureAwait(true).GetAwaiter().GetResult().ToList();
            var roles    = await guild.GetRoles();

            var emojis  = guild.GetEmojisAsync().ConfigureAwait(true).GetAwaiter().GetResult().ToList();
            var members = guild.GetAllMembersAsync().ConfigureAwait(true).GetAwaiter().GetResult().ToList();

            var owner  = guild.Owner;
            var prefix = redis.GetAsync <Defcon.Data.Guilds.Guild>(RedisKeyNaming.Guild(context.Guild.Id)).GetAwaiter().GetResult().Prefix;

            var guildAuthor = new EmbedAuthor {
                Name = guild.Name, Icon = guild.IconUrl
            };

            var ownerDetails = new StringBuilder()
                               .AppendLine($"Username: {owner.Mention} {Formatter.InlineCode(owner.GetUsertag())}")
                               .AppendLine($"Identity: {Formatter.InlineCode(owner.Id.ToString())}")
                               .ToString();

            var premiumTierCount     = guild.PremiumSubscriptionCount;
            var premiumTierSubsLabel = premiumTierCount == 1 ? "1 subscription" : $"{premiumTierCount} subscriptions";
            var premiumTierDetails   = new StringBuilder()
                                       .AppendLine($"{await guild.GetPremiumTier()}")
                                       .AppendLine(premiumTierSubsLabel)
                                       .ToString();

            var membersTotal       = guild.MemberCount;
            var botsCount          = members.Count(x => x.IsBot);
            var humansCount        = membersTotal - botsCount;
            var membersOnlineCount = await members.Online();

            var membersDnDCount = await members.DoNotDisturb();

            var membersIdleCount = await members.Idle();

            var membersOfflineCount = membersTotal - (membersOnlineCount + membersIdleCount + membersDnDCount);

            var membersLabel = members.Count == 1 ? "1 Member" : $"{membersTotal} Members";

            var memberDetails = new StringBuilder().AppendLineBold(":busts_in_silhouette: Humans", humansCount)
                                .AppendLineBold(":robot: Bots", botsCount)
                                .AppendLineBold(":green_circle: Online", membersOnlineCount)
                                .AppendLineBold(":orange_circle: Idle", membersIdleCount)
                                .AppendLineBold(":red_circle: DnD", membersDnDCount)
                                .AppendLineBold(":white_circle: Offline", membersOfflineCount)
                                .ToString();

            var totalChannelsCount   = channels.Count;
            var categoryChannelCount = await channels.Categories();

            var textChannelCount = await channels.Texts();

            var nsfwChannelCount = await channels.NSFW();

            var voiceChannelCount = await channels.Voices();

            var channelsLabel = totalChannelsCount == 1 ? "1 Channel" : $"{totalChannelsCount} Channels";

            var channelDetails = new StringBuilder().AppendLineBold(":file_folder: Category", categoryChannelCount)
                                 .AppendLineBold(":speech_balloon: Text", textChannelCount)
                                 .AppendLineBold(":underage: NSFW", nsfwChannelCount)
                                 .AppendLineBold(":loud_sound: Voice", voiceChannelCount)
                                 .ToString();


            var afkChannel = guild.AfkChannel != null ? guild.AfkChannel.Name : "Not set";
            var afkTimeout = guild.AfkTimeout / 60;

            var miscDetails = new StringBuilder().AppendLineBold("AFK Channel", afkChannel)
                              .AppendLineBold("AFK Timeout", $"{afkTimeout}min")
                              .AppendLineBold("Roles", roles.Count)
                              .AppendLineBold("Emojis", emojis.Count)
                              .ToString();

            var fields = new List <EmbedField>
            {
                new EmbedField {
                    Inline = false, Name = "Owner", Value = ownerDetails
                },
                new EmbedField {
                    Inline = true, Name = "Premium", Value = premiumTierDetails
                },
                new EmbedField {
                    Inline = true, Name = "Verification Level", Value = $"{guild.VerificationLevel}"
                },
                new EmbedField {
                    Inline = true, Name = "Region", Value = $"{guild.VoiceRegion.Name}"
                },
                new EmbedField {
                    Inline = true, Name = membersLabel, Value = memberDetails
                },
                new EmbedField {
                    Inline = true, Name = channelsLabel, Value = channelDetails
                },
                new EmbedField {
                    Inline = true, Name = "Misc", Value = miscDetails
                }
            };

            var guildDays = await guild.GetDays();

            var guildSinceDays = guildDays == 1 ? $"yesterday" : guildDays == 0 ? "today" : $"{Formatter.Bold($"{guildDays}")} days ago";

            var embed = new Embed
            {
                Description = new StringBuilder()
                              .AppendLine($"Identity: {Formatter.InlineCode($"{guild.Id}")}")
                              .AppendLine($"Created at: {await guild.CreatedAtLongDateTimeString()} ({guildSinceDays})")
                              .AppendLine($"Server Prefix: {Formatter.InlineCode(prefix)}")
                              .ToString(),
                Thumbnail = guild.IconUrl,
                Author    = guildAuthor,
                Fields    = fields
            };

            await context.SendEmbedMessageAsync(embed);
        }
 public static API.EmbedAuthor ToModel(this EmbedAuthor entity)
 {
     return(new API.EmbedAuthor {
         Name = entity.Name, Url = entity.Url, IconUrl = entity.IconUrl
     });
 }
Beispiel #23
0
        private async Task Update()
        {
            if (this.Message == null)
            {
                return;
            }
            string display = this.DisplayCallback?.Invoke(this.Data[this.CurrentIndex]);

            await this.Message.ModifyAsync(prop =>
            {
                if (this.Embed != null)
                {
                    Embed oldEmbed       = this.Embed;
                    EmbedBuilder builder = new EmbedBuilder();
                    builder
                    .WithLimitedTitle(oldEmbed.Title)
                    .WithLimitedDescription(display);

                    if (oldEmbed.Color.HasValue)
                    {
                        builder.WithColor(oldEmbed.Color.Value);
                    }

                    if (oldEmbed.Timestamp.HasValue)
                    {
                        builder.WithTimestamp(oldEmbed.Timestamp.Value);
                    }

                    if (oldEmbed.Author.HasValue)
                    {
                        EmbedAuthor oldAuthor            = oldEmbed.Author.Value;
                        EmbedAuthorBuilder authorBuilder = new EmbedAuthorBuilder();
                        authorBuilder
                        .WithIconUrl(oldAuthor.IconUrl)
                        .WithName(oldAuthor.Name)
                        .WithUrl(oldAuthor.Url);
                        builder.WithAuthor(authorBuilder);
                    }

                    if (oldEmbed.Footer.HasValue)
                    {
                        EmbedFooter oldFooter            = oldEmbed.Footer.Value;
                        EmbedFooterBuilder footerBuilder = new EmbedFooterBuilder();
                        footerBuilder
                        .WithText(oldFooter.Text)
                        .WithIconUrl(oldFooter.IconUrl);
                        builder.WithFooter(footerBuilder);
                    }

                    this.DisplayEmbedCallback?.Invoke(this.Data[this.CurrentIndex], builder);

                    this.Embed = builder.Build();
                    prop.Embed = this.Embed;
                }
                else
                {
                    prop.Content = display;
                }
            });

            this.Refresh();
        }
Beispiel #24
0
        public async Task LoadChannel(CommandContext ctx, ulong guildId, ulong channelId)
        {
            var guild = await ctx.Client.GetGuildAsync(guildId);

            var selectedChannel = guild.GetChannel(channelId);

            await ctx.RespondAsync("What do you want the new channel to be named?");

            var intr     = ctx.Client.GetInteractivityModule(); // Grab the interactivity module
            var response = await intr.WaitForMessageAsync(
                c => c.Author.Id == ctx.Message.Author.Id,      // Make sure the response is from the same person who sent the command
                TimeSpan.FromSeconds(60)                        // Wait 60 seconds for a response instead of the default 30 we set earlier!
                );

            if (response == null)
            {
                await ctx.RespondAsync("Sorry, I didn't get a response!");

                return;
            }

            if (string.IsNullOrEmpty(response.Message.Content))
            {
                await ctx.RespondAsync("Name cannot be empty!");

                return;
            }

            var channelName = response.Message.Content;

            await ctx.RespondAsync("Starting copy...");

            await ctx.RespondAsync("Collecting messages...");

            var messag = await selectedChannel.GetMessagesAsync();

            var messCopy = messag.ToList();

            var more = await selectedChannel.GetMessagesAsync(100, messag.LastOrDefault().Id);

            while (more.Count > 0)
            {
                messCopy.AddRange(more);
                more = await selectedChannel.GetMessagesAsync(100, more.LastOrDefault().Id);
            }

            await ctx.RespondAsync("Organizing messages...");

            messCopy.Reverse();

            var newMess = new List <DiscordMessage>();

            await ctx.RespondAsync("Creating channel...");

            var newChan = await ctx.Guild.CreateChannelAsync(channelName, selectedChannel.Type);

            await ctx.RespondAsync($"Posting {messCopy.Count} messages... (this could take awhile)");

            foreach (var mes in messCopy)
            {
                if (!string.IsNullOrEmpty(mes.Content))
                {
                    var whAu = new EmbedAuthor {
                        Name = mes.Author.Username, IconUrl = mes.Author.AvatarUrl
                    };
                    var what = new DiscordEmbedBuilder {
                        Description = mes.Content, Author = whAu, Timestamp = mes.Timestamp
                    };

                    await newChan.SendMessageAsync(null, false, what);
                }

                if (mes.Attachments.Count > 0)
                {
                    foreach (var att in mes.Attachments)
                    {
                        var whAu = new EmbedAuthor {
                            Name = mes.Author.Username, IconUrl = mes.Author.AvatarUrl
                        };
                        var what = new DiscordEmbedBuilder {
                            ImageUrl = att.Url, Author = whAu, Timestamp = mes.Timestamp
                        };

                        await newChan.SendMessageAsync(null, false, what);
                    }
                }
            }

            await ctx.RespondAsync($"{newChan.Name} copy complete!");
        }