Example #1
0
        public override Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            switch (input.ToLower())
            {
            case "0":
            case "stats":
            case "statystyki":
                return(Task.FromResult(TypeReaderResult.FromSuccess(ProfileType.Stats)));

            case "1":
            case "image":
            case "obrazek":
                return(Task.FromResult(TypeReaderResult.FromSuccess(ProfileType.Img)));

            case "2":
            case "ugly":
            case "brzydkie":
                return(Task.FromResult(TypeReaderResult.FromSuccess(ProfileType.StatsWithImg)));

            case "3":
            case "cards":
            case "karcianka":
                return(Task.FromResult(TypeReaderResult.FromSuccess(ProfileType.Cards)));

            default:
                return(Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "Nie rozpoznano typu nastawy!")));
            }
        }
Example #2
0
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            var defaultRes = await base.ReadAsync(context, input, services);

            if (defaultRes.IsSuccess)
            {
                return(TypeReaderResult.FromSuccess(new DiscordUser(defaultRes.BestMatch as IUser)));
            }

            if (!MentionUtils.TryParseUser(input, out var uid) && !ulong.TryParse(input, out uid))
            {
                return(TypeReaderResult.FromError(CommandError.ParseFailed, "Could not find User"));
            }
            if (!SnowFlakeUtils.IsValidSnowflake(uid))
            {
                return(TypeReaderResult.FromError(CommandError.ParseFailed, "Could not find User"));
            }

            // We could at least get a uid.
            // Use our user services
            var userService = services.GetRequiredService <IUserService>();
            var user        = await userService.GetOrSetAndGet(uid);

            if (!user.HasValue)
            {
                return(TypeReaderResult.FromError(CommandError.ParseFailed, "Could not find User"));
            }

            return(TypeReaderResult.FromSuccess(new DiscordUser(~user)));
        }
Example #3
0
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            var baseResult = await base.ReadAsync(context, input, services);

            if (baseResult.IsSuccess)
            {
                return(TypeReaderResult.FromSuccess(DiscordUserEntity.FromIUser(baseResult.BestMatch as IUser)));
            }

            if (ulong.TryParse(input, out var uid))
            {
                //Any ulong is technically a valid snowflake, but we try to do some basic validation
                //by parsing the timestamp (in ms) part out of it - we consider it to be an invalid snowflake if:
                // - it's less than or equal to the discord epoch baseline
                // - it's greater than or equal to the current timestamp
                var        snowflakeTimestamp   = (long)(uid >> 22);
                const long discordEpochUnixTime = 1420070400000;

                //Jan 1, 2015
                var discordEpoch = DateTimeOffset.FromUnixTimeMilliseconds(discordEpochUnixTime);

                //The supposed timestamp
                var snowFlakeDateTime = DateTimeOffset.FromUnixTimeMilliseconds(snowflakeTimestamp + discordEpochUnixTime);
                if (snowFlakeDateTime <= discordEpoch || snowFlakeDateTime >= DateTimeOffset.UtcNow)
                {
                    return(TypeReaderResult.FromError(CommandError.ParseFailed, "Snowflake was almost certainly invalid."));
                }

                return(TypeReaderResult.FromSuccess(new DiscordUserEntity(uid)));
            }

            return(TypeReaderResult.FromError(CommandError.ParseFailed, "Could not find user / parse user ID"));
        }
        public override Task <TypeReaderResult> ReadAsync(ICommandContext ctx, string input, IServiceProvider provider)
        {
            if (!(ctx is ArcadeContext context))
            {
                return(Task.FromResult(TypeReaderResult.FromError(CommandError.Unsuccessful, "Invalid command context specified")));
            }

            if (ulong.TryParse(input, out ulong uId))
            {
                if (context.Data.Users.Values.ContainsKey(uId))
                {
                    return(Task.FromResult(TypeReaderResult.FromSuccess(context.Data.Users.Values[uId])));
                }
            }

            ArcadeUser match = context.Data.Users.Values.Values.FirstOrDefault(x => x.Username.Equals(input, StringComparison.OrdinalIgnoreCase));

            if (match != null)
            {
                return(Task.FromResult(TypeReaderResult.FromSuccess(match)));
            }

            TypeReaderResult result = base.ReadAsync(ctx, input, provider).ConfigureAwait(false).GetAwaiter().GetResult();

            if (result.IsSuccess && result.BestMatch is SocketUser best && context.TryGetUser(best.Id, out match))
            {
                return(Task.FromResult(TypeReaderResult.FromSuccess(match)));
            }

            return(Task.FromResult(TypeReaderResult.FromError(CommandError.ObjectNotFound, "Could not find the specified account.")));
        }
        public override Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            var database = services.GetRequiredService <DatabaseService>();

            if (context.Guild == null)
            {
                return(Task.FromResult(TypeReaderResult.FromError(CommandError.UnmetPrecondition, "Event roles are avaivable only inside guild context.")));
            }
            EventRole er = null;

            if (int.TryParse(input, out int id))
            {
                er = database.EventRoles.FirstOrDefault(r => r.Id == id);
            }
            else
            {
                return(Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "Event role id is not a valid number.")));
            }
            if (er == null)
            {
                return(Task.FromResult(TypeReaderResult.FromError(CommandError.ObjectNotFound, "Specified event role was not found.")));
            }
            if (er.Event?.GuildId != context.Guild.Id)
            {
                return(Task.FromResult(TypeReaderResult.FromError(CommandError.Exception, "Cross guild event role access is denied.")));
            }
            return(Task.FromResult(TypeReaderResult.FromSuccess(er)));
        }
        public override Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            var match = _pattern.Match(input);

            if (match.Success)
            {
                var groups = match.Groups;

                int parseAt(int i)
                {
                    int.TryParse(groups[i].Value, out int v);
                    return(v);
                }

                TimeSpan result = new TimeSpan(
                    parseAt(1) * 365 + parseAt(2) * 30 + parseAt(3) * 7 + parseAt(4),
                    parseAt(5),
                    parseAt(6),
                    parseAt(7));

                return(Task.FromResult(TypeReaderResult.FromSuccess(result)));
            }

            return(Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "Input could not be parsed as abbreviated timespan.")));
        }
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            await Task.Yield();

            if (string.IsNullOrWhiteSpace(input))
            {
                return(TypeReaderResult.FromError(CommandError.ParseFailed, "Input is empty."));
            }

            var i = input.Trim().ToLowerInvariant();

            if (TryHandlePercentage(services, context, context.User.Id, i, out var num))
            {
                return(TypeReaderResult.FromSuccess(new ShmartNumber(num, i)));
            }
            try
            {
                var expr = new NCalc.Expression(i, NCalc.EvaluateOptions.IgnoreCase);
                expr.EvaluateParameter += (str, ev) => EvaluateParam(str, ev, context, services);
                var lon = (long)(decimal.Parse(expr.Evaluate().ToString()));
                return(TypeReaderResult.FromSuccess(new ShmartNumber(lon, input)));
            }
            catch (Exception ex)
            {
                _log.Info(ex);
                return(TypeReaderResult.FromError(CommandError.ParseFailed, "Invalid input"));
            }
        }
Example #8
0
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            var members = services.GetRequiredService <MemberStore>();

            // If the sender of the command is in a system themselves,
            // then try searching by the member's name
            if (context is PKCommandContext ctx && ctx.SenderSystem != null)
            {
                var foundByName = await members.GetByName(ctx.SenderSystem, input);

                if (foundByName != null)
                {
                    return(TypeReaderResult.FromSuccess(foundByName));
                }
            }

            // Otherwise, if sender isn't in a system, or no member found by that name,
            // do a standard by-hid search.
            var foundByHid = await members.GetByHid(input);

            if (foundByHid != null)
            {
                return(TypeReaderResult.FromSuccess(foundByHid));
            }
            return(TypeReaderResult.FromError(CommandError.ObjectNotFound, $"Member with ID `{input}` not found."));
        }
Example #9
0
        public override Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return(Task.FromResult(TypeReaderResult.FromError(new InvalidDataException("The input was empty."))));
            }

            switch (input.ToLower())
            {
            case "0":
            case "temp":
            case "temporary":
            case "auto":
            case "automatic":
                return(Task.FromResult(TypeReaderResult.FromSuccess(AutomationType.Temporary)));

            case "1":
            case "perm":
            case "perma":
            case "permanent":
                return(Task.FromResult(TypeReaderResult.FromSuccess(AutomationType.Permanent)));

            default:
                return(Task.FromResult(TypeReaderResult.FromError(new InvalidDataException("The input did not match any of the values."))));
            }
        }
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            var baseResult = await base.ReadAsync(context, input, services);

            if (baseResult.IsSuccess)
            {
                return(TypeReaderResult.FromSuccess(DiscordUserEntity.FromIUser(baseResult.BestMatch as IUser)));
            }

            if (ulong.TryParse(input, out var uid))
            {
                //Any ulong is technically a valid snowflake, but we try to do some basic validation
                //by parsing the timestamp (in ms) part out of it - if it's less than or equal to 0, it's
                //before the Discord epoch of Jan 1, 2015, and thus invalid
                var snowflakeTimestamp = (long)(uid >> 22);

                if (snowflakeTimestamp <= 0)
                {
                    return(TypeReaderResult.FromError(CommandError.ParseFailed, "Snowflake was almost certainly invalid."));
                }

                return(TypeReaderResult.FromSuccess(new DiscordUserEntity(uid)));
            }

            return(TypeReaderResult.FromError(CommandError.ParseFailed, "Could not find user / parse user ID"));
        }
Example #11
0
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            var client  = services.GetService <IDiscordClient>();
            var systems = services.GetService <SystemStore>();

            // System references can take three forms:
            // - The direct user ID of an account connected to the system
            // - A @mention of an account connected to the system (<@uid>)
            // - A system hid

            // First, try direct user ID parsing
            if (ulong.TryParse(input, out var idFromNumber))
            {
                return(await FindSystemByAccountHelper(idFromNumber, client, systems));
            }

            // Then, try mention parsing.
            if (MentionUtils.TryParseUser(input, out var idFromMention))
            {
                return(await FindSystemByAccountHelper(idFromMention, client, systems));
            }

            // Finally, try HID parsing
            var res = await systems.GetByHid(input);

            if (res != null)
            {
                return(TypeReaderResult.FromSuccess(res));
            }
            return(TypeReaderResult.FromError(CommandError.ObjectNotFound, $"System with ID `{input}` not found."));
        }
Example #12
0
        public override Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            switch (input.ToLower())
            {
            case "info":
            case "informacje":
                return(Task.FromResult(TypeReaderResult.FromSuccess(SlotMachineSetting.Info)));

            case "beat":
            case "stawka":
                return(Task.FromResult(TypeReaderResult.FromSuccess(SlotMachineSetting.Beat)));

            case "mnożnik":
            case "mnoznik":
            case "multiplier":
                return(Task.FromResult(TypeReaderResult.FromSuccess(SlotMachineSetting.Multiplier)));

            case "rows":
            case "rzedy":
            case "rzędy":
                return(Task.FromResult(TypeReaderResult.FromSuccess(SlotMachineSetting.Rows)));

            default:
                return(Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "Nie rozpoznano typu nastawy!")));
            }
        }
Example #13
0
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            var command = context.Message.Content;
            var prefix  = await StaticBase.GetGuildPrefixAsync(context.Guild.Id);

            if (!command.StartsWith(prefix))
            {
                prefix = Program.Client.CurrentUser.Mention;
            }
            var module = command.Remove(0, prefix.Length).Split(" ").First(x => x.Length > 0);
            var worked = Enum.TryParse <TrackerType>(module, true, out TrackerType type);

            if (!new List <TrackerType> {
                TrackerType.HTML, TrackerType.JSON, TrackerType.Overwatch, TrackerType.RSS, TrackerType.Youtube, TrackerType.YoutubeLive, TrackerType.GW2
            }.Any(x => x == type))
            {
                input = input.ToLower();
            }

            var result = StaticBase.Trackers[type].GetTracker(context.Channel.Id, input);

            if (result != null)
            {
                return(TypeReaderResult.FromSuccess(result));
            }

            await MopsBot.Data.Interactive.MopsPaginator.CreatePagedMessage(context.Channel.Id, StaticBase.Trackers[type].GetTrackersEmbed(context.Channel.Id, true));

            return(TypeReaderResult.FromError(CommandError.ParseFailed, $"Could not find a {module}-tracker for {input} in this channel."));
        }
        public TypeReaderResult ReadSync(ICommandContext context, string input, IServiceProvider services)
        {
            if (input == null)
            {
                return(TypeReaderResult.FromError(CommandError.ParseFailed, ParseError));
            }

            input = input.Trim();
            if (input.Length != 2 && input.Length != 3)
            {
                return(TypeReaderResult.FromError(CommandError.ParseFailed, ParseError));
            }
            foreach (char c in input)
            {
                if (!(char.IsUpper(c) && char.IsLetter(c)))
                {
                    return(TypeReaderResult.FromError(CommandError.ParseFailed, ParseError));
                }
            }

            var locationResolver = services.GetService <ILocationResolutionService>();

            if (locationResolver != null && !locationResolver.IsValidLocation(input))
            {
                return(TypeReaderResult.FromError(CommandError.ObjectNotFound, InvalidLocationError));
            }

            return(TypeReaderResult.FromSuccess((LocationCode)input));
        }
Example #15
0
        public override Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            var regex = new Regex(@"^(0[0-9]|1[0-9]|2[0-3])(?::|\.)([0-5][0-9])(?:\+([1-9][0-9]*))?$");

            var match = regex.Match(input);

            if (!match.Success)
            {
                var errorMessage = "Invalid format. The allowed format is: 12:45, 12.45, 12:45+1";
                return(Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, errorMessage)));
            }

            var hour   = int.Parse(match.Groups[1].Value);
            var minute = int.Parse(match.Groups[2].Value);

            if (hour > 23)
            {
                new Exception("Invalid hour. There're only 24 hours in a day... stupid.");
            }
            if (minute > 59)
            {
                new Exception("Invalid minute. There're only 60 minuts an hour... stupid.");
            }

            var now  = DateTime.Now;
            var time = new DateTime(now.Year, now.Month, now.Day, hour, minute, 0);

            if (match.Groups[3].Success)
            {
                var offset = int.Parse(match.Groups[3].Value);
                time = time.AddDays(offset);
            }

            return(Task.FromResult(TypeReaderResult.FromSuccess(time)));
        }
Example #16
0
        public override async Task <TypeReaderResult> Read(ICommandContext context, string input, IServiceProvider services)
        {
            input = input.ToUpperInvariant();

            var crs = ((INServiceProvider)services).GetService <CustomReactionsService>();

            if (crs.GlobalReactions.Any(x => x.Trigger.ToUpperInvariant() == input))
            {
                return(TypeReaderResult.FromSuccess(new CommandOrCrInfo(input)));
            }
            var guild = context.Guild;

            if (guild != null)
            {
                if (crs.GuildReactions.TryGetValue(guild.Id, out var crs2))
                {
                    if (crs2.Concat(crs.GlobalReactions).Any(x => x.Trigger.ToUpperInvariant() == input))
                    {
                        return(TypeReaderResult.FromSuccess(new CommandOrCrInfo(input)));
                    }
                }
            }

            var cmd = await base.Read(context, input, services);

            return(cmd.IsSuccess ? TypeReaderResult.FromSuccess(new CommandOrCrInfo(((CommandInfo)cmd.Values.First().Value).Name)) : TypeReaderResult.FromError(CommandError.ParseFailed, "No such command or cr found."));
        }
        public override Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            switch (input.ToLower())
            {
            case "c":
            case "card":
            case "karta":
                return(Task.FromResult(TypeReaderResult.FromSuccess(WishlistObjectType.Card)));

            case "p":
            case "postac":
            case "postać":
            case "character":
                return(Task.FromResult(TypeReaderResult.FromSuccess(WishlistObjectType.Character)));

            case "t":
            case "title":
            case "tytuł":
            case "tytul":
                return(Task.FromResult(TypeReaderResult.FromSuccess(WishlistObjectType.Title)));

            default:
                return(Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "Nie rozpoznano typu id!")));
            }
        }
Example #18
0
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            try
            {
                var   ctx  = (ICustomCommandContext)context;
                IUser?user = null;
                if (MentionUtils.TryParseUser(input, out ulong userId) ||
                    ulong.TryParse(input, out userId))
                {
                    if (userId == 0)
                    {
                        return(TypeReaderResult.FromError(CommandError.ParseFailed, Texts.CommandInvalidUserError));
                    }
                    user ??= await ctx.GetUserAsync(userId).ConfigureAwait(false);
                }

                if (ctx.Guild is SocketGuild socketGuild)
                {
                    user ??= await GetSocketGuildUserByName(socketGuild, input);

                    user ??= await GetUserByBan(socketGuild, input);
                }

                Thread.CurrentThread.CurrentUICulture = ctx.BonusGuild?.Settings.CultureInfo ?? Constants.DefaultCultureInfo;
                return(user is { }
                    ? TypeReaderResult.FromSuccess(user)
                    : TypeReaderResult.FromError(CommandError.ParseFailed, Texts.CommandInvalidUserError));
            }
Example #19
0
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            input = input.ToUpperInvariant();

            var _crs = ((INServiceProvider)services).GetService <CustomReactionsService>();

            if (_crs.GlobalReactions.Any(x => x.Trigger.ToUpperInvariant() == input))
            {
                return(TypeReaderResult.FromSuccess(new CommandOrCrInfo(input, CommandOrCrInfo.Type.Custom)));
            }
            var guild = context.Guild;

            if (guild != null)
            {
                if (_crs.GuildReactions.TryGetValue(guild.Id, out var crs))
                {
                    if (crs.Concat(_crs.GlobalReactions).Any(x => x.Trigger.ToUpperInvariant() == input))
                    {
                        return(TypeReaderResult.FromSuccess(new CommandOrCrInfo(input, CommandOrCrInfo.Type.Custom)));
                    }
                }
            }

            var cmd = await new CommandTypeReader(_client, _cmds).ReadAsync(context, input, services).ConfigureAwait(false);

            if (cmd.IsSuccess)
            {
                return(TypeReaderResult.FromSuccess(new CommandOrCrInfo(((CommandInfo)cmd.Values.First().Value).Name, CommandOrCrInfo.Type.Normal)));
            }
            return(TypeReaderResult.FromError(CommandError.ParseFailed, "No such command or cr found."));
        }
Example #20
0
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider __)
        {
            await Task.Yield();

            var result = TimeSpan.Zero;

            if (input == "0")
            {
                return(TypeReaderResult.FromSuccess((TimeSpan?)null));
            }

            if (TimeSpan.TryParse(input, out result))
            {
                return(TypeReaderResult.FromSuccess(new TimeSpan?(result)));
            }

            var mtc = TimeSpanRegex.Match(input);

            if (!mtc.Success)
            {
                return(TypeReaderResult.FromError(CommandError.ParseFailed, "Invalid TimeSpan string"));
            }

            var d = 0;
            var h = 0;
            var m = 0;
            var s = 0;

            foreach (var gp in RegexGroups)
            {
                var gpc = mtc.Groups[gp].Value;
                if (string.IsNullOrWhiteSpace(gpc))
                {
                    continue;
                }

                var gpt = gpc.Last();
                int.TryParse(gpc.Substring(0, gpc.Length - 1), out var val);
                switch (gpt)
                {
                case 'd':
                    d = val;
                    break;

                case 'h':
                    h = val;
                    break;

                case 'm':
                    m = val;
                    break;

                case 's':
                    s = val;
                    break;
                }
            }
            result = new TimeSpan(d, h, m, s);
            return(TypeReaderResult.FromSuccess(new TimeSpan?(result)));
        }
        public override Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            var _cmds       = services.GetService <CommandService>();
            var _cmdHandler = services.GetService <CommandHandler>();

            input = input.ToUpperInvariant();
            var prefix = _cmdHandler.GetPrefix(context.Guild);

            if (!input.StartsWith(prefix.ToUpperInvariant(), StringComparison.InvariantCulture))
            {
                return(Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "No such command found.")));
            }

            input = input.Substring(prefix.Length);

            var cmd = _cmds.Commands.FirstOrDefault(c =>
                                                    c.Aliases.Select(a => a.ToUpperInvariant()).Contains(input));

            if (cmd == null)
            {
                return(Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "No such command found.")));
            }

            return(Task.FromResult(TypeReaderResult.FromSuccess(cmd)));
        }
Example #22
0
        public override Task <TypeReaderResult> Read(ICommandContext context, string input, IServiceProvider services)
        {
            ChartSize size;

            switch (input)
            {
            case "3x3":
            case "3":
                size = ChartSize.Small;
                break;

            case "4x4":
            case "4":
                size = ChartSize.Medium;
                break;

            case "5x5":
            case "5":
                size = ChartSize.Large;
                break;

            default:
                return(Task.FromResult(TypeReaderResult.FromError(
                                           CommandError.ParseFailed,
                                           "Check the given chart size. Must be one of the following: 3x3 (small), 4x4 (medium), 5x5 (large).")));
            }
            return(Task.FromResult(TypeReaderResult.FromSuccess(size)));
        }
Example #23
0
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            if (ulong.TryParse(input, out ulong result))
            {
                var msg = await context.Channel.GetMessageAsync(result);

                if (msg == null)
                {
                    return(TypeReaderResult.FromError(CommandError.ParseFailed, "No message was found in this channel for this id."));
                }
                return(TypeReaderResult.FromSuccess(msg));
            }
            var match = Regex.Match(input, "https:\\/\\/([^\\.]+\\.)?discordapp.com\\/channels\\/([0-9]{18})\\/([0-9]{18})\\/([0-9]{18})");

            if (match.Success && context.Channel is ITextChannel && match.Groups[2].Value == context.Guild.Id.ToString())
            {
                var msg = await(await context.Guild.GetTextChannelAsync(ulong.Parse(match.Groups[3].Value)))?.GetMessageAsync(ulong.Parse(match.Groups[4].Value));
                if (msg == null)
                {
                    return(TypeReaderResult.FromError(CommandError.ParseFailed, "No message was found in this guild from this url."));
                }
                return(TypeReaderResult.FromSuccess(msg));
            }
            return(TypeReaderResult.FromError(CommandError.ParseFailed, "Can't convert string to IMessage."));
        }
        /// <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.")));
        }
Example #25
0
        public override Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            bool result;

            if (bool.TryParse(input, out result))
            {
                return(Task.FromResult(TypeReaderResult.FromSuccess(result)));
            }

            List <string> trueStrings  = new() { "true", "yes", "y" };
            List <string> falseStrings = new() { "false", "no", "n" };

            if (trueStrings.Any(s => s == input.ToLowerInvariant()))
            {
                return(Task.FromResult(TypeReaderResult.FromSuccess(true)));
            }
            else if (falseStrings.Any(s => s == input.ToLowerInvariant()))
            {
                return(Task.FromResult(TypeReaderResult.FromSuccess(false)));
            }


            return(Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "Input could not be parsed as a boolean.")));
        }
    }
}
Example #26
0
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input,
                                                                IServiceProvider services)
        {
            var result = await base.ReadAsync(context, input, services).ConfigureAwait(false);

            if (result.IsSuccess)
            {
                return(result);
            }
            var restClient = services.GetService <DiscordRestClient>();

            if (restClient == null || !ulong.TryParse(input, out var userId))
            {
                return(result);
            }
            if (context.Guild != null)
            {
                var guildUser = await restClient.GetGuildUserAsync(context.Guild.Id, userId).ConfigureAwait(false);

                if (guildUser != null)
                {
                    return(TypeReaderResult.FromSuccess(guildUser));
                }
            }

            var user = await restClient.GetUserAsync(userId).ConfigureAwait(false);

            return(user != null?TypeReaderResult.FromSuccess(user) : result);
        }
Example #27
0
            public override async Task <TypeReaderResult> Read(ICommandContext context, string input, IServiceProvider services)
            {
                var idMatch = _mentionParser.Match(input);

                if (!idMatch.Success || !UInt64.TryParse(idMatch.Groups["digits"].Value, out var id))
                {
                    var nameDiscrimMatch = _nameDiscrimParser.Match(input);
                    if (!nameDiscrimMatch.Success)
                    {
                        return(TypeReaderResult.FromError(CommandError.ParseFailed, "Could not parse input."));
                    }
                    id = (await context.Client.GetUserAsync(nameDiscrimMatch.Groups["name"].Value, nameDiscrimMatch.Groups["discrim"].Value)).Id;
                }

                var svc = services.GetService <TService>();

                if (svc != null)
                {
                    var game = svc.GetGameFromChannel(context.Channel);
                    if (game != null)
                    {
                        var player = game.Players.SingleOrDefault(p => p.User.Id == id);
                        if (player != null)
                        {
                            return(TypeReaderResult.FromSuccess(player));
                        }
                        return(TypeReaderResult.FromError(CommandError.ObjectNotFound, "Not a player in this game."));
                    }
                    return(TypeReaderResult.FromError(CommandError.ObjectNotFound, "No game going on."));
                }
                return(TypeReaderResult.FromError(CommandError.ObjectNotFound, "No service found."));
            }
        public override Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider _)
        {
            input = input.ToUpperInvariant();
            switch (input)
            {
            case "1":
            case "T":
            case "TRUE":
            case "ENABLE":
            case "ENABLED":
            case "ALLOW":
            case "PERMIT":
            case "UNBAN":
                return(Task.FromResult(TypeReaderResult.FromSuccess(PermissionAction.Enable)));

            case "0":
            case "F":
            case "FALSE":
            case "DENY":
            case "DISABLE":
            case "DISABLED":
            case "DISALLOW":
            case "BAN":
                return(Task.FromResult(TypeReaderResult.FromSuccess(PermissionAction.Disable)));

            default:
                return(Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "Did not receive a valid boolean value")));
            }
        }
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            if (NeoSmart.Unicode.Emoji.IsEmoji(input))
            {
                return(TypeReaderResult.FromSuccess(new Emoji(input)));
            }

            if (Emote.TryParse(input, out Emote emote))
            {
                return(TypeReaderResult.FromSuccess(emote));
            }

            if (ulong.TryParse(input, out ulong emoteId))
            {
                emote = await context.Guild.GetEmoteAsync(emoteId);

                if (emote != null)
                {
                    return(TypeReaderResult.FromSuccess(emote));
                }
            }

            emote = context.Guild.Emotes.FirstOrDefault(o => o.Name == input);

            if (emote != null)
            {
                return(TypeReaderResult.FromSuccess(emote));
            }

            return(TypeReaderResult.FromError(CommandError.ObjectNotFound, "Požadovaný emote se nepodařilo najít a současně to není unicode emoji."));
        }
Example #30
0
            public override async Task <TypeReaderResult> ReadAsync(
                ICommandContext context,
                string input,
                IServiceProvider services)
            {
                var result = await base.ReadAsync(context, input, services).ConfigureAwait(false);

                if (!(result.IsSuccess && result.BestMatch is IUser user))
                {
                    return(result);
                }

                var svc = services.GetService <TService>();

                if (svc != null)
                {
                    var game = svc.GetGameFromChannel(context.Channel);
                    if (game != null)
                    {
                        var player = game.Players.SingleOrDefault(p => p.User.Id == user.Id);
                        return((player != null)
                            ? TypeReaderResult.FromSuccess(player)
                            : TypeReaderResult.FromError(CommandError.ObjectNotFound, "Specified user not a player in this game."));
                    }
                    return(TypeReaderResult.FromError(CommandError.ObjectNotFound, "No game going on."));
                }
                return(TypeReaderResult.FromError(CommandError.ObjectNotFound, "Game service not found."));
            }