Example #1
0
        public async Task<string> Admin_TimeoutUserAsync (CommandArgs e, double minutes, IGuildUser user)
        {
            var response = await TimeoutUserAsync(e, minutes, user);

            if (response == 1)
                return $"timed out {user.Mention} for {minutes} minutes.";
            else if (response == 2)
                return $"added {minutes} more minutes to {user.Mention}'s timeout.";
            else if (response == 3)
                return $"removed {user.Mention}'s time out. Hooray!";
            else
                return $"failed to time out {user.Mention}. You might stupid.";
        }
Example #2
0
        /// <summary>
        /// Times out a user.
        /// </summary>
        /// <param name="minutes">How long to time the user out.</param>
        /// <param name="user">User to time out</param>
        /// <returns>0, 1, 2 or 3 if the timing out failed, succeeded, time was added or the time out was removed. Respectively.</returns>
        public async Task<int> TimeoutUserAsync(CommandArgs e, double minutes, IGuildUser user)
        {
            List<TimedoutUser> users;
            timedoutUsers.TryGetValue(e.Guild.Id, out users);

            if (users == null)
            {
                users = new List<TimedoutUser>();
                timedoutUsers.Add(e.Guild.Id, users);
            }

            var userTimeout = users.FirstOrDefault(x => x.userID  == user.Id);

            if (userTimeout == null)
            {
                if (minutes <= 0)
                    return 0; //Failed

                await StartTimeoutAsync(e, minutes, user, users);

                return 1;
            }
            else
            {
                if (minutes <= 0)
                {
                    await StopTimeoutAsync(users, userTimeout, user, e.Guild);
                    return 3;
                }

                var timeToAdd = (DateTime.Now - userTimeout.t).TotalMinutes;
                timeToAdd = userTimeout.timeoutTime - timeToAdd;

                Console.WriteLine($"{user.Username}'s timeout has been lengthed to {timeToAdd + minutes}");
                await StopTimeoutAsync(users, userTimeout, user, e.Guild);
                await StartTimeoutAsync(e, timeToAdd + minutes, user,  users);

                return 2; // Time added
            }
        }
 public static async Task RoleSuccessFailAsync(bool success, CommandArgs e)
 {
     if (success)
         await Tools.ReplyAsync(e, "👌🏽", false);
     else
         await Tools.ReplyAsync(e, "🖕🏽", false);
 }
Example #4
0
 public static int GetPerms(CommandArgs e, IGuildUser u)
 {
     return GetPerms(e.Guild.Id, u);
 }
Example #5
0
        public static SocketUser GetUser(CommandArgs eventArgs)
        {
            try
            {
                string userName = string.Empty;

                for (int i = 0; i < eventArgs.Args.Length - 1; i++)
                {
                    userName += eventArgs.Args[i] + ' ';
                }

                if (userName[0] == '@')
                    userName = userName.Substring(1);

                userName = userName.Remove(userName.Length - 1);

                var user = eventArgs.Guild.Users.FirstOrDefault(x => x.Username == userName);

                return user;
            }
            catch (Exception e)
            {
                Console.WriteLine($"[EXCEPTION] Couldn't get user! {e.Message}");
                return null;
            }
        }
Example #6
0
 public static Task<IUserMessage> ReplyAsync(CommandArgs e, string text, bool mentionUser)
     => ReplyAsync(e.Author, e.Channel, text, mentionUser);
Example #7
0
 public static Task<IUserMessage> ReplyAsync(CommandArgs e, string text)
     => ReplyAsync(e.Author, e.Channel, text, true);
        public CommandsPlugin(DiscordSocketClient client, Func<SocketUser, ulong, int> getPermissions = null, char commandChar = '/')
        {
            _client = client;
            _getPermissions = getPermissions;
            Commands = new List<Command>();

            CommandChar = commandChar;
            UseCommandChar = true;

            var timeValues = new Dictionary<SocketUser, Dictionary<Command, DateTime>>();

            client.MessageReceived += async (message) =>
            {
                //Don't bother to process if there are no commands.
                if (Commands.Count == 0)
                    return;

                //Ignore ourselves.
                if (message.Author.Id == _client.CurrentUser.Id)
                    return;


                string msg = message.Content;
                if (UseCommandChar)
                {
                    if (msg.Length == 0)
                        return;

                    if (msg[0] == CommandChar)
                        msg = msg.Substring(1);
                    else
                        return;
                }

                CommandPart[] args;
                if (!CommandParser.ParseArgs(msg, out args))
                    return;

                try
                {

                    foreach (var command in Commands)
                    {
                        if (args.Length < command.Parts.Length)
                            continue;

                        bool isValid = true;
                        for (int i = 0; i < command.Parts.Length; i++)
                        {
                            if (!string.Equals(args[i].Value, command.Parts[i], StringComparison.OrdinalIgnoreCase))
                            {
                                isValid = false;
                                break;
                            }
                        }

                        //Check if alias
                        if (command.alias != null)
                        {
                            foreach (var alias in command.alias)
                            {
                                if (args[0].Value == alias)
                                {
                                    isValid = true;
                                    break;
                                }
                            }
                        }

                        if (!isValid)
                            continue;

                        //Check Arg Count.
                        int argCount = args.Length - command.Parts.Length;
                        if (argCount < command.MinArgs || argCount > command.MaxArgs)
                            continue;

                        //Clean Args brb getting drinks got milk kek
                        string[] newArgs = new string[argCount];
                        for (int i = 0; i < newArgs.Length; i++)
                            newArgs[i] = args[i + command.Parts.Length].Value;

                        //Get ArgText
                        string argText;
                        if (argCount == 0)
                            argText = String.Empty;
                        else
                            argText = msg.Substring(args[command.Parts.Length].Index);

                        //Check perms
                        int permissions = getPermissions != null ? getPermissions(message.Author, ((Discord.ITextChannel)message.Channel).Guild.Id) : 0;
                        var eventArgs = new CommandArgs(message, command, msg, argText, permissions, newArgs);
                        if (permissions < command.MinPerms)
                        {
                            await BotTools.Tools.ReplyAsync(message.Author, message.Channel, "You do not have the correct permissions to use this command.", true);
                            return;
                        }

                        //try to delete the message if the parameter is set.
                        try
                        {
                            if (command.IsHidden && (message.Channel as IPrivateChannel) == null)
                                await message.DeleteAsync();
                        }
                        catch (Exception) { }

                        if (message.Channel as IPrivateChannel == null)
                        {
                            //check if admin, if so he can ignore the time constraint and shit.
                            bool timeCheck = true;
                            if (!command.DelayUnignorable)
                            {
                                var info = BotTools.Tools.GetServerInfo(((ITextChannel)message.Channel).GuildId);
                                if (info.roleImportancy.Count > 0)
                                {
                                    for (int i = 0; i < info.roleImportancy.Count; i++)
                                    {
                                        ulong importantRole = info.roleImportancy.Keys.ToArray()[i];
                                        int importantRoleAmnt = info.roleImportancy.Values.ToArray()[i];
                                        SocketRole role = (message.Channel as ITextChannel)?.Guild.GetRole(importantRole) as SocketRole;

                                        if (role == null) continue;

                                        if ((message.Author as IGuildUser).RoleIds.Contains(role.Id) && importantRoleAmnt >= 15)
                                        {
                                            timeCheck = false;
                                            break;
                                        }
                                    }
                                }
                            }


                            //Check if outside of time limit
                            if (command.CommandDelay != null)
                            {
                                if (timeCheck)
                                {
                                    Dictionary<Command, DateTime> dict;
                                    DateTime time;

                                    //if the user does not have a key, make one. Then get the key.
                                    if (!timeValues.ContainsKey(message.Author))
                                        timeValues.Add(message.Author, new Dictionary<Command, DateTime>());

                                    dict = timeValues[message.Author];

                                    bool skipTimeCheck = false;
                                    //The above gets the time, and if that returns null it adds the current command with the current time to the dict. Then exit the while function.
                                    if (!dict.ContainsKey(command))
                                    {
                                        dict.Add(command, DateTime.UtcNow);
                                        skipTimeCheck = true;
                                    }

                                    if (!skipTimeCheck)
                                    {
                                        time = dict[command];
                                        double test = (DateTime.UtcNow - time).TotalSeconds;
                                        if ((DateTime.UtcNow - time).TotalSeconds < command.CommandDelay)
                                        {
                                            string waitTime = String.Empty;
                                            int seconds = (int)(command.CommandDelay - (DateTime.UtcNow - time).TotalSeconds);

                                            #region time calculator
                                            int days, hours, minutes = 0;

                                            minutes = seconds / 60;
                                            seconds %= 60;
                                            hours = minutes / 60;
                                            minutes %= 60;
                                            days = hours / 24;
                                            hours %= 24;

                                            if (days > 0)
                                            {
                                                string postfix;
                                                if (days == 1)
                                                    postfix = "day";
                                                else
                                                    postfix = "days";

                                                waitTime += $"{days} {postfix}";
                                            }

                                            if (hours > 0)
                                            {
                                                if (waitTime.Length > 0)
                                                    waitTime += ", ";

                                                string postfix;
                                                if (hours == 1)
                                                    postfix = "hour";
                                                else
                                                    postfix = "hours";
                                                waitTime += $"{hours} {postfix}";
                                            }

                                            if (minutes > 0)
                                            {
                                                if (waitTime.Length > 0)
                                                    waitTime += ", ";

                                                string postfix;
                                                if (minutes == 1)
                                                    postfix = "minute";
                                                else
                                                    postfix = "minutes";
                                                waitTime += $"{minutes} {postfix}";
                                            }

                                            if (seconds > 0)
                                            {
                                                if (waitTime.Length > 0)
                                                    waitTime += " and ";

                                                string postfix;
                                                if (seconds == 1)
                                                    postfix = "second";
                                                else
                                                    postfix = "seconds";
                                                waitTime += $"{seconds} {postfix}";
                                            }
                                            #endregion

                                            if (command.FailHandler == null)
                                                await ((ITextChannel)eventArgs.Channel).SendMessageAsync($"{message.Author.Mention}: You need to wait {waitTime} before you can use /{command.Parts[0]}.");
                                            else
                                            {
                                                try
                                                {
                                                    //why is this here
                                                }
                                                catch (Exception ex)
                                                {
                                                    RaiseCommandError(eventArgs, ex);
                                                }
                                            }
                                            return;
                                        }
                                    }

                                    dict[command] = DateTime.UtcNow;
                                }
                            }
                        }

                        //Run Command
                        Console.WriteLine($"[CommandEvent] {message.Author.Username} used command: {String.Join("", eventArgs.Command.Parts)}.");
                        RaiseRanCommand(eventArgs);
                        try
                        {
                            var task = command.Handler(eventArgs);
                            if (task != null)
                                await task;
                        }
                        catch (Exception ex)
                        {
                            RaiseCommandError(eventArgs, ex);
                            Console.WriteLine(ex);  
                        }
                        break;
                    }

                }
                catch (Exception ex)
                {
                    await BotTools.Tools.ReplyAsync(message.Author, message.Channel, $"Plugin error: {ex.Message}", true);
                    BotTools.Tools.LogError("Error with plugin or something.", ex.Message);
                }

            };

        }
Example #9
0
 public CommandErrorEvent(CommandArgs arg, Exception ex)
     : base(arg.Message, arg.Command, arg.CommandText, arg.ArgText, arg.Permssions, arg.Args)
 {
     Exception = ex;
 }
Example #10
0
 public CommandArgsError(CommandArgs args, Exception ex)
     : base(args.Message, args.Command, args.CommandText, args.ArgText, args.Permssions, args.Args)
 {
     this.Ex = ex;
 }
Example #11
0
 private void RaiseUnknownCommand(CommandArgs args)
 {
     UnknownCommand?.Invoke(this, args);
 }
Example #12
0
 private void RaiseRanCommand(CommandArgs args)
 {
     RanCommand?.Invoke(this, args);
 }
Example #13
0
 private void RaiseCommandError(CommandArgs args, Exception ex)
 {
     CommandError?.Invoke(this, new CommandErrorEvent(args, ex));
 }
Example #14
0
        private async Task StartTimeoutAsync(CommandArgs e, double minutes, IGuildUser user, List<TimedoutUser> users)
        {
            users.Add(new TimedoutUser(user));
            var info = users[users.Count - 1];
            info.SetTimer(new TimeSpan(0, (int)minutes, (int)minutes % 60), new TimeoutInfo(users, info, user, user.Guild));

            timedoutUsers[user.GuildId] = new List<TimedoutUser>(users);
            
            info.t = DateTime.Now;
            info.timeoutTime = minutes;

            SocketRole role = null;
            var roles = e.Guild.Roles.ToArray();
            for(int i = 0; i < roles.Length; i++)
            {
                if(roles[i].Name == "qttimedout")
                {
                    role = roles[i];
                    break;
                }
            }

            if (role == null)
                return;

            var userroles = user.RoleIds.ToList();
            userroles.Add(role.Id);
            try
            {
                await user.ModifyAsync(x => x.RoleIds = userroles.ToArray());
            }
            catch (Exception) { }
            return;
        }
Example #15
0
 public static YouTubeSelector NewSelector(CommandArgs cmdArgs, string[] urlIds)
 {
     return new YouTubeSelector(cmdArgs, urlIds);
 }
Example #16
0
            /// <summary>
            /// Create a new selector and add it to the list
            /// </summary>
            /// <param name="cmdArgs">the channel and user it's waiting for a message.</param>
            /// <param name="urlIds">all the YouTube url Ids</param>
            public YouTubeSelector(CommandArgs cmdArgs, string[] urlIds)
            {
                this.CmdArgs = cmdArgs;
                this.URLIds = urlIds;
                StartedWaiting = DateTime.Now;

                //Add it to the list
                utubeSelectors.Add(this);
            }