示例#1
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"));
        }
示例#2
0
        public override ValueTask <TypeParserResult <CachedGuild> > ParseAsync(Parameter parameter, string value, CommandContext ctx)
        {
            var context = (AdminCommandContext)ctx;

            CachedGuild guild = null;

            // parse by ID
            if (ulong.TryParse(value, out var id) && id > 0)
            {
                guild = context.Client.GetGuild(id);
            }

            if (guild is null)
            {
                var matchingGuilds =
                    context.Client.Guilds.Values.Where(x => x.Name.Equals(value, StringComparison.OrdinalIgnoreCase))
                    .ToList();

                if (matchingGuilds.Count > 1)
                {
                    return(TypeParserResult <CachedGuild> .Unsuccessful(context.Localize("guildparser_multiple")));
                }

                guild = matchingGuilds.FirstOrDefault();
            }

            return(!(guild is null)
                ? TypeParserResult <CachedGuild> .Successful(guild)
                : TypeParserResult <CachedGuild> .Unsuccessful(context.Localize("guildparser_notfound")));
        }
示例#3
0
        public override ValueTask <TypeParserResult <SocketRole> > ParseAsync(
            Parameter param,
            string value,
            CommandContext context,
            IServiceProvider provider)
        {
            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> .Unsuccessful(
                               "Multiple roles found. Try mentioning the role or using its ID."));
                }

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

            return(role is null
                ? TypeParserResult <SocketRole> .Unsuccessful($"Role `{value}` not found.")
                : TypeParserResult <SocketRole> .Successful(role));
        }
示例#4
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));
        }
示例#5
0
        public override async ValueTask <TypeParserResult <IMessage> > ParseAsync(Parameter parameter, string value, ScrapContext context)
        {
            var      messages = context.Channel.CachedMessages;
            IMessage message  = null;

            if (ulong.TryParse(value, out ulong id))
            {
                message = await context.Channel.GetMessageAsync(id);
            }

            if (message is null)
            {
                var match = messages.Where(x =>
                                           x.Content.EqualsIgnoreCase(value));
                if (match.Count() > 1)
                {
                    return(TypeParserResult <IMessage> .Unsuccessful(
                               "Multiple messages found, try using its ID."));
                }

                message = match.FirstOrDefault();
            }
            return(message is null
                ? TypeParserResult <IMessage> .Unsuccessful("Message not found.")
                : TypeParserResult <IMessage> .Successful(message));
        }
示例#6
0
        public override ValueTask <TypeParserResult <Color> > ParseAsync(Parameter parameter, string value, CommandContext context)
        {
            var valueSpan = value.AsSpan();

            if (valueSpan.Length > 2)
            {
                var valid = false;
                if (valueSpan[0] == '0' && (valueSpan[1] == 'x' || valueSpan[1] == 'X') && valueSpan.Length == 8)
                {
                    valid     = true;
                    valueSpan = valueSpan.Slice(2);
                }
                else if (value[0] == '#' && value.Length == 7)
                {
                    valid     = true;
                    valueSpan = valueSpan.Slice(1);
                }

                if (valid && int.TryParse(valueSpan, NumberStyles.HexNumber, null, out var result))
                {
                    return(TypeParserResult <Color> .Successful(result));
                }
            }

            return(TypeParserResult <Color> .Unsuccessful("Invalid color hex value provided."));
        }
示例#7
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)));
        }
示例#8
0
        public override ValueTask <TypeParserResult <IEmoji> > ParseAsync(Parameter parameter, string value, CommandContext ctx)
        {
            var context = (AdminCommandContext)ctx;
            var random  = context.ServiceProvider.GetRequiredService <Random>();
            var validSearchableEmojis = context.Client.Guilds.Values.SelectMany(x => x.Emojis.Values).ToList();

            if (!EmojiTools.TryParse(value, out var emoji))
            {
                if (Snowflake.TryParse(value, out var id))
                {
                    emoji = validSearchableEmojis.FirstOrDefault(x => x.Id == id);
                }
                else
                {
                    var matchingEmojis = validSearchableEmojis
                                         .Where(x => x.Name.Equals(value, StringComparison.OrdinalIgnoreCase)).ToList();

                    if (matchingEmojis.Count > 0 && !parameter.Checks.OfType <RequireGuildEmojiAttribute>().Any())
                    {
                        emoji = matchingEmojis.GetRandomElement(random);
                    }
                }
            }

            return(!(emoji is null)
                ? TypeParserResult <IEmoji> .Successful(emoji)
                : TypeParserResult <IEmoji> .Unsuccessful(context.Localize("emojiparser_notfound")));
        }
示例#9
0
        public override ValueTask <TypeParserResult <SocketGuild> > ParseAsync(
            Parameter parameter,
            string value,
            CommandContext context,
            IServiceProvider provider)
        {
            var         ctx   = context.Cast <VolteContext>();
            SocketGuild guild = default;

            var guilds = ctx.Client.Guilds;

            if (ulong.TryParse(value, out var id))
            {
                guild = guilds.FirstOrDefault(x => x.Id == id);
            }

            if (guild is null)
            {
                var match = guilds.Where(x =>
                                         x.Name.EqualsIgnoreCase(value)).ToList();
                if (match.Count > 1)
                {
                    return(TypeParserResult <SocketGuild> .Unsuccessful(
                               "Multiple guilds found with that name, try using its ID."));
                }

                guild = match.FirstOrDefault();
            }

            return(guild is null
                ? TypeParserResult <SocketGuild> .Unsuccessful("Guild not found.")
                : TypeParserResult <SocketGuild> .Successful(guild));
        }
示例#10
0
        public override ValueTask <TypeParserResult <SocketTextChannel> > ParseAsync(
            Parameter param,
            string value,
            CommandContext context,
            IServiceProvider provider)
        {
            var ctx = context.Cast <VolteContext>();
            SocketTextChannel channel = default;

            if (ulong.TryParse(value, out var id) || MentionUtils.TryParseChannel(value, out id))
            {
                channel = ctx.Client.GetChannel(id).Cast <SocketTextChannel>();
            }

            if (channel is null)
            {
                var match = ctx.Guild.TextChannels.Where(x => x.Name.EqualsIgnoreCase(value))
                            .ToList();
                if (match.Count > 1)
                {
                    return(new ValueTask <TypeParserResult <SocketTextChannel> >(TypeParserResult <SocketTextChannel> .Unsuccessful(
                                                                                     "Multiple channels found. Try mentioning the channel or using its ID.")));
                }
            }

            return(channel is null
                ? TypeParserResult <SocketTextChannel> .Unsuccessful("Channel not found.")
                : TypeParserResult <SocketTextChannel> .Successful(channel));
        }
        public override ValueTask <TypeParserResult <DateTimeOffset> > ParseAsync(Parameter parameter, string value, MummyContext context)
        {
            DateTimeOffset dateTimeOffset = new DateTimeOffset(DateTime.MinValue, TimeSpan.Zero);

            if (!value.EndsWith("dmy", StringComparison.CurrentCultureIgnoreCase) && !value.EndsWith("mdy", StringComparison.CurrentCultureIgnoreCase))
            {
                return(TypeParserResult <DateTimeOffset> .Unsuccessful("failed to parse expected mdy or dmy"));
            }
            if (value.EndsWith("dmy", StringComparison.CurrentCultureIgnoreCase))
            {
                var time = value.Substring(0, value.IndexOf("dmy"));
                if (!DateTimeOffset.TryParse(time, CultureInfo.CurrentCulture, styles: DateTimeStyles.AssumeUniversal, out dateTimeOffset))
                {
                    return(TypeParserResult <DateTimeOffset> .Unsuccessful("failed to parse time (something doesnt look right in the time part)"));
                }
            }
            if (value.EndsWith("mdy", StringComparison.CurrentCultureIgnoreCase))
            {
                var time = value.Substring(0, value.IndexOf("mdy"));
                if (!DateTimeOffset.TryParse(time, CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.AssumeUniversal, out dateTimeOffset))
                {
                    return(TypeParserResult <DateTimeOffset> .Unsuccessful("failed to parse time (something doesnt look right in the time part)"));
                }
            }
            if (dateTimeOffset != new DateTimeOffset(DateTime.MinValue, TimeSpan.Zero))
            {
                return(TypeParserResult <DateTimeOffset> .Successful(dateTimeOffset));
            }

            return(TypeParserResult <DateTimeOffset> .Unsuccessful("something went badly wrong and i entirely failed to parse your time"));
        }
示例#12
0
        ParseAsync(Parameter parameter, string value, CommandContext context)
        {
            if (LocalCustomEmoji.TryParse(value, out var localCustomEmoji))
            {
                return(TypeParserResult <IEmoji> .Successful(localCustomEmoji));
            }

            if (emojis == null)
            {
                await Locker.WaitAsync();

                try
                {
                    await GetEmojis();
                }
                finally
                {
                    Locker.Release();
                }
            }

            var match = emojis.FirstOrDefault(x => x.Surrogates == value ||
                                              x.NamesWithColons.Any(n => n.Equals(value, System.StringComparison.OrdinalIgnoreCase)) ||
                                              x.Names.Any(n => n.Equals(value, System.StringComparison.OrdinalIgnoreCase)));

            if (match != null)
            {
                var localEmoji = new LocalEmoji(match.Surrogates);
                return(TypeParserResult <IEmoji> .Successful(localEmoji));
            }

            return(TypeParserResult <IEmoji> .Unsuccessful("Invalid custom emoji format."));
        }
示例#13
0
        public override ValueTask <TypeParserResult <IUser> > ParseAsync(Parameter param, string value, ScrapContext context)
        {
            var   users = context.Guild.Users.OfType <IUser>().ToList();
            IUser user  = null;

            if (ulong.TryParse(value, out ulong id) || MentionUtils.TryParseUser(value, out id))
            {
                user = context.Client.GetUser(id);
            }

            if (user is null)
            {
                var match = users.Where(x =>
                                        x.Username.EqualsIgnoreCase(value) ||
                                        (x as SocketGuildUser).Nickname.EqualsIgnoreCase(value)).ToList();
                if (match.Count() > 1)
                {
                    return(TypeParserResult <IUser> .Unsuccessful(
                               "Multiple users found, try mentioning the user or using their ID."));
                }

                user = match.FirstOrDefault();
            }
            return(user is null
                ? TypeParserResult <IUser> .Unsuccessful("User not found.")
                : TypeParserResult <IUser> .Successful(user));
        }
示例#14
0
        public override ValueTask <TypeParserResult <ITextChannel> > ParseAsync(Parameter param, string value, ScrapContext context)
        {
            var          channels = context.Guild.Channels.OfType <ITextChannel>().ToList();
            ITextChannel channel  = null;

            if (ulong.TryParse(value, out ulong id) || MentionUtils.TryParseChannel(value, out id))
            {
                channel = context.Client.GetChannel(id) as ITextChannel;
            }

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

                channel = match.FirstOrDefault();
            }
            return(channel is null
                ? TypeParserResult <ITextChannel> .Unsuccessful("User not found.")
                : TypeParserResult <ITextChannel> .Successful(channel));
        }
示例#15
0
        public override async Task <TypeParserResult <TChannel> > ParseAsync(
            Parameter param,
            string value,
            ICommandContext context,
            IServiceProvider provider)
        {
            var      ctx     = (DepressedBotContext)context;
            TChannel channel = null;

            if (ulong.TryParse(value, out var id) || MentionUtils.TryParseChannel(value, out id))
            {
                channel = (await ctx.Guild.GetTextChannelsAsync()).FirstOrDefault(x => x.Id == id) as TChannel;
            }

            if (channel is null)
            {
                var match = (await ctx.Guild.GetTextChannelsAsync()).Where(x => x.Name.EqualsIgnoreCase(value))
                            .ToList();
                if (match.Count > 1)
                {
                    return(TypeParserResult <TChannel> .Unsuccessful(
                               "Multiple channels found. Try mentioning the channel or using its ID."));
                }
            }

            return(channel is null
                ? TypeParserResult <TChannel> .Unsuccessful("Channel not found.")
                : TypeParserResult <TChannel> .Successful(channel));
        }
        public override ValueTask <TypeParserResult <CachedVoiceChannel> > ParseAsync(Parameter parameter, string value, RiasCommandContext context)
        {
            var localization = context.ServiceProvider.GetRequiredService <Localization>();

            if (context.Guild is null)
            {
                return(TypeParserResult <CachedVoiceChannel> .Unsuccessful(localization.GetText(context.Guild?.Id, Localization.TypeParserCachedVoiceChannelNotGuild)));
            }

            CachedVoiceChannel channel;

            if (Snowflake.TryParse(value, out var id))
            {
                channel = context.Guild.GetVoiceChannel(id);
                if (channel != null)
                {
                    return(TypeParserResult <CachedVoiceChannel> .Successful(channel));
                }
            }

            channel = context.Guild.VoiceChannels.FirstOrDefault(c => string.Equals(c.Value.Name, value, StringComparison.OrdinalIgnoreCase)).Value;
            if (channel != null)
            {
                return(TypeParserResult <CachedVoiceChannel> .Successful(channel));
            }

            if (parameter.IsOptional)
            {
                return(TypeParserResult <CachedVoiceChannel> .Successful((CachedVoiceChannel)parameter.DefaultValue));
            }

            return(TypeParserResult <CachedVoiceChannel> .Unsuccessful(localization.GetText(context.Guild?.Id, Localization.AdministrationVoiceChannelNotFound)));
        }
示例#17
0
        public override async ValueTask <TypeParserResult <IUser> > ParseAsync(Parameter parameter, string value, RiasCommandContext context)
        {
            var cachedMemberTypeParser = await new CachedMemberTypeParser().ParseAsync(parameter, value, context);

            if (cachedMemberTypeParser.IsSuccessful)
            {
                return(TypeParserResult <IUser> .Successful(cachedMemberTypeParser.Value));
            }

            var   localization = context.ServiceProvider.GetRequiredService <Localization>();
            IUser?user         = null;

            if (Snowflake.TryParse(value, out var id))
            {
                user = await context.ServiceProvider.GetRequiredService <Rias>().GetUserAsync(id);
            }

            if (user != null)
            {
                return(TypeParserResult <IUser> .Successful(user));
            }

            if (parameter.IsOptional)
            {
                return(TypeParserResult <IUser> .Successful((CachedMember)parameter.DefaultValue));
            }

            return(TypeParserResult <IUser> .Unsuccessful(localization.GetText(context.Guild?.Id, Localization.AdministrationUserNotFound)));
        }
示例#18
0
        public override ValueTask <TypeParserResult <CachedRole> > ParseAsync(Parameter parameter, string value, CommandContext ctx)
        {
            var context = (AdminCommandContext)ctx;

            if (context.IsPrivate)
            {
                return(TypeParserResult <CachedRole> .Unsuccessful(context.Localize("requirecontext_guild")));
            }

            CachedRole role = null;

            // Parse by ID or mention
            if (Snowflake.TryParse(value, out var id) || Discord.TryParseRoleMention(value, out id))
            {
                role = context.Guild.GetRole(id);
            }

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

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

                role = matches.FirstOrDefault();
            }

            return(!(role is null)
                ? TypeParserResult <CachedRole> .Successful(role)
                : TypeParserResult <CachedRole> .Unsuccessful(context.Localize("roleparser_notfound")));
        }
示例#19
0
 public override ValueTask <TypeParserResult <Uri> > ParseAsync(Parameter parameter, string value, CommandContext context,
                                                                IServiceProvider provider)
 {
     return(Uri.IsWellFormedUriString(value, UriKind.Absolute)
         ? TypeParserResult <Uri> .Successful(new Uri(value))
         : TypeParserResult <Uri> .Unsuccessful("Unknown URL."));
 }
示例#20
0
        public override ValueTask <TypeParserResult <Color> > ParseAsync(Parameter parameter, string value, RiasCommandContext context)
        {
            var hex = RiasUtilities.HexToInt(value);

            if (hex.HasValue)
            {
                return(TypeParserResult <Color> .Successful(new Color(hex.Value)));
            }

            var color = default(System.Drawing.Color);

            if (Enum.TryParse <System.Drawing.KnownColor>(value.Replace(" ", ""), true, out var knownColor))
            {
                color = System.Drawing.Color.FromKnownColor(knownColor);
            }

            if (!color.IsEmpty)
            {
                return(TypeParserResult <Color> .Successful(new Color(color.R, color.G, color.B)));
            }

            if (parameter.IsOptional)
            {
                return(TypeParserResult <Color> .Successful((Color)parameter.DefaultValue));
            }

            var localization = context.ServiceProvider.GetRequiredService <Localization>();

            return(TypeParserResult <Color> .Unsuccessful(localization.GetText(context.Guild?.Id, Localization.TypeParserInvalidColor)));
        }
示例#21
0
        public override ValueTask <TypeParserResult <Color> > ParseAsync(Parameter parameter, string value, MummyContext context)
        {
            if (value.StartsWith("0x", StringComparison.CurrentCultureIgnoreCase) ||
                value.StartsWith("&H", StringComparison.CurrentCultureIgnoreCase))
            {
                value = value.Substring(2);
            }
            if (value.StartsWith("#", StringComparison.CurrentCultureIgnoreCase))
            {
                value = value.Substring(1);
            }

            Color color;

            if (int.TryParse(value, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var hex))
            {
                color = new Color(hex);
                return(TypeParserResult <Color> .Successful(color));
            }
            else if (IsRGB(value, out (int red, int green, int blue)rgb))
            {
                color = new Color(rgb.red, rgb.green, rgb.blue);
                return(TypeParserResult <Color> .Successful(color));
            }
            else
            {
                return(TypeParserResult <Color> .Unsuccessful("Could not parse color"));
            }
        }
示例#22
0
 public override ValueTask <TypeParserResult <Uri> > ParseAsync(Parameter parameter, string value,
                                                                CommandContext context)
 {
     value = value.Replace("<", "").Replace(">", "");
     return(Uri.IsWellFormedUriString(value, UriKind.Absolute)
         ? TypeParserResult <Uri> .Successful(new Uri(value))
         : TypeParserResult <Uri> .Unsuccessful("Unknown URL."));
 }
示例#23
0
 public override ValueTask <TypeParserResult <IEmote> > ParseAsync(
     Parameter param,
     string value,
     CommandContext context,
     IServiceProvider provider)
 => Emote.TryParse(value, out var emote)
         ? TypeParserResult <IEmote> .Successful(emote)
         : Regex.Match(value, "[^\u0000-\u007F]+", RegexOptions.IgnoreCase).Success
             ? TypeParserResult <IEmote> .Successful(new Emoji(value))
             : TypeParserResult <IEmote> .Unsuccessful("Emote not found.");
示例#24
0
        public override ValueTask <TypeParserResult <TimeSpan> > ParseAsync(Parameter parameter, string input, CommandContext context)
        {
            var result = input.ParseAsTimeSpan(out var timespan);

            if (result == TimeSpanParseResult.Success)
            {
                return(TypeParserResult <TimeSpan> .Successful(timespan));
            }
            return(TypeParserResult <TimeSpan> .Unsuccessful(result.ToString()));
        }
示例#25
0
        public override ValueTask <TypeParserResult <Command> > ParseAsync(Parameter parameter, string value, ScrapContext context)
        {
            var _commands = context.ServiceProvider.GetService <CommandService>();

            var command = _commands.FindCommands(value).FirstOrDefault()?.Command;

            return(command == null
                ? TypeParserResult <Command> .Unsuccessful("Could not find a command matching your input!")
                : TypeParserResult <Command> .Successful(command));
        }
        public override ValueTask <TypeParserResult <TChannel> > ParseAsync(Parameter parameter, string value, CommandContext ctx)
        {
            var context = (AdminCommandContext)ctx;

            if (context.IsPrivate)
            {
                return(TypeParserResult <TChannel> .Unsuccessful(context.Localize("requirecontext_guild")));
            }

            TChannel channel = null;
            IEnumerable <TChannel> channels;

            if (typeof(CachedVoiceChannel).IsAssignableFrom(typeof(TChannel)))
            {
                channels = context.Guild.VoiceChannels.Values.OfType <TChannel>().ToList();
            }
            else if (typeof(CachedCategoryChannel).IsAssignableFrom(typeof(TChannel)))
            {
                channels = context.Guild.CategoryChannels.Values.OfType <TChannel>().ToList();
            }
            else if (typeof(CachedTextChannel).IsAssignableFrom(typeof(TChannel)))
            {
                channels = context.Guild.TextChannels.Values.OfType <TChannel>().ToList();
            }
            else
            {
                channels = context.Guild.Channels.Values.OfType <TChannel>().ToList();
            }


            // Parse by channel ID (or text channel mention)
            if (Snowflake.TryParse(value, out var id) || Discord.TryParseChannelMention(value, out id))
            {
                channel = channels.FirstOrDefault(x => x.Id == id);
            }

            // Parse by channel name
            if (channel is null)
            {
                var matchingChannels = channels
                                       .Where(x => x.Name.Equals(value, StringComparison.OrdinalIgnoreCase))
                                       .ToList();

                if (matchingChannels.Count > 1)
                {
                    return(TypeParserResult <TChannel> .Unsuccessful(context.Localize("channelparser_multiple")));
                }

                channel = matchingChannels.FirstOrDefault();
            }

            return(!(channel is null)
                ? TypeParserResult <TChannel> .Successful(channel)
                : TypeParserResult <TChannel> .Unsuccessful(context.Localize("channelparser_notfound")));
        }
示例#27
0
        public override ValueTask <TypeParserResult <CachedMember> > ParseAsync(Parameter parameter, string value, CommandContext _)
        {
            var context = (DiscordCommandContext)_;

            if (context.Guild == null)
            {
                throw new InvalidOperationException("This can only be used in a guild.");
            }

            CachedMember member = null;

            if (Discord.TryParseUserMention(value, out var id) || Snowflake.TryParse(value, out id))
            {
                context.Guild.Members.TryGetValue(id, out member);
            }

            var values = context.Guild.Members.Values;

            if (member == null)
            {
                var hashIndex = value.LastIndexOf('#');
                if (hashIndex != -1 && hashIndex + 5 == value.Length)
                {
                    member = values.FirstOrDefault(x =>
                    {
                        var valueSpan         = value.AsSpan();
                        var nameSpan          = valueSpan.Slice(0, value.Length - 5);
                        var discriminatorSpan = valueSpan.Slice(hashIndex + 1);
                        return(x.Name.AsSpan().Equals(nameSpan, default) &&
                               x.Discriminator.AsSpan().Equals(discriminatorSpan, default));
                    });
                }
            }

            if (member == null)
            {
                // TODO custom result type returning the members?
                var matchingMembers = values.Where(x => x.Name == value || x.Nick == value).ToArray();
                if (matchingMembers.Length > 1)
                {
                    return(TypeParserResult <CachedMember> .Unsuccessful("Multiple matches found. Mention the member, use their tag or their ID."));
                }

                if (matchingMembers.Length == 1)
                {
                    member = matchingMembers[0];
                }
            }

            return(member == null
                ? TypeParserResult <CachedMember> .Unsuccessful("No member found matching the input.")
                : TypeParserResult <CachedMember> .Successful(member));
        }
        public override ValueTask <TypeParserResult <LocalizedLanguage> > ParseAsync(Parameter parameter, string value, CommandContext ctx)
        {
            var context      = (AdminCommandContext)ctx;
            var localization = context.ServiceProvider.GetRequiredService <LocalizationService>();

            return(localization.Languages.FirstOrDefault(x =>
                                                         x.CultureCode.Equals(value, StringComparison.OrdinalIgnoreCase) ||
                                                         x.EnglishName.Equals(value, StringComparison.OrdinalIgnoreCase) ||
                                                         x.NativeName.Equals(value, StringComparison.OrdinalIgnoreCase)) is { } language
                ? TypeParserResult <LocalizedLanguage> .Successful(language)
                : TypeParserResult <LocalizedLanguage> .Unsuccessful(context.Localize("languageparser_notfound")));
        }
示例#29
0
        public override ValueTask <TypeParserResult <Tag> > ParseAsync(
            Parameter parameter,
            string value,
            CommandContext context,
            IServiceProvider provider)
        {
            var ctx = context.Cast <VolteContext>();
            var tag = ctx.GuildData.Extras.Tags.FirstOrDefault(x => x.Name.EqualsIgnoreCase(value));

            return(tag is null
                ? TypeParserResult <Tag> .Unsuccessful($"The tag **{value}** doesn't exist in this guild. " +
                                                       $"Try using the `{ctx.GuildData.Configuration.CommandPrefix}tags` command to see all tags in this guild.")
                : TypeParserResult <Tag> .Successful(tag));
        }
示例#30
0
 public override ValueTask <TypeParserResult <bool> > ParseAsync(Parameter parameter, string value, MummyContext context)
 {
     if (value.Equals("on", StringComparison.CurrentCultureIgnoreCase))
     {
         return(TypeParserResult <bool> .Successful(true));
     }
     else if (value.Equals("off", StringComparison.CurrentCultureIgnoreCase))
     {
         return(TypeParserResult <bool> .Successful(false));
     }
     else
     {
         return(TypeParserResult <bool> .Unsuccessful($"could not parse {parameter.Name} as on/off"));
     }
 }