예제 #1
0
        public override ValueTask <TypeParserResult <SocketRole> > ParseAsync(
            Parameter param,
            string value,
            CommandContext context)
        {
            var        ctx  = context.Cast <VolteContext>();
            SocketRole role = default;

            if (ulong.TryParse(value, out var id) || MentionUtils.TryParseRole(value, out id))
            {
                role = ctx.Guild.GetRole(id).Cast <SocketRole>();
            }

            if (role is null)
            {
                var match = ctx.Guild.Roles.Where(x => x.Name.EqualsIgnoreCase(value)).ToList();
                if (match.Count > 1)
                {
                    return(TypeParserResult <SocketRole> .Failed(
                               "Multiple roles found. Try mentioning the role or using its ID."));
                }

                role = match.FirstOrDefault().Cast <SocketRole>();
            }

            return(role is null
                ? TypeParserResult <SocketRole> .Failed($"Role `{value}` not found.")
                : TypeParserResult <SocketRole> .Successful(role));
        }
예제 #2
0
        public override Task <TypeParserResult <TRole> > ParseAsync(
            Parameter param,
            string value,
            ICommandContext context,
            IServiceProvider provider)
        {
            var   ctx  = (DepressedBotContext)context;
            TRole role = null;

            if (ulong.TryParse(value, out var id) || MentionUtils.TryParseRole(value, out id))
            {
                role = ctx.Guild.GetRole(id) as TRole;
            }

            if (role is null)
            {
                var match = ctx.Guild.Roles.Where(x => x.Name.EqualsIgnoreCase(value)).ToList();
                if (match.Count > 1)
                {
                    return(Task.FromResult(TypeParserResult <TRole> .Unsuccessful(
                                               "Multiple roles found. Try mentioning the role or using its ID.")
                                           ));
                }

                role = match.FirstOrDefault() as TRole;
            }

            return(role is null
                ? Task.FromResult(TypeParserResult <TRole> .Unsuccessful("Role not found."))
                : Task.FromResult(TypeParserResult <TRole> .Successful(role)));
        }
예제 #3
0
        public override ValueTask <TypeParserResult <SocketRole> > ParseAsync(string value, VolteContext ctx)
        {
            SocketRole role = default;

            if (ulong.TryParse(value, out var id) || MentionUtils.TryParseRole(value, out id))
            {
                role = ctx.Guild.GetRole(id).Cast <SocketRole>();
            }

            if (role is null)
            {
                var match = ctx.Guild.Roles.Where(x => x.Name.EqualsIgnoreCase(value)).ToList();
                if (match.Count > 1)
                {
                    return(Failure(
                               "Multiple roles found. Try mentioning the role or using its ID."));
                }

                role = match.FirstOrDefault().Cast <SocketRole>();
            }

            return(role is null
                ? Failure($"Role {Format.Code(value)} not found.")
                : Success(role));
        }
예제 #4
0
        public override Task <TypeParserResult <T> > ParseAsync(Parameter parameter, string value, ICommandContext context, IServiceProvider provider)
        {
            var _context = context as GuildContext;
            var results  = new Dictionary <ulong, GenericParseResult <T> >();
            var roles    = _context.Guild.Roles;

            //By Mention (1.0)
            if (MentionUtils.TryParseRole(value, out ulong id))
            {
                AddResult(results, _context.Guild.GetRole(id) as T, 1.00f);
            }

            //By Id (0.9)
            if (ulong.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out id))
            {
                AddResult(results, _context.Guild.GetRole(id) as T, 0.90f);
            }

            //By Name (0.7-0.8)
            foreach (var role in roles.Where(x => string.Equals(value, x.Name, StringComparison.OrdinalIgnoreCase)))
            {
                AddResult(results, role as T, role.Name == value ? 0.80f : 0.70f);
            }

            if (results.Count > 0)
            {
                return(Task.FromResult(new TypeParserResult <T>(results.Values.OrderBy(a => a.Score).FirstOrDefault()?.Value)));
            }

            return(Task.FromResult(new TypeParserResult <T>("Role not found.")));
        }
예제 #5
0
        /// <summary>
        /// Tries to parses a given string as a role.
        /// </summary>
        /// <param name="guild">The guild in which to search for the role.</param>
        /// <param name="input">A string representing a role by mention, id, or name.</param>
        /// <returns>The results of the parse.</returns>
        public static Task <TypeReaderResult> ReadAsync(IGuild guild, string input)
        {
            if (guild != null)
            {
                var results = new Dictionary <ulong, TypeReaderValue>();
                IReadOnlyCollection <IRole> roles = guild.Roles;
                ulong id;

                // By Mention (1.0)
                if (MentionUtils.TryParseRole(input, out id))
                {
                    AddResult(results, guild.GetRole(id) as T, 1.00f);
                }

                // By Id (0.9)
                if (ulong.TryParse(input, NumberStyles.None, CultureInfo.InvariantCulture, out id))
                {
                    AddResult(results, guild.GetRole(id) as T, 0.90f);
                }

                // By Name (0.7-0.8)
                // Acounts for name being null because GetrolesAsync returns categories in 1.0.
                foreach (IRole role in roles.Where(x => string.Equals(input, x.Name, StringComparison.OrdinalIgnoreCase)))
                {
                    AddResult(results, role as T, role.Name == input ? 0.80f : 0.70f);
                }

                if (results.Count > 0)
                {
                    return(Task.FromResult(TypeReaderResult.FromSuccess(results.Values)));
                }
            }

            return(Task.FromResult(TypeReaderResult.FromError(CommandError.ObjectNotFound, "Role not found.")));
        }
예제 #6
0
        public async Task <RuntimeResult> Lock(GuildEmote emote, [Remainder] string roles = "")
        {
            var roleList = new List <IRole>();

            foreach (var x in roles.Split(','))
            {
                var text = x.Trim();
                if (ulong.TryParse(text, out var id))
                {
                    roleList.Add(Context.Guild.GetRole(id));
                }
                else if (MentionUtils.TryParseRole(text, out id))
                {
                    roleList.Add(Context.Guild.GetRole(id));
                }
                else if (!string.IsNullOrWhiteSpace(text))
                {
                    return(new BotResult($"Could not parse `{text}` as any role. Either mention it or use the role's id."));
                }
            }
            await Context.Guild.ModifyEmoteAsync(emote, x =>
            {
                x.Roles = roleList;
            });

            await ReplyAsync("Done.");

            return(new BotResult());
        }
예제 #7
0
        public override ValueTask <TypeParserResult <SocketRole> > ParseAsync(Parameter parameter, string value,
                                                                              SocketCommandContext context, IServiceProvider provider)
        {
            if (MentionUtils.TryParseRole(value, out var id))
            {
                var role = context.Guild.GetRole(id);
                return(role != null
                    ? TypeParserResult <SocketRole> .Successful(role)
                    : TypeParserResult <SocketRole> .Unsuccessful("Couldn't parse role"));
            }

            if (ulong.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out id))
            {
                var role = context.Guild.GetRole(id);
                return(role != null
                    ? TypeParserResult <SocketRole> .Successful(role)
                    : TypeParserResult <SocketRole> .Unsuccessful("Couldn't parse role"));
            }

            var roleCheck = context.Guild.Roles.FirstOrDefault(x => x.Name == value);

            return(roleCheck != null
                ? TypeParserResult <SocketRole> .Successful(roleCheck)
                : TypeParserResult <SocketRole> .Unsuccessful("Couldn't parse role"));
        }
예제 #8
0
        public override Task <TypeReaderResult> Read(ICommandContext context, string input)
        {
            ulong id;

            if (context.Guild != null)
            {
                var results = new Dictionary <ulong, TypeReaderValue>();
                var roles   = context.Guild.Roles;

                //By Mention (1.0)
                if (MentionUtils.TryParseRole(input, out id))
                {
                    AddResult(results, context.Guild.GetRole(id) as T, 1.00f);
                }

                //By Id (0.9)
                if (ulong.TryParse(input, NumberStyles.None, CultureInfo.InvariantCulture, out id))
                {
                    AddResult(results, context.Guild.GetRole(id) as T, 0.90f);
                }

                //By Name (0.7-0.8)
                foreach (var role in roles.Where(x => string.Equals(input, x.Name, StringComparison.OrdinalIgnoreCase)))
                {
                    AddResult(results, role as T, role.Name == input ? 0.80f : 0.70f);
                }

                if (results.Count > 0)
                {
                    return(Task.FromResult(TypeReaderResult.FromSuccess(results.Values.ToReadOnlyCollection())));
                }
            }
            return(Task.FromResult(TypeReaderResult.FromError(CommandError.ObjectNotFound, "Role not found.")));
        }
예제 #9
0
        public override ValueTask <TypeParserResult <IRole> > ParseAsync(Parameter param, string value, ScrapContext context)
        {
            var   roles = context.Guild.Roles.ToList();
            IRole role  = null;

            if (ulong.TryParse(value, out ulong id) || MentionUtils.TryParseRole(value, out id))
            {
                role = context.Guild.GetRole(id) as IRole;
            }

            if (role is null)
            {
                var match = roles.Where(x =>
                                        x.Name.EqualsIgnoreCase(value));
                if (match.Count() > 1)
                {
                    return(TypeParserResult <IRole> .Unsuccessful(
                               "Multiple roles found, try mentioning the role or using its ID."));
                }

                role = match.FirstOrDefault();
            }
            return(role is null
                ? TypeParserResult <IRole> .Unsuccessful("Role not found.")
                : TypeParserResult <IRole> .Successful(role));
        }
예제 #10
0
        public override ValueTask <TypeReaderResponse> Read(IMessageContext context, string input)
        {
            if (context.Guild != null)
            {
                var results = new Dictionary <ulong, TypeReaderValue>();
                var roles   = context.Guild.Roles;

                //By Mention (1.0)
                if (MentionUtils.TryParseRole(input, out ulong id))
                {
                    AddResult(results, context.Guild.GetRole(id) as T, 1.00f);
                }

                //By Id (0.9)
                if (ulong.TryParse(input, NumberStyles.None, CultureInfo.InvariantCulture, out id))
                {
                    AddResult(results, context.Guild.GetRole(id) as T, 0.90f);
                }

                //By Name (0.7-0.8)
                foreach (var role in roles.Where(x => string.Equals(input, x.Name, StringComparison.OrdinalIgnoreCase)))
                {
                    AddResult(results, role as T, role.Name == input ? 0.80f : 0.70f);
                }

                if (results.Count > 0)
                {
                    return(ValueTask.FromResult(TypeReaderResponse.FromSuccess(results.Values)));
                }
            }
            return(ValueTask.FromResult(TypeReaderResponse.FromError(TYPEREADER_ENTITY_NOTFOUND, input, typeof(T))));
        }
예제 #11
0
        public static SocketRole ParseRole(SocketGuild guild, string text)
        {
            ulong roleId;

            if (MentionUtils.TryParseRole(text, out roleId))
            {
                return(guild.GetRole(roleId));
            }
            return(null);
        }
예제 #12
0
        public static SocketRole FirstRoleByName(this SocketGuild guild, string name)
        {
            if (MentionUtils.TryParseRole(name, out var id))
            {
                return(guild.Roles.FirstOrDefault(role => role.Id == id));
            }

            return(guild.Roles.FirstOrDefault(role =>
                                              Regex.IsMatch(role.Name, name, RegexOptions.IgnoreCase)
                                              ));
        }
예제 #13
0
        private async Task HandleStaffRoleUpdate(SetUpRequest request, IUserMessage message)
        {
            await message.Channel.SendMessageAsync("Enter the staff role used for high level permissions");

            while (true)
            {
                var response = await _discordMessageService.WaitForNextMessageFromUser(request.Message.Author.Id, TimeSpan.FromSeconds(30));

                if (response is null)
                {
                    break;
                }

                var isValidUlong = ulong.TryParse(response.Content, out var roleId) ||
                                   MentionUtils.TryParseRole(response.Content, out roleId);

                if (isValidUlong)
                {
                    var isValidCategory = _discordGuildService.HasRole(roleId);

                    if (!isValidCategory)
                    {
                        await response.AddErrorEmote();

                        continue;
                    }

                    await _behaviourConfigurationService.SetStaffRole(roleId);

                    await response.AddSuccessEmote();

                    break;
                }

                var hasNamedRole = _discordGuildService.HasRole(response.Content);

                if (!hasNamedRole)
                {
                    await response.AddErrorEmote();

                    continue;
                }

                var namedRoleId = _discordGuildService.GetRoleId(response.Content);

                await _behaviourConfigurationService.SetStaffRole(namedRoleId);

                await response.AddSuccessEmote();

                break;
            }
        }
예제 #14
0
 public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
 {
     if (!context.Message.MentionedUserIds.Any() && !context.Message.MentionedRoleIds.Any())
     {
         return(TypeReaderResult.FromError(CommandError.Unsuccessful, "Could not parse, no mentions in message"));
     }
     if (MentionUtils.TryParseRole(input, out var roleId) && context.Guild.GetRole(roleId) is { } parsedRole)
     {
         return(TypeReaderResult.FromSuccess(parsedRole));
     }
     if (MentionUtils.TryParseUser(input, out var userId) && await context.Guild.GetUserAsync(userId) is { } parsedUser)
     {
         return(TypeReaderResult.FromSuccess(parsedUser));
     }
     return(TypeReaderResult.FromError(CommandError.ParseFailed, "Could not parse mention"));
 }
예제 #15
0
        public static IEnumerable <SocketUser> ParseUsers(DiscordSocketClient discord, string text, SocketGuild guild)
        {
            if (guild != null)
            {
                ulong roleId;
                if (MentionUtils.TryParseRole(text, out roleId))
                {
                    return(guild.Users.Where(u => u.Roles.Any(r => r.Id == roleId)));
                }
            }
            ulong channelId;

            if (MentionUtils.TryParseChannel(text, out channelId))
            {
                return(discord.GetChannel(channelId).Users);
            }
            var user = ParseUser(discord, text);

            return(user != null ? new[] { user } : null);
        }
예제 #16
0
        public override ValueTask <TypeParserResult <SocketRole> > ParseAsync(Parameter parameter, string value, CommandContext context,
                                                                              IServiceProvider provider)
        {
            var abyssContext = context.ToRequestContext();

            if (abyssContext.Guild == null)
            {
                return(new TypeParserResult <SocketRole>("Not applicable in a DM."));
            }
            var results = new Dictionary <ulong, RoleParseResult>();
            var roles   = abyssContext.Guild.Roles;

            //By Mention (1.0)
            if (MentionUtils.TryParseRole(value, out var id))
            {
                AddResult(results, abyssContext.Guild.GetRole(id), 1.00f);
            }

            //By Id (0.9)
            if (ulong.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out id))
            {
                AddResult(results, abyssContext.Guild.GetRole(id), 0.90f);
            }

            //By Name (0.7-0.8)
            foreach (var role in roles.Where(x => string.Equals(value, x.Name, StringComparison.OrdinalIgnoreCase)))
            {
                AddResult(results, role, role.Name == value ? 0.80f : 0.70f);
            }

            if (results.Count > 0 && results.Values.Count > 0)
            {
                return
                    (new TypeParserResult <SocketRole>(results.Values.OrderBy(a => a.Score).FirstOrDefault()?.Value));
            }

            return(new TypeParserResult <SocketRole>("Role not found."));
        }
예제 #17
0
        public override Task <TypeParserResult <TRole> > ParseAsync(Parameter parameter, string value, ICommandContext ctx, IServiceProvider provider)
        {
            var context = (AdminCommandContext)ctx;

            if (context.IsPrivate)
            {
                return(Task.FromResult(TypeParserResult <TRole> .Unsuccessful("requirecontext_guild")));
            }

            TRole role = null;

            // Parse by ID or mention
            if (ulong.TryParse(value, out var id) || MentionUtils.TryParseRole(value, out id))
            {
                role = context.Guild.GetRole(id) as TRole;
            }

            // Parse by name
            if (role is null)
            {
                var matches = context.Guild.Roles.Where(x => x.Name.Equals(value, StringComparison.OrdinalIgnoreCase))
                              .ToList();

                if (matches.Count > 1)
                {
                    return(Task.FromResult(
                               TypeParserResult <TRole> .Unsuccessful(context.Localize("roleparser_multiple"))));
                }

                role = matches.FirstOrDefault() as TRole;
            }

            return(Task.FromResult(!(role is null)
                ? TypeParserResult <TRole> .Successful(role)
                : TypeParserResult <TRole> .Unsuccessful(context.Localize("roleparser_notfound"))));
        }
예제 #18
0
        public static ImmutableArray <ITag> ParseTags(string text, IMessageChannel channel, IGuild guild, IReadOnlyCollection <IUser> userMentions)
        {
            var tags = ImmutableArray.CreateBuilder <ITag>();

            int index = 0;

            while (true)
            {
                index = text.IndexOf('<', index);
                if (index == -1)
                {
                    break;
                }
                int endIndex = text.IndexOf('>', index + 1);
                if (endIndex == -1)
                {
                    break;
                }
                string content = text.Substring(index, endIndex - index + 1);

                if (MentionUtils.TryParseUser(content, out ulong id))
                {
                    IUser mentionedUser = null;
                    foreach (var mention in userMentions)
                    {
                        if (mention.Id == id)
                        {
                            mentionedUser = channel?.GetUserAsync(id, CacheMode.CacheOnly).GetAwaiter().GetResult();
                            if (mentionedUser == null)
                            {
                                mentionedUser = mention;
                            }
                            break;
                        }
                    }
                    tags.Add(new Tag <IUser>(TagType.UserMention, index, content.Length, id, mentionedUser));
                }
                else if (MentionUtils.TryParseChannel(content, out id))
                {
                    IChannel mentionedChannel = null;
                    if (guild != null)
                    {
                        mentionedChannel = guild.GetChannelAsync(id, CacheMode.CacheOnly).GetAwaiter().GetResult();
                    }
                    tags.Add(new Tag <IChannel>(TagType.ChannelMention, index, content.Length, id, mentionedChannel));
                }
                else if (MentionUtils.TryParseRole(content, out id))
                {
                    IRole mentionedRole = null;
                    if (guild != null)
                    {
                        mentionedRole = guild.GetRole(id);
                    }
                    tags.Add(new Tag <IRole>(TagType.RoleMention, index, content.Length, id, mentionedRole));
                }
                else if (Emote.TryParse(content, out var emoji))
                {
                    tags.Add(new Tag <Emote>(TagType.Emoji, index, content.Length, emoji.Id, emoji));
                }
                else //Bad Tag
                {
                    index = index + 1;
                    continue;
                }
                index = endIndex + 1;
            }

            index = 0;
            while (true)
            {
                index = text.IndexOf("@everyone", index);
                if (index == -1)
                {
                    break;
                }

                var tagIndex = FindIndex(tags, index);
                if (tagIndex.HasValue)
                {
                    tags.Insert(tagIndex.Value, new Tag <object>(TagType.EveryoneMention, index, "@everyone".Length, 0, null));
                }
                index++;
            }

            index = 0;
            while (true)
            {
                index = text.IndexOf("@here", index);
                if (index == -1)
                {
                    break;
                }

                var tagIndex = FindIndex(tags, index);
                if (tagIndex.HasValue)
                {
                    tags.Insert(tagIndex.Value, new Tag <object>(TagType.HereMention, index, "@here".Length, 0, null));
                }
                index++;
            }

            return(tags.ToImmutable());
        }
예제 #19
0
        public static bool FromString(string input, ICommandContext context, out GuildRoleConfig roleConfig)
        {
            roleConfig = new GuildRoleConfig();

            input = input.ToLowerInvariant();

            string[] inputsplit = input.Split(' ');

            if (inputsplit.Where(x => x.StartsWith("cost=")).Any())
            {
                if (ulong.TryParse(inputsplit.LastOrDefault(x => x.StartsWith("cost=")).Replace("cost=", ""), out ulong result))
                {
                    roleConfig.Cost = result;
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                roleConfig.Cost = 0;
            }

            if (inputsplit.Where(x => x.StartsWith("require-level=")).Any())
            {
                if (ulong.TryParse(inputsplit.LastOrDefault(x => x.StartsWith("require-level=")).Replace("require-level=", ""), out ulong result))
                {
                    roleConfig.RequireLevel = result;
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                roleConfig.RequireLevel = 0;
            }

            if (inputsplit.Where(x => x.StartsWith("require-role=")).Any())
            {
                var first = inputsplit.LastOrDefault(x => x.StartsWith("require-role="));
                if (first["require-role=".Count()] == '"')
                {
                    var last = inputsplit.LastOrDefault(x => x.EndsWith("\""));

                    int firstIndex = 0;
                    int lastIndex  = 0;
                    for (var x = 0; x < inputsplit.Count(); x++)
                    {
                        if (inputsplit[x] == first)
                        {
                            firstIndex = x;
                        }
                        if (inputsplit[x] == last)
                        {
                            lastIndex = x;
                        }
                    }

                    var skipped = inputsplit.Skip(firstIndex).Take(lastIndex - firstIndex);
                }
                var   roleraw    = inputsplit.FirstOrDefault(x => x.StartsWith("require-role=")).Replace("require-role=", "");
                IRole role       = null;
                bool  gottenRole = true;

                if (MentionUtils.TryParseRole(roleraw, out ulong roleID))
                {
                    role = context.Guild.GetRole(roleID);
                }
                else
                {
                    gottenRole = false;
                }

                if (ulong.TryParse(roleraw, out roleID))
                {
                    role = context.Guild.GetRole(roleID);
                }
                else
                {
                    gottenRole = false;
                }

                if (!gottenRole)
                {
                    role = context.Guild.Roles.FirstOrDefault(x => x.Name.ToLowerInvariant() == roleraw.ToLowerInvariant());
                }

                if (role != null)
                {
                    roleConfig.RequiredRole = role;
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                roleConfig.RequiredRole = null;
            }

            if (inputsplit.Where(x => x.StartsWith("automatic=")).Any())
            {
                if (bool.TryParse(inputsplit.LastOrDefault(x => x.StartsWith("automatic=")).Replace("automatic=", ""), out bool result))
                {
                    roleConfig.Automatic = result;
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                roleConfig.Automatic = false;
            }

            return(true);
        }
예제 #20
0
        public static ImmutableArray <ITag> ParseTags(string text, IMessageChannel channel, IGuild guild, IReadOnlyCollection <IUser> userMentions)
        {
            var tags      = ImmutableArray.CreateBuilder <ITag>();
            int index     = 0;
            var codeIndex = 0;

            // checks if the tag being parsed is wrapped in code blocks
            bool CheckWrappedCode()
            {
                // util to check if the index of a tag is within the bounds of the codeblock
                bool EnclosedInBlock(Match m)
                => m.Groups[1].Index < index && index < m.Groups[2].Index;

                // loop through all code blocks that are before the start of the tag
                while (codeIndex < index)
                {
                    var blockMatch = BlockCodeRegex.Match(text, codeIndex);
                    if (blockMatch.Success)
                    {
                        if (EnclosedInBlock(blockMatch))
                        {
                            return(true);
                        }
                        // continue if the end of the current code was before the start of the tag
                        codeIndex += blockMatch.Groups[2].Index + blockMatch.Groups[2].Length;
                        if (codeIndex < index)
                        {
                            continue;
                        }
                        return(false);
                    }
                    var inlineMatch = InlineCodeRegex.Match(text, codeIndex);
                    if (inlineMatch.Success)
                    {
                        if (EnclosedInBlock(inlineMatch))
                        {
                            return(true);
                        }
                        // continue if the end of the current code was before the start of the tag
                        codeIndex += inlineMatch.Groups[2].Index + inlineMatch.Groups[2].Length;
                        if (codeIndex < index)
                        {
                            continue;
                        }
                        return(false);
                    }
                    return(false);
                }
                return(false);
            }

            while (true)
            {
                index = text.IndexOf('<', index);
                if (index == -1)
                {
                    break;
                }
                int endIndex = text.IndexOf('>', index + 1);
                if (endIndex == -1)
                {
                    break;
                }
                if (CheckWrappedCode())
                {
                    break;
                }
                string content = text.Substring(index, endIndex - index + 1);

                if (MentionUtils.TryParseUser(content, out ulong id))
                {
                    IUser mentionedUser = null;
                    foreach (var mention in userMentions)
                    {
                        if (mention.Id == id)
                        {
                            mentionedUser = channel?.GetUserAsync(id, CacheMode.CacheOnly).GetAwaiter().GetResult();
                            if (mentionedUser == null)
                            {
                                mentionedUser = mention;
                            }
                            break;
                        }
                    }
                    tags.Add(new Tag <IUser>(TagType.UserMention, index, content.Length, id, mentionedUser));
                }
                else if (MentionUtils.TryParseChannel(content, out id))
                {
                    IChannel mentionedChannel = null;
                    if (guild != null)
                    {
                        mentionedChannel = guild.GetChannelAsync(id, CacheMode.CacheOnly).GetAwaiter().GetResult();
                    }
                    tags.Add(new Tag <IChannel>(TagType.ChannelMention, index, content.Length, id, mentionedChannel));
                }
                else if (MentionUtils.TryParseRole(content, out id))
                {
                    IRole mentionedRole = null;
                    if (guild != null)
                    {
                        mentionedRole = guild.GetRole(id);
                    }
                    tags.Add(new Tag <IRole>(TagType.RoleMention, index, content.Length, id, mentionedRole));
                }
                else if (Emote.TryParse(content, out var emoji))
                {
                    tags.Add(new Tag <Emote>(TagType.Emoji, index, content.Length, emoji.Id, emoji));
                }
                else //Bad Tag
                {
                    index++;
                    continue;
                }
                index = endIndex + 1;
            }

            index     = 0;
            codeIndex = 0;
            while (true)
            {
                index = text.IndexOf("@everyone", index);
                if (index == -1)
                {
                    break;
                }
                if (CheckWrappedCode())
                {
                    break;
                }
                var tagIndex = FindIndex(tags, index);
                if (tagIndex.HasValue)
                {
                    tags.Insert(tagIndex.Value, new Tag <IRole>(TagType.EveryoneMention, index, "@everyone".Length, 0, guild?.EveryoneRole));
                }
                index++;
            }

            index     = 0;
            codeIndex = 0;
            while (true)
            {
                index = text.IndexOf("@here", index);
                if (index == -1)
                {
                    break;
                }
                if (CheckWrappedCode())
                {
                    break;
                }
                var tagIndex = FindIndex(tags, index);
                if (tagIndex.HasValue)
                {
                    tags.Insert(tagIndex.Value, new Tag <IRole>(TagType.HereMention, index, "@here".Length, 0, guild?.EveryoneRole));
                }
                index++;
            }

            return(tags.ToImmutable());
        }
예제 #21
0
            public async Task SetUpReactionRoleAsync()
            {
                var embed = new EmbedBuilder
                {
                    Description = $"Podaj link do wiadomości, która ma mieć reakcję",
                    Footer      = new EmbedFooterBuilder
                    {
                        Text = "Krok 1/3 | napisz 'cancel' aby anulować"
                    }
                }.Build();
                var msg = await ReplyAsync(embed : embed);

                var response = await NextMessageAsync(timeout : TimeSpan.FromMinutes(1));

                if (response == null)
                {
                    await msg.DeleteAsync();
                    await ReplyAsync("Czas minął, spróbuj jeszcze raz");

                    return;
                }
                else if (response.Content.ToLower() == "cancel")
                {
                    await msg.DeleteAsync();
                    await ReplyAsync("Tworzenie roli anulowane");

                    return;
                }

                var messageUrl   = response.Content;
                var messageSplit = messageUrl.Split('/');

                if (ulong.TryParse(messageSplit[4], out ulong guildId) &&
                    ulong.TryParse(messageSplit[5], out ulong channelId) &&
                    ulong.TryParse(messageSplit[6], out ulong messageId))

                {
                    if (guildId != Context.Guild.Id)
                    {
                        await ReplyAsync("Wiadomość nie jest z tego serwera");

                        return;
                    }
                    var channel = Context.Guild.GetTextChannel(channelId);
                    if (channel == null)
                    {
                        await ReplyAsync("Nieprawidłowy kanał");

                        return;
                    }
                    var message = await channel.GetMessageAsync(messageId);

                    if (message == null)
                    {
                        await ReplyAsync("Niaprawidłowa wiadomość");

                        return;
                    }

                    embed = new EmbedBuilder
                    {
                        Description = "Wybierz w jaki sposób reakcja ma działać:\n0 - daje i zabiera\n1 - tylko daje po zareagowaniu\n2 - tylko zabiera po zareagowaniu\n3 - daje jedną i zabiera inną",
                        Footer      = new EmbedFooterBuilder
                        {
                            Text = "Krok 2/3 | napisz 'cancel' aby anulować"
                        }
                    }.Build();

                    await response.DeleteAsync();

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

                    response = await NextMessageAsync(timeout : TimeSpan.FromMinutes(1));

                    if (response == null)
                    {
                        await msg.DeleteAsync();
                        await ReplyAsync("Czas minął, spróbuj jeszcze raz");

                        return;
                    }
                    else if (response.Content.ToLower() == "cancel")
                    {
                        await msg.DeleteAsync();
                        await ReplyAsync("Tworzenie roli anulowane");

                        return;
                    }

                    if (!int.TryParse(response.Content, out int actionNum))
                    {
                        await msg.DeleteAsync();
                        await ReplyAsync("Czy na pewno wiadomość zawierała odpowiednią zawartość?");

                        return;
                    }

                    var action = (ReactionAction)actionNum;

                    if (action == ReactionAction.GiveRemove || action == ReactionAction.Give || action == ReactionAction.Remove)
                    {
                        embed = new EmbedBuilder
                        {
                            Description = "Podaj reakcję i rolę w formacie: emoji - id roli/wzmianka/nazwa\nPrzykład: 🎶 - 722411980635504647\nNie używaj customowych emoji z innych serwerów!",
                            Footer      = new EmbedFooterBuilder
                            {
                                Text = "Krok 3/3 | napisz 'cancel' aby anulować"
                            }
                        }.Build();

                        await response.DeleteAsync();

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

                        response = await NextMessageAsync(timeout : TimeSpan.FromMinutes(1));

                        if (response == null)
                        {
                            await msg.DeleteAsync();
                            await ReplyAsync("Czas minął, spróbuj jeszcze raz");

                            return;
                        }
                        else if (response.Content.ToLower() == "cancel")
                        {
                            await msg.DeleteAsync();
                            await ReplyAsync("Tworzenie roli anulowane");

                            return;
                        }

                        IEmote emote;
                        if (Emote.TryParse(response.Content.Split('-')[0].Trim(), out Emote emoteTmp))
                        {
                            emote = emoteTmp;
                        }
                        else
                        {
                            emote = new Emoji(response.Content.Split('-')[0].Trim());
                        }
                        if (emote == null)
                        {
                            await ReplyAsync("Coś poszło nie tak, miałem problem z tą emotką");

                            return;
                        }

                        var roleString  = response.Content.Split('-')[1].Trim();
                        var roleResults = new Dictionary <ulong, TypeReaderValue>();

                        //By Mention (1.0)
                        if (MentionUtils.TryParseRole(roleString, out var id))
                        {
                            AddRoleResult(roleResults, Context.Guild.GetRole(id) as IRole, 1.00f);
                        }

                        //By Id (0.9)
                        if (ulong.TryParse(roleString, NumberStyles.None, CultureInfo.InvariantCulture, out id))
                        {
                            AddRoleResult(roleResults, Context.Guild.GetRole(id) as IRole, 0.90f);
                        }

                        //By Name (0.7-0.8)
                        foreach (var roleTmp in Context.Guild.Roles.Where(x => string.Equals(roleString, x.Name, StringComparison.OrdinalIgnoreCase)))
                        {
                            AddRoleResult(roleResults, roleTmp as IRole, roleTmp.Name == roleString ? 0.80f : 0.70f);
                        }

                        await response.DeleteAsync();

                        if (roleResults.Count == 0)
                        {
                            await msg.DeleteAsync();
                            await ReplyAsync("Coś poszło nie tak, czy rola została dobrze podana?");

                            return;
                        }

                        var role = (SocketRole) new List <TypeReaderValue>(roleResults.Values).OrderBy(x => x.Score).First().Value;

                        if (role == null)
                        {
                            await msg.DeleteAsync();
                            await ReplyAsync("Coś poszło nie tak, czy rola została dobrze podana?");

                            return;
                        }

                        if (_git.Config.Servers[guildId].ReactionRoles.ContainsKey(channelId) &&
                            _git.Config.Servers[guildId].ReactionRoles[channelId].ContainsKey(messageId) &&
                            _git.Config.Servers[guildId].ReactionRoles[channelId][messageId].Any(x => x.Roles.ContainsKey(emote.ToString())))
                        {
                            await msg.DeleteAsync();
                            await ReplyAsync("Ta emotka jest już wykorzystana w tej wiadomości na tym kanale");

                            return;
                        }

                        if (!_git.Config.Servers[guildId].ReactionRoles.ContainsKey(channelId))
                        {
                            _git.Config.Servers[guildId].ReactionRoles.Add(channelId, new Dictionary <ulong, List <ReactionRole> >());
                        }
                        if (!_git.Config.Servers[guildId].ReactionRoles[channelId].ContainsKey(messageId))
                        {
                            _git.Config.Servers[guildId].ReactionRoles[channelId].Add(messageId, new List <ReactionRole>());
                        }

                        _git.Config.Servers[guildId].ReactionRoles[channelId][messageId].Add(new ReactionRole
                        {
                            Action = action,
                            Roles  = new Dictionary <string, ulong>()
                            {
                                { emote.ToString(), role.Id }
                            }
                        });

                        await(await Context.Guild.GetTextChannel(channelId).GetMessageAsync(messageId)).AddReactionAsync(emote);
                        await msg.ModifyAsync((x) =>
                        {
                            x.Content = "Utworzono pomyślnie";
                            x.Embed   = null;
                        });

                        await _git.UploadConfig();
                    }
                    else if (action == ReactionAction.OneOfMany)
                    {
                        await response.DeleteAsync();

                        Dictionary <string, ulong> roleKvp = new Dictionary <string, ulong>();
                        List <IEmote> emotes = new List <IEmote>();

                        embed = new EmbedBuilder
                        {
                            Description = "Podaj reakcję i rolę w formacie: emoji - id roli/wzmianka/nazwa\nPrzykład: 🎶 - 722411980635504647\nPodaj co najmniej 2 reakcje\nGdy podasz wszystkie reakcje które chcesz, wyślij wiadomość 'continue'\nNie używaj customowych emoji z innych serwerów!",
                            Footer      = new EmbedFooterBuilder
                            {
                                Text = "Krok 3/3 | napisz 'cancel' aby anulować"
                            }
                        }.Build();
                        await msg.ModifyAsync((x) =>
                        {
                            x.Embed = embed;
                        });

                        bool finished = false;

                        do
                        {
                            response = await NextMessageAsync(timeout : TimeSpan.FromMinutes(1));

                            if (response == null)
                            {
                                await msg.DeleteAsync();
                                await ReplyAndDeleteAsync("Czas minął, spróbuj jeszcze raz", timeout : TimeSpan.FromSeconds(2));

                                continue;
                            }
                            else if (response.Content.ToLower() == "cancel")
                            {
                                await msg.DeleteAsync();
                                await ReplyAsync("Tworzenie roli anulowane");

                                return;
                            }
                            else if (response.Content.ToLower() == "continue")
                            {
                                finished = true;
                                await response.DeleteAsync();

                                continue;
                            }

                            IEmote emote;
                            if (Emote.TryParse(response.Content.Split('-')[0].Trim(), out Emote emoteTmp))
                            {
                                emote = emoteTmp;
                            }
                            else
                            {
                                emote = new Emoji(response.Content.Split('-')[0].Trim());
                            }
                            if (emote == null)
                            {
                                await ReplyAndDeleteAsync("Coś poszło nie tak, spróbuj ponownie lub anuluj", timeout : TimeSpan.FromSeconds(2));

                                continue;
                            }

                            var roleString  = response.Content.Split('-')[1].Trim();
                            var roleResults = new Dictionary <ulong, TypeReaderValue>();

                            //By Mention (1.0)
                            if (MentionUtils.TryParseRole(roleString, out var id))
                            {
                                AddRoleResult(roleResults, Context.Guild.GetRole(id) as IRole, 1.00f);
                            }

                            //By Id (0.9)
                            if (ulong.TryParse(roleString, NumberStyles.None, CultureInfo.InvariantCulture, out id))
                            {
                                AddRoleResult(roleResults, Context.Guild.GetRole(id) as IRole, 0.90f);
                            }

                            //By Name (0.7-0.8)
                            foreach (var roleTmp in Context.Guild.Roles.Where(x => string.Equals(roleString, x.Name, StringComparison.OrdinalIgnoreCase)))
                            {
                                AddRoleResult(roleResults, roleTmp as IRole, roleTmp.Name == roleString ? 0.80f : 0.70f);
                            }

                            await response.DeleteAsync();

                            if (roleResults.Count == 0)
                            {
                                await ReplyAndDeleteAsync("Coś poszło nie tak, czy rola została dobrze podana?", timeout : TimeSpan.FromSeconds(2));

                                continue;
                            }

                            var role = (SocketRole) new List <TypeReaderValue>(roleResults.Values).OrderBy(x => x.Score).First().Value;

                            if (role == null)
                            {
                                await ReplyAndDeleteAsync("Coś poszło nie tak, czy rola została dobrze podana?", timeout : TimeSpan.FromSeconds(2));

                                continue;
                            }

                            if (_git.Config.Servers[guildId].ReactionRoles.ContainsKey(channelId) &&
                                _git.Config.Servers[guildId].ReactionRoles[channelId].ContainsKey(messageId) &&
                                _git.Config.Servers[guildId].ReactionRoles[channelId][messageId].Any(x => x.Roles.ContainsKey(emote.ToString())))
                            {
                                await ReplyAndDeleteAsync("Ta emotka jest już wykorzystana w tej wiadomości na tym kanale", timeout : TimeSpan.FromSeconds(2));

                                continue;
                            }

                            await ReplyAndDeleteAsync("Dodano rolę", timeout : TimeSpan.FromSeconds(1));

                            emotes.Add(emote);

                            roleKvp.Add(emote.ToString(), role.Id);
                        } while (!finished);

                        if (!_git.Config.Servers[guildId].ReactionRoles.ContainsKey(channelId))
                        {
                            _git.Config.Servers[guildId].ReactionRoles.Add(channelId, new Dictionary <ulong, List <ReactionRole> >());
                        }
                        if (!_git.Config.Servers[guildId].ReactionRoles[channelId].ContainsKey(messageId))
                        {
                            _git.Config.Servers[guildId].ReactionRoles[channelId].Add(messageId, new List <ReactionRole>());
                        }

                        _git.Config.Servers[guildId].ReactionRoles[channelId][messageId].Add(new ReactionRole
                        {
                            Action = action,
                            Roles  = roleKvp
                        });

                        foreach (var emote in emotes)
                        {
                            await(await Context.Guild.GetTextChannel(channelId).GetMessageAsync(messageId)).AddReactionAsync(emote);
                        }

                        await msg.ModifyAsync((x) =>
                        {
                            x.Content = "Utworzono pomyślnie";
                            x.Embed   = null;
                        });

                        await _git.UploadConfig();
                    }
                    else
                    {
                        await msg.DeleteAsync();
                        await ReplyAndDeleteAsync($"Zły numer - powinien być: 0, 1, 2, 3; otrzymano: {actionNum}", timeout : TimeSpan.FromSeconds(5));
                    }
                }
            }