public async override Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            if (ulong.TryParse(input, out var id) || MentionUtils.TryParseUser(input, out id))
            {
                var user = Program.GetUserOrDefault(id);
                if (user == null)
                {
                    var usr = Program.Client.GetUser(id);
                    if (usr == null)
                    {
                        return(TypeReaderResult.FromError(CommandError.ParseFailed, $"Unknown user by id {id}"));
                    }
                    user = Program.GetUser(usr);
                }
                return(TypeReaderResult.FromSuccess(user));
            }
            var u2 = Program.Users.FirstOrDefault(x => x.Name == input || x.Username == input);

            if (u2 != null)
            {
                return(TypeReaderResult.FromSuccess(u2));
            }
            var result = await new UserTypeReader <IUser>().ReadAsync(context, input, services);

            return(result);
        }
Example #2
0
        public static bool HasMentionPrefix(this IUserMessage msg, IUser user, ref int argPos)
        {
            var text = msg.Content;

            if (text.Length <= 3 || text[0] != '<' || text[1] != '@')
            {
                return(false);
            }

            int endPos = text.IndexOf('>');

            if (endPos == -1)
            {
                return(false);
            }

            // Must end in "> "
            if (text.Length < endPos + 2 || text[endPos + 1] != ' ')
            {
                return(false);
            }

            if (!MentionUtils.TryParseUser(text.Substring(0, endPos + 1), out ulong userId))
            {
                return(false);
            }

            if (userId == user.Id)
            {
                argPos = endPos + 2;
                return(true);
            }

            return(false);
        }
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) || MentionUtils.TryParseUser(input, out 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"));
        }
Example #4
0
        public async Task WordLengthAsync(int wordLength = 1)
        {
            if (wordLength <= 0)
            {
                await ReplyAsync("You must specify a minimum length greater than 0.");

                return;
            }

            if (Context.Message.Author.Username.Equals("Luneth"))
            {
                await ReplyAsync($"{MentionUtils.MentionUser(Context.Message.Author.Id)} you can't use that!");

                return;
            }

            var dict = LoadMessages(wordLength);
            var kv   = dict.FirstOrDefault(x => x.Value == dict.Values.Max());

            if (string.IsNullOrEmpty(kv.Key))
            {
                await ReplyAsync($"There are no words that are {wordLength} letters long.");
            }
            else
            {
                if (MentionUtils.TryParseUser(kv.Key, out ulong mention))
                {
                    await ReplyAsync("This would ping someone :(");
                }
                else
                {
                    await ReplyAsync($"The most common word with {wordLength} letters is \"{kv.Key}\" with {kv.Value} occurences.");
                }
            }
        }
        public Option <string> Normalize(string input)
        {
            var firstWord = input.Trim().Split(' ').First();

            return(MentionUtils.TryParseUser(firstWord, out var id) && id == user.Id
                ? Option.Some(input.Length == firstWord.Length ? string.Empty : input.Remove(0, firstWord.Length + 1))
                : default);
        private async Task <RetrieveEntityResult <IUser> > ReadUserAsync(ICommandContext context, string input)
        {
            // By Mention
            if (!MentionUtils.TryParseUser(input, out var id))
            {
                var getUserByMentionResult = await GetUserByIdAsync(context, id);

                if (getUserByMentionResult.IsSuccess)
                {
                    return(getUserByMentionResult);
                }
            }

            // By Id
            if (!ulong.TryParse(input, NumberStyles.None, CultureInfo.InvariantCulture, out id))
            {
                return(await FindBestMatchingUserAsync(context, input));
            }

            var getUserByIdResult = await GetUserByIdAsync(context, id);

            if (getUserByIdResult.IsSuccess)
            {
                return(getUserByIdResult);
            }

            return(await FindBestMatchingUserAsync(context, input));
        }
Example #7
0
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            // Try to get the result from the base user reader.
            // If that fails, try to solely parse the ID.

            TypeReaderResult result = await base.ReadAsync(context, input, services);

            if (result.IsSuccess)
            {
                IGuildUser     user  = result.BestMatch as IGuildUser;
                GuildUserProxy proxy = new GuildUserProxy
                {
                    GuildUser = user,
                    ID        = user.Id
                };
                return(TypeReaderResult.FromSuccess(proxy));
            }
            else
            {
                if (MentionUtils.TryParseUser(input, out ulong userId) || ulong.TryParse(input, out userId))
                {
                    return(TypeReaderResult.FromSuccess(new GuildUserProxy {
                        ID = userId
                    }));
                }
            }

            return(TypeReaderResult.FromError(CommandError.ObjectNotFound, "User not found."));
        }
Example #8
0
        public static bool HasMentionPrefix(this IMessage message, IUser user, out string parsed)
        {
            var content = message.Content;

            parsed = "";
            if (content.Length <= 3 || content[0] != '<' || content[1] != '@')
            {
                return(false);
            }

            var endPos = content.IndexOf('>');

            if (endPos == -1)
            {
                return(false);
            }

            if (content.Length < endPos + 2 || content[endPos + 1] != ' ')
            {
                return(false);
            }

            if (!MentionUtils.TryParseUser(content.Substring(0, endPos + 1), out var userId))
            {
                return(false);
            }

            if (userId != user.Id)
            {
                return(false);
            }
            parsed = content.Substring(endPos + 2);
            return(true);
        }
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            IGuildUser gUserResult = null;
            IUser      userResult;

            //By Mention (1.0)
            if (MentionUtils.TryParseUser(input, out var id))
            {
                if (context.Guild != null)
                {
                    gUserResult = await context.Guild.GetUserAsync(id, CacheMode.AllowDownload);
                }
                if (gUserResult != null)
                {
                    return(TypeReaderResult.FromSuccess(new UserRef(gUserResult)));
                }
                else
                {
                    userResult = await context.Client.GetUserAsync(id, CacheMode.AllowDownload);
                }
                if (userResult != null)
                {
                    return(TypeReaderResult.FromSuccess(new UserRef(userResult)));
                }
                else
                {
                    return(TypeReaderResult.FromSuccess(new UserRef(id)));
                }
            }

            //By Id (0.9)
            if (ulong.TryParse(input, NumberStyles.None, CultureInfo.InvariantCulture, out id))
            {
                if (context.Guild != null)
                {
                    gUserResult = await context.Guild.GetUserAsync(id, CacheMode.AllowDownload);
                }
                if (gUserResult != null)
                {
                    return(TypeReaderResult.FromSuccess(new UserRef(gUserResult)));
                }
                else
                {
                    userResult = await context.Client.GetUserAsync(id, CacheMode.AllowDownload);
                }
                if (userResult != null)
                {
                    return(TypeReaderResult.FromSuccess(new UserRef(userResult)));
                }
                else
                {
                    return(TypeReaderResult.FromSuccess(new UserRef(id)));
                }
            }

            return(TypeReaderResult.FromError(CommandError.ObjectNotFound, "User not found."));
        }
        // TODO Apply Option Pattern
        private static async Task <IGuildUser> ParseByMentionAsync(IGuild guild, string input)
        {
            if (MentionUtils.TryParseUser(input, out var id))
            {
                return(await guild.GetUserAsync(id).ConfigureAwait(false));
            }

            return(null);
        }
Example #11
0
        public Option <string> Normalize(string input)
        {
            var firstWord = input.Split(' ').First();

            if (MentionUtils.TryParseUser(firstWord, out var id) && id == user.Id)
            {
                return(Option.Some(input.Remove(0, firstWord.Length)));
            }

            return(default);
Example #12
0
        public async Task <IUser> MatchUser()
        {
            var text = PeekArgument();

            if (MentionUtils.TryParseUser(text, out var id))
            {
                return(await Shard.Rest.GetUserAsync(id)); // TODO: this should properly fetch
            }
            return(null);
        }
Example #13
0
        public static bool TryParseUser(string text, out ulong id)
        {
            if (MentionUtils.TryParseUser(text, out ulong parsedId))
            {
                id = parsedId;
                return(true);
            }

            id = 0;
            return(false);
        }
Example #14
0
 public static bool TryParseMention(this string potentialMention, out ulong id)
 {
     if (ulong.TryParse(potentialMention, out id))
     {
         return(true);
     }
     if (MentionUtils.TryParseUser(potentialMention, out id))
     {
         return(true);
     }
     return(false);
 }
Example #15
0
        // Extensions for Discord Class SocketGuild
        public static SocketGuildUser FirstUserByName(this SocketGuild guild, string name)
        {
            if (MentionUtils.TryParseUser(name, out var id))
            {
                return(guild.Users.FirstOrDefault(user => user.Id == id));
            }

            return(guild.Users.FirstOrDefault(user =>
                                              Regex.IsMatch(user.Username, name, RegexOptions.IgnoreCase) ||
                                              Regex.IsMatch(user.Nickname ?? "", name, RegexOptions.IgnoreCase)
                                              ));
        }
Example #16
0
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            var discordUserId = MentionUtils.TryParseUser(input, out var userId);

            if (await context.Guild.GetUserAsync(userId) is SocketGuildUser discordUser)
            {
                var miunieUserResult = _convertor.UserConvertor.DiscordMemberToMiunieUser(discordUser);
                return(TypeReaderResult.FromSuccess(miunieUserResult));
            }

            return(TypeReaderResult.FromError(CommandError.ParseFailed, "Input could not be parsed as a MiunieUser."));
        }
Example #17
0
        public async Task <RuntimeResult> DeleteMessagesForceAsync(string userMention, int limit = 1)
        {
            if (!MentionUtils.TryParseUser(userMention, out ulong userId))
            {
                return(Reply("Please mention a user."));
            }

            var messagesToDelete = new List <IMessage>();
            IEnumerable <IMessage> messages;
            IMessage lastMessage = null;

            do
            {
                if (lastMessage == null)
                {
                    messages = await Context.Channel.GetMessagesAsync().FlattenAsync();
                }
                else
                {
                    messages = await Context.Channel.GetMessagesAsync(lastMessage, Direction.Before).FlattenAsync();
                }
                if (!messages.Any())
                {
                    break;
                }
                lastMessage = messages.Last();
                messages    = messages.Where(m => m.Author.Id == userId);
                int amountFetched = messages.Count();
                if (amountFetched == 0)
                {
                    continue;
                }
                int missingAmount = limit - messagesToDelete.Count;
                if (amountFetched > missingAmount)
                {
                    messages = messages.Take(missingAmount);
                }

                messagesToDelete.AddRange(messages);
            }while (messagesToDelete.Count < limit);

            var dateNow           = DateTime.Now.AddMinutes(5);
            var notTooOldMessages = messages.Where(m => (dateNow - m.CreatedAt).Days < 14);
            var tooOldMessages    = messages.Where(m => (dateNow - m.CreatedAt).Days >= 14);

            await((ITextChannel)Context.Channel).DeleteMessagesAsync(notTooOldMessages);
            foreach (var oldMsg in tooOldMessages)
            {
                await oldMsg.DeleteAsync();
            }

            return(Reply($"Deleted {messages.Count()} messages of the user."));
        }
Example #18
0
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            var result        = new List <SocketGuildUser>();
            var allGuildUsers = await context.Guild
                                .GetUsersAsync();

            var users = input
                        .ToLower()
                        .Split(' ');

            foreach (var baseUser in users)
            {
                SocketGuildUser user = null;
                ulong           id;

                if (MentionUtils.TryParseUser(baseUser, out id))
                {
                    user = await context.Channel.GetUserAsync(id) as SocketGuildUser;
                }

                else if (ulong.TryParse(baseUser, out id))
                {
                    user = await context.Channel.GetUserAsync(id) as SocketGuildUser;
                }

                else
                {
                    user = allGuildUsers
                           .FirstOrDefault(u =>
                                           u.Username?.ToLower() == baseUser ||
                                           u.Nickname?.ToLower() == baseUser)
                           as SocketGuildUser;
                }

                if (user == null)
                {
                    return(TypeReaderResult.FromError(CommandError.ParseFailed, $"User ID: {baseUser} could not be found."));
                }
                else
                {
                    result.Add(user);
                }
            }

            if (result != null)
            {
                return(TypeReaderResult.FromSuccess(result));
            }
            else
            {
                return(TypeReaderResult.FromError(CommandError.ParseFailed, $"Input could not be parsed. [ListSocketGuildUserTR]."));
            }
        }
Example #19
0
        public override async ValueTask <TypeParserResult <RestGuildUser> > ParseAsync(string value, VolteContext ctx)
        {
            RestGuildUser user = null;

            if (ulong.TryParse(value, out var id) || MentionUtils.TryParseUser(value, out id))
            {
                user = await ctx.Client.Rest.GetGuildUserAsync(ctx.Guild.Id, id);
            }

            return(user is null
                ? Failure("User not found.")
                : Success(user));
        }
Example #20
0
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            input = input.Trim(',', '.');

            var baseResult = await base.ReadAsync(context, input, services);

            if (baseResult.IsSuccess)
            {
                return(TypeReaderResult.FromSuccess(new DiscordUserOrMessageAuthorEntity(((IUser)baseResult.BestMatch).Id)));
            }

            if (MentionUtils.TryParseUser(input, out var userId))
            {
                return(SnowflakeUtilities.IsValidSnowflake(userId)
                    ? GetUserResult(userId)
                    : GetInvalidSnowflakeResult());
            }

            // The base class covers users that are in the guild, and the previous condition covers mentioning users that are not in the guild.
            // At this point, it's one of the following:
            //   - A snowflake for a user not in the guild.
            //   - A snowflake for a message in the guild.
            //   - Something we can't handle.
            if (ulong.TryParse(input, out var snowflake))
            {
                if (!SnowflakeUtilities.IsValidSnowflake(snowflake))
                {
                    return(GetInvalidSnowflakeResult());
                }

                // Try to find the user if they are not in the guild
                var restClient = services.GetRequiredService <IDiscordRestClient>();

                var user = await restClient.GetUserAsync(snowflake);

                if (user is not null)
                {
                    return(GetUserResult(user.Id));
                }

                var messageService = services.GetRequiredService <IMessageService>();

                if (await messageService.FindMessageAsync(context.Guild.Id, snowflake) is { } message)
                {
                    return(GetMessageAuthorResult(message.Author.Id, message.Channel.Id, message.Id));
                }
            }

            return(GetBadInputResult());
        }
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            /* No need to check if context is in guild, because it always is (see CommandHandler) */
            var restClient = (context.Client as DiscordSocketClient).Rest;

            /* By mention or by id */
            if (MentionUtils.TryParseUser(input, out ulong userId) || ulong.TryParse(input, out userId))
            {
                IUser user = await context.Guild.GetUserAsync(userId);

                user = user ?? await restClient.GetUserAsync(userId);

                return(TypeReaderResult.FromSuccess(user));
            }

            /* By Username */
            var channelUsers = context.Channel.GetUsersAsync(CacheMode.CacheOnly).Flatten();
            var channelUser  = await channelUsers.FirstOrDefaultAsync(x => string.Equals(input, x.Username, StringComparison.OrdinalIgnoreCase));

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

            var guildUsers = await context.Guild.GetUsersAsync(CacheMode.CacheOnly).ConfigureAwait(false);

            var guildUser = guildUsers.FirstOrDefault(x => string.Equals(input, x.Nickname, StringComparison.OrdinalIgnoreCase));

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

            /* By Nickname */
            var cUser = await channelUsers.FirstOrDefaultAsync(x => string.Equals(input, (x as IGuildUser)?.Nickname, StringComparison.OrdinalIgnoreCase));

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

            var gUser = guildUsers.FirstOrDefault(x => string.Equals(input, x.Nickname, StringComparison.OrdinalIgnoreCase));

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

            return(TypeReaderResult.FromError(CommandError.ObjectNotFound, $"User not found."));
        }
Example #22
0
        //modified code taken from Discord.Net.Commands.UserTypeReader
        public static async Task <IGuildUser> GetUserAsync(this IGuild guild, string input)
        {
            var guildUsers = await guild.GetUsersAsync().ConfigureAwait(false);

            IGuildUser user;

            if (MentionUtils.TryParseUser(input, out var id))
            {
                user = await guild.GetUserAsync(id).ConfigureAwait(false);

                if (user != null)
                {
                    return(user);
                }
            }

            if (ulong.TryParse(input, NumberStyles.None, CultureInfo.InvariantCulture, out id))
            {
                user = await guild.GetUserAsync(id).ConfigureAwait(false);

                if (user != null)
                {
                    return(user);
                }
            }

            var index = input.LastIndexOf('#');

            if (index >= 0)
            {
                var username = input.Substring(0, index);
                if (ushort.TryParse(input.Substring(index + 1), out var discrim))
                {
                    user = guildUsers.FirstOrDefault(x => x.DiscriminatorValue == discrim && string.Equals(username, x.Username, StringComparison.OrdinalIgnoreCase));
                    if (user != null)
                    {
                        return(user);
                    }
                }
            }

            user = guildUsers.FirstOrDefault(gu => string.Equals(input, gu.Username, StringComparison.OrdinalIgnoreCase));
            if (user != null)
            {
                return(user);
            }

            user = guildUsers.FirstOrDefault(gu => string.Equals(input, gu.Nickname, StringComparison.OrdinalIgnoreCase));
            return(user);
        }
Example #23
0
        public async Task SudoerAddRemoveCommandAsync(string function, string username)
        {
            ulong userid;
            var   userWasProvided = MentionUtils.TryParseUser(username, out userid);

            // check if the function passed is correct
            if (function != "add" && function != "remove")
            {
                await ReplyAsync("You didn't correctly specify what you wanted to do. Try \"add\" or \"remove\".");

                return;
            }

            // check if the user passed exists & was parsed correctly
            if (!userWasProvided)
            {
                await ReplyAsync("You didn't specify a user to run the command on. Try @mentioning a user.");

                return;
            }

            var user = Context.Guild.GetUser(userid) as IUser;

            string replyFunctionText;

            if (function == "add")
            {
                replyFunctionText = "added to";
            }
            else
            {
                replyFunctionText = "removed from";
            }

            switch (function)
            {
            case "add":
                await DatabaseSudo.AddUserToSudoers(user);

                break;

            case "remove":
                await DatabaseSudo.RemoveUserFromSudoers(user);

                break;
            }

            await ReplyAsync($"{user.Username} was successfully {replyFunctionText} the sudoers list.");
        }
Example #24
0
        public override ValueTask <TypeParserResult <SocketGuildUser> > ParseAsync(Parameter parameter, string value, CommandContext context,
                                                                                   IServiceProvider provider)
        {
            var abyssContext = context.ToRequestContext();
            var channel      = abyssContext.Channel;
            var results      = new Dictionary <ulong, UserParseResolveResult>();
            var channelUsers = abyssContext.Guild.Users;

            // Parse mention
            if (MentionUtils.TryParseUser(value, out var id))
            {
                AddResult(results,
                          channel.GetUser(id),
                          1.00f);
            }

            // by Discord snowflake ID
            if (ulong.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out id) && abyssContext.Guild != null)
            {
                AddResult(results,
                          channel.GetUser(id), 0.90f);
            }

            // Parse username & discrim
            var index = value.LastIndexOf('#');

            if (index >= 0)
            {
                var username = value.Substring(0, index);
                if (ushort.TryParse(value.Substring(index + 1), out var discriminator))
                {
                    var guildUser = channelUsers.FirstOrDefault(x => x.DiscriminatorValue == discriminator &&
                                                                string.Equals(username, x.Username,
                                                                              StringComparison.OrdinalIgnoreCase));

                    AddResult(results, guildUser, guildUser?.Username == username ? 0.85f : 0.75f);
                }
            }

            var user = results.Count > 0
                ? results.OrderBy(d => d.Value.Score).FirstOrDefault().Value.Value
                : channelUsers.FirstOrDefault(a =>
                                              a.Username.StartsWith(value, StringComparison.OrdinalIgnoreCase) ||
                                              (a.Nickname?.ToLower().StartsWith(value.ToLower()) ?? false));

            return(user == null
                ? new TypeParserResult <SocketGuildUser>($"A user by the name/ID of {value} was not found.")
                : new TypeParserResult <SocketGuildUser>(user));
        }
Example #25
0
        public override ValueTask <TypeParserResult <SocketGuildUser> > ParseAsync(Parameter parameter, string value,
                                                                                   SocketCommandContext context, IServiceProvider provider)
        {
            if (MentionUtils.TryParseUser(value, out var id))
            {
                var user = context.Guild.GetUser(id);
                return(user != null
                    ? TypeParserResult <SocketGuildUser> .Successful(user)
                    : TypeParserResult <SocketGuildUser> .Unsuccessful("Failed to parse user"));
            }

            if (ulong.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out id))
            {
                var user = context.Guild.GetUser(id);
                return(user != null
                    ? TypeParserResult <SocketGuildUser> .Successful(user)
                    : TypeParserResult <SocketGuildUser> .Unsuccessful("Failed to parse user"));
            }

            var index = value.LastIndexOf('#');

            if (index >= 0)
            {
                var username = value.Substring(0, index);
                if (ushort.TryParse(value.Substring(index + 1), out var discriminator))
                {
                    var user = context.Guild.Users.FirstOrDefault(x => x.DiscriminatorValue == discriminator &&
                                                                  string.Equals(username, x.Username,
                                                                                StringComparison.OrdinalIgnoreCase));
                    return(user != null
                        ? TypeParserResult <SocketGuildUser> .Successful(user)
                        : TypeParserResult <SocketGuildUser> .Unsuccessful("Failed to parse user"));
                }
            }

            var userNick = context.Guild.Users.FirstOrDefault(x => x.Nickname == value);

            if (userNick != null)
            {
                return(TypeParserResult <SocketGuildUser> .Successful(userNick));
            }

            var usernameParse = context.Guild.Users.FirstOrDefault(x => x.Username == value);

            return(usernameParse != null
                ? TypeParserResult <SocketGuildUser> .Successful(usernameParse)
                : TypeParserResult <SocketGuildUser> .Unsuccessful("Failed to parse user"));
        }
Example #26
0
        public override async Task <TypeReaderResult> ReadAsync(
            ICommandContext context,
            string input,
            IServiceProvider services)
        {
            var result = await base.ReadAsync(context, input, services);

            if (result.IsSuccess)
            {
                return(result);
            }
            else
            {
                DiscordRestClient restClient = (context.Client as DiscordSocketClient).Rest;
                if (MentionUtils.TryParseUser(input, out var id))
                {
                    RestUser user = await restClient.GetUserAsync(id);

                    if (user != null)
                    {
                        return(TypeReaderResult.FromSuccess(user));
                    }
                }
                if (ulong.TryParse(input, NumberStyles.None, CultureInfo.InvariantCulture, out id))
                {
                    RestUser user = await restClient.GetUserAsync(id);

                    if (user != null)
                    {
                        return(TypeReaderResult.FromSuccess(user));
                    }
                }
                return(TypeReaderResult.FromError(CommandError.ObjectNotFound, "User not found."));
            }

            /*
             * 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.");*/
        }
Example #27
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"));
 }
Example #28
0
        public static bool HasMentionPrefix(string content, ref int argPos)
        {
            // Roughly ported from Discord.Commands.MessageExtensions.HasMentionPrefix
            if (string.IsNullOrEmpty(content) || content.Length <= 3 || (content[0] != '<' || content[1] != '@'))
            {
                return(false);
            }
            int num = content.IndexOf('>');

            if (num == -1 || content.Length < num + 2 || content[num + 1] != ' ' || !MentionUtils.TryParseUser(content.Substring(0, num + 1), out _))
            {
                return(false);
            }
            argPos = num + 2;
            return(true);
        }
Example #29
0
        public bool MatchUserRaw(out ulong id)
        {
            id = 0;

            var text = PeekArgument();

            if (MentionUtils.TryParseUser(text, out var mentionId))
            {
                id = mentionId;
            }
            else if (ulong.TryParse(text, out var rawId))
            {
                id = rawId;
            }

            return(id != 0);
        }
Example #30
0
        public List <Command> Load()
        {
            List <Command> commands = new List <Command>();

            Command getGuildCommand = new Command("getguild");

            getGuildCommand.Usage              = "getguild <user|guild|name>";
            getGuildCommand.Description        = "Gets information about guilds this bot is in.";
            getGuildCommand.RequiredPermission = Command.PermissionLevels.GlobalAdmin;
            getGuildCommand.ToExecute          = async(context) =>
            {
                if (MentionUtils.TryParseUser(context.ParameterString, out var userId))
                {
                    if (Core.DiscordClient.GetUser(userId) is SocketUser user)
                    {
                        await PrintUserGuilds(context, user);
                    }
                    else
                    {
                        await context.Message.ReplyAsync($"User with ID `{userId}` not found.");
                    }
                }
                else if (ulong.TryParse(context.ParameterString, out var id))
                {
                    if (Core.DiscordClient.GetGuild(id) is SocketGuild guild)
                    {
                        await PrintGuildInformation(context, guild);
                    }
                    else if (Core.DiscordClient.GetUser(id) is SocketUser user)
                    {
                        await PrintUserGuilds(context, user);
                    }
                    else
                    {
                        await context.Message.ReplyAsync($"User or guild with ID `{userId}` not found.");
                    }
                }
                else
                {
                    await PerformGuildSearch(context, context.ParameterString);
                }
            };
            commands.Add(getGuildCommand);

            return(commands);
        }