Пример #1
0
        void AddBindingIfValid(List <RaidChannelBinding> channelBindings, SocketGuild guild, ChannelOptions channelOptions)
        {
            var channelFrom = guild.TextChannels.FirstOrDefault(t => t.Name == channelOptions.From);
            var channelTo   = guild.TextChannels.FirstOrDefault(t => t.Name == channelOptions.To);

            bool channelFromBinding = channelFrom == null && channelOptions.From != "*";
            bool channelToBinding   = channelTo == null;

            if (channelFromBinding || channelToBinding)
            {
                if (channelFromBinding)
                {
                    logger.LogError($"Unknown from channel binding '{channelOptions.From}'");
                }
                if (channelToBinding)
                {
                    logger.LogError($"Unknown to channel binding '{channelOptions.To}'");
                }
                return;
            }

            IMentionable mention = null;

            if (!string.IsNullOrEmpty(channelOptions.Mention))
            {
                mention = guild.Roles.FirstOrDefault(t => t.Name == channelOptions.Mention);
                if (mention == null)
                {
                    logger.LogError($"Unknown role '{channelOptions.Mention}'");
                }
            }

            channelBindings.Add(new RaidChannelBinding(channelFrom, channelTo, mention, channelOptions.ScheduledRaids));
        }
Пример #2
0
        public async Task Reminder(IMentionable mention, string dateString, string subject)
        {
            var date     = dateString.Split('-')[0].Split('/');
            var time     = dateString.Split('-')[1].Split(':');
            var dateTime = new DateTime(int.Parse(date[2]), int.Parse(date[1]), int.Parse(date[0]), int.Parse(time[0]), int.Parse(time[1]), 5);

            if ((dateTime - DateTime.Now).Ticks > 0)
            {
                var message = await ReplyAsync($"I'll remind {mention} to {subject} at {dateTime}");

                await Task.Delay(5000); // 5 seconds

                await message.DeleteAsync();

                while (DateTime.Now <= dateTime)
                {
                    await Task.Delay(10000);
                }
                await ReplyAsync($"Hey {mention.Mention}, you need to {subject} !");
            }
            else
            {
                await ReplyAsync("You can't wait for a past date !");
            }
        }
Пример #3
0
 public RaidChannelBinding(ITextChannel from, ITextChannel to, IMentionable mention, bool scheduledRaids)
 {
     From           = from;
     To             = to;
     Mention        = mention;
     ScheduledRaids = scheduledRaids;
 }
        /// <summary>
        /// Attempts to query for users, channels, and roles if they havent been found yet, and set them in the mentionable
        /// </summary>
        private async Task FillMentionable(string token, string guildId, IMentionable mentionable)
        {
            for (int i = 0; i < mentionable.MentionedUsers.Count; i++)
            {
                var user = mentionable.MentionedUsers[i];
                if (user.Name == "Unknown" && user.Discriminator == 0)
                {
                    try
                    {
                        mentionable.MentionedUsers[i] = _userCache.GetOrDefault(user.Id) ?? (await GetMemberAsync(token, guildId, user.Id));
                    }
                    catch (HttpErrorStatusCodeException e) { } // This likely means the user doesnt exist any more, so ignore
                }
            }

            for (int i = 0; i < mentionable.MentionedChannels.Count; i++)
            {
                var channel = mentionable.MentionedChannels[i];
                if (channel.Name == "deleted-channel" && channel.GuildId == null)
                {
                    try
                    {
                        mentionable.MentionedChannels[i] = _channelCache.GetOrDefault(channel.Id) ?? (await GetChannelAsync(token, channel.Id));
                    }
                    catch (HttpErrorStatusCodeException e) { } // This likely means the user doesnt exist any more, so ignore
                }
            }

            // Roles are already gotten via GetGuildRolesAsync at the start
        }
        /// <summary>
        /// Attempts to copy the full rich embed from a message, if it has one.
        /// </summary>
        /// <param name="message">The quoted message.</param>
        /// <param name="executingUser">The user that quoted the message.</param>
        /// <param name="embed">The embed to replace.</param>
        /// <returns>true if a rich embed was copied; otherwise, false.</returns>
        private bool TryCopyRichEmbed
        (
            [NotNull] IMessage message,
            [NotNull] IMentionable executingUser,
            [NotNull] ref EmbedBuilder embed
        )
        {
            var firstEmbed = message.Embeds.FirstOrDefault();

            if (firstEmbed?.Type != EmbedType.Rich)
            {
                return(false);
            }

            embed = message.Embeds
                    .First()
                    .ToEmbedBuilder()
                    .AddField
                    (
                "Quoted by",
                $"{executingUser.Mention} from **[#{message.Channel.Name}]({message.GetJumpUrl()})**",
                true
                    );

            if (firstEmbed.Color is null)
            {
                embed.Color = Color.DarkGrey;
            }

            return(true);
        }
        public Embed CreateFeedbackEmbed([NotNull] IMentionable invoker, Color color, [NotNull] string contents)
        {
            var eb = CreateEmbedBase(color);

            eb.WithDescription($"{invoker.Mention} | {contents}");

            return(eb.Build());
        }
Пример #7
0
        private string EmbedDescriptionToHtml(string content, IMentionable mentionable)
        {
            if (content == null)
            {
                return(null);
            }

            return($"<div class='embed-description markup'>{MarkdownToHtml(content, mentionable, true)}</div>");
        }
Пример #8
0
        private string EmbedFieldsToHtml(IReadOnlyList <EmbedField> fields, IMentionable mentionable)
        {
            if (fields.Count == 0)
            {
                return(null);
            }

            return($"<div class='embed-fields'>{string.Join("", fields.Select(f => EmbedFieldToHtml(f.Name, f.Value, f.Inline, mentionable)))}</div>");
        }
Пример #9
0
 private async Task AnnouceJoinedUser(IMentionable user)
 {
     var welcomeChannel  = _client.GetChannel(ClientToken.GuildChannels.Welcome) as SocketTextChannel;
     var rulesChannel    = _client.GetChannel(ClientToken.GuildChannels.Rules) as SocketTextChannel;
     var birthdayChannel = _client.GetChannel(ClientToken.GuildChannels.Birthday) as SocketTextChannel;
     var selfRoleChannel = _client.GetChannel(ClientToken.GuildChannels.SelfRole) as SocketTextChannel;
     await welcomeChannel.SendMessageAsync($"Hey! {user.Mention} just joined {welcomeChannel.Guild.Name}! ♡ Check out " +
                                           $"the {rulesChannel.Mention}, post your birthday here {birthdayChannel.Mention}, and get yourself " +
                                           $"some {selfRoleChannel.Mention}!");
 }
Пример #10
0
        private string EmbedFieldToHtml(string name, string value, bool?inline, IMentionable mentionable)
        {
            if (name == null && value == null)
            {
                return(null);
            }

            string cls = "embed-field" + (inline == true ? " embed-field-inline" : "");

            string fieldName  = name != null ? $"<div class='embed-field-name'>{MarkdownToHtml(name)}</div>" : null;
            string fieldValue = value != null ? $"<div class='embed-field-value markup'>{MarkdownToHtml(value, mentionable, true)}</div>" : null;

            return($"<div class='{cls}'>{fieldName}{fieldValue}</div>");
        }
Пример #11
0
        public async Task DisplayPermissionsCommand(SocketMessage message, IMentionable mention)
        {
            if (!(message.Channel is SocketTextChannel channel))
            {
                return;
            }
            var guildData = dataStore.GetGuildData(channel.Guild);
            Func <Permissions, bool> checkPermission;

            if (mention is SocketRole role)
            {
                checkPermission = (p => guildData.RoleHasPermission(role, p));
            }
            else if (mention is SocketUser user)
            {
                var guildUser = channel.GetUser(user.Id);
                checkPermission = (p => guildData.UserHasPermission(guildUser, p));
            }
            else
            {
                return;
            }
            var text = "";

            foreach (Permissions perm in Enum.GetValues(typeof(Permissions)))
            {
                if (perm != Permissions.None && checkPermission(perm))
                {
                    if (text != "")
                    {
                        text += ", ";
                    }
                    text += perm.ToString();
                }
            }
            if (text == "")
            {
                text = "no special permissions.";
            }
            else
            {
                text = "these permissions: " + text + ".";
            }
            await channel.SendMessageAsync($"{mention.Mention} has " + text);
        }
 /// <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 void AddMeta
 (
     [NotNull] IMessage message,
     [NotNull] IMentionable quotingUser,
     [NotNull] ref EmbedBuilder embed
 )
 {
     embed
     .WithAuthor(message.Author)
     .WithFooter(GetPostedTimeInfo(message))
     .WithColor(new Color(95, 186, 125))
     .AddField
     (
         "Quoted by",
         $"{quotingUser.Mention} from **[#{message.Channel.Name}]({message.GetJumpUrl()})**",
         true
     );
 }
Пример #13
0
        public async Task <List <object> > ConvertChainCommandsToObjects(SocketUserMessage e, List <object> input, int depth)
        {
            List <object> converted = new List <object> ();

            foreach (object obj in input)
            {
                object result    = obj;
                string stringObj = obj.ToString();

                if (stringObj.Length > 0)
                {
                    if (stringObj [0].IsTrigger())
                    {
                        Program.FoundCommandResult foundCommandResult = await Program.FindAndExecuteCommand(e, stringObj, Program.commands, depth + 1, false, true);

                        if (foundCommandResult.result != null)
                        {
                            result = foundCommandResult.result.value;
                        }
                    }
                    else if (stringObj [0] == '{')
                    {
                        int endIndex = stringObj.IndexOf('}');
                        if (endIndex != -1)
                        {
                            string varName = stringObj.Substring(1, endIndex - 1);
                            result = CommandVariables.Get(e.Id, varName);
                        }
                    }
                    else if (stringObj [0] == '<')
                    {
                        IMentionable mentionable = Utility.ConvertMentionToObject(stringObj);
                        result = mentionable;
                    }
                }

                converted.Add(result);
            }

            return(converted);
        }
        public EmbedBuilder CreateMessageQuote([NotNull] IMessage message, [NotNull] IMentionable quotingUser)
        {
            var eb = new EmbedBuilder();

            if (TryCopyRichEmbed(message, quotingUser, ref eb))
            {
                return(eb);
            }

            if (!TryAddImageAttachmentInfo(message, ref eb))
            {
                TryAddOtherAttachmentInfo(message, ref eb);
            }

            AddContent(message, ref eb);
            AddOtherEmbed(message, ref eb);
            AddActivity(message, ref eb);
            AddMeta(message, quotingUser, ref eb);

            return(eb);
        }
Пример #15
0
        public async Task RemovePermissionCommand(SocketMessage message, IMentionable mention, string permission)
        {
            if (!(message.Channel is SocketTextChannel channel))
            {
                return;
            }
            if (!(mention is SocketEntity <ulong> entity))
            {
                return;
            }
            if (!Enum.TryParse <Permissions>(permission, true, out var perm))
            {
                await channel.SendMessageAsync("Unknown permission.");

                return;
            }
            var guildData = dataStore.GetGuildData(channel.Guild);

            guildData.RemovePermission(entity, perm);
            await channel.SendMessageAsync($"Removed permission {perm.ToString()} from {mention.Mention}");
        }
Пример #16
0
        public async Task GiveXp(decimal xp, User user, SocketGuild guild, IMentionable socketUser, IUnitOfWork unitOfWork)
        {
            user.Xp += xp;
            var xpNeeded = user.Xp >= user.Level * 25;

            if (xpNeeded)
            {
                var server = await unitOfWork.Servers.GetOrAddServerAsync(guild.Id, guild.Name, guild.MemberCount).ConfigureAwait(false);

                while (xpNeeded)
                {
                    user.Xp -= user.Level * 25;
                    user.Level++;
                    xpNeeded = user.Xp >= user.Level * 25;
                }

                if (server.LevelUpChannel != null)
                {
                    await guild.GetTextChannel((ulong)server.LevelUpChannel).SendMessageAsync($"{socketUser.Mention} just leveled up to lvl: {user.Level} :tada:\n" +
                                                                                              "Use `?level` for more info.").ConfigureAwait(false);
                }
            }
        }
Пример #17
0
 public MessageBuilder Mention(IMentionable mentionable)
 {
     _msg.Append(CreateMentionString(mentionable, null));
     return(this);
 }
Пример #18
0
 private async Task AnnouceUserBanned(IMentionable user, IGuild guild)
 {
     var goodbyeChannel = _client.GetChannel(ClientToken.GuildChannels.Goodbye) as SocketTextChannel;
     await goodbyeChannel.SendMessageAsync($"{user.Mention} has been banned from {guild.Name} for now! Oh well, probably had it coming.");
 }
Пример #19
0
 private async Task AnnouceUserLeft(IMentionable user)
 {
     var goodbyeChannel = _client.GetChannel(ClientToken.GuildChannels.Goodbye) as SocketTextChannel;
     await goodbyeChannel.SendMessageAsync($"{user.Mention} has left {goodbyeChannel.Guild.Name}! :(");
 }
Пример #20
0
        private string MarkdownToHtml(string content, IMentionable mentionable = null, bool allowLinks = false)
        {
            // A lot of these regexes were inspired by or taken from MarkdownSharp

            // HTML-encode content
            content = HtmlEncode(content);

            // Encode multiline codeblocks (```text```)
            content = Regex.Replace(content,
                                    @"```+(?:[^`]*?\n)?([^`]+)\n?```+",
                                    m => $"\x1AM{Base64Encode(m.Groups[1].Value)}\x1AM");

            // Encode inline codeblocks (`text`)
            content = Regex.Replace(content,
                                    @"`([^`]+)`",
                                    m => $"\x1AI{Base64Encode(m.Groups[1].Value)}\x1AI");

            // Encode URLs
            content = Regex.Replace(content,
                                    @"(\b(?:(?:https?|ftp|file)://|www\.|ftp\.)(?:\([-a-zA-Z0-9+&@#/%?=~_|!:,\.\[\];]*\)|[-a-zA-Z0-9+&@#/%?=~_|!:,\.\[\];])*(?:\([-a-zA-Z0-9+&@#/%?=~_|!:,\.\[\];]*\)|[-a-zA-Z0-9+&@#/%=~_|$]))",
                                    m => $"\x1AL{Base64Encode(m.Groups[1].Value)}\x1AL");

            // Process bold (**text**)
            content = Regex.Replace(content, @"(\*\*)(?=\S)(.+?[*_]*)(?<=\S)\1", "<b>$2</b>");

            // Process underline (__text__)
            content = Regex.Replace(content, @"(__)(?=\S)(.+?)(?<=\S)\1", "<u>$2</u>");

            // Process italic (*text* or _text_)
            content = Regex.Replace(content, @"(\*|_)(?=\S)(.+?)(?<=\S)\1", "<i>$2</i>");

            // Process strike through (~~text~~)
            content = Regex.Replace(content, @"(~~)(?=\S)(.+?)(?<=\S)\1", "<s>$2</s>");

            // Decode and process multiline codeblocks
            content = Regex.Replace(content, "\x1AM(.*?)\x1AM",
                                    m => $"<div class=\"pre\">{Base64Decode(m.Groups[1].Value)}</div>");

            // Decode and process inline codeblocks
            content = Regex.Replace(content, "\x1AI(.*?)\x1AI",
                                    m => $"<span class=\"pre\">{Base64Decode(m.Groups[1].Value)}</span>");

            if (allowLinks)
            {
                content = Regex.Replace(content, "\\[([^\\]]+)\\]\\(\x1AL(.*?)\x1AL\\)",
                                        m => $"<a href=\"{Base64Decode(m.Groups[2].Value)}\">{m.Groups[1].Value}</a>");
            }

            // Decode and process URLs
            content = Regex.Replace(content, "\x1AL(.*?)\x1AL",
                                    m => $"<a href=\"{Base64Decode(m.Groups[1].Value)}\">{Base64Decode(m.Groups[1].Value)}</a>");

            // New lines
            content = content.Replace("\n", "<br />");

            // Meta mentions (@everyone)
            content = content.Replace("@everyone", "<span class=\"mention\">@everyone</span>");

            // Meta mentions (@here)
            content = content.Replace("@here", "<span class=\"mention\">@here</span>");

            if (mentionable != null)
            {
                // User mentions (<@id> and <@!id>)
                foreach (var mentionedUser in mentionable.MentionedUsers)
                {
                    content = Regex.Replace(content, $"&lt;@!?{mentionedUser.Id}&gt;",
                                            $"<span class=\"mention\" title=\"{HtmlEncode(mentionedUser.FullName)}\">" +
                                            $"@{HtmlEncode(mentionedUser.Name)}" +
                                            "</span>");
                }

                // Role mentions (<@&id>)
                foreach (var mentionedRole in mentionable.MentionedRoles)
                {
                    content = content.Replace($"&lt;@&amp;{mentionedRole.Id}&gt;",
                                              "<span class=\"mention\">" +
                                              $"@{HtmlEncode(mentionedRole.Name)}" +
                                              "</span>");
                }

                // Channel mentions (<#id>)
                foreach (var mentionedChannel in mentionable.MentionedChannels)
                {
                    content = content.Replace($"&lt;#{mentionedChannel.Id}&gt;",
                                              "<span class=\"mention\">" +
                                              $"#{HtmlEncode(mentionedChannel.Name)}" +
                                              "</span>");
                }
            }

            // Custom emojis (<:name:id>)
            content = Regex.Replace(content, "&lt;(:.*?:)(\\d*)&gt;",
                                    "<img class=\"emoji\" title=\"$1\" src=\"https://cdn.discordapp.com/emojis/$2.png\" />");

            return(content);
        }
Пример #21
0
 public static async Task <bool> IsMentionableByAsync(this IMentionable obj, LazyUser user, Server inServer, [CanBeNull] Client client)
 {
     return(await obj.IsMentionableByAsync(user.Id, inServer.Id, client));
 }
Пример #22
0
 public static async Task <bool> IsMentionableByAsync(this IMentionable obj, ulong userId, ulong inServerId)
 {
     return(await obj.IsMentionableByAsync(userId, inServerId, null));
 }
Пример #23
0
 public static async Task <bool> IsMentionableByAsync(this IMentionable obj, LazyUser user, Server inServer)
 {
     return(await obj.IsMentionableByAsync(user.Id, inServer.Id, null));
 }
Пример #24
0
 public static bool IsMentionableBy(this IMentionable obj, ulong userId, ulong inServerId, [CanBeNull] Client client)
 {
     return(obj.IsMentionableByAsync(userId, inServerId, client).Await());
 }
Пример #25
0
 public static bool IsMentionableBy(this IMentionable obj, LazyUser user, Server inServer, [CanBeNull] Client client)
 {
     return(obj.IsMentionableByAsync(user, inServer, client).Await());
 }
Пример #26
0
 public static bool IsMentionableBy(this IMentionable obj, ulong userId, Server inServer)
 {
     return(obj.IsMentionableByAsync(userId, inServer).Await());
 }
Пример #27
0
 public static bool IsMentionableBy(this IMentionable obj, LazyUser user, Server inServer)
 {
     return(obj.IsMentionableByAsync(user, inServer).Await());
 }
Пример #28
0
 public static string CreateMentionString(IMentionable mentionable, [CanBeNull] Client client)
 {
     // TODO: Call mentionable.IsMentionableBy to determine when IsMentionable is Maybe (pass current user object).
     return(mentionable.IsMentionable.IsTrue() ? mentionable.MentionContent : mentionable.MentionFallbackName);
 }
Пример #29
0
 public static string CreateMentionString(IMentionable mentionable)
 {
     return(CreateMentionString(mentionable, null));
 }