Пример #1
0
        public static void ListBroadcasts(CommandArgs args)
        {
            int pageParamIndex = 1;
            int pageNumber;

            List <string> broadcastNames = PaginationTools.BuildLinesFromTerms(Database.Broadcasts.Select(e => e.Name));

            if (!PaginationTools.TryParsePageNumber(args.Parameters, pageParamIndex, args.Player, out pageNumber))
            {
                return;
            }

            PaginationTools.SendPage(args.Player, pageNumber, broadcastNames,
                                     new PaginationTools.Settings
            {
                HeaderFormat           = "Broadcasts ({0}/{1}):",
                FooterFormat           = $"Type /autobc list {{0}} for more.",
                MaxLinesPerPage        = 4,
                NothingToDisplayString = "There aren't any Broadcasts set."
            });
        }
Пример #2
0
        private void BindPrefixCMD(CommandArgs args)
        {
            string Parameter = (args.Parameters.Count == 0) ? "help" : args.Parameters[0].ToLower();

            switch (Parameter)
            {
            case "add":
            case "del":
            {
                if (!BTExtensions.IsAdmin(args.Player))
                {
                    return;
                }
                string Parameter2 = (args.Parameters.Count == 1) ? "help" : args.Parameters[1].ToLower();
                switch (Parameter2)
                {
                case "g":
                case "group":
                {
                    BTExtensions.ManagePrefixGroups(args);
                    return;
                }

                case "p":
                case "prefix":
                {
                    BTExtensions.ManagePrefixesInPrefixGroups(args);
                    return;
                }

                default:
                {
                    args.Player.SendSuccessMessage("BindPrefix help (1/1):");
                    args.Player.SendInfoMessage("{0}bprefix add group [Name] [Permission] [AllowedPrefixes (1 3 10...)]\r\n" +
                                                "{0}bprefix del group [Name]\r\n" +
                                                "{0}bprefix <add/del> prefix [Name] [PrefixID]", TShock.Config.CommandSpecifier);
                    return;
                }
                }
            }

            case "list":
            {
                var Available = BTExtensions.AvailablePrefixes(args.Player);
                if (Available.Item1)
                {
                    args.Player.SendSuccessMessage("All prefixes available.");
                }
                else if (Available.Item2.Count == 0)
                {
                    args.Player.SendSuccessMessage("No prefixes available.");
                }
                else
                {
                    args.Player.SendSuccessMessage("Available prefixes: {0}.", string.Join(", ", Available.Item2));
                }
                return;
            }

            case "listgr":
            {
                if (!BTExtensions.IsAdmin(args.Player))
                {
                    return;
                }
                args.Player.SendSuccessMessage("Available prefix groups:");
                args.Player.SendInfoMessage(string.Join("\r\n", Prefixes.Select(p =>
                                                                                string.Format("Name: {0}. Permission: {1}. Prefixes: {2}.",
                                                                                              p.Name, p.Permission, string.Join(", ", p.AllowedPrefixes)))));
                return;
            }

            case "help":
            {
                List <string> Help = new List <string>
                {
                    string.Format("{0}bpr [PrefixID]", TShock.Config.CommandSpecifier),
                    string.Format("{0}bpr list [page]", TShock.Config.CommandSpecifier)
                };
                if (args.Player.HasPermission("bindtools.admin"))
                {
                    List <string> Help2 = new List <string>
                    {
                        string.Format("{0}bpr listgr [page]", TShock.Config.CommandSpecifier),
                        string.Format("{0}bpr add <group/g> [Name] [Permission] [AllowedPrefixes (1 3 10...)]", TShock.Config.CommandSpecifier),
                        string.Format("{0}bpr del <group/g> [Name]", TShock.Config.CommandSpecifier),
                        string.Format("{0}bpr <add/del> <prefix/p> [Name] [PrefixID]", TShock.Config.CommandSpecifier)
                    };
                    Help.AddRange(Help2);
                }
                int page = 1;
                if ((args.Parameters.Count > 1) &&
                    (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out page)))
                {
                    return;
                }
                PaginationTools.SendPage(args.Player, page, Help,
                                         new PaginationTools.Settings
                    {
                        HeaderFormat = "BindPrefix help ({0}/{1}):",
                        FooterFormat = "Type {0}bpr help {{0}} for more info.".SFormat(TShock.Config.CommandSpecifier)
                    }
                                         );
                return;
            }
            }

            Tuple <bool, List <int> > Allowed = BTExtensions.AvailablePrefixes(args.Player);

            if (((Allowed.Item2 == null) || (Allowed.Item2.Count == 0)) && !Allowed.Item1)
            {
                args.Player.SendErrorMessage("No prefixes allowed.");
                return;
            }
            if (args.Parameters.Count != 1)
            {
                args.Player.SendErrorMessage("/bpr [PrefixID]");
                return;
            }
            if ((args.Player.TPlayer.selectedItem > 9) && (args.Player.TPlayer.selectedItem != 58))
            {
                args.Player.SendMessage("Please select an item from your hotbar or cursor", Color.Red);
                return;
            }
            if (!int.TryParse(args.Parameters[0], out int Prefix) ||
                (Prefix < 0) || (Prefix > (Lang.prefix.Length - 1)))
            {
                args.Player.SendErrorMessage("Invalid PrefixID!");
                return;
            }
            if (((Allowed.Item2 == null) || (!Allowed.Item2.Contains(Prefix))) && !Allowed.Item1)
            {
                args.Player.SendErrorMessage("This prefix is not allowed!");
                return;
            }

            bool SSC = Main.ServerSideCharacter;

            if (!SSC)
            {
                Main.ServerSideCharacter = true;
                NetMessage.SendData((int)PacketTypes.WorldInfo, args.Player.Index, -1, NetworkText.Empty);
            }

            Item Item = args.Player.TPlayer.inventory[args.Player.TPlayer.selectedItem];

            Item.prefix = (byte)Prefix;
            args.Player.TPlayer.inventory[args.Player.TPlayer.selectedItem] = Item;
            NetMessage.SendData((int)PacketTypes.PlayerSlot, -1, -1, NetworkText.FromLiteral(Item.Name), args.Player.Index, args.Player.TPlayer.selectedItem, Prefix);
            NetMessage.SendData((int)PacketTypes.PlayerSlot, args.Player.Index, -1, NetworkText.FromLiteral(Item.Name), args.Player.Index, args.Player.TPlayer.selectedItem, Prefix);

            if (!SSC)
            {
                Main.ServerSideCharacter = false;
                NetMessage.SendData((int)PacketTypes.WorldInfo, args.Player.Index, -1, NetworkText.Empty);
            }

            args.Player.SendSuccessMessage("Successfully changed [i:{0}]'s prefix to {1} ({2})", args.Player.TPlayer.inventory[args.Player.TPlayer.selectedItem].netID, Prefix, Lang.prefix[Prefix].Value);
        }
Пример #3
0
        void Schematic(CommandArgs e)
        {
            string subCmd = e.Parameters.Count == 0 ? "help" : e.Parameters[0].ToLowerInvariant();

            switch (subCmd)
            {
            case "del":
            case "delete":
            {
                if (e.Parameters.Count != 2)
                {
                    e.Player.SendErrorMessage("Invalid syntax! Proper syntax: //schematic delete <name>");
                    return;
                }
                string schematicPath = Path.Combine("worldedit", String.Format("schematic-{0}.dat", e.Parameters[1]));
                if (!File.Exists(schematicPath))
                {
                    e.Player.SendErrorMessage("Invalid schematic '{0}'!");
                    return;
                }
                File.Delete(schematicPath);
                e.Player.SendErrorMessage("Deleted schematic '{0}'.", e.Parameters[1]);
            }
                return;

            case "help":
                e.Player.SendSuccessMessage("Schematics Subcommands:");
                e.Player.SendInfoMessage("//schematic delete <name>");
                e.Player.SendInfoMessage("//schematic list [page]");
                e.Player.SendInfoMessage("//schematic load <name>");
                e.Player.SendInfoMessage("//schematic save <name>");
                return;

            case "list":
            {
                if (e.Parameters.Count > 2)
                {
                    e.Player.SendErrorMessage("Invalid syntax! Proper syntax: //schematic list [page]");
                    return;
                }

                int pageNumber;
                if (!PaginationTools.TryParsePageNumber(e.Parameters, 1, e.Player, out pageNumber))
                {
                    return;
                }

                var schematics = from s in Directory.EnumerateFiles("worldedit", "schematic-*.dat")
                                 select s.Substring(20, s.Length - 24);

                PaginationTools.SendPage(e.Player, pageNumber, PaginationTools.BuildLinesFromTerms(schematics),
                                         new PaginationTools.Settings
                    {
                        HeaderFormat = "Schematics ({0}/{1}):",
                        FooterFormat = "Type //schematic list {0} for more."
                    });
            }
                return;

            case "load":
            {
                if (e.Parameters.Count != 2)
                {
                    e.Player.SendErrorMessage("Invalid syntax! Proper syntax: //schematic load <name>");
                    return;
                }
                string schematicPath = Path.Combine("worldedit", String.Format("schematic-{0}.dat", e.Parameters[1]));
                if (!File.Exists(schematicPath))
                {
                    e.Player.SendErrorMessage("Invalid schematic '{0}'!");
                    return;
                }

                string clipboardPath = Path.Combine("worldedit", String.Format("clipboard-{0}.dat", e.Player.User.Name));
                File.Copy(schematicPath, clipboardPath, true);
                e.Player.SendSuccessMessage("Loaded schematic '{0}' to clipboard.", e.Parameters[1]);
            }
                return;

            case "save":
            {
                if (e.Parameters.Count != 2)
                {
                    e.Player.SendErrorMessage("Invalid syntax! Proper syntax: //schematic save <name>");
                    return;
                }
                string clipboardPath = Path.Combine("worldedit", String.Format("clipboard-{0}.dat", e.Player.User.Name));
                if (!File.Exists(clipboardPath))
                {
                    e.Player.SendErrorMessage("Invalid clipboard!");
                    return;
                }

                string schematicPath = Path.Combine("worldedit", String.Format("schematic-{0}.dat", e.Parameters[1]));
                File.Copy(clipboardPath, schematicPath, true);
                e.Player.SendSuccessMessage("Saved clipboard to schematic '{0}'.", e.Parameters[1]);
            }
                return;

            default:
                e.Player.SendErrorMessage("Invalid subcommand.");
                return;
            }
        }
Пример #4
0
        private void ChestCMD(CommandArgs args)
        {
            if (!usingInfChests)
            {
                args.Player.SendErrorMessage("InfiniteChests are currently disabled on this server.");
                return;
            }

            if (args.Parameters.Count == 0 || args.Parameters[0].ToLower() == "help")
            {
                List <string> help = new List <string>();

                args.Player.SendErrorMessage("Invalid syntax:");
                if (args.Player.HasPermission("ic.claim"))
                {
                    help.Add("/chest <claim/unclaim>");
                }
                if (args.Player.HasPermission("ic.info"))
                {
                    help.Add("/chest info");
                }
                if (args.Player.HasPermission("ic.search"))
                {
                    help.Add("/chest search <item name>");
                }
                if (args.Player.HasPermission("ic.claim"))
                {
                    help.Add("/chest allow <player name>");
                    help.Add("/chest remove <player name>");
                    help.Add("/chest allowgroup <group name>");
                    help.Add("/chest removegroup <group name>");
                }
                if (args.Player.HasPermission("ic.public"))
                {
                    help.Add("/chest public");
                }
                if (args.Player.HasPermission("ic.refill"))
                {
                    help.Add("/chest refill <seconds>");
                }
                help.Add("/chest cancel");

                int pageNumber;
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
                {
                    return;
                }

                PaginationTools.SendPage(args.Player, pageNumber, help, new PaginationTools.Settings()
                {
                    HeaderFormat = "Chest Subcommands ({0}/{1}):", FooterFormat = "Type /chest help {0} for more."
                });

                return;
            }

            PlayerInfo info = args.Player.GetData <PlayerInfo>(PIString);

            switch (args.Parameters[0].ToLower())
            {
            case "claim":
                if (!args.Player.HasPermission("ic.claim"))
                {
                    args.Player.SendErrorMessage("You do not have permission to claim chests.");
                    break;
                }
                args.Player.SendInfoMessage("Open a chest to claim it.");
                info.Action = ChestAction.Protect;
                break;

            case "unclaim":
                if (!args.Player.HasPermission("ic.claim"))
                {
                    args.Player.SendErrorMessage("You do not have permission to claim chests.");
                    break;
                }
                args.Player.SendInfoMessage("Open a chest to unclaim it.");
                info.Action = ChestAction.Unprotect;
                break;

            case "info":
                if (!args.Player.HasPermission("ic.info"))
                {
                    args.Player.SendErrorMessage("You do not have permission to view chest info.");
                    break;
                }
                args.Player.SendInfoMessage("Open a chest to get information about it.");
                info.Action = ChestAction.GetInfo;
                break;

            case "search":
                if (!args.Player.HasPermission("ic.search"))
                {
                    args.Player.SendErrorMessage("You do not have permission to search for chest items.");
                    break;
                }
                if (args.Parameters.Count < 2)
                {
                    args.Player.SendErrorMessage("Invalid syntax: /chest search <item name>");
                    break;
                }
                string name = string.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1));

                Item        exactmatch     = null;
                List <Item> partialMatches = new List <Item>();
                for (int i = 0; i < Main.maxItemTypes; i++)
                {
                    Item item = new Item();
                    item.SetDefaults(i);

                    if (item.Name.ToLower() == name.ToLower())
                    {
                        exactmatch = item;
                        break;
                    }
                    else if (item.Name.ToLower().Contains(name.ToLower()))
                    {
                        partialMatches.Add(item);
                    }
                }
                if (exactmatch != null)
                {
                    int count = DB.SearchChests(exactmatch.netID);
                    args.Player.SendSuccessMessage($"There are {count} chest(s) with {exactmatch.Name}(s).");
                }
                else if (partialMatches.Count == 1)
                {
                    int count = DB.SearchChests(partialMatches[0].netID);
                    args.Player.SendSuccessMessage($"There are {count} chest(s) with {partialMatches[0].Name}(s).");
                }
                else if (partialMatches.Count > 1)
                {
                    args.Player.SendErrorMessage($"Multiple matches found for item '{name}'.");
                }
                else
                {
                    args.Player.SendErrorMessage($"No matches found for item '{name}'.");
                }
                break;

            case "allow":
                if (!args.Player.HasPermission("ic.claim"))
                {
                    args.Player.SendErrorMessage("You do not have permission to allow other users to access this chest.");
                    return;
                }
                if (args.Parameters.Count < 2)
                {
                    args.Player.SendErrorMessage("Invalid syntax: /chest allow <player name>");
                }
                else
                {
                    name = string.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1));
                    var user = TShock.Users.GetUserByName(name);

                    if (user == null)
                    {
                        args.Player.SendErrorMessage("No player found by the name " + name);
                        return;
                    }
                    info.ExtraInfo = user.ID.ToString();
                    info.Action    = ChestAction.SetUser;
                    args.Player.SendInfoMessage("Open a chest to allow " + name + " to access it.");
                }
                break;

            case "remove":
                if (!args.Player.HasPermission("ic.claim"))
                {
                    args.Player.SendErrorMessage("You do not have permission to remove chest access from other users.");
                    return;
                }
                if (args.Parameters.Count < 2)
                {
                    args.Player.SendErrorMessage("Invalid syntax: /chest remove <player name>");
                }
                else
                {
                    name = string.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1));
                    var user = TShock.Users.GetUserByName(name);

                    if (user == null)
                    {
                        args.Player.SendErrorMessage("No player found by the name " + name);
                        return;
                    }
                    info.ExtraInfo = user.ID.ToString();
                    info.Action    = ChestAction.SetUser;
                    args.Player.SendInfoMessage("Open a chest to remove chest access from  " + name + ".");
                }
                break;

            case "allowgroup":
            case "allowg":
                if (!args.Player.HasPermission("ic.claim"))
                {
                    args.Player.SendErrorMessage("You do not have permission to allow other groups to access this chest.");
                    return;
                }
                if (args.Parameters.Count != 2)
                {
                    args.Player.SendErrorMessage("Invalid syntax: /chest allowgroup <group name>");
                }
                else
                {
                    var group = TShock.Groups.GetGroupByName(args.Parameters[1]);

                    if (group == null)
                    {
                        args.Player.SendErrorMessage("No group found by the name " + args.Parameters[1]);
                        return;
                    }
                    info.ExtraInfo = group.Name;
                    info.Action    = ChestAction.SetGroup;
                    args.Player.SendInfoMessage("Open a chest to allow users from the group " + group.Name + " to access it.");
                }
                break;

            case "removegroup":
            case "removeg":
                if (!args.Player.HasPermission("ic.claim"))
                {
                    args.Player.SendErrorMessage("You do not have permission to remove chest access from other groups.");
                    return;
                }
                if (args.Parameters.Count != 2)
                {
                    args.Player.SendErrorMessage("Invalid syntax: /chest removegroup <group name>");
                }
                else
                {
                    var group = TShock.Groups.GetGroupByName(args.Parameters[1]);

                    if (group == null)
                    {
                        args.Player.SendErrorMessage("No group found by the name " + args.Parameters[1]);
                        return;
                    }
                    info.ExtraInfo = group.Name;
                    info.Action    = ChestAction.SetGroup;
                    args.Player.SendInfoMessage("Open a chest to remove chest access from users in the group " + group.Name + ".");
                }
                break;

            case "public":
                if (!args.Player.HasPermission("ic.public"))
                {
                    args.Player.SendErrorMessage("You do not have permission to change a chest's public setting.");
                    break;
                }
                info.Action = ChestAction.TogglePublic;
                args.Player.SendInfoMessage("Open a chest to toggle the chest's public setting.");
                break;

            case "refill":
                if (!args.Player.HasPermission("ic.refill"))
                {
                    args.Player.SendErrorMessage("You do not have permission to set a chest's refill time.");
                    break;
                }
                if (args.Parameters.Count != 2)                         // /chest refill <time>
                {
                    args.Player.SendErrorMessage("Invalid syntax: /chest refill <seconds>");
                    break;
                }
                int refillTime;
                if (!int.TryParse(args.Parameters[1], out refillTime) || refillTime < -1 || refillTime > 99999)
                {
                    args.Player.SendErrorMessage("Invalid refill time.");
                    break;
                }
                info.Action    = ChestAction.SetRefill;
                info.ExtraInfo = refillTime.ToString();
                if (refillTime != -1)
                {
                    args.Player.SendInfoMessage("Open a chest to set its refill time to " + refillTime + " seconds.");
                }
                else
                {
                    args.Player.SendInfoMessage("Open a chest to remove auto-refill.");
                }
                break;

            case "cancel":
                info.Action = ChestAction.None;
                args.Player.SendInfoMessage("Canceled chest action.");
                break;

            default:
                args.Player.SendErrorMessage("Invalid syntax. Use '/chest help' for help.");
                break;
            }
        }
Пример #5
0
        private void msg(CommandArgs args)
        {
            int output;

            if ((args.Parameters.Count < 1))
            {
                args.Player.SendMessage("* Send message to someone: /msg <player> <message>", Color.LightBlue);
                args.Player.SendMessage("* Check your unread messages: /msg unread", Color.LightBlue);
                args.Player.SendMessage("* Check your read messages: /msg read", Color.LightBlue);
                args.Player.SendMessage("* Check your sent messages: /msg sent", Color.LightBlue);
                args.Player.SendMessage("* Check all your inbox: /msg inbox", Color.LightBlue);
                args.Player.SendMessage("* Read a message: /msg <ID>", Color.LightBlue);
                args.Player.SendMessage("* Delete a message: /msg del <ID>", Color.LightBlue);
                return;
            }
            if (args.Parameters[0] == "unread")
            {
                int pageNumber = 1;
                int count      = 0;
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
                {
                    return;
                }
                var lines    = new List <string> {
                };
                String total = "";
                using (var reader = MessengerDB.QueryReader("SELECT * FROM Messages"))
                {
                    while (reader.Read())
                    {
                        if ((reader.Get <string>("Receiver") == args.Player.Name) && (reader.Get <string>("Status") == "Unread"))
                        {
                            total = "[ID " + reader.Get <int>("ID") + "] [" + reader.Get <string>("Time").Remove(19) + "] " + "* " + reader.Get <string>("Sender") + ": " + reader.Get <string>("Message");
                            count++;
                            lines.Add(total);
                        }
                    }
                }
                PaginationTools.SendPage(args.Player, pageNumber, lines,
                                         new PaginationTools.Settings
                {
                    HeaderFormat    = "Unread messages ({0}/{1}):",
                    FooterFormat    = "Type {0}msg unread {{0}} for more messages. Message wil not be marked as read until you use /msg <id>".SFormat(Commands.Specifier),
                    MaxLinesPerPage = 4
                });
                if (count == 0)
                {
                    args.Player.SendMessage("No messages found.", Color.LightBlue);
                }
                return;
            }

            if (args.Parameters[0] == "read")
            {
                int pageNumber = 1;
                int count      = 0;
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
                {
                    return;
                }
                var lines    = new List <string> {
                };
                String total = "";
                using (var reader = MessengerDB.QueryReader("SELECT * FROM Messages"))
                {
                    while (reader.Read())
                    {
                        if ((reader.Get <string>("Receiver") == args.Player.Name) && (reader.Get <string>("Status") == "Read"))
                        {
                            count++;
                            total = "[ID " + reader.Get <int>("ID") + "] [" + reader.Get <string>("Time").Remove(19) + "] " + "* " + reader.Get <string>("Sender") + ": " + reader.Get <string>("Message");
                            lines.Add(total);
                        }
                    }
                }
                PaginationTools.SendPage(args.Player, pageNumber, lines,
                                         new PaginationTools.Settings
                {
                    HeaderFormat    = "Read messages ({0}/{1}):",
                    FooterFormat    = "Type {0}msg read {{0}} for more messages.".SFormat(Commands.Specifier),
                    MaxLinesPerPage = 4
                });
                if (count == 0)
                {
                    args.Player.SendMessage("No messages found.", Color.LightBlue);
                }
                return;
            }

            if (args.Parameters[0] == "sent")
            {
                int pageNumber = 1;
                int count      = 0;
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
                {
                    return;
                }
                var lines    = new List <string> {
                };
                String total = "";
                using (var reader = MessengerDB.QueryReader("SELECT * FROM Messages"))
                {
                    while (reader.Read())
                    {
                        if ((reader.Get <string>("Sender") == args.Player.Name))
                        {
                            count++;
                            total = "[ID " + reader.Get <int>("ID") + "] [" + reader.Get <string>("Time").Remove(19) + "] " + "* To: " + reader.Get <string>("Receiver") + ": " + reader.Get <string>("Message");
                            lines.Add(total);
                        }
                    }
                }
                PaginationTools.SendPage(args.Player, pageNumber, lines,
                                         new PaginationTools.Settings
                {
                    HeaderFormat    = "Sent messages ({0}/{1}):",
                    FooterFormat    = "Type {0}msg sent {{0}} for more messages.".SFormat(Commands.Specifier),
                    MaxLinesPerPage = 4
                });
                if (count == 0)
                {
                    args.Player.SendMessage("No messages found.", Color.LightBlue);
                }
                return;
            }

            if (args.Parameters[0] == "inbox")
            {
                int pageNumber = 1;
                int count      = 0;
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
                {
                    return;
                }
                var lines    = new List <string> {
                };
                String total = "";
                using (var reader = MessengerDB.QueryReader("SELECT * FROM Messages"))
                {
                    while (reader.Read())
                    {
                        if ((reader.Get <string>("Receiver") == args.Player.Name) && (reader.Get <string>("Status") != "Deleted"))
                        {
                            count++;
                            total = "[ID " + reader.Get <int>("ID") + "] [" + reader.Get <string>("Time").Remove(19) + "] " + "* " + reader.Get <string>("Sender") + ": " + reader.Get <string>("Message");
                            lines.Add(total);
                        }
                    }
                }
                PaginationTools.SendPage(args.Player, pageNumber, lines,
                                         new PaginationTools.Settings
                {
                    HeaderFormat    = "Inbox ({0}/{1}):",
                    FooterFormat    = "Type {0}msg inbox {{0}} for more messages.".SFormat(Commands.Specifier),
                    MaxLinesPerPage = 4
                });
                if (count == 0)
                {
                    args.Player.SendMessage("No messages found.", Color.LightBlue);
                }
                return;
            }

            if ((Int32.TryParse(args.Parameters[0], out output)) && (args.Parameters.Count == 1))
            {
                bool found = false;
                int  id    = Convert.ToInt32(args.Parameters[0]);
                using (var reader = MessengerDB.QueryReader("SELECT * FROM Messages"))
                {
                    while (reader.Read())
                    {
                        if ((reader.Get <int>("ID") == id) && (reader.Get <String>("Receiver") == args.Player.Name))
                        {
                            found = true;
                            args.Player.SendMessage("[" + reader.Get <string>("Time").Remove(19) + "] ", Color.LightBlue);
                            args.Player.SendMessage("* " + reader.Get <string>("Sender") + ": " + reader.Get <string>("Message"), Color.LightBlue);
                        }
                    }
                }
                if (found)
                {
                    var update = MessengerDB.Query("UPDATE Messages SET Status=@0 WHERE id= @1;", "Read", id);

                    return;
                }
                if (!found)
                {
                    args.Player.SendMessage("No message is found with that ID.", Color.LightBlue);
                    return;
                }
            }

            if (args.Parameters[0] == "del")
            {
                if ((args.Parameters.Count == 1) || (!Int32.TryParse(args.Parameters[1], out output)))
                {
                    args.Player.SendMessage("Invalid Syntax or ID: /msg del <ID>", Color.LightBlue);
                    return;
                }
                bool found = false;
                int  id    = Convert.ToInt32(args.Parameters[1]);
                using (var reader = MessengerDB.QueryReader("SELECT * FROM Messages"))
                {
                    while (reader.Read())
                    {
                        if ((reader.Get <int>("ID") == id) && (reader.Get <String>("Receiver") == args.Player.Name) && (reader.Get <String>("Status") != "Deleted"))
                        {
                            found = true;
                        }
                    }
                }
                if (found)
                {
                    var update = MessengerDB.Query("UPDATE Messages SET Status=@0 WHERE id= @1;", "Deleted", id);
                    args.Player.SendMessage("The Message has been deleted.", Color.LightBlue);
                    return;
                }
                if (!found)
                {
                    args.Player.SendMessage("No message is found with that ID.", Color.LightBlue);
                    return;
                }
            }

            #region addmsg

            if ((TShock.Users.GetUsersByName(args.Parameters[0]).Count == 0))
            {
                args.Player.SendMessage("No player with the name of \"" + args.Parameters[0] + "\" is found.", Color.LightBlue);
                return;
            }
            User   plyname = TShock.Users.GetUsersByName(args.Parameters[0])[0];
            string message = args.Parameters[1];
            if (args.Parameters.Count == 1)
            {
                args.Player.SendMessage("Message is empty.", Color.LightBlue);
                return;
            }
            if ((args.Parameters.Count > 2))
            {
                message = args.Parameters[1];
                for (int i = 2; i < args.Parameters.Count; i++)
                {
                    message = message + " " + args.Parameters[i];
                }
            }
            var add = MessengerDB.Query("INSERT INTO Messages (Time, Sender, Receiver, Message, WorldID, Status) VALUES (@0, @1, @2, @3, @4, @5);", DateTime.Now, args.Player.Name, plyname.Name, message, Main.worldID, "Unread");
            if ((TShock.Utils.FindPlayer(plyname.Name).Count == 0))
            {
                args.Player.SendMessage("Player " + plyname.Name + " is not online. They will be notified about your message on their next login.", Color.LightBlue);
                return;
            }
            if ((TShock.Utils.FindPlayer(plyname.Name).Count != 0))
            {
                if (((TShock.Utils.FindPlayer(plyname.Name)[0].RealPlayer)) && ((TShock.Utils.FindPlayer(plyname.Name)[0].ConnectionAlive)))
                {
                    TSPlayer receiver = TShock.Utils.FindPlayer(plyname.Name)[0];
                    args.Player.SendMessage("Player " + plyname.Name + " is online. They will be notified about your message.", Color.LightBlue);
                    int notiid = 0;
                    using (var reader = MessengerDB.QueryReader("SELECT * FROM Messages"))
                    {
                        while (reader.Read())
                        {
                            if ((reader.Get <string>("Receiver") == plyname.Name) && (reader.Get <string>("Status") == "Unread") && (reader.Get <string>("Sender") == args.Player.Name) && (reader.Get <int>("WorldID") == Main.worldID) && (reader.Get <string>("Message") == message))
                            {
                                notiid = reader.Get <int>("ID");
                            }
                        }
                    }
                    receiver.SendMessage("[Messenger] Player " + args.Player.Name + " has send you a message. Read it now using /msg " + notiid, Color.LightBlue);
                    return;
                }
            }
            #endregion addmsg
        }
Пример #6
0
        private static void CellManage(CommandArgs args)
        {
            var cmd  = args.Parameters.Count > 0 ? args.Parameters[0].ToLower() : "help";
            var info = PlayerInfo.GetInfo(args.Player);

            switch (cmd)
            {
            case "f**k":
            case "艹":
            {
                if (!args.Player.HasPermission("pm.admin.fuckcell"))
                {
                    args.Player.SendErrorMessage("无权限执行.");
                    return;
                }
                if (args.Parameters.Count != 1)
                {
                    args.Player.SendErrorMessage("语法无效. 正确语法: /mp f**k");
                    return;
                }
                info.Status     = PlayerInfo.PointStatus.Delegate;
                info.OnGetPoint = InternalFuckCell;
                args.Player.SendErrorMessage("在属地内放置任意物块, 来艹无聊的东西.");

                void InternalFuckCell(int tileX, int tileY, TSPlayer player)
                {
                    var cell = Plots.GetCellByPosition(tileX, tileY);

                    if (cell != null)
                    {
                        Plots.FuckCell(cell);
                        player.SendSuccessMessage("愉悦, 艹完了.");
                        return;
                    }
                    player.SendErrorMessage("选择点不在属地内.");
                }
            }
            break;

            case "info":
            {
                if (args.Parameters.Count != 1)
                {
                    args.Player.SendErrorMessage("语法无效. 正确语法: /gm get");
                    return;
                }
                info.Status     = PlayerInfo.PointStatus.Delegate;
                info.OnGetPoint = InternalCellInfo;
                args.Player.SendInfoMessage("在属地内放置任意物块, 来查看属地信息.");

                void InternalCellInfo(int tileX, int tileY, TSPlayer player)
                {
                    var cell = Plots.GetCellByPosition(tileX, tileY);

                    if (cell != null)
                    {
                        cell.GetInfo(player);
                        return;
                    }
                    player.SendErrorMessage("选择点不在属地内.");
                }
            }
            break;

            case "chown":
            {
                if (args.Parameters.Count < 2)
                {
                    args.Player.SendErrorMessage("语法无效. 正确语法: {0}", TShock.Utils.ColorTag("/cm chown <账户名>", Color.Cyan));
                    return;
                }

                info.Status     = PlayerInfo.PointStatus.Delegate;
                info.OnGetPoint = InternalChownWithPoint;
                args.Player.SendInfoMessage("在你的属地内放置物块来更换领主.");

                void InternalChownWithPoint(int x, int y, TSPlayer receiver) => InternalChown(args.Parameters, receiver, Plots.GetCellByPosition(x, y));

                void InternalChown(IEnumerable <string> parameters, TSPlayer player, Cell target)
                {
                    var playerName = string.Join(" ", parameters.Skip(1));
                    var user       = TShock.UserAccounts.GetUserAccountByName(playerName);

                    if (user == null)
                    {
                        player.SendErrorMessage("用户 " + playerName + " 未找到");
                        return;
                    }

                    if (target != null)
                    {
                        if (target.Owner != player.Account.Name && !player.HasPermission("pm.admin.editall"))
                        {
                            player.SendErrorMessage("你不是该属地的主人.");
                            return;
                        }

                        Plots.ChangeOwner(target, user);
                        player.SendSuccessMessage("完成更换主人.");
                    }
                    else
                    {
                        player.SendErrorMessage("该点坐标不在属地内.");
                    }
                }
            }
            break;

            case "help":
            {
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out var pageNumber))
                {
                    return;
                }
                var list = new List <string>
                {
                    "info - 获取选中点区域信息",
                    "f**k - 重置选中点区域",
                    "chown - 更改选中点区域所有者(未完成)",
                    "help [页码] - 获取帮助"
                };
                PaginationTools.SendPage(args.Player, pageNumber, list,
                                         new PaginationTools.Settings
                    {
                        HeaderFormat           = "玩家属地管理子指令说明 ({0}/{1}):",
                        FooterFormat           = "键入 {0}cm help {{0}} 以获取下一页列表.".SFormat(Commands.Specifier),
                        NothingToDisplayString = "当前没有说明."
                    });
            }
            break;

            default:
            {
                args.Player.SendWarningMessage("子指令无效! 输入 {0} 获取帮助信息.",
                                               TShock.Utils.ColorTag("/cm help", Color.Cyan));
            }
            break;
            }
        }
Пример #7
0
        private static void AreaManage(CommandArgs args)
        {
            var cmd  = args.Parameters.Count > 0 ? args.Parameters[0].ToLower() : "help";
            var info = PlayerInfo.GetInfo(args.Player);

            switch (cmd)
            {
            case "点":
            case "point":
            {
                if (args.Parameters.Count != 2)
                {
                    args.Player.SendErrorMessage("语法无效. 正确语法: /am point <1/2>");
                    return;
                }

                if (!byte.TryParse(args.Parameters[1], out var point) || point > 2 || point < 1)
                {
                    args.Player.SendErrorMessage("选点无效. 正确: /am point <1/2>");
                    return;
                }

                info.Status = (PlayerInfo.PointStatus)point;
                args.Player.SendInfoMessage("敲击物块以设定点 {0}", point);
            }
            break;

            case "定义":
            case "define":
            {
                if (args.Parameters.Count != 2)
                {
                    args.Player.SendErrorMessage("语法无效. 正确语法: /am define <区域名>");
                    return;
                }
                if (info.X == -1 || info.Y == -1 || info.X2 == -1 || info.Y2 == -1)
                {
                    args.Player.SendErrorMessage("你需要先选择区域.");
                    return;
                }
                if (Plots.AddPlot(info.X, info.Y, info.X2 - info.X, info.Y2 - info.Y,
                                  args.Parameters[1], args.Player.Name,
                                  Main.worldID.ToString(), Config.PlotStyle))
                {
                    args.Player.SendSuccessMessage("添加属地 {0} 完毕.", args.Parameters[1]);
                }
                else
                {
                    args.Player.SendSuccessMessage("属地 {0} 已经存在, 请更换属地名后重试.", args.Parameters[1]);
                }
            }
            break;

            case "删除":
            case "del":
            {
                if (args.Parameters.Count != 2)
                {
                    args.Player.SendErrorMessage("语法无效. 正确语法: /am del <区域名>");
                    return;
                }
                var name = args.Parameters[1];
                var plot = Plots.GetPlotByName(name);
                if (plot == null)
                {
                    args.Player.SendErrorMessage("未找到属地!");
                    return;
                }
                if (Plots.DelPlot(plot))
                {
                    args.Player.SendSuccessMessage("成功删除属地.");
                    return;
                }
                args.Player.SendErrorMessage("删除属地失败!");
            }
            break;

            case "划分":
            case "mark":
            {
                if (args.Parameters.Count < 2 || args.Parameters.Count > 3)
                {
                    args.Player.SendErrorMessage("语法无效. 正确语法: /am mark <区域名> [Clear:true/false]");
                    return;
                }
                var name = args.Parameters[1];
                var plot = Plots.GetPlotByName(name);
                if (plot == null)
                {
                    args.Player.SendErrorMessage("未找到属地!");
                    return;
                }
                var clear = true;
                if (args.Parameters.Count == 3)
                {
                    switch (args.Parameters[2].ToLower())
                    {
                    case "true":
                        break;

                    case "false":
                        clear = false;
                        break;

                    default:
                        args.Player.SendErrorMessage("Clear属性值只能为 true/false");
                        return;
                    }
                }
                plot.Generate(clear);
            }
            break;

            case "信息":
            case "info":
            {
                if (args.Parameters.Count != 2)
                {
                    args.Player.SendErrorMessage("语法无效. 正确语法: /am info <区域名>");
                    return;
                }
                var name = args.Parameters[1];
                var plot = Plots.GetPlotByName(name);
                if (plot == null)
                {
                    args.Player.SendErrorMessage("未找到属地!");
                    return;
                }

                if (!PaginationTools.TryParsePageNumber(args.Parameters, 2, args.Player, out var pageNumber))
                {
                    return;
                }
                var list = new List <string>
                {
                    $" * 区域信息: {{{plot.X}, {plot.Y}, {plot.Width}, {plot.Height}}}",
                    $" * 格子信息: w={plot.CellWidth}, h={plot.CellHeight}, cur={plot.Cells.Length}, used={plot.Cells.Count(c=>!string.IsNullOrWhiteSpace(c.Owner))}",
                    $" * 创建者名: {plot.Owner}"
                };
                PaginationTools.SendPage(args.Player, pageNumber, list,
                                         new PaginationTools.Settings
                    {
                        HeaderFormat           = "属地 " + plot.Name + " 说明 ({0}/{1}):",
                        FooterFormat           = "键入 {0}pm info {1} {{0}} 以获取下一页列表.".SFormat(Commands.Specifier, plot.Name),
                        NothingToDisplayString = "当前没有说明."
                    });
            }
            break;

            case "列表":
            case "list":
            {
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out var pageNumber))
                {
                    return;
                }

                var plots = Plots.Plots.Select(p => p.Name);

                PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(plots),
                                         new PaginationTools.Settings
                    {
                        HeaderFormat           = "属地列表 ({0}/{1}):",
                        FooterFormat           = "键入 {0}pm list {{0}} 以获取下一页列表.".SFormat(Commands.Specifier),
                        NothingToDisplayString = "当前没有属地."
                    });
            }
            break;

            case "重载":
            case "reload":
            {
                Plots.Reload();
                Config = Configuration.Read(Configuration.ConfigPath);
                Config.Write(Configuration.ConfigPath);
                args.Player.SendSuccessMessage("重载完毕.");
            }
            break;

            case "帮助":
            case "help":
            {
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out int pageNumber))
                {
                    return;
                }
                var list = new List <string>
                {
                    "point <1/2> - 选中点/区域",
                    "define <属地名> - 定义属地",
                    "del <属地名> - 删除属地",
                    "mark <属地名> - 在属地中生成格子",
                    "info <属地名> - 查看属地属性",
                    "list [页码] - 查看现有的属地",
                    "help [页码] - 获取帮助",
                    "reload - 载入数据库数据"
                };
                PaginationTools.SendPage(args.Player, pageNumber, list,
                                         new PaginationTools.Settings
                    {
                        HeaderFormat           = "属地管理子指令说明 ({0}/{1}):",
                        FooterFormat           = "键入 {0}am help {{0}} 以获取下一页列表.".SFormat(Commands.Specifier),
                        NothingToDisplayString = "当前没有说明."
                    });
            }
            break;

            default:
            {
                args.Player.SendWarningMessage("子指令无效! 输入 {0} 获取帮助信息.",
                                               TShock.Utils.ColorTag("/am help", Color.Cyan));
            }
            break;
            }
        }
Пример #8
0
        private void CheckReports(CommandArgs args)
        {
            //Pull unhandled reports from the db
            var reports = new List <Report>();

            using (var reader = Db.QueryReader("SELECT * FROM Reports"))
            {
                while (reader.Read())
                {
                    reports.Add(new Report(
                                    reader.Get <int>("ReportId"),
                                    reader.Get <int>("UserID"),
                                    reader.Get <int>("ReportedID"),
                                    reader.Get <string>("Message"),
                                    reader.Get <string>("Position"),
                                    reader.Get <int>("State"))
                                );
                }
            }
            if (reports.Count < 1)
            {
                args.Player.SendSuccessMessage("There are no reports to view.");
                return;
            }

            IOrderedEnumerable <Report> orderedReports =
                from r in reports orderby r.ReportID descending orderby r.State ascending select r;

            if (args.Parameters.Count == 0)
            {
                PaginationTools.SendPage(args.Player, 1, orderedReports.Select(r => r.ToString()).ToList(),
                                         new PaginationTools.Settings
                {
                    HeaderFormat = "Report IDs. Use /checkreports <id> to check a specific report. Page {0} of {1}",
                    FooterFormat = "Use /checkreports page {0} for more"
                });
            }

            else if (args.Parameters.Count >= 1)
            {
                if (String.Equals(args.Parameters[0], "page", StringComparison.InvariantCultureIgnoreCase))
                {
                    int pageNumber;
                    if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
                    {
                        return;
                    }

                    PaginationTools.SendPage(args.Player, pageNumber, orderedReports.Select(r => r.ToString()).ToList(),
                                             new PaginationTools.Settings
                    {
                        HeaderFormat =
                            "Report IDs. Use /checkreports <id> to check a specific report. Page {0} of {1}",
                        FooterFormat = "Use /checkreports page {0} for more"
                    });
                    return;
                }

                Report report;
                int    searchId;
                if (!int.TryParse(args.Parameters[0], out searchId))
                {
                    var search  = string.Join(" ", args.Parameters.Skip(1));
                    var matches = reports.Where(r => r.Message.ToLower().Contains(search.ToLower())).ToList();
                    if (matches.Count < 1)
                    {
                        args.Player.SendErrorMessage("No report messages matched your search '{0}'", search);
                        return;
                    }
                    if (matches.Count > 1)
                    {
                        SendMultipleMatches(args.Player, matches.Select(m => m.ToString()));
                        return;
                    }
                    report = matches[0];
                }
                else
                {
                    report = reports.FirstOrDefault(r => r.ReportID == searchId);
                    if (report == null)
                    {
                        args.Player.SendErrorMessage("No report ID matched your search '{0}'", searchId);
                        return;
                    }
                }

                if (report.Header != string.Empty)
                {
                    args.Player.SendWarningMessage(string.Format("----{0}-----", report.Header));
                }
                args.Player.SendSuccessMessage("Report ID: #{0}", report.ReportID);
                if (report.ReportedID != -1)
                {
                    args.Player.SendSuccessMessage("Reported user: {0}", TShock.Users.GetUserByID(report.ReportedID).Name);
                }
                args.Player.SendSuccessMessage("Reported by: {0} at position ({1})",
                                               TShock.Users.GetUserByID(report.UserID).Name, report.x + "," + report.y);
                args.Player.SendSuccessMessage("Report reason: {0}", report.Message);
                if (args.Player.Index > _teleports.Length || args.Player.Index < 0)
                {
                    args.Player.SendWarningMessage("Failed to assign a teleport for this report.");
                    args.Player.SendWarningMessage("Please make sure you are logged in while using this command");
                    return;
                }
                _teleports[args.Player.Index] = new Vector2(report.x, report.y);
                _report[args.Player.Index]    = report;
                args.Player.SendWarningMessage("Use /rteleport to move to the report location.");

                Db.SetValue("State", 1, "ReportID", report.ReportID);
            }
        }
Пример #9
0
        public static void CmdUic(CommandArgs args)
        {
            if (args.Parameters.Count < 1)
            {
                args.Player.SendErrorMessage("Invalid syntax. Try /uix [playerName]");
                return;
            }

            if (args.Parameters[0] == "self")
            {
                SPlayer player = Statistics.Tools.GetPlayer(args.Player.Index);
                if (player == null)
                {
                    return;
                }

                if (player.TsPlayer.IsLoggedIn)
                {
                    int pageNumber;
                    if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
                    {
                        return;
                    }

                    Tools.SendUic(args.Player, player, pageNumber);
                }
                else
                {
                    args.Player.SendErrorMessage("You must be logged in to use this on yourself");
                }
            }
            else
            {
                string name;
                var    needNumber = false;
                if (args.Parameters.Count > 1)
                {
                    var newArgs = new List <string>(args.Parameters);
                    newArgs.RemoveAt(newArgs.Count - 1);
                    name       = string.Join(" ", newArgs);
                    needNumber = true;
                }
                else
                {
                    name = string.Join(" ", args.Parameters);
                }

                int pageNumber;
                if (!PaginationTools.TryParsePageNumber(args.Parameters,
                                                        needNumber ? args.Parameters.Count - 1 : args.Parameters.Count + 1, args.Player, out pageNumber))
                {
                    return;
                }

                IPAddress ip;
                if (IPAddress.TryParse(name, out ip))
                {
                    var players = Statistics.Tools.GetPlayersByIp(ip.ToString());

                    if (players.Count > 1)
                    {
                        TShock.Utils.SendMultipleMatchError(args.Player, players.Select(p => p.Name));
                        return;
                    }

                    if (players.Count == 0)
                    {
                        var splayers = Statistics.Tools.GetStoredPlayersByIp(ip.ToString());

                        if (splayers.Count > 1)
                        {
                            TShock.Utils.SendMultipleMatchError(args.Player, splayers.Select(p => p.name));
                            return;
                        }
                        if (splayers.Count == 0)
                        {
                            args.Player.SendErrorMessage("No matches found for query '{0}'", name);
                            return;
                        }

                        var splayer = splayers[0];
                        Tools.SendUic(args.Player, splayer, pageNumber);

                        return;
                    }

                    var player = players[0];

                    Tools.SendUix(args.Player, player, pageNumber);
                    return;
                }

                var players2 = Statistics.Tools.GetPlayers(name);

                if (players2.Count > 1)
                {
                    TShock.Utils.SendMultipleMatchError(args.Player, players2.Select(p => p.Name));
                    return;
                }
                if (players2.Count == 0)
                {
                    args.Player.SendErrorMessage(
                        "Invalid player. Try /check name {0} to make sure you're using the right username",
                        name);
                    return;
                }

                var player2 = players2[0];

                Tools.SendUic(args.Player, player2, pageNumber);
            }
        }
Пример #10
0
        private static void MiscMod(CommandArgs args)
        {
            if (args.Parameters.Count == 0)
            {
                args.Player.SendErrorMessage("Wrong Syntax. " + miscParameters);
                return;
            }

            int pageNumber;
            int selection;

            switch (args.Parameters[0])
            {
            case "enableplugin":
            case "ep":
                PvPController.config.enablePlugin = !PvPController.config.enablePlugin;
                args.Player.SendSuccessMessage("Plugin enabled: " + PvPController.config.enablePlugin);
                break;

            case "deathitemtag":
            case "dit":
                if (args.Parameters.Count == 1)
                {
                    args.Player.SendErrorMessage("Wrong Syntax. /miscmod deathitemtag <message>");
                    return;
                }

                PvPController.config.deathItemTag = args.Parameters[1];
                args.Player.SendSuccessMessage("Death tag set to: " + args.Parameters[1]);
                break;

            case "iframetime":
            case "ift":
                if (args.Parameters.Count == 1)
                {
                    args.Player.SendErrorMessage("Wrong Syntax. /miscmod iframetime <seconds>");
                    return;
                }

                int iframeTime;

                if (!Int32.TryParse(args.Parameters[1], out iframeTime))
                {
                    args.Player.SendErrorMessage("Invalid iframetime of " + args.Parameters[1]);
                    return;
                }

                PvPController.config.iframeTime = iframeTime * 1000.0;
                args.Player.SendSuccessMessage("Invincibility frame time set to " + iframeTime + "s");
                break;

            case "deathmessages":
            case "dm":

                if (args.Parameters.Count == 1)
                {
                    args.Player.SendErrorMessage("Wrong syntax. /miscmod deathmessages <add/del/list>");
                    return;
                }

                switch (args.Parameters[1])
                {
                case "add":
                    if (args.Parameters.Count == 2)
                    {
                        args.Player.SendErrorMessage("Invalid Syntax. /miscmod deathmessages add <normal/reflection> <deathmessage>");
                        return;
                    }

                    if (args.Parameters[2] == "normal")
                    {
                        PvPController.config.normalDeathMessages.Add(args.Parameters[3]);
                        args.Player.SendSuccessMessage("Normal death message added: \"" + args.Parameters[3] + "\"");
                    }
                    else if (args.Parameters[2] == "reflection")
                    {
                        PvPController.config.reflectedDeathMessages.Add(args.Parameters[3]);
                        args.Player.SendSuccessMessage("Reflection death message added: \"" + args.Parameters[3] + "\"");
                    }
                    else
                    {
                        args.Player.SendErrorMessage("Invalid Syntax. /miscmod deathmessages add <normal/reflection> <deathmessage>");
                    }
                    break;

                case "del":
                    if (args.Parameters.Count == 2)
                    {
                        args.Player.SendErrorMessage("Invalid Syntax. /miscmod deathmessages del <normal/reflection> <death message #>");
                        return;
                    }

                    if (args.Parameters[2] == "normal")
                    {
                        if (!Int32.TryParse(args.Parameters[3], out selection) || selection > PvPController.config.normalDeathMessages.Count)
                        {
                            args.Player.SendErrorMessage("Invalid selection of " + args.Parameters[3]);
                            return;
                        }

                        selection--;

                        args.Player.SendSuccessMessage("Deleted normal death message: " + PvPController.config.normalDeathMessages[selection]);

                        PvPController.config.normalDeathMessages.RemoveAt(selection);
                    }
                    else if (args.Parameters[2] == "reflection")
                    {
                        if (!Int32.TryParse(args.Parameters[3], out selection) || selection > PvPController.config.normalDeathMessages.Count)
                        {
                            args.Player.SendErrorMessage("Invalid selection of " + args.Parameters[3]);
                            return;
                        }

                        selection--;

                        args.Player.SendSuccessMessage("Deleted reflection death message: " + PvPController.config.reflectedDeathMessages[selection]);

                        PvPController.config.reflectedDeathMessages.RemoveAt(selection);
                    }
                    else
                    {
                        args.Player.SendErrorMessage("Invalid Syntax. /miscmod deathmessages del <normal/reflection> <death message #>");
                    }
                    break;

                case "list":
                    if (args.Parameters.Count == 2)
                    {
                        args.Player.SendErrorMessage("Invalid Syntax. /miscmod deathmessages list <normal/reflection>");
                        return;
                    }

                    if (args.Parameters[2] == "normal")
                    {
                        if (!PaginationTools.TryParsePageNumber(args.Parameters, 3, args.Player, out pageNumber))
                        {
                            return;
                        }

                        PaginationTools.SendPage(args.Player, pageNumber, PvPController.config.normalDeathMessages, new PaginationTools.Settings()
                        {
                            HeaderFormat = "Normal Death Messages list ({0}/{1}):",
                            FooterFormat = "Type {0}miscmod deathmessages normal {{0}} for more death messages.".SFormat((args.Silent ? TShock.Config.CommandSilentSpecifier : TShock.Config.CommandSpecifier))
                        });
                    }
                    else if (args.Parameters[2] == "reflection")
                    {
                        if (!PaginationTools.TryParsePageNumber(args.Parameters, 3, args.Player, out pageNumber))
                        {
                            return;
                        }

                        PaginationTools.SendPage(args.Player, pageNumber, PvPController.config.reflectedDeathMessages, new PaginationTools.Settings()
                        {
                            HeaderFormat = "Reflected Death Messages list ({0}/{1}):",
                            FooterFormat = "Type {0}miscmod deathmessages reflection {{0}} for more death messages.".SFormat((args.Silent ? TShock.Config.CommandSilentSpecifier : TShock.Config.CommandSpecifier))
                        });
                    }
                    else
                    {
                        args.Player.SendErrorMessage("Invalid Syntax. /miscmod deathmessages list <normal/reflection>");
                    }
                    break;

                default:
                    args.Player.SendErrorMessage("Wrong syntax. /miscmod deathmessages <add/del/list>");
                    break;
                }

                break;

            default:
                args.Player.SendErrorMessage("Wrong Syntax. " + miscParameters);
                break;
            }
        }
Пример #11
0
        public static void InventoryCommand(CommandArgs args)
        {
            if (!args.Player.IsLoggedIn)
            {
                args.Player.SendErrorMessage("You must be logged in to do that.");
                return;
            }

            if (args.Parameters.Count < 1)
            {
                args.Player.SendErrorMessage("Invalid syntax! Proper syntax:");
                args.Player.SendErrorMessage("{0}inventory save <name> - saves/updates your current inventory", TShock.Config.CommandSpecifier);
                args.Player.SendErrorMessage("{0}inventory load <name> - loads an inventory", TShock.Config.CommandSpecifier);
                args.Player.SendErrorMessage("{0}inventory delete <name> - deletes an inventory", TShock.Config.CommandSpecifier);
                args.Player.SendErrorMessage("{0}inventory list - lists all your inventories", TShock.Config.CommandSpecifier);
                return;
            }

            switch (args.Parameters[0].ToLower())
            {
            case "save":
                #region Save Inventory
            {
                if (args.Parameters.Count < 2)
                {
                    args.Player.SendErrorMessage("Invalid syntax: {0}inventory save <inventory name>", TShock.Config.CommandSpecifier);
                    return;
                }
                else
                {
                    if (!Instance.Players.ContainsKey(args.Player.User.ID))
                    {
                        Instance.Players.Add(args.Player.User.ID, new UIPlayer(args.Player.User.ID, new Dictionary <string, NetItem[]>()));
                    }

                    args.Parameters.RemoveRange(0, 1);                                     // Remove "save"
                    string inventoryName = string.Join(" ", args.Parameters.Select(x => x));
                    if (Instance.Players.ContainsKey(args.Player.User.ID) && Instance.Players[args.Player.User.ID].InventoryCount() >= Instance.Configuration.MaxInventories && !args.Player.HasPermission(Instance.Configuration.BypassMaxPermission))
                    {
                        args.Player.SendErrorMessage("You have reached the max amount of inventories.");
                        return;
                    }
                    else
                    {
                        Instance.Players[args.Player.User.ID].CreateInventory(inventoryName);
                        args.Player.SendSuccessMessage($"Inventory saved ('{inventoryName}')!");
                    }
                }
            }
                #endregion
                break;

            case "load":
                #region Load Inventory
            {
                if (args.Parameters.Count != 2)
                {
                    args.Player.SendErrorMessage("Invalid syntax: {0}inventory load <inventory name>", TShock.Config.CommandSpecifier);
                    return;
                }
                else if (!Instance.Players.ContainsKey(args.Player.User.ID))
                {
                    args.Player.SendErrorMessage("You don't have any inventories saved!");
                    return;
                }
                else
                {
                    args.Parameters.RemoveRange(0, 1);
                    string inventoryName = string.Join(" ", args.Parameters.Select(x => x));
                    if (!Instance.Players[args.Player.User.ID].HasInventory(inventoryName))
                    {
                        args.Player.SendErrorMessage($"No inventories under the name of '{inventoryName}' were found. \nMake sure you spelled it correctly.");
                        return;
                    }
                    else
                    {
                        Instance.Players[args.Player.User.ID].LoadInventory(inventoryName);
                        args.Player.SendSuccessMessage($"Loaded inventory '{inventoryName}'!");
                    }
                }
            }
                #endregion
                break;

            case "del":
            case "rem":
            case "delete":
            case "remove":
                #region Delete Inventory
            {
                if (args.Parameters.Count != 2)
                {
                    args.Player.SendErrorMessage("Invalid syntax: {0}inventory delete <name>", TShock.Config.CommandSpecifier);
                    return;
                }
                else if (!Instance.Players.ContainsKey(args.Player.User.ID))
                {
                    args.Player.SendErrorMessage("You don't have any inventories saved!");
                    return;
                }
                else
                {
                    args.Parameters.RemoveRange(0, 1);
                    string inventoryName = string.Join(" ", args.Parameters.Select(x => x));
                    if (!Instance.Players[args.Player.User.ID].HasInventory(inventoryName))
                    {
                        args.Player.SendErrorMessage($"No inventories under the name of '{inventoryName}' were found. \nMake sure you spelled it correctly.");
                        return;
                    }
                    else
                    {
                        Instance.Players[args.Player.User.ID].DeleteInventory(inventoryName);
                        args.Player.SendSuccessMessage($"Deleted inventory '{inventoryName}'!");
                    }
                }
            }
                #endregion
                break;

            case "list":
                #region List Inventories
            {
                if (!Instance.Players.ContainsKey(args.Player.User.ID))
                {
                    args.Player.SendErrorMessage("You don't have any inventories saved!");
                    return;
                }

                if (args.Parameters.Count > 2)
                {
                    args.Player.SendErrorMessage("Invalid syntax: {0}inventory list [page]", TShock.Config.CommandSpecifier);
                    return;
                }
                else
                {
                    int pageNum;
                    if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNum))
                    {
                        return;
                    }

                    PaginationTools.SendPage(args.Player, pageNum, PaginationTools.BuildLinesFromTerms(Instance.Players[args.Player.User.ID].GetInventories()),
                                             new PaginationTools.Settings
                        {
                            HeaderFormat           = "Inventories ({0}/{1})",
                            FooterFormat           = "Type {0}inventory list {{0}} for more.".SFormat(TShock.Config.CommandSpecifier),
                            NothingToDisplayString = "You have no inventories to display."
                        });
                }
            }
                #endregion
                break;
            }
        }
Пример #12
0
        private void CIDRBanCommand(CommandArgs args)
        {
            TSPlayer player = args.Player;

            // check subcommands, no subcommands imply "help"
            string subcmd = args.Parameters.Count == 0 ? "help" : args.Parameters[0].ToLower();

            switch (subcmd)
            {
            case "help":
            {
                player.SendInfoMessage("CIDR Bans Plugin");
                player.SendInfoMessage("Description: Allows banning CIDR ranges");
                player.SendInfoMessage("Syntax: {0}cidrban <add/addtemp/del/list> [arguments]", Commands.Specifier);
                player.SendInfoMessage("Type {0}help cidrban for more info.", Commands.Specifier);
            }
            break;

            case "add":
            {
                // ensure proper usage
                if (args.Parameters.Count < 2)
                {
                    player.SendErrorMessage("Invalid syntax! Proper syntax: {0}cidrban add <range> [reason]", Commands.Specifier);
                    return;
                }
                if (!Regex.IsMatch(args.Parameters[1], rangeregex))
                {
                    player.SendErrorMessage("Invalid CIDR range string! Proper format: 0-255.0-255.0-255.0-255/0-32");
                    return;
                }

                // parse reason string, set to default if none
                if (args.Parameters.Count < 3)
                {
                    args.Parameters.Add("Manually added IP address ban.");
                }
                args.Parameters[2] = String.Join(" ", args.Parameters.GetRange(2, args.Parameters.Count - 2));

                // add ban to database
                if (cidrbans.AddCIDRBan(args.Parameters[1], args.Parameters[2], player.Name, DateTime.UtcNow.ToString("s")))
                {
                    player.SendSuccessMessage("Banned range {0} for '{1}'.", args.Parameters[1], args.Parameters[2]);
                }
                else
                {
                    player.SendErrorMessage("Adding range {0} into database failed.", args.Parameters[1]);
                }
            }
            break;

            case "addtemp":
            {
                // ensure proper usage
                if (args.Parameters.Count < 3)
                {
                    player.SendErrorMessage("Invalid syntax! Proper syntax: {0}cidrban addtemp <range> <time> [reason]", Commands.Specifier);
                    return;
                }
                if (!Regex.IsMatch(args.Parameters[1], rangeregex))
                {
                    player.SendErrorMessage("Invalid CIDR range string! Proper format: 0-255.0-255.0-255.0-255/0-32");
                    return;
                }

                // parse time into seconds
                int exp;
                if (!TShock.Utils.TryParseTime(args.Parameters[2], out exp))
                {
                    args.Player.SendErrorMessage("Invalid time string! Proper format: _d_h_m_s, with at least one time specifier.");
                    args.Player.SendErrorMessage("For example, 1d and 10h-30m+2m are both valid time strings, but 2 is not.");
                    return;
                }

                // parse reason string, set to default if none
                if (args.Parameters.Count < 4)
                {
                    args.Parameters.Add("Manually added IP address ban.");
                }
                args.Parameters[3] = String.Join(" ", args.Parameters.GetRange(3, args.Parameters.Count - 3));

                // add ban to database
                if (cidrbans.AddCIDRBan(args.Parameters[1], args.Parameters[3], player.Name,
                                        DateTime.UtcNow.ToString("s"), DateTime.UtcNow.AddSeconds(exp).ToString("s")))
                {
                    player.SendSuccessMessage("Banned range {0} for '{1}'.", args.Parameters[1], args.Parameters[3]);
                }
                else
                {
                    player.SendErrorMessage("Adding range {0} into database failed.", args.Parameters[1]);
                }
            }
            break;

            case "del":
            {
                // ensure proper usage
                if (args.Parameters.Count < 2)
                {
                    player.SendErrorMessage("Invalid syntax! Proper syntax: {0}cidrban del <ip/range>", Commands.Specifier);
                    return;
                }

                // remove ban via range
                if (Regex.IsMatch(args.Parameters[1], rangeregex))
                {
                    if (cidrbans.DelCIDRBanByRange(args.Parameters[1]))
                    {
                        player.SendSuccessMessage("Unbanned range {0}.", args.Parameters[1]);
                    }
                    else
                    {
                        player.SendErrorMessage("Removing range {0} from database failed.", args.Parameters[1]);
                    }
                    return;
                }

                // remove ban via ip
                if (Regex.IsMatch(args.Parameters[1], ipregex))
                {
                    // remove all ranges containing ip
                    List <string> removed = cidrbans.DelCIDRBanByIP(args.Parameters[1]);
                    if (removed.Count == 0)
                    {
                        player.SendErrorMessage("Removing range {0} from database failed.", args.Parameters[1]);
                        return;
                    }
                    player.SendSuccessMessage("Removed {0} range{1} from the database:", removed.Count, removed.Count == 1 ? "" : "s");
                    player.SendInfoMessage(String.Join(", ", removed));
                    return;
                }

                // improper argument format
                player.SendErrorMessage("Invalid syntax! Proper syntax: {0}cidrban del <ip/range>", Commands.Specifier);
                player.SendErrorMessage("IP proper format: 0-255.0-255.0-255.0-255");
                player.SendErrorMessage("CIDR range proper format : 0-255.0-255.0-255.0-255/0-32");
            }
            break;

            case "list":
            {
                // integrate pagination tool
                int pagenumber;
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pagenumber))
                {
                    return;
                }

                // fetch only ranges from the list
                List <CIDRBan> list     = cidrbans.GetCIDRBanList();
                var            namelist = from ban in list
                                          select ban.CIDR;

                // show data from user's specified page
                PaginationTools.SendPage(player, pagenumber, PaginationTools.BuildLinesFromTerms(namelist),
                                         new PaginationTools.Settings
                    {
                        HeaderFormat           = "CIDR Range Bans ({0}/{1}):",
                        FooterFormat           = "Type {0}ban list {{0}} for more.".SFormat(Commands.Specifier),
                        NothingToDisplayString = "There are currently no CIDR range bans."
                    });
            }
            break;

            default:
            {
                player.SendErrorMessage("Invalid subcommand. Type {0}help cidrban for information.", Commands.Specifier);
            }
            break;
            }
        }
Пример #13
0
        private void Buy(CommandArgs args)
        {
            if ((args.Parameters.Count < 1))
            {
                args.Player.SendErrorMessage("Check out our Shop, use: /buy name or /buy menu");
                return;
            }
            if (args.Parameters[0] == "menu")
            {
                int pageNumber = 1;
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
                {
                    return;
                }
                var lines = new List <string> {
                };
                foreach (var gooda in config.All)
                {
                    string total = "* " + gooda.DisplayName + " - ";
                    foreach (var item in gooda.IncludeItems)
                    {
                        total = total + ItemToTag(item) + " - " + Wolfje.Plugins.SEconomy.Money.Parse(Convert.ToString(gooda.Price));
                    }
                    if (args.Player.Group.HasPermission(gooda.RequirePermission))
                    {
                        lines.Add(total);
                    }
                    else if (!config.HideUnavailableGoods)
                    {
                        string perm = args.Player.Group.HasPermission(gooda.RequirePermission) ? "[Available]" : "[Shortage]";
                        lines.Add(perm + total);
                    }
                }
                PaginationTools.SendPage(args.Player, pageNumber, lines,
                                         new PaginationTools.Settings
                {
                    HeaderFormat    = "Menu ({0}/{1}):",
                    FooterFormat    = "Type {0}buy menu {{0}} for more goods.".SFormat(Commands.Specifier),
                    MaxLinesPerPage = 9
                }
                                         );
                return;
            }
            var    Find        = new Goods();
            bool   FindSuccess = false;
            int    number      = args.Parameters.Count;
            string medname     = args.Parameters[0];

            for (int i = 1; i < number; i++)
            {
                medname = medname + " " + args.Parameters[i];
            }
            foreach (var i1 in config.All)
            {
                if (medname.ToLower() == i1.DisplayName.ToLower())
                {
                    Find        = i1;
                    FindSuccess = true;
                }
            }



            if ((!FindSuccess) || (!args.Player.Group.HasPermission(Find.RequirePermission) && config.HideUnavailableGoods))
            {
                args.Player.SendErrorMessage("Can't find a good with given name. Type /buy menu for list.");
                return;
            }
            if (!args.Player.Group.HasPermission(Find.RequirePermission))
            {
                args.Player.SendErrorMessage("There is a shortage! Why not try another goods?");
                return;
            }



            var   UsernameBankAccount = SEconomyPlugin.Instance.GetBankAccount(args.Player.Name);
            var   playeramount        = UsernameBankAccount.Balance;
            Money amount         = -Find.Price;
            Money amount2        = Find.Price;
            var   amount3        = Wolfje.Plugins.SEconomy.Money.Parse(Convert.ToString(amount2));
            var   Journalpayment = Wolfje.Plugins.SEconomy.Journal.BankAccountTransferOptions.AnnounceToSender;



            if (args.Player == null || UsernameBankAccount == null)
            {
                args.Player.SendErrorMessage("Can't find the account for {0}.", args.Player.Name);
                return;
            }

            if (playeramount < amount2)
            {
                args.Player.SendErrorMessage("The price of " + Find.DisplayName + " is " + Wolfje.Plugins.SEconomy.Money.Parse(Convert.ToString(Find.Price)) + " , but you only have " + UsernameBankAccount.Balance + " in your account.");
                return;
            }



            if (!args.Player.InventorySlotAvailable)
            {
                args.Player.SendErrorMessage("Your inventory is full.");
                return;
            }



            SEconomyPlugin.Instance.WorldAccount.TransferToAsync(UsernameBankAccount, amount,
                                                                 Journalpayment, string.Format("Pay {0} to shop", amount2),
                                                                 string.Format("Buying " + Find.DisplayName));
            args.Player.SendSuccessMessage("You have paid {0} to buy {1}.", amount2, Find.DisplayName);
            TShock.Log.ConsoleInfo("{0} has paid {2} to buy {1}.", args.Player.Name, Find.DisplayName, amount2);
            foreach (var item in Find.IncludeItems)
            {
                var q = new Item();
                q.netDefaults(item.netID);
                q.stack = item.stack;
                q.Prefix(item.prefix);
                args.Player.GiveItemCheck(q.type, q.Name, q.width, q.height, q.stack, q.prefix);
            }
            var num = ShopDB.Query("INSERT INTO ShopHistory (Time, Account, ItemName, WorldID, price) VALUES (@0, @1, @2, @3, @4);", DateTime.Now, args.Player.Name, Find.DisplayName, Main.worldID, amount3);
        }
Пример #14
0
        public static void BroadcastInfo(CommandArgs args)
        {
            int pageParamIndex = 1;
            int pageNumber;

            if (args.Parameters.Count < 1)
            {
                throw new CommandException("Invalid usage! Usage: /autobc info <broadcast name>");
            }

            string broadcastName = args.Parameters[0];

            if (!Utils.BroadcastExists(broadcastName))
            {
                throw new CommandException("A Broadcast with that name does not exist! Type /autobc list, for a list of Broadcasts.");
            }

            Broadcast broadcast = Utils.GetBroadcastByName(broadcastName);

            string messages = string.Join("; ", broadcast.Messages);

            if (broadcast.Messages.Count > 1)
            {
                messages = $"Enter /autobc listmessages \"{broadcastName}\" for the messages of this broadcast.";
            }
            string triggerRegions = string.Join("; ", broadcast.TriggerRegions);

            /*if (broadcast.TriggerRegions.Count > 4)
             *      triggerRegions = $"Enter /autobc listregions \"{broadcastName}\" for the triggerRegions of this broadcast.";*/
            string groups = string.Join("; ", broadcast.Groups);

            /*	if (broadcast.TriggerRegions.Count > 5)
             *              groups = $"Enter /autobc listregions \"{broadcastName}\" for the triggerRegions of this broadcast.";*/
            string triggerWords = string.Join("; ", broadcast.TriggerWords);

            /*	if (broadcast.TriggerRegions.Count > 5)
             *              triggerRegions = $"Enter /autobc listregions \"{broadcastName}\" for the triggerRegions of this broadcast.";*/


            string[] broadcastInfo = new[]
            {
                $"Enabled: {(broadcast.Enabled ? "true" : "false")}",
                $"Interval: {broadcast.Interval}",
                $"StartDelay: {broadcast.StartDelay}",
                $"Color: {string.Join(", ", broadcast.Color)}",
                $"Message: {messages}",
                $"TriggerRegion: {triggerRegions}",
                $"RegionTriggerTo: {broadcast.RegionTriggerTo}",
                $"Groups: {groups}",
                $"triggerWords: {triggerWords}",
                $"TriggerToWholeGroup: {(broadcast.TriggerToWholeGroup ? "true" : "false")}",
            };


            if (!PaginationTools.TryParsePageNumber(args.Parameters, pageParamIndex, args.Player, out pageNumber))
            {
                return;
            }

            PaginationTools.SendPage(args.Player, pageNumber, broadcastInfo,
                                     new PaginationTools.Settings
            {
                HeaderFormat    = $"\"{broadcastName}\" Info ({{0}}/{{1}}):",
                FooterFormat    = $"Type /autobc info \"{broadcastName}\" {{0}} for more.",
                MaxLinesPerPage = 5,
            });
        }
Пример #15
0
        void Craft(CommandArgs args)
        {
            Item item;
            var  player = Utils.GetPlayer(args.Player.Index);

            if (args.Parameters.Count == 0)
            {
                args.Player.SendErrorMessage("Invalid syntax! Proper syntax: /craft <recipe/-quit/-list/-allcats/-cat{0}>",
                                             (config.CraftFromInventory) ? "/-confirm" : "");
                return;
            }

            var subcmd = args.Parameters[0].ToLower();

            switch (subcmd)
            {
            case "-list":
                int page;
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out page))
                {
                    return;
                }

                List <string> allRec = new List <string>();

                // Add any recipe that isn't invisible kappa
                foreach (Recipe rec in CmdRec.config.Recipes.FindAll(r => !r.invisible))
                {
                    allRec.Add(rec.name);
                }
                PaginationTools.SendPage(args.Player, page, PaginationTools.BuildLinesFromTerms(allRec),
                                         new PaginationTools.Settings
                {
                    HeaderFormat           = "Recipes ({0}/{1}):",
                    FooterFormat           = "Type /craft -list {0} for more.",
                    NothingToDisplayString = "There are currently no recipes defined!"
                });
                return;

            case "-allcats":
                int pge;
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pge))
                {
                    return;
                }

                List <string> allCat = new List <string>();

                // Another ditto from -list
                foreach (Recipe rec in CmdRec.config.Recipes.FindAll(r => !r.invisible))
                {
                    rec.categories.ForEach(i => {
                        if (!allCat.Contains(i))
                        {
                            allCat.Add(i);
                        }
                    });
                }
                PaginationTools.SendPage(args.Player, 1, PaginationTools.BuildLinesFromTerms(allCat),
                                         new PaginationTools.Settings
                {
                    HeaderFormat           = "Recipe Categories ({0}/{1}):",
                    FooterFormat           = "Type /craft -cat {0} for more.",
                    NothingToDisplayString = "There are currently no categories defined!"
                });
                return;

            case "-cat":
                if (args.Parameters.Count < 2)
                {
                    args.Player.SendErrorMessage("Invalid category!");
                    return;
                }

                args.Parameters.RemoveAt(0);
                string cat = string.Join(" ", args.Parameters);
                if (!cats.Contains(cat.ToLower()))
                {
                    args.Player.SendErrorMessage("Invalid category!");
                    return;
                }
                else
                {
                    List <string> catrec = new List <string>();

                    // Keep bringing them!
                    foreach (Recipe rec in config.Recipes.FindAll(r => !r.invisible))
                    {
                        rec.categories.ForEach(i =>
                        {
                            if (cat.ToLower() == i.ToLower())
                            {
                                catrec.Add(rec.name);
                            }
                        });
                    }
                    args.Player.SendInfoMessage("Recipes in this category:");
                    args.Player.SendInfoMessage("{0}", String.Join(", ", catrec));
                }
                return;

            case "-quit":
                args.Player.SendInfoMessage("Returning dropped items...");
                foreach (RecItem itm in player.droppedItems)
                {
                    item = new Item();
                    item.SetDefaults(itm.name);
                    args.Player.GiveItem(item.type, itm.name, item.width, item.height, itm.stack, itm.prefix);
                    player.TSPlayer.SendInfoMessage("Returned {0}.", Utils.FormatItem((Item)itm));
                }
                player.activeRecipe = null;
                player.droppedItems.Clear();
                player.TSPlayer.SendInfoMessage("Successfully quit crafting.");
                return;

            case "-confirm":
                if (!config.CraftFromInventory)
                {
                    args.Player.SendErrorMessage("Crafting from inventory is disabled!");
                }
                int count = 0;
                Dictionary <int, bool> finishedGroup = new Dictionary <int, bool>();
                Dictionary <int, int>  slots         = new Dictionary <int, int>();
                int ingredientCount = player.activeIngredients.Count;
                foreach (Ingredient ing in player.activeIngredients)
                {
                    if (!finishedGroup.ContainsKey(ing.group))
                    {
                        finishedGroup.Add(ing.group, false);
                    }
                    else if (ing.group != 0)
                    {
                        ingredientCount--;
                    }
                }
                foreach (Ingredient ing in player.activeIngredients)
                {
                    if (ing.group == 0 || !finishedGroup[ing.group])
                    {
                        Dictionary <int, RecItem> ingSlots = new Dictionary <int, RecItem>();
                        for (int i = 58; i >= 0; i--)
                        {
                            item = args.TPlayer.inventory[i];
                            if (ing.name == item.name && (ing.prefix == -1 || ing.prefix == item.prefix))
                            {
                                ingSlots.Add(i, new RecItem(item.name, item.stack, item.prefix));
                            }
                        }
                        if (ingSlots.Count == 0)
                        {
                            continue;
                        }

                        int totalStack = 0;
                        foreach (var key in ingSlots.Keys)
                        {
                            totalStack += ingSlots[key].stack;
                        }

                        if (totalStack >= ing.stack)
                        {
                            foreach (var key in ingSlots.Keys)
                            {
                                slots.Add(key, (ingSlots[key].stack < ing.stack) ? args.TPlayer.inventory[key].stack : ing.stack);
                            }
                            if (ing.group != 0)
                            {
                                finishedGroup[ing.group] = true;
                            }
                            count++;
                        }
                    }
                }
                if (count < ingredientCount)
                {
                    args.Player.SendErrorMessage("Insufficient ingredients!");
                    return;
                }
                if (!args.Player.InventorySlotAvailable)
                {
                    args.Player.SendErrorMessage("Insufficient inventory space!");
                    return;
                }
                foreach (var slot in slots)
                {
                    item = args.TPlayer.inventory[slot.Key];
                    var ing = player.activeIngredients.GetIngredient(item.name, item.prefix);
                    if (ing.stack > 0)
                    {
                        int stack;
                        if (ing.stack < slot.Value)
                        {
                            stack = ing.stack;
                        }
                        else
                        {
                            stack = slot.Value;
                        }

                        item.stack -= stack;
                        ing.stack  -= stack;
                        NetMessage.SendData((int)PacketTypes.PlayerSlot, -1, -1, "", args.Player.Index, slot.Key);
                        if (!player.droppedItems.ContainsItem(item.name, item.prefix))
                        {
                            player.droppedItems.Add(new RecItem(item.name, stack, item.prefix));
                        }
                        else
                        {
                            player.droppedItems.GetItem(item.name, item.prefix).stack += slot.Value;
                        }
                    }
                }
                List <Product> lDetPros = Utils.DetermineProducts(player.activeRecipe.products);
                foreach (Product pro in lDetPros)
                {
                    Item product = new Item();
                    product.SetDefaults(pro.name);
                    product.Prefix(pro.prefix);
                    pro.prefix = product.prefix;
                    player.TSPlayer.GiveItem(product.type, product.name, product.width, product.height, pro.stack, product.prefix);
                    player.TSPlayer.SendSuccessMessage("Received {0}.", Utils.FormatItem((Item)pro));
                }
                List <RecItem> prods = new List <RecItem>();
                lDetPros.ForEach(i => prods.Add(new RecItem(i.name, i.stack, i.prefix)));
                Log.Recipe(new LogRecipe(player.activeRecipe.name, player.droppedItems, prods), player.name);
                player.activeRecipe = null;
                player.droppedItems.Clear();
                player.TSPlayer.SendInfoMessage("Finished crafting.");
                return;

            default:
                if (player.activeRecipe != null)
                {
                    args.Player.SendErrorMessage("You must finish crafting or quit your current recipe!");
                    return;
                }
                string str = string.Join(" ", args.Parameters);
                if (!recs.Contains(str.ToLower()))
                {
                    args.Player.SendErrorMessage("Invalid recipe!");
                    return;
                }
                foreach (Recipe rec in config.Recipes)
                {
                    if (str.ToLower() == rec.name.ToLower())
                    {
                        if (!rec.permissions.Contains("") && !args.Player.Group.CheckPermissions(rec.permissions))
                        {
                            args.Player.SendErrorMessage("You do not have the required permission to craft the recipe: {0}!", rec.name);
                            return;
                        }
                        if (!Utils.CheckIfInRegion(args.Player, rec.regions))
                        {
                            args.Player.SendErrorMessage("You are not in a valid region to craft the recipe: {0}!", rec.name);
                            return;
                        }
                        player.activeIngredients = new List <Ingredient>(rec.ingredients.Count);
                        rec.ingredients.ForEach(i =>
                        {
                            player.activeIngredients.Add(i.Clone());
                        });
                        player.activeRecipe = rec.Clone();
                        break;
                    }
                }
                if (player.activeRecipe != null)
                {
                    List <string> inglist = Utils.ListIngredients(player.activeRecipe.ingredients);
                    args.Player.SendInfoMessage("The {0} recipe requires {1} to craft. {2}",
                                                player.activeRecipe.name,
                                                (inglist.Count > 1) ? String.Join(", ", inglist.ToArray(), 0, inglist.Count - 1) + ", and " + inglist.LastOrDefault() : inglist[0],
                                                (config.CraftFromInventory) ? "Type \"/craft -confirm\" to craft." : "Please drop all required items.");
                }
                break;
            }
        }
Пример #16
0
        private void ClanCommand(CommandArgs e)
        {
            int pageNumber;
            var parameters     = e.Parameters;
            var player         = e.Player;
            var invitationData = player.GetData <Clan>(InvitationKey);
            var playerMetadata = player.GetData <PlayerMetadata>(DataKey);

            if (parameters.Count < 1)
            {
                player.SendErrorMessage($"Invalid syntax! Use {TShock.Config.CommandSpecifier}clan help for help.");
                return;
            }

            switch (parameters[0].ToLowerInvariant())
            {
            case "accept":
            {
                if (playerMetadata != null)
                {
                    player.SendErrorMessage("You are already in a clan!");
                    return;
                }
                if (invitationData == null)
                {
                    player.SendErrorMessage("You do not have a pending invitation.");
                    return;
                }

                var metadata = _memberManager.Add(invitationData, ClanRank.DefaultRank, player.User.Name);
                player.RemoveData(InvitationKey);
                player.SetData(DataKey, metadata);
                player.SendSuccessMessage($"You have joined clan '{metadata.Clan.Name}'!");
                metadata.Clan.SendMessage($"(Clan) {player.User.Name} has joined the clan!", player.Index);
            }
            break;

            case "color":
            {
                if (playerMetadata == null)
                {
                    player.SendErrorMessage("You are not in a clan!");
                    return;
                }
                if (!playerMetadata.Rank.HasPermission(ClansPermissions.SetClanChatColor))
                {
                    player.SendErrorMessage("You do not have permission to change the clan's chat color.");
                    return;
                }
                if (parameters.Count != 2)
                {
                    player.SendErrorMessage(
                        $"Invalid syntax! Proper syntax: {TShock.Config.CommandSpecifier}clan color <rrr,ggg,bbb>");
                    return;
                }

                var colorString = parameters[1].Split(',');
                if (colorString.Length != 3 || !byte.TryParse(colorString[0], out var _) ||
                    !byte.TryParse(colorString[1], out var _) || !byte.TryParse(colorString[2], out var _))
                {
                    player.SendErrorMessage("Invalid color format.");
                    return;
                }

                playerMetadata.Clan.ChatColor = parameters[1];
                _clanManager.Update(playerMetadata.Clan);
                player.SendInfoMessage($"Set clan chat color to '{parameters[1]}'.");
            }
            break;

            case "create":
            {
                if (!player.IsLoggedIn)
                {
                    player.SendErrorMessage("You must be logged in to do that.");
                    return;
                }
                if (!player.HasPermission(ClansPermissions.CreatePermission))
                {
                    player.SendErrorMessage("You do not have permission to create clans.");
                    return;
                }
                if (playerMetadata != null)
                {
                    player.SendErrorMessage("You are already in a clan!");
                    return;
                }
                if (_clanManager.GetAll().Count == _configuration.ClanLimit)
                {
                    player.SendErrorMessage("The clan limit has been reached.");
                    return;
                }
                if (parameters.Count < 2)
                {
                    player.SendErrorMessage(
                        $"Invalid syntax! Proper syntax: {TShock.Config.CommandSpecifier}clan create <clan name>");
                    return;
                }

                parameters.RemoveAt(0);
                var clanName = string.Join(" ", parameters);
                if (clanName.Length > _configuration.MaximumNameLength)
                {
                    player.SendErrorMessage(
                        $"Clan name must not be longer than {_configuration.MaximumNameLength} characters.");
                    return;
                }

                var clan = _clanManager.Get(clanName);
                if (clan != null)
                {
                    player.SendErrorMessage($"Clan '{clanName}' already exists.");
                    return;
                }

                clan = _clanManager.Add(clanName, player.User.Name);
                var metadata = _memberManager.Add(clan, ClanRank.OwnerRank, player.User.Name);
                player.SetData(DataKey, metadata);
                player.SendInfoMessage($"You have created clan '{clanName}'.");
                if (!e.Silent)
                {
                    TSPlayer.All.SendInfoMessage($"Clan '{clanName}' has been established!");
                }
            }
            break;

            case "deny":
            case "decline":
            {
                if (playerMetadata != null)
                {
                    player.SendErrorMessage("You are already in a clan!");
                    return;
                }
                if (invitationData == null)
                {
                    player.SendErrorMessage("You do not have a pending invitation.");
                    return;
                }

                player.RemoveData(InvitationKey);
                player.SendSuccessMessage("You have declined the invitation.");
            }
            break;

            case "disband":
            {
                if (playerMetadata == null)
                {
                    player.SendErrorMessage("You are not in a clan!");
                    return;
                }
                if (playerMetadata.Clan.Owner != player.User.Name)
                {
                    player.SendErrorMessage("You are not the clan's owner!");
                    return;
                }

                _clanManager.Remove(playerMetadata.Clan.Name);
                var players = from plr in TShock.Players
                              where plr != null && plr.IsLoggedIn
                              let metadata = plr.GetData <PlayerMetadata>(DataKey)
                                             where metadata != null && metadata.Clan.Name == playerMetadata.Clan.Name
                                             select plr;
                foreach (var player2 in players)
                {
                    player2.RemoveData(DataKey);
                    _memberManager.Remove(player2.User.Name);
                }

                TSPlayer.All.SendInfoMessage($"Clan '{playerMetadata.Clan.Name}' has been disbanded!");
            }
            break;

            case "ff":
            case "friendlyfire":
            {
                if (playerMetadata == null)
                {
                    player.SendErrorMessage("You are not in a clan!");
                    return;
                }
                if (!playerMetadata.Rank.HasPermission(ClansPermissions.ToggleFriendlyFire))
                {
                    player.SendErrorMessage(
                        "You do not have permission to change the clan's friendly fire status!");
                    return;
                }

                playerMetadata.Clan.IsFriendlyFire = !playerMetadata.Clan.IsFriendlyFire;
                _clanManager.Update(playerMetadata.Clan);
                player.SendInfoMessage(
                    $"Friendly fire is now {(playerMetadata.Clan.IsFriendlyFire ? "ON" : "OFF")}.");
            }
            break;

            case "help":
            {
                if (!PaginationTools.TryParsePageNumber(parameters, 1, player, out pageNumber))
                {
                    player.SendErrorMessage("Invalid page number!");
                    return;
                }

                var help = new List <string>
                {
                    "create <clan name> - creates a new clan with the specified name",
                    "disband - disbands a clan",
                    "quit - leaves a clan",
                    "friendlyfire - toggles friendly fire",
                    "invite <player name> - invites a player to join the clan",
                    "accept - accepts a clan invitation",
                    "decline = declines a clan invitation",
                    "setrank <player name> <rank name> - sets a player's rank",
                    "kick <player name> - kicks a player from the clan",
                    "prefix <new prefix> - sets a clan's prefix",
                    "color <rrr,ggg,bbb> - sets a clan's chat color",
                    "motd <new MOTD> - sets a clan's message of the day",
                    "members - lists a clan's members",
                    "list - lists all clans"
                };

                PaginationTools.SendPage(player, pageNumber, help, new PaginationTools.Settings
                    {
                        HeaderFormat = "Clan Sub-commands ({0}/{1})",
                        FooterFormat = $"Type {TShock.Config.CommandSpecifier}clan help {{0}} for more."
                    });
            }
            break;

            case "invite":
            {
                if (playerMetadata == null)
                {
                    player.SendErrorMessage("You are not in a clan!");
                    return;
                }
                if (!playerMetadata.Rank.HasPermission(ClansPermissions.InvitePlayers))
                {
                    player.SendErrorMessage("You do not have permission to invite players.");
                    return;
                }
                if (parameters.Count < 2)
                {
                    player.SendErrorMessage(
                        $"Invalid syntax! Proper syntax: {TShock.Config.CommandSpecifier}clan invite <player name>");
                    return;
                }

                parameters.RemoveAt(0);
                var playerName = string.Join(" ", parameters);
                var matches    = TShock.Utils.FindPlayer(playerName);
                if (matches.Count == 0)
                {
                    player.SendErrorMessage("Invalid player!");
                    return;
                }
                if (matches.Count > 1)
                {
                    TShock.Utils.SendMultipleMatchError(player, matches.Select(p => p.Name));
                    return;
                }

                var match = matches[0];
                if (!match.IsLoggedIn)
                {
                    player.SendErrorMessage("The player is not logged in.");
                    return;
                }
                if (match.GetData <PlayerMetadata>(DataKey) != null)
                {
                    player.SendErrorMessage("This player is already in a clan!");
                    return;
                }
                if (match.GetData <Clan>(InvitationKey) != null)
                {
                    player.SendErrorMessage("This player already has a pending invitation.");
                    return;
                }

                match.SetData(InvitationKey, playerMetadata.Clan);
                match.SendInfoMessage($"You have been invited to join clan '{playerMetadata.Clan.Name}'!");
                match.SendInfoMessage(
                    $"Type {TShock.Config.CommandSpecifier}clan accept to accept the invitation.");
                match.SendInfoMessage(
                    $"Type {TShock.Config.CommandSpecifier}clan decline to decline the invitation.");
                player.SendSuccessMessage($"'{match.Name}' has been invited to join your clan!");
            }
            break;

            case "kick":
            {
                if (playerMetadata == null)
                {
                    player.SendErrorMessage("You are not in a clan!");
                    return;
                }
                if (!playerMetadata.Rank.HasPermission(ClansPermissions.KickMembers))
                {
                    player.SendErrorMessage("You do not have permission to kick members!");
                    return;
                }
                if (parameters.Count < 2)
                {
                    player.SendErrorMessage(
                        $"Invalid syntax! Proper syntax: {TShock.Config.CommandSpecifier}clan kick <player name>");
                    return;
                }

                parameters.RemoveAt(0);
                var username = string.Join(" ", parameters);
                var users    = TShock.Users.GetUsersByName(username);
                if (users.Count == 0)
                {
                    player.SendErrorMessage("Invalid player!");
                    return;
                }
                if (users.Count > 1)
                {
                    TShock.Utils.SendMultipleMatchError(player, users.Select(u => u.Name));
                    return;
                }

                var user         = users[0];
                var userMetadata = _memberManager.Get(user.Name);
                if (userMetadata?.Clan.Name != playerMetadata.Clan.Name)
                {
                    player.SendErrorMessage("This player is not in your clan!");
                    return;
                }
                if (userMetadata.Rank.HasPermission(ClansPermissions.ImmuneToKick))
                {
                    player.SendErrorMessage("You cannot kick this player!");
                    return;
                }

                _memberManager.Remove(user.Name);
                var kickedPlayer = TShock.Players.Single(p => p?.User?.Name == user.Name);
                if (kickedPlayer != null)
                {
                    kickedPlayer.RemoveData(DataKey);
                    kickedPlayer.SendInfoMessage("You have been kicked from the clan!");
                }

                player.SendInfoMessage($"'{user.Name}' has been kicked from the clan!");
            }
            break;

            case "list":
            {
                if (!PaginationTools.TryParsePageNumber(parameters, 1, player, out pageNumber))
                {
                    player.SendErrorMessage("Invalid page number!");
                    return;
                }

                var clanList = PaginationTools.BuildLinesFromTerms(_clanManager.GetAll().Select(c => c.Name));
                PaginationTools.SendPage(player, pageNumber, clanList, new PaginationTools.Settings
                    {
                        HeaderFormat           = "Clan List ({0}/{1})",
                        FooterFormat           = $"Type {TShock.Config.CommandSpecifier}clan list {{0}} for more.",
                        NothingToDisplayString = "There are no clans to list."
                    });
            }
            break;

            case "members":
            {
                if (playerMetadata == null)
                {
                    player.SendErrorMessage("You are not in a clan!");
                    return;
                }
                if (!PaginationTools.TryParsePageNumber(parameters, 1, player, out pageNumber))
                {
                    player.SendErrorMessage("Invalid page number!");
                    return;
                }

                var memberList = PaginationTools.BuildLinesFromTerms(playerMetadata.Clan.Members);
                PaginationTools.SendPage(player, pageNumber, memberList, new PaginationTools.Settings
                    {
                        HeaderFormat = "Clan Members ({0}/{1})",
                        FooterFormat = $"Type {TShock.Config.CommandSpecifier}clan members {{0}} for more."
                    });
            }
            break;

            case "motd":
            {
                if (playerMetadata == null)
                {
                    player.SendErrorMessage("You are not in a clan!");
                    return;
                }
                if (parameters.Count < 2)
                {
                    if (string.IsNullOrWhiteSpace(playerMetadata.Clan.Motd))
                    {
                        player.SendInfoMessage("Your clan does not have a message of the day set.");
                        return;
                    }

                    player.SendMessage(
                        $"[Clan '{playerMetadata.Clan.Name}' Message of the Day] {playerMetadata.Clan.Motd}",
                        playerMetadata.Clan.ChatColor.GetColor());
                }
                else
                {
                    if (!playerMetadata.Rank.HasPermission(ClansPermissions.SetClanMotd))
                    {
                        player.SendErrorMessage(
                            "You do not have permission to change the clan's message of the day!");
                        return;
                    }

                    parameters.RemoveAt(0);
                    var newMotd = string.Join(" ", parameters);
                    playerMetadata.Clan.Motd = newMotd;
                    _clanManager.Update(playerMetadata.Clan);
                    player.SendInfoMessage($"The clan's message of the day has been set to '{newMotd}'.");
                }
                break;
            }

            case "prefix":
            {
                if (playerMetadata == null)
                {
                    player.SendErrorMessage("You are not in a clan!");
                    return;
                }
                if (!playerMetadata.Rank.HasPermission(ClansPermissions.SetClanPrefix))
                {
                    player.SendErrorMessage("You do not have permission to change the clan's prefix.");
                    return;
                }
                if (parameters.Count < 2)
                {
                    player.SendErrorMessage(
                        $"Invalid syntax! Proper syntax: {TShock.Config.CommandSpecifier}clan prefix <prefix>");
                    return;
                }

                parameters.RemoveAt(0);
                var prefix = string.Join(" ", parameters);
                if (prefix.Length > _configuration.MaximumPrefixLength)
                {
                    player.SendErrorMessage(
                        $"Clan prefix must not be longer than {_configuration.MaximumPrefixLength} characters.");
                    return;
                }

                playerMetadata.Clan.Prefix = prefix;
                _clanManager.Update(playerMetadata.Clan);
                player.SendInfoMessage($"Set clan prefix to '{prefix}'.");
            }
            break;

            case "setrank":
            {
                if (playerMetadata == null)
                {
                    player.SendErrorMessage("You are not in a clan!");
                    return;
                }
                if (!playerMetadata.Rank.HasPermission(ClansPermissions.SetMemberRank))
                {
                    player.SendErrorMessage("You do not have permission to modify ranks!");
                    return;
                }
                if (parameters.Count != 3)
                {
                    player.SendErrorMessage(
                        $"Invalid syntax! Proper syntax: {TShock.Config.CommandSpecifier}clan setrank <player name> <rank>");
                    return;
                }

                var username = e.Parameters[1];
                var users    = TShock.Users.GetUsersByName(username);
                if (users.Count == 0)
                {
                    player.SendErrorMessage("Invalid player!");
                    return;
                }
                if (users.Count > 1)
                {
                    TShock.Utils.SendMultipleMatchError(player, users.Select(u => u.Name));
                    return;
                }

                var user         = users[0];
                var userMetadata = _memberManager.Get(user.Name);
                if (userMetadata?.Clan.Name != playerMetadata.Clan.Name)
                {
                    player.SendErrorMessage("This player is not in your clan!");
                    return;
                }

                var rankName = e.Parameters[2];
                var rank     = playerMetadata.Clan.Ranks.SingleOrDefault(r => r.Name == rankName);
                if (rank == null)
                {
                    player.SendErrorMessage($"Invalid rank '{rankName}'.");
                    return;
                }

                userMetadata.Rank = rank;
                _memberManager.Update(user.Name, rank.Name);
                player.SendInfoMessage($"Set {user.Name}'s rank to '{rank.Name}'.");
            }
            break;

            case "quit":
            case "leave":
            {
                if (playerMetadata == null)
                {
                    player.SendErrorMessage("You are not in a clan!");
                    return;
                }
                if (playerMetadata.Clan.Owner == player.User.Name)
                {
                    goto case "disband";
                }

                player.RemoveData(DataKey);
                player.SendSuccessMessage("You have left the clan!");
            }
            break;

            default:
                player.SendErrorMessage(
                    $"Invalid sub-command! Type {TShock.Config.CommandSpecifier}clan help for a list of valid commands.");
                break;
            }
        }
Пример #17
0
        public void MainCommand(CommandArgs args)
        {
            string cmd = "help";

            if (args.Parameters.Count > 0)
            {
                cmd = args.Parameters[0].ToLower();
            }
            switch (cmd)
            {
            case "set":
                SetWarpplate(args);
                break;

            case "del":
            case "delete":
            case "remove":
                DeleteWarpplate(args);
                break;

            case "setdest":
            case "setdestination":
                SetWarpplateDestination(args);
                break;

            case "deldest":
            case "deletedestination":
                RemoveWarpplateDestination(args);
                break;

            case "info":
                WarpplateInformation(args);
                break;

            case "list":
                ListWarpplates(args);
                break;

            case "allow":
            case "toggle":
                WarpplateAllow(args);
                break;

            case "reload":
                ReloadWarpplates(args);
                break;

            case "delay":
                SetWarpplateDelay(args);
                break;

            case "width":
                SetWarpplateWidth(args);
                break;

            case "height":
                SetWarpplateHeight(args);
                break;

            case "resize":
            case "size":
                SetWarpplateSize(args);
                break;

            case "label":
            case "display":
                SetWarpplateLabel(args);
                break;

            case "dim":
            case "dimension":
                if (!args.Player.HasPermission("warpplate.setdimensional"))
                {
                    args.Player.SendErrorMessage("You do not have permission to set a dimensional warpplate.");
                    break;
                }
                SetWarpplateDimension(args);
                break;

            case "help":
            default:
            {
                int pageNumber     = 1;
                int pageParamIndex = 0;
                if (args.Parameters.Count > 1)
                {
                    pageParamIndex = 1;
                }
                if (!PaginationTools.TryParsePageNumber(args.Parameters, pageParamIndex, args.Player, out pageNumber))
                {
                    return;
                }

                List <String> lines = new List <String> {
                    "set <name> - Set new warpplate at your position.",
                    "delete <name> - Deletes the given warpplate.",
                    "setdest <name> <destination> - Set destination for the given warpplate.",
                    "deldest <name> - Delete the destination for the given warpplate.",
                    "info <name> - Display info for the given warpplate.",
                    "list - List all warpplates in the world.",
                    "toggle - Enable/Disable activating warpplates for yourself.",
                    "reload - Reload warpplate information from database.",
                    "delay [<name>] <delay in seconds> - Set delay for warpplate.",
                    "width [<name>] <width in blocks> - Set width for warpplate.",
                    "height [<name>] <height in blocks> - Set height for warpplate.",
                    "resize [<name>] <width> <height> - Resize dimensions for warpplate.",
                    "label [<name>] <label name> - Set the label name for the warpplate destination."
                };
                if (args.Player.HasPermission("warpplate.setdimensional"))
                {
                    lines.Add("dim [<name>] <dimension name> - Set dimension destination for the warpplate.");
                }

                PaginationTools.SendPage(
                    args.Player, pageNumber, lines,
                    new PaginationTools.Settings
                    {
                        HeaderFormat = "Warpplate Sub-Commands ({0}/{1}):",
                        FooterFormat = "Type {0}wp {{0}} for more sub-commands.".SFormat(TShock.Config.CommandSpecifier)
                    }
                    );
                break;
            }
            }
        }
Пример #18
0
        void ClanCmd(CommandArgs args)
        {
            string cmd = args.Parameters.Count > 0 ? args.Parameters[0].ToLower() : "help";

            Clan MyClan = null;

            if (args.Player != TSPlayer.Server)
            {
                MyClan = ClanManager.FindClanByPlayer(args.Player);
            }

            switch (cmd)
            {
                #region checkupdate
            case "checkupdate":
            {
                if (!args.Player.Group.HasPermission(Permission.Create))
                {
                    args.Player.SendErrorMessage("You do not have permission to check for updates!");
                    return;
                }

                if (!updateChecker.UpdateAvailable)
                {
                    updateChecker.CheckForUpdate();
                }

                if (updateChecker.UpdateAvailable)
                {
                    args.Player.SendInfoMessage("There is an update available for the Clans plugin!");
                    args.Player.SendInfoMessage("Type /clan changelog to see the changelog!");
                }
                args.Player.SendErrorMessage("No update available!");
            }
            break;
                #endregion checkupdate

                #region changelog
            case "changelog":
            {
                if (!updateChecker.UpdateAvailable)
                {
                    args.Player.SendErrorMessage("There is no update available! Type \"/clan checkupdate\" to check for updates!");
                    return;
                }
                args.Player.SendSuccessMessage("Changelog for the latest version (" + updateChecker.NewVersion + "):");
                for (int i = 0; i < updateChecker.ChangeLog.Length; i++)
                {
                    args.Player.SendInfoMessage(updateChecker.ChangeLog[i]);
                }
            }
            break;
                #endregion changelog

                #region create
            case "create":
            {
                if (!args.Player.Group.HasPermission(Permission.Create))
                {
                    args.Player.SendErrorMessage("You do not have permission to create a clan!");
                    return;
                }
                if (args.Parameters.Count < 2)
                {
                    args.Player.SendErrorMessage("Invalid syntax! proper syntax: /clan create <name>");
                    return;
                }
                if (ClanManager.Config.MaxNumberOfClans > 0 && ClanManager.Clans.Keys.Count >= ClanManager.Config.MaxNumberOfClans)
                {
                    args.Player.SendErrorMessage("The maximum amount of clans has been reached, sorry mate.");
                    return;
                }
                string name = String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1));
                if (MyClan != null)
                {
                    args.Player.SendErrorMessage("You are already in a clan!");
                    return;
                }
                if (ClanManager.FindClanByName(name) != null)
                {
                    args.Player.SendErrorMessage("This clan already exists!");
                    return;
                }
                if (!ClanManager.CreateClan(args.Player, new Clan()
                    {
                        Name = name, Owner = args.Player.UserAccountName
                    }))
                {
                    args.Player.SendErrorMessage("Something went wrong! Please contact an administrator.");
                }
            }
            break;
                #endregion create

                #region join
            case "join":
            {
                if (args.Parameters.Count < 2)
                {
                    args.Player.SendErrorMessage("Invalid syntax! proper syntax: /clan join <clan name>");
                    return;
                }
                string name = String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1));
                if (MyClan != null)
                {
                    args.Player.SendErrorMessage("You are already in a clan!");
                    return;
                }
                Clan c = ClanManager.FindClanByName(name);
                if (c == null)
                {
                    args.Player.SendErrorMessage("This clan does not exists!");
                    return;
                }
                if (c.IsBanned(args.Player.UserAccountName))
                {
                    args.Player.SendErrorMessage("You have been banned from this clan!");
                    return;
                }
                if (c.InviteMode == InviteMode.True)
                {
                    args.Player.SendErrorMessage("This clan is in invite-only mode, please ask for an invitation.");
                    return;
                }
                ClanManager.JoinClan(args.Player, c);
            }
            break;
                #endregion join

                #region leave
            case "leave":
            {
                if (MyClan == null)
                {
                    args.Player.SendErrorMessage("You are not in a clan!");
                    return;
                }
                if (args.Parameters.Count == 2)
                {
                    if (args.Parameters[1].ToLower() == "confirm")
                    {
                        ClanManager.LeaveClan(args.Player, MyClan);
                    }
                    else
                    {
                        args.Player.SendErrorMessage("Invalid syntax! proper syntax: /clan leave confirm");
                    }
                }
                else
                {
                    if (args.Player.UserAccountName == MyClan.Owner)
                    {
                        args.Player.SendErrorMessage("You are the owner of this clan, this means that if you leave, the clan will disband!");
                    }
                    args.Player.SendInfoMessage("Are you sure you want to leave this clan? type \"/clan leave confirm\"");
                }
            }
            break;
                #endregion leave

                #region inviteMode
            case "invitemode":
            {
                if (MyClan == null)
                {
                    args.Player.SendErrorMessage("You are not in a clan!");
                    return;
                }
                if (MyClan.Owner != args.Player.UserAccountName)
                {
                    args.Player.SendErrorMessage("You are not allowed to alter the clan's invitemode settings!");
                    return;
                }
                string subcmd = args.Parameters.Count == 2 ? args.Parameters[1].ToLower() : string.Empty;
                switch (subcmd)
                {
                case "true":
                    ClanManager.SetInviteMode(MyClan, InviteMode.True);
                    break;

                case "false":
                    ClanManager.SetInviteMode(MyClan, InviteMode.False);
                    break;

                default:
                    args.Player.SendErrorMessage("Invalid syntax! proper syntax: /clan invitemode <true/false>");
                    return;
                }
                args.Player.SendInfoMessage("Clan invite mode has been set to " + (MyClan.InviteMode == InviteMode.True ? "true" : "false"));
            }
            break;
                #endregion inviteMode

                #region reloadclans
            case "reloadclans":
            {
                if (!args.Player.Group.HasPermission(Permission.Reload))
                {
                    args.Player.SendErrorMessage("You do not have permission to create a clan!");
                    return;
                }
                ClanManager.ReloadAll();
                args.Player.SendInfoMessage("All clans and their members have been reloaded!");
                break;
            }
                #endregion reloadclans

                #region reloadconfig
            case "reloadconfig":
            {
                if (!args.Player.Group.HasPermission(Permission.Reload))
                {
                    args.Player.SendErrorMessage("You do not have permission to create a clan!");
                    return;
                }
                ClanManager.ReloadConfig(args.Player);
            }
            break;
                #endregion reloadconfig

                #region list
            case "list":
            {
                int pageNumber;
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
                {
                    return;
                }
                IEnumerable <string> clanNames = ClanManager.Clans.Keys;
                PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(clanNames),
                                         new PaginationTools.Settings
                    {
                        HeaderFormat           = "Clans ({0}/{1}):",
                        FooterFormat           = "Type /clan list {0} for more.",
                        NothingToDisplayString = "There aren't any clans!",
                    });
            }
            break;
                #endregion list

                #region tp
            case "tp":
            {
                if (MyClan == null)
                {
                    args.Player.SendErrorMessage("You are not in a clan!");
                    return;
                }
                if (MyClan.TileX == 0 || MyClan.TileY == 0)
                {
                    args.Player.SendErrorMessage("Your clan has no spawn point defined!");
                    return;
                }
                args.Player.Teleport(MyClan.TileX * 16, MyClan.TileY * 16);
            }
            break;
                #endregion tp

                #region setspawn
            case "setspawn":
            {
                if (MyClan == null)
                {
                    args.Player.SendErrorMessage("You are not in a clan!");
                    return;
                }
                if (MyClan.Owner != args.Player.UserAccountName)
                {
                    args.Player.SendErrorMessage("You are not allowed to alter the clan's spawnpoint!");
                    return;
                }
                ClanManager.SetSpawn(MyClan, args.Player);
                args.Player.SendInfoMessage(string.Format("Your clan's spawnpoint has been changed to X:{0}, Y:{1}", MyClan.TileX, MyClan.TileY));
            }
            break;
                #endregion setspawn

                #region setcolor
            case "setcolor":
            {
                if (MyClan == null)
                {
                    args.Player.SendErrorMessage("You are not in a clan!");
                    return;
                }
                if (MyClan.Owner != args.Player.UserAccountName)
                {
                    args.Player.SendErrorMessage("You are not allowed to alter the clan's chatcolor!");
                    return;
                }
                if (args.Parameters.Count < 2)
                {
                    args.Player.SendErrorMessage("Invalid syntax! proper syntax: /clan setcolor  <0-255,0-255,0-255>");
                    return;
                }
                if (!ClanManager.SetColor(MyClan, args.Parameters[1]))
                {
                    args.Player.SendErrorMessage("Invalid color format! proper example: /clan setcolor 125,255,137");
                }
            }
            break;
                #endregion setcolor

                #region who
            case "who":
            {
                int pageNumber;
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
                {
                    return;
                }
                IEnumerable <string> clanMembers = MyClan.OnlineClanMembers.Values.Select(m => m.TSPlayer.Name);
                PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(clanMembers),
                                         new PaginationTools.Settings
                    {
                        HeaderFormat = "Online Clanmembers ({0}/{1}):",
                        FooterFormat = "Type /clan who {0} for more.",
                    });
            }
            break;
                #endregion who

                #region find
            case "find":
            {
                if (args.Parameters.Count < 2)
                {
                    args.Player.SendErrorMessage("Invalid syntax! proper syntax: /clan find <player>");
                    return;
                }
                var foundplr = TShock.Utils.FindPlayer(args.Parameters[1]);
                if (foundplr.Count == 0)
                {
                    args.Player.SendMessage("Invalid player!", Color.Red);
                    return;
                }
                else if (foundplr.Count > 1)
                {
                    args.Player.SendMessage(string.Format("More than one ({0}) player matched!", foundplr.Count), Color.Red);
                    return;
                }
                TSPlayer plr = foundplr[0];
                Clan     c   = ClanManager.FindClanByPlayer(plr);
                if (c == null)
                {
                    args.Player.SendErrorMessage(string.Format("{0} is not in a clan!", plr.Name));
                    return;
                }
                args.Player.SendInfoMessage(string.Format("{0} is in clan: {1}", plr.Name, c.Name));
            }
            break;
                #endregion find

                #region togglechat
            case "togglechat":
            {
                MyClan.OnlineClanMembers[args.Player.Index].DefaultToClanChat = !MyClan.OnlineClanMembers[args.Player.Index].DefaultToClanChat;
                args.Player.SendInfoMessage(MyClan.OnlineClanMembers[args.Player.Index].DefaultToClanChat ? "You will now automaticly talk in the clanchat!" : "You are now using global chat, use /c to talk in clanchat");
            }
            break;
                #endregion togglechat

                #region rename
            case "rename":
            {
                if (MyClan == null)
                {
                    args.Player.SendErrorMessage("You are not in a clan!");
                    return;
                }
                if (MyClan.Owner != args.Player.UserAccountName)
                {
                    args.Player.SendErrorMessage("You are not allowed to alter the clan's name!");
                    return;
                }
                string name = String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1));
                if (ClanManager.FindClanByName(name) != null)
                {
                    args.Player.SendErrorMessage("A clan with this name already exists!");
                    return;
                }
                ClanManager.Rename(MyClan, args.Player, name);
                MyClan.Broadcast("Your clan has been renamed to " + MyClan.Name);
            }
            break;
                #endregion rename

                #region help
            default:
            case "help":
            {
                int pageNumber;
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
                {
                    return;
                }

                PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(HelpMsg),
                                         new PaginationTools.Settings
                    {
                        HeaderFormat = "Clans help page ({0}/{1})",
                        FooterFormat = "Type /clan help {0} for more.",
                    });
            }
            break;
                #endregion help
            }
        }
Пример #19
0
        private void ManageInventories(CommandArgs e)
        {
            if (!e.Player.IsLoggedIn)
            {
                e.Player.SendErrorMessage("You must be logged in to do that.");
                return;
            }

            if (e.Parameters.Count < 1)
            {
                e.Player.SendErrorMessage("Invalid syntax! Proper syntax:");
                e.Player.SendErrorMessage("{0}inventory save <name> - saves/updates your current inventory", TShock.Config.CommandSpecifier);
                e.Player.SendErrorMessage("{0}inventory load <name> - loads an inventory", TShock.Config.CommandSpecifier);
                e.Player.SendErrorMessage("{0}inventory delete <name> - deletes an inventory", TShock.Config.CommandSpecifier);
                e.Player.SendErrorMessage("{0}inventory list - lists all your inventories", TShock.Config.CommandSpecifier);
                return;
            }

            switch (e.Parameters[0].ToLowerInvariant())
            {
            case "save":
            {
                if (e.Parameters.Count < 2)
                {
                    e.Player.SendErrorMessage($"Invalid syntax! Proper syntax: {Commands.Specifier}inventory save <inventory name>");
                    return;
                }

                e.Parameters.RemoveRange(0, 1);
                var inventoryName = string.Join(" ", e.Parameters);
                if (!_database.SaveInventory(e.Player, inventoryName))
                {
                    e.Player.SendErrorMessage("You have reached the max amount of inventories.");
                    return;
                }

                e.Player.SendSuccessMessage($"Inventory '{inventoryName}' has been saved.");
            }
            break;

            case "load":
            {
                if (e.Parameters.Count < 2)
                {
                    e.Player.SendErrorMessage($"Invalid syntax! Proper syntax: {Commands.Specifier}inventory load <inventory name>");
                    return;
                }

                var player = _database.Get(e.Player.User);
                if (player == null)
                {
                    e.Player.SendErrorMessage("You do not have any inventories saved.");
                    return;
                }

                e.Parameters.RemoveRange(0, 1);
                var inventoryName = string.Join(" ", e.Parameters);
                if (!player.HasInventory(inventoryName))
                {
                    e.Player.SendErrorMessage($"No inventories under the name '{inventoryName}' were found.");
                    return;
                }

                _database.LoadInventory(e.Player, inventoryName);
                e.Player.SendSuccessMessage($"Loaded inventory '{inventoryName}'.");
            }
            break;

            case "del":
            case "rem":
            case "delete":
            case "remove":
            {
                if (e.Parameters.Count < 2)
                {
                    e.Player.SendErrorMessage($"Invalid syntax! Proper syntax: {Commands.Specifier}inventory delete <inventory name>");
                    return;
                }

                var player = _database.Get(e.Player.User);
                if (player == null)
                {
                    e.Player.SendErrorMessage("You do not have any inventories saved.");
                    return;
                }

                e.Parameters.RemoveRange(0, 1);
                var inventoryName = string.Join(" ", e.Parameters);
                if (!player.HasInventory(inventoryName))
                {
                    e.Player.SendErrorMessage($"No inventories under the name '{inventoryName}' were found.");
                    return;
                }

                _database.DeleteInventory(e.Player, inventoryName);
                e.Player.SendSuccessMessage($"Deleted inventory '{inventoryName}'.");
            }
            break;

            case "list":
            {
                var player = _database.Get(e.Player.User);
                if (player == null)
                {
                    e.Player.SendErrorMessage("You do not have any inventories saved.");
                    return;
                }

                if (e.Parameters.Count > 2)
                {
                    e.Player.SendErrorMessage($"Invalid syntax! Proper syntax: {Commands.Specifier}inventory list [page]");
                    return;
                }


                if (!PaginationTools.TryParsePageNumber(e.Parameters, 1, e.Player, out var pageNum))
                {
                    return;
                }

                PaginationTools.SendPage(e.Player, pageNum, PaginationTools.BuildLinesFromTerms(player.GetInventoryNames),
                                         new PaginationTools.Settings
                    {
                        HeaderFormat           = "Inventories ({0}/{1})",
                        FooterFormat           = $"Type {Commands.Specifier}inventory list {{0}} for more.",
                        NothingToDisplayString = "You have no inventories to display."
                    });
            }
            break;
            }
        }
Пример #20
0
        private static void RegionExtenionCmd(CommandArgs args)
        {
            var param = args.Parameters;
            var plr   = args.Player;

            if (param.Count < 1)
            {
                param.Add("help");
            }
            int           pCount    = param.Count;
            string        specifier = TShock.Config.CommandSpecifier;
            string        regionName;
            List <string> lines;

            switch (param[0])
            {
                #region rename
            case "rename":
            case "rn":
                if (pCount != 3)
                {
                    plr.SendErrorMessage("Invalid syntax! Proper syntax: {0}/re rename <oldname> <newname>", specifier);
                    return;
                }

                string newName = param[2];
                string oldName = param[1];
                if (TShock.Regions.GetRegionByName(oldName) == null)
                {
                    plr.SendErrorMessage($"Invalid region \"{oldName}\".");
                    return;
                }
                if (newName == oldName)
                {
                    plr.SendErrorMessage("Both names are the same.");
                    return;
                }
                if (TShock.Regions.GetRegionByName(newName) != null)
                {
                    plr.SendErrorMessage($"Region \"{newName}\" already exists.");
                    return;
                }
                if (Plugin.ExtManager.Rename(oldName, newName))
                {
                    plr.SendSuccessMessage("Region renamed successfully!");
                }
                else
                {
                    plr.SendErrorMessage("Failed to rename the region!");
                }
                break;

                #endregion
                #region move
            case "move":
                if (pCount != 4)
                {
                    plr.SendErrorMessage("Invalid syntax! Proper syntax: {0}/re move <regionname> <u/d/r/l> <amount>", specifier);
                    return;
                }

                regionName = param[1];
                var region = TShock.Regions.GetRegionByName(regionName);
                if (region == null)
                {
                    plr.SendErrorMessage($"Invalid region \"{param[1]}\".");
                    return;
                }

                int amount;
                if (!int.TryParse(param[3], out amount))
                {
                    plr.SendErrorMessage("Invalid amount!");
                    return;
                }
                int addX = 0;
                int addY = 0;
                if (param[2].Contains("u"))
                {
                    addY = -amount;
                }
                else if (param[2].Contains("d"))
                {
                    addY = amount;
                }
                if (param[2].Contains("r"))
                {
                    addX = amount;
                }
                else if (param[2].Contains("l"))
                {
                    addX = -amount;
                }
                else
                {
                    plr.SendErrorMessage("Invalid direction! u/d/r/l only!", specifier);
                    return;
                }

                if (TShock.Regions.PositionRegion(regionName, region.Area.X + addX, region.Area.Y + addY, region.Area.Width, region.Area.Height))
                {
                    plr.SendSuccessMessage("Region move success!");
                }
                else
                {
                    plr.SendErrorMessage("Region move failed!");
                }
                break;

                #endregion
                #region fastregion
            case "fastregion":
            case "fr":
                if (pCount < 2)
                {
                    plr.SendErrorMessage("Invalid syntax! Proper syntax: {0}/re fr <regionname> [username] [z] [protect]", specifier);
                    return;
                }
                if (Plugin.FindFastRegionByUser(plr.Account) != -1)
                {
                    plr.SendErrorMessage("You already have active fastregion request!");
                    return;
                }
                regionName = param[1];
                if (TShock.Regions.GetRegionByName(regionName) != null)
                {
                    if (Plugin.Config.AutoCompleteSameName)
                    {
                        regionName = Utils.AutoCompleteSameName(regionName, Plugin.Config.AutoCompleteSameNameFormat);
                    }
                    else
                    {
                        plr.SendErrorMessage($"Region \"{regionName}\" already exist.");
                        return;
                    }
                }
                string ownerName = plr.Account.Name;
                int    z         = 0;
                bool   protect   = true;
                if (pCount > 2)
                {
                    if (TShock.UserAccounts.GetUserAccountByName(param[2]) == null)
                    {
                        plr.SendErrorMessage("Invalid user name!");
                        return;
                    }
                    ownerName = param[2];
                    if (pCount > 3)
                    {
                        if (!int.TryParse(param[3], out z))
                        {
                            plr.SendErrorMessage("Invalid z value!");
                            return;
                        }
                        if (pCount > 4)
                        {
                            if (!bool.TryParse(param[4], out protect))
                            {
                                plr.SendErrorMessage("Invalid protect value! true/false only.");
                                return;
                            }
                        }
                    }
                }
                Plugin.FastRegions.Add(new FastRegion(plr, regionName, ownerName, z, protect));
                break;

            case "frb":
            case "frbreak":
            case "fastregionbreak":
            case "fastregionb":
                int id = Plugin.FindFastRegionByUser(plr.Account);
                if (id == -1)
                {
                    plr.SendErrorMessage("You dont have active fastregion request!");
                    return;
                }
                Plugin.FastRegions.RemoveAt(id);
                plr.SendSuccessMessage("Your fastregion request breaked!");
                break;

                #endregion
                #region clearmembers
            case "clearm":
            case "clearmembers":
                if (pCount != 2)
                {
                    plr.SendErrorMessage("Invalid syntax! Proper syntax: {0}/re clearm <regionname>", specifier);
                    return;
                }
                if (TShock.Regions.GetRegionByName(param[1]) == null)
                {
                    plr.SendErrorMessage($"Invalid region \"{param[1]}\".");
                    return;
                }
                if (Plugin.ExtManager.ClearAllowUsers(param[1]))
                {
                    plr.SendSuccessMessage("Region clear member success!");
                }
                else
                {
                    plr.SendErrorMessage("Region clear member failed!");
                }
                break;

                #endregion
                #region setowner
            case "setowner":
                if (pCount != 3)
                {
                    plr.SendErrorMessage("Invalid syntax! Proper syntax: {0}/re setowner <regionname> <username>", specifier);
                    return;
                }
                if (TShock.Regions.GetRegionByName(param[1]) == null)
                {
                    plr.SendErrorMessage($"Invalid region \"{param[1]}\".");
                    return;
                }
                if (TShock.UserAccounts.GetUserAccountByName(param[2]) == null)
                {
                    plr.SendErrorMessage($"Invalid username \"{param[2]}\".");
                }
                if (TShock.Regions.ChangeOwner(param[1], param[2]))
                {
                    plr.SendSuccessMessage("Region changeowner success!");
                }
                else
                {
                    plr.SendErrorMessage("Region changeowner failed!");
                }
                break;

                #endregion
                #region listown
            case "lo":
            case "listown":
                if (pCount != 3)
                {
                    plr.SendErrorMessage("Invalid syntax! Proper syntax: {0}/re lo <playername> <page>", specifier);
                    return;
                }
                ;
                if (TShock.UserAccounts.GetUserAccountByName(param[1]) == null)
                {
                    plr.SendErrorMessage($"Invalid username \"{param[1]}\".");
                }
                ;
                var player  = TShock.UserAccounts.GetUserAccountByName(param[1]);
                var regions = TShock.Regions.Regions.FindAll(reg => reg.Owner == player.Name && reg.WorldID == Main.worldID.ToString());
                int pageNumberList;
                if (!PaginationTools.TryParsePageNumber(param, 2, plr, out pageNumberList))
                {
                    return;
                }
                List <string> regionNamesList = new List <string>();
                for (int i = 0; i < regions.Count; i++)
                {
                    regionNamesList.Add(regions[i].Name);
                }
                PaginationTools.SendPage(plr, pageNumberList, PaginationTools.BuildLinesFromTerms(regionNamesList),
                                         new PaginationTools.Settings
                {
                    HeaderFormat           = "Player regions ({0}/{1}):",
                    FooterFormat           = "Type {0}/re lo {1} {{0}} for more.".SFormat(specifier, param[1]),
                    NothingToDisplayString = "There are currently no regions."
                });
                break;

                #endregion
                #region help
            case "help":
                int pageNumber;
                if (!PaginationTools.TryParsePageNumber(param, 1, plr, out pageNumber))
                {
                    return;
                }

                lines = new List <string> {
                    "rename <oldname> <newname> - Set the name of the region.",
                    "move <regionname> <u/d/r/l> <amount> - Move region coordinate at the given direction.",
                    "fr <regionname> [ownername] [z] [protect] - Defines the region with given points.",
                    "frbreak - Break fastregion request.",
                    "clearm <regionname> - Clear all allowed members at the given region.",
                    "setowner <regionname> <username> - Set region owner."
                };

                PaginationTools.SendPage(
                    plr, pageNumber, lines,
                    new PaginationTools.Settings
                {
                    HeaderFormat = "Available Region Extension Sub-Commands ({0}/{1}):",
                    FooterFormat = "Type {0}/re help {{0}} for more sub-commands.".SFormat(specifier)
                }
                    );
                break;

                #endregion
            default:
                plr.SendErrorMessage("Invalid sub-command! Check {0}/re help for more information.", specifier);
                break;
            }
        }
Пример #21
0
        private static void MyPlot(CommandArgs args)
        {
            if (!args.Player.IsLoggedIn)
            {
                args.Player.SendErrorMessage("你未登录, 无法使用属地.");
                return;
            }

            var cmd  = args.Parameters.Count > 0 ? args.Parameters[0].ToLower() : "help";
            var info = PlayerInfo.GetInfo(args.Player);

            switch (cmd)
            {
            case "获取":
            case "get":
            {
                if (args.Parameters.Count != 1)
                {
                    args.Player.SendErrorMessage("语法无效. 正确语法: {0}", TShock.Utils.ColorTag("/属地 获取", Color.Cyan));
                    return;
                }

                var count = Plots.GetTotalCells(args.Player.Account.Name);
                var max   = args.Player.GetMaxCells();
                if (max != -1 && count >= args.Player.GetMaxCells())
                {
                    args.Player.SendErrorMessage("你无法获取更多属地. (你当前有{0}个/最多{1}个)", count, max);
                    return;
                }
                info.Status     = PlayerInfo.PointStatus.Delegate;
                info.OnGetPoint = InternalApply;
                args.Player.SendInfoMessage("在空白属地内放置任意物块, 来确定你的属地位置.");

                void InternalApply(int x, int y, TSPlayer receiver) => Plots.ApplyForCell(receiver, x, y);
            }
            break;

            case "自动获取":
            case "autoget":
            {
                if (args.Parameters.Count != 1)
                {
                    args.Player.SendErrorMessage("语法无效. 正确语法: {0}", TShock.Utils.ColorTag("/属地 自动获取", Color.Cyan));
                    return;
                }

                var count = Plots.GetTotalCells(args.Player.Account.Name);
                var max   = args.Player.GetMaxCells();
                if (max != -1 && count >= args.Player.GetMaxCells())
                {
                    args.Player.SendErrorMessage("你无法获取更多属地. (你当前有{0}个/最多{1}个)", count, max);
                    return;
                }

                Plots.ApplyForCell(args.Player);
            }
            break;

            case "允许":
            case "添加":
            case "allow":
            {
                if (args.Parameters.Count < 2)
                {
                    args.Player.SendErrorMessage("语法无效. 正确语法: {0}", TShock.Utils.ColorTag("/属地 允许 <玩家名>", Color.Cyan));
                    return;
                }

                var count = Plots.GetTotalCells(args.Player.Account.Name);
                switch (count)
                {
                case 0:
                    args.Player.SendErrorMessage("你没有属地!");
                    break;

                case 1:
                    var cell = Plots.GetOnlyCellOfPlayer(args.Player.Account.Name);
                    if (cell == null)
                    {
                        args.Player.SendErrorMessage("载入属地失败! 请联系管理 (不唯一或缺少)");
                        return;
                    }
                    InternalSetUser(args.Parameters, args.Player, cell, true);
                    break;

                default:
                    if (count > 1)
                    {
                        info.Status     = PlayerInfo.PointStatus.Delegate;
                        info.OnGetPoint = InternalSetUserWithPoint;
                        args.Player.SendInfoMessage("在你的属地内放置物块来添加用户.");
                    }
                    break;
                }

                void InternalSetUserWithPoint(int x, int y, TSPlayer receiver) => InternalSetUser(args.Parameters, receiver, Plots.GetCellByPosition(x, y), true);
            }
            break;

            case "禁止":
            case "删除":
            case "disallow":
            {
                if (args.Parameters.Count < 2)
                {
                    args.Player.SendErrorMessage("语法无效. 正确语法: {0}", TShock.Utils.ColorTag("/属地 禁止 <玩家名>", Color.Cyan));
                    return;
                }

                var count = Plots.GetTotalCells(args.Player.Account.Name);
                switch (count)
                {
                case 0:
                    args.Player.SendErrorMessage("你没有属地!");
                    break;

                case 1:
                    var cell = Plots.GetOnlyCellOfPlayer(args.Player.Account.Name);
                    if (cell == null)
                    {
                        args.Player.SendErrorMessage("载入属地失败! 请联系管理 (不唯一或缺少)");
                        return;
                    }
                    InternalSetUser(args.Parameters, args.Player, cell, false);
                    break;

                default:
                    if (count > 1)
                    {
                        info.Status     = PlayerInfo.PointStatus.Delegate;
                        info.OnGetPoint = InternalSetUserWithPoint;
                        args.Player.SendInfoMessage("在你的属地内放置物块来移除用户.");
                    }
                    break;
                }

                void InternalSetUserWithPoint(int x, int y, TSPlayer receiver) => InternalSetUser(args.Parameters, receiver, Plots.GetCellByPosition(x, y), false);
            }
            break;

            case "信息":
            case "查询":
            case "info":
            {
                if (args.Parameters.Count != 1)
                {
                    args.Player.SendErrorMessage("语法无效. 正确语法: {0}", TShock.Utils.ColorTag("/属地 信息", Color.Cyan));
                    return;
                }
                info.Status     = PlayerInfo.PointStatus.Delegate;
                info.OnGetPoint = InternalGetInfo;
                args.Player.SendInfoMessage("在你的属地内放置任意物块, 来查看你的属地信息.");

                void InternalGetInfo(int tileX, int tileY, TSPlayer player)
                {
                    var cell = Plots.GetCellByPosition(tileX, tileY);

                    if (cell != null)
                    {
                        if (cell.Owner != player.Account.Name && !player.HasPermission("pm.admin.editall"))
                        {
                            player.SendErrorMessage("你不是该属地的主人.");
                            return;
                        }
                        cell.GetInfo(player);
                        return;
                    }
                    player.SendErrorMessage("选择点不在属地内.");
                }
            }
            break;

            case "帮助":
            case "help":
            {
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out var pageNumber))
                {
                    return;
                }
                var list = new List <string>
                {
                    "获取 - 获取选中点区域 (get/获取)",
                    "自动获取 - 自动获取区域 (autoget/自动获取)",
                    "允许 <玩家名> - 给自己的属地增加协助者 (allow/允许/添加)",
                    "禁止 <玩家名> - 移除协助者 (disallow/禁止/删除)",
                    "信息 - 查看当前点坐标所在属地的信息 (info/信息/查询)",
                    "帮助 [页码] - 获取帮助 (help/帮助)"
                };
                PaginationTools.SendPage(args.Player, pageNumber, list,
                                         new PaginationTools.Settings
                    {
                        HeaderFormat           = "玩家属地子指令说明 ({0}/{1}):",
                        FooterFormat           = "键入 {0}属地 帮助 {{0}} 以获取下一页列表.".SFormat(Commands.Specifier),
                        NothingToDisplayString = "当前没有说明."
                    });
            }
            break;

            default:
            {
                args.Player.SendWarningMessage("子指令无效! 输入 {0} 获取帮助信息.",
                                               TShock.Utils.ColorTag("/属地 帮助", Color.Cyan));
            }
            break;
            }

            void InternalSetUser(IEnumerable <string> parameters, TSPlayer player, Cell target, bool allow)
            {
                var playerName = string.Join(" ", parameters.Skip(1));
                var user       = TShock.UserAccounts.GetUserAccountByName(playerName);

                if (user == null)
                {
                    player.SendErrorMessage("玩家 " + playerName + " 未找到");
                    return;
                }

                if (target != null)
                {
                    if (target.Owner != player.Account.Name && !player.HasPermission("pm.admin.editall"))
                    {
                        player.SendErrorMessage("你不是该属地的主人.");
                        return;
                    }

                    if (allow)
                    {
                        if (Plots.AddCellUser(target, user))
                        {
                            player.SendInfoMessage("添加用户 " + playerName + " 完毕.");
                        }
                        else
                        {
                            player.SendErrorMessage("添加用户时出现问题.");
                        }
                    }
                    else
                    {
                        if (Plots.RemoveCellUser(target, user))
                        {
                            player.SendInfoMessage("移除用户 " + playerName + " 完毕.");
                        }
                        else
                        {
                            player.SendErrorMessage("移除用户时出现问题.");
                        }
                    }
                }
                else
                {
                    player.SendErrorMessage("该点坐标不在属地内.");
                }
            }
        }
Пример #22
0
        private static void RegionOwningCmd(CommandArgs args)
        {
            var param = args.Parameters;
            var plr   = args.Player;

            if (param.Count < 1)
            {
                param.Add("help");
            }
            int    pCount    = param.Count;
            string specifier = TShock.Config.CommandSpecifier;
            var    regions   = TShock.Regions.Regions.FindAll(reg => reg.Owner == plr.Account.Name && reg.WorldID == Main.worldID.ToString());

            switch (param[0])
            {
                #region list
            case "list":
                int pageNumberList;
                if (!PaginationTools.TryParsePageNumber(param, 1, plr, out pageNumberList))
                {
                    return;
                }
                List <string> regionNamesList = new List <string>();
                for (int i = 0; i < regions.Count; i++)
                {
                    regionNamesList.Add(regions[i].Name);
                }
                PaginationTools.SendPage(plr, pageNumberList, PaginationTools.BuildLinesFromTerms(regionNamesList),
                                         new PaginationTools.Settings
                {
                    HeaderFormat           = "Your regions ({0}/{1}):",
                    FooterFormat           = "Type {0}/ro list {{0}} for more.".SFormat(specifier),
                    NothingToDisplayString = "There are currently no regions."
                });
                break;

                #endregion
                #region info
            case "info":
                if (pCount == 1 || pCount > 3)
                {
                    args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region info <region> [page]", specifier);
                    return;
                }

                string regionName = param[1];

                Region region = regions.FirstOrDefault(reg => reg.Name == regionName);
                if (region == null)
                {
                    plr.SendErrorMessage("Invalid region \"{0}\"!", regionName);
                    return;
                }

                int pageNumberIndex = 2;
                int pageNumberInfo;
                if (!PaginationTools.TryParsePageNumber(param, pageNumberIndex, plr, out pageNumberInfo))
                {
                    return;
                }

                List <string> lines = new List <string>
                {
                    string.Format("X: {0}; Y: {1}; W: {2}; H: {3}, Z: {4}", region.Area.X, region.Area.Y, region.Area.Width, region.Area.Height, region.Z),
                    string.Concat("Owner: ", region.Owner),
                    string.Concat("Protected: ", region.DisableBuild.ToString()),
                };

                if (region.AllowedIDs.Count > 0)
                {
                    IEnumerable <string> sharedUsersSelector = region.AllowedIDs.Select(userId =>
                    {
                        UserAccount user = TShock.UserAccounts.GetUserAccountByID(userId);
                        if (user != null)
                        {
                            return(user.Name);
                        }

                        return(string.Concat("{ID: ", userId, "}"));
                    });
                    List <string> extraLines = PaginationTools.BuildLinesFromTerms(sharedUsersSelector.Distinct());
                    extraLines[0] = "Shared with: " + extraLines[0];
                    lines.AddRange(extraLines);
                }
                else
                {
                    lines.Add("Region is not shared with any users.");
                }

                if (region.AllowedGroups.Count > 0)
                {
                    List <string> extraLines = PaginationTools.BuildLinesFromTerms(region.AllowedGroups.Distinct());
                    extraLines[0] = "Shared with groups: " + extraLines[0];
                    lines.AddRange(extraLines);
                }
                else
                {
                    lines.Add("Region is not shared with any groups.");
                }

                PaginationTools.SendPage(
                    plr, pageNumberInfo, lines, new PaginationTools.Settings
                {
                    HeaderFormat = string.Format("Information About Region \"{0}\" ({{0}}/{{1}}):", region.Name),
                    FooterFormat = string.Format("Type {0}/ro info {1} {{0}} for more information.", specifier, regionName)
                }
                    );
                break;

                #endregion
                #region allow
            case "allow":
                if (pCount != 3)
                {
                    plr.SendErrorMessage("Invalid syntax! Proper syntax: {0}/ro allow <name> <region>", specifier);
                    return;
                }
                if (regions.FirstOrDefault(reg => reg.Name == param[2]) == null)
                {
                    plr.SendErrorMessage($"Invalid region \"{param[2]}\".");
                    return;
                }
                if (TShock.UserAccounts.GetUserAccountByName(param[1]) == null)
                {
                    plr.SendErrorMessage($"Invalid username \"{param[1]}\".");
                    return;
                }
                if (TShock.Regions.AddNewUser(param[2], param[1]))
                {
                    plr.SendSuccessMessage($"Allowed user {param[1]} into {param[2]}");
                }
                break;

                #endregion
                #region remove
            case "remove":
                if (pCount != 3)
                {
                    plr.SendErrorMessage("Invalid syntax! Proper syntax: {0}/ro remove <name> <region>", specifier);
                    return;
                }
                if (regions.FirstOrDefault(reg => reg.Name == param[2]) == null)
                {
                    plr.SendErrorMessage($"Invalid region \"{param[2]}\".");
                    return;
                }
                if (TShock.UserAccounts.GetUserAccountByName(param[1]) == null)
                {
                    plr.SendErrorMessage($"Invalid username \"{param[1]}\".");
                }
                if (TShock.Regions.RemoveUser(param[2], param[1]))
                {
                    plr.SendSuccessMessage($"Removed user {param[1]} from {param[2]}");
                }

                break;

                #endregion
                #region clearmembers
            case "clearmembers":
            case "clearm":
                if (pCount != 2)
                {
                    plr.SendErrorMessage("Invalid syntax! Proper syntax: {0}/ro clearm <regionname>", specifier);
                    return;
                }
                if (regions.FirstOrDefault(reg => reg.Name == param[1]) == null)
                {
                    plr.SendErrorMessage($"Invalid region \"{param[1]}\".");
                    return;
                }
                if (Plugin.ExtManager.ClearAllowUsers(param[1]))
                {
                    plr.SendSuccessMessage("Region clear member success!");
                }
                else
                {
                    plr.SendErrorMessage("Region clear member failed!");
                }
                break;

                #endregion
                #region giveowner
            case "giveowner":
            case "giveown":
            case "gow":
            case "go":
                if (pCount != 3)
                {
                    plr.SendErrorMessage("Invalid syntax! Proper syntax: {0}/ro gow <user> <region>", specifier);
                    return;
                }
                if (regions.FirstOrDefault(reg => reg.Name == param[2]) == null)
                {
                    plr.SendErrorMessage($"Invalid region \"{param[2]}\".");
                    return;
                }
                if (TShock.UserAccounts.GetUserAccountByName(param[1]) == null)
                {
                    plr.SendErrorMessage($"Invalid username \"{param[1]}\".");
                }
                if (TShock.Regions.ChangeOwner(param[2], param[1]))
                {
                    plr.SendSuccessMessage("Region changeowner success!");
                }
                else
                {
                    plr.SendErrorMessage("Region changeowner failed!");
                }
                break;

                #endregion
                #region help
            case "help":
                int pageNumber;
                if (!PaginationTools.TryParsePageNumber(param, 1, plr, out pageNumber))
                {
                    return;
                }

                lines = new List <string> {
                    "list - Lists of all your regions.",
                    "allow <user> <region> - Allows a user to a region.",
                    "remove <user> <region> - Removes a user from a region.",
                    "giveown <user> <region> - Change owner of region (You lose own for region!).",
                    "clearm <regionname> - Removes all allowed users from region",
                    "info <region> - Displays several information about the given region."
                };

                PaginationTools.SendPage(
                    plr, pageNumber, lines,
                    new PaginationTools.Settings
                {
                    HeaderFormat = "Available Region Owning Sub-Commands ({0}/{1}):",
                    FooterFormat = "Type {0}/ro help {{0}} for more sub-commands.".SFormat(specifier)
                }
                    );
                break;

                #endregion
            default:
                plr.SendErrorMessage("Invalid sub-command! Check {0}/ro help for more information.", specifier);
                break;
            }
        }
Пример #23
0
        private void RegionSetProperties(CommandArgs args)
        {
            if (args.Parameters.Count == 0)
            {
                args.Player.SendErrorMessage("Invalid syntax! Type /rt --help to get instructions.");
                return;
            }

            var cmd = args.Parameters[0].Trim().ToLowerInvariant();

            if (cmd.StartsWith("set-"))
            {
                #region set-prop
                if (args.Parameters.Count < 3)
                {
                    args.Player.SendErrorMessage("Invalid syntax! Proper syntax: /rt set-<prop> <region> [--del] <value>");
                    return;
                }
                var propset = cmd.Substring(4);
                // check the property
                if (!PropStrings.Any(strarray => strarray.Contains(propset)))
                {
                    args.Player.SendErrorMessage("Invalid property!");
                    return;
                }
                // get the shortest representation of property.
                // e.g. event => e, projban => pb
                propset = PropStrings.Single(props => props.Contains(propset))[0];
                // check existance of region
                var region = TShock.Regions.GetRegionByName(args.Parameters[1]);
                if (region == null)
                {
                    args.Player.SendErrorMessage("Invalid region!");
                    return;
                }
                // if region hasn't been added into database
                var rt = RtRegions.GetRtRegionByRegionId(region.ID);
                if (rt == null)
                {
                    RtRegions.AddRtRegion(region.ID);
                    rt = RtRegions.GetRtRegionByRegionId(region.ID);
                }
                // has parameter --del
                var isDel = string.Equals(args.Parameters[2], "--del", StringComparison.OrdinalIgnoreCase);
                // sometimes commands with --del don't need <value> e.g. /rt set-tg <region> --del
                if (isDel && args.Parameters.Count == 3 && !DoNotNeedDelValueProps.Contains(propset))
                {
                    args.Player.SendErrorMessage($"Invalid syntax! Proper syntax: /rt set-{propset} <region> [--del] <value>");
                    return;
                }
                var propValue = isDel && args.Parameters.Count == 3 ? null : isDel
                                        ? string.Join(" ", args.Parameters.GetRange(3, args.Parameters.Count - 3))
                                        : string.Join(" ", args.Parameters.GetRange(2, args.Parameters.Count - 2));

                try
                {
                    switch (propset)
                    {
                    case "e":
                        var validatedEvents = Events.ValidateEventWhenAdd(propValue, out var invalids);
                        if (!isDel)
                        {
                            RtRegions.AddEvents(rt, validatedEvents);
                        }
                        else
                        {
                            RtRegions.RemoveEvents(rt, validatedEvents);
                        }
                        args.Player.SendSuccessMessage("Region {0} has been modified successfully!", region.Name);
                        if (!string.IsNullOrWhiteSpace(invalids))
                        {
                            args.Player.SendErrorMessage("Invalid events: {0}", invalids);
                        }
                        break;

                    case "pb":
                        if (short.TryParse(propValue, out var id) && id > 0 && id < Main.maxProjectileTypes)
                        {
                            if (!isDel)
                            {
                                RtRegions.AddProjban(rt, id);
                                args.Player.SendSuccessMessage("Banned projectile {0} in region {1}.", id, region.Name);
                            }
                            else
                            {
                                RtRegions.RemoveProjban(rt, id);
                                args.Player.SendSuccessMessage("Unbanned projectile {0} in region {1}.", id, region.Name);
                            }
                        }
                        else
                        {
                            args.Player.SendErrorMessage("Invalid projectile ID!");
                        }
                        break;

                    case "ib":
                        var items = TShock.Utils.GetItemByIdOrName(propValue);
                        if (items.Count == 0)
                        {
                            args.Player.SendErrorMessage("Invalid item.");
                        }
                        else if (items.Count > 1)
                        {
                            TShock.Utils.SendMultipleMatchError(args.Player, items.Select(i => i.Name));
                        }
                        else
                        {
                            if (!isDel)
                            {
                                RtRegions.AddItemban(rt, items[0].Name);
                                args.Player.SendSuccessMessage("Banned {0} in region {1}.", items[0].Name, region.Name);
                            }
                            else
                            {
                                RtRegions.RemoveItemban(rt, items[0].Name);
                                args.Player.SendSuccessMessage("Unbanned {0} in region {1}.", items[0].Name, region.Name);
                            }
                        }
                        break;

                    case "tb":
                        if (short.TryParse(propValue, out var tileid) && tileid >= 0 && tileid < Main.maxTileSets)
                        {
                            if (!isDel)
                            {
                                RtRegions.AddTileban(rt, tileid);
                                args.Player.SendSuccessMessage("Banned tile {0} in region {1}.", tileid, region.Name);
                            }
                            else
                            {
                                RtRegions.RemoveTileban(rt, tileid);
                                args.Player.SendSuccessMessage("Unbanned tile {0} in region {1}.", tileid, region.Name);
                            }
                        }
                        else
                        {
                            args.Player.SendErrorMessage("Invalid tile ID!");
                        }
                        break;

                    case "em":
                        RtRegions.SetEnterMessage(rt, !isDel ? propValue : null);
                        if (!isDel)
                        {
                            args.Player.SendSuccessMessage("Set enter message of region {0} to '{1}'", region.Name, propValue);
                            if (!rt.HasEvent(Event.EnterMsg))
                            {
                                args.Player.SendWarningMessage("Add event ENTERMESSAGE if you want to make it work.");
                            }
                        }
                        else
                        {
                            args.Player.SendSuccessMessage("Removed enter message of region {0}.", region.Name);
                        }
                        break;

                    case "lm":
                        RtRegions.SetLeaveMessage(rt, !isDel ? propValue : null);
                        if (!isDel)
                        {
                            args.Player.SendSuccessMessage("Set leave message of region {0} to '{1}'", region.Name, propValue);
                            if (!rt.HasEvent(Event.LeaveMsg))
                            {
                                args.Player.SendWarningMessage("Add event LEAVEMESSAGE if you want to make it work.");
                            }
                        }
                        else
                        {
                            args.Player.SendSuccessMessage("Removed leave message of region {0}.", region.Name);
                        }
                        break;

                    case "msg":
                        RtRegions.SetMessage(rt, !isDel ? propValue : null);
                        if (!isDel)
                        {
                            args.Player.SendSuccessMessage("Set message of region {0} to '{1}'", region.Name, propValue);
                            if (!rt.HasEvent(Event.Message))
                            {
                                args.Player.SendWarningMessage("Add event MESSAGE if you want to make it work.");
                            }
                        }
                        else
                        {
                            args.Player.SendSuccessMessage("Removed message of region {0}.", region.Name);
                        }
                        break;

                    case "mi":
                        if (isDel)
                        {
                            throw new Exception("Invalid usage! Proper usage: /rt set-mi <region> <interval>");
                        }
                        if (!int.TryParse(propValue, out var itv) || itv < 0)
                        {
                            throw new Exception("Invalid interval. (Interval must be integer >= 0)");
                        }
                        RtRegions.SetMsgInterval(rt, itv);
                        args.Player.SendSuccessMessage("Set message interval of region {0} to {1}.", region.Name, itv);
                        if (!rt.HasEvent(Event.Message))
                        {
                            args.Player.SendWarningMessage("Add event MESSAGE if you want to make it work.");
                        }
                        break;

                    case "tg":
                        if (!isDel && propValue != "null")
                        {
                            RtRegions.SetTempGroup(rt, propValue);
                            args.Player.SendSuccessMessage("Set tempgroup of region {0} to {1}.", region.Name, propValue);
                            if (!rt.HasEvent(Event.TempGroup))
                            {
                                args.Player.SendWarningMessage("Add event TEMPGROUP if you want to make it work.");
                            }
                        }
                        else
                        {
                            RtRegions.SetTempGroup(rt, null);
                            args.Player.SendSuccessMessage("Removed tempgroup of region {0}.", region.Name);
                        }
                        break;

                    case "tp":
                        // ReSharper disable once PossibleNullReferenceException
                        var permissions = propValue.ToLower().Split(',').Where(s => !string.IsNullOrWhiteSpace(s)).ToList();
                        if (!isDel)
                        {
                            RtRegions.AddPermissions(rt, permissions);
                            args.Player.SendSuccessMessage("Region {0} has been modified successfully.", region.Name);
                        }
                        else
                        {
                            RtRegions.DeletePermissions(rt, permissions);
                            args.Player.SendSuccessMessage("Region {0} has been modified successfully.", region.Name);
                        }
                        break;
                    }
                }
                catch (Exception ex)
                {
                    args.Player.SendErrorMessage(ex.Message);
                }
                #endregion
            }
            else
            {
                switch (cmd)
                {
                case "show":
                    #region show
                {
                    if (args.Parameters.Count != 2)
                    {
                        args.Player.SendErrorMessage("Invalid syntax! Usage: /rt show <region>");
                        return;
                    }

                    var region = TShock.Regions.GetRegionByName(args.Parameters[1]);
                    if (region == null)
                    {
                        args.Player.SendErrorMessage("Invalid region!");
                        return;
                    }
                    var rt = RtRegions.GetRtRegionByRegionId(region.ID);
                    if (rt == null)
                    {
                        args.Player.SendInfoMessage("{0} has not been set up yet. Use: /rt set-<prop> <name> <value>", region.Name);
                        return;
                    }

                    var infos = new List <string> {
                        $"*** Information of region {rt.Region.Name} ***",
                        $" * Events: {rt.Events}",
                        $" * TempGroup: {rt.TempGroup?.Name ?? "None"}",
                        $" * Message & Interval: {rt.Message ?? "None"}({rt.MsgInterval}s)",
                        $" * EnterMessage: {rt.EnterMsg ?? "None"}",
                        $" * LeaveMessage: {rt.LeaveMsg ?? "None"}",
                        $" * Itembans: {(string.IsNullOrWhiteSpace(rt.Itembans) ? "None" : rt.Itembans)}",
                        $" * Projbans: {(string.IsNullOrWhiteSpace(rt.Projbans) ? "None" : rt.Projbans)}",
                        $" * Tilebans: {(string.IsNullOrWhiteSpace(rt.Tilebans) ? "None" : rt.Tilebans)}"
                    };
                    infos.ForEach(args.Player.SendInfoMessage);
                }
                    #endregion
                    break;

                case "reload":
                    RtRegions.Reload();
                    args.Player.SendSuccessMessage("Reloaded regions from database successfully.");
                    break;

                case "--help":
                    #region Help
                    if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out var pageNumber))
                    {
                        return;
                    }

                    var lines = new List <string>
                    {
                        "*** Usage: /rt set-<prop> <region> [--del] <value>",
                        "           /rt show <region>",
                        "           /rt reload",
                        "           /rt --help [page]",
                        "*** Avaliable properties:"
                    };
                    lines.AddRange(PaginationTools.BuildLinesFromTerms(PropStrings, array =>
                    {
                        var strarray = (string[])array;
                        return($"{strarray[0]}({string.Join("/", strarray.Skip(1))})");
                    }, ",", 75).Select(s => s.Insert(0, "   * ")));
                    lines.Add("*** Available events:");
                    lines.AddRange(Events.EventsDescriptions.Select(pair => $"   * {pair.Key} - {pair.Value}"));

                    PaginationTools.SendPage(args.Player, pageNumber, lines,
                                             new PaginationTools.Settings
                    {
                        HeaderFormat = "RegionTrigger Instructions ({0}/{1}):",
                        FooterFormat = "Type {0}rt --help {{0}} for more instructions.".SFormat(Commands.Specifier)
                    }
                                             );
                    #endregion
                    break;

                default:
                    args.Player.SendErrorMessage("Invalid syntax! Type /rt --help for instructions.");
                    return;
                }
            }
        }
        private static void Help(CommandArgs e)
        {
            if (e.Parameters.Count > 1)
            {
                e.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}help <command/page>", TShock.Config.CommandSpecifier);
                return;
            }

            if (e.Parameters.Count == 0 || int.TryParse(e.Parameters[0], out int pageNumber))
            {
                if (!PaginationTools.TryParsePageNumber(e.Parameters, 0, e.Player, out pageNumber))
                {
                    return;
                }

                var playerInfo = e.Player.GetData <PlayerInfo>(PlayerInfo.DataKey);
                var cmdNames   = from cmd in Commands.ChatCommands
                                 where cmd.CanRun(e.Player) && (!playerInfo?.Permissions.Negated(cmd.Permissions.ElementAtOrDefault(0)) ?? true) ||
                                 (playerInfo?.Permissions.ContainsPermission(cmd.Permissions.ElementAtOrDefault(0)) ?? true) && (cmd.Name != "auth" || TShock.AuthToken != 0)
                                 orderby cmd.Name
                                 select TShock.Config.CommandSpecifier + cmd.Name;

                PaginationTools.SendPage(e.Player, pageNumber, PaginationTools.BuildLinesFromTerms(cmdNames),
                                         new PaginationTools.Settings
                {
                    HeaderFormat = "Commands ({0}/{1}):",
                    FooterFormat = "Type {0}help {{0}} for more.".SFormat(TShock.Config.CommandSpecifier)
                });
            }
            else
            {
                var commandName = e.Parameters[0].ToLower();
                if (commandName.StartsWith(TShock.Config.CommandSpecifier))
                {
                    commandName = commandName.Substring(1);
                }

                var command = Commands.ChatCommands.Find(c => c.Names.Contains(commandName));
                if (command == null)
                {
                    e.Player.SendErrorMessage("Invalid command.");
                    return;
                }
                if (!command.CanRun(e.Player) && !e.Player.HasPermission(command.Permissions[0]))
                {
                    e.Player.SendErrorMessage("You do not have access to this command.");
                    return;
                }

                e.Player.SendSuccessMessage("{0}{1} help: ", TShock.Config.CommandSpecifier, command.Name);
                if (command.HelpDesc == null)
                {
                    e.Player.SendInfoMessage(command.HelpText);
                    return;
                }
                foreach (var line in command.HelpDesc)
                {
                    e.Player.SendInfoMessage(line);
                }
            }
        }
        private bool TryExecuteSubCommand(string commandNameLC, CommandArgs args)
        {
            switch (commandNameLC)
            {
            case "commands":
            case "cmds":
                args.Player.SendMessage("Available Sub-Commands:", Color.White);
                args.Player.SendMessage("/ac blocks", Color.Yellow);
                args.Player.SendMessage("/ac toggle|switch", Color.Yellow);

                if (args.Player.Group.HasPermission(AdvancedCircuitsPlugin.ReloadCfg_Permission))
                {
                    args.Player.SendMessage("/ac reloadcfg", Color.Yellow);
                }

                return(true);

            case "reloadcfg":
                if (args.Player.Group.HasPermission(AdvancedCircuitsPlugin.ReloadCfg_Permission))
                {
                    this.PluginTrace.WriteLineInfo("Reloading configuration file.");
                    try {
                        this.ReloadConfigurationCallback();
                        this.PluginTrace.WriteLineInfo("Configuration file successfully reloaded.");

                        if (args.Player != TSPlayer.Server)
                        {
                            args.Player.SendMessage("Configuration file successfully reloaded.", Color.Yellow);
                        }
                    } catch (Exception ex) {
                        this.PluginTrace.WriteLineError(
                            "Reloading the configuration file failed. Keeping old configuration. Exception details:\n{0}", ex
                            );
                    }
                }
                else
                {
                    args.Player.SendErrorMessage("You do not have the necessary permission to do that.");
                }

                return(true);

            case "blocks":
            case "ores":
            case "tiles":
                int pageNumber;
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
                {
                    return(true);
                }

                PaginationTools.SendPage(
                    args.Player, pageNumber,
                    new List <string>()
                {
                    "Copper Ore - OR-Gate",
                    "Silver Ore - AND-Gate",
                    "Gold Ore - XOR-Gate / XOR-Port",
                    "Obsidian - NOT-Gate / NOT-Port",
                    "Iron Ore - Swapper",
                    "Spike - Crossover Bridge",
                    "Glass - Input Port",
                    "Active Stone - Active Stone and Block Activator",
                    "Adamantite Ore - Wireless Transmitter"
                },
                    new PaginationTools.Settings {
                    HeaderFormat    = "Advanced Circuits Special Blocks (Page {0} of {1})",
                    HeaderTextColor = Color.Lime,
                    LineTextColor   = Color.LightGray,
                    MaxLinesPerPage = 4,
                }
                    );

                return(true);

            case "toggle":
            case "switch":
                args.Player.SendInfoMessage("Place or destroy a wire on the component you want to toggle.");

                if (args.Parameters.Count > 3)
                {
                    args.Player.SendErrorMessage("Proper syntax: /ac switch [state] [+p]");
                    args.Player.SendInfoMessage("Type /ac switch help to get more help to this command.");
                    return(true);
                }

                bool persistentMode = false;
                bool?newState       = null;
                if (args.Parameters.Count > 1)
                {
                    int newStateRaw;
                    if (int.TryParse(args.Parameters[1], out newStateRaw))
                    {
                        newState = (newStateRaw == 1);
                    }

                    persistentMode = args.ContainsParameter("+p", StringComparison.InvariantCultureIgnoreCase);
                }

                CommandInteraction interaction = this.StartOrResetCommandInteraction(args.Player);
                interaction.DoesNeverComplete = persistentMode;
                interaction.TileEditCallback  = (player, editType, blockType, location, blockStyle) => {
                    if (
                        editType != TileEditType.PlaceTile ||
                        editType != TileEditType.PlaceWall ||
                        editType != TileEditType.DestroyWall ||
                        editType != TileEditType.PlaceActuator
                        )
                    {
                        CommandInteractionResult result = new CommandInteractionResult {
                            IsHandled = true, IsInteractionCompleted = true
                        };
                        ITile tile = TerrariaUtils.Tiles[location];

                        if (
                            !args.Player.HasBuildPermission(location.X, location.Y) || (
                                this.PluginCooperationHandler.IsProtectorAvailable &&
                                this.PluginCooperationHandler.Protector_CheckProtected(args.Player, location, false)
                                ))
                        {
                            player.SendErrorMessage("This object is protected.");
                            player.SendTileSquare(location, 1);
                            return(result);
                        }

                        int hitBlockType = tile.type;
                        if (tile.active() && hitBlockType == TileID.ActiveStoneBlock)
                        {
                            if (newState == null || newState == false)
                            {
                                TerrariaUtils.Tiles.SetBlock(location, TileID.InactiveStoneBlock);
                            }
                            else
                            {
                                args.Player.SendTileSquare(location);
                            }
                        }
                        else if (hitBlockType == TileID.InactiveStoneBlock)
                        {
                            if (tile.active() && newState == null || newState == true)
                            {
                                TerrariaUtils.Tiles.SetBlock(location, TileID.ActiveStoneBlock);
                            }
                            else
                            {
                                args.Player.SendTileSquare(location);
                            }
                        }
                        else if (tile.active() && TerrariaUtils.Tiles.IsMultistateObject(hitBlockType))
                        {
                            ObjectMeasureData measureData = TerrariaUtils.Tiles.MeasureObject(location);
                            bool currentState             = TerrariaUtils.Tiles.ObjectHasActiveState(measureData);
                            if (newState == null)
                            {
                                newState = !TerrariaUtils.Tiles.ObjectHasActiveState(measureData);
                            }

                            if (currentState != newState.Value)
                            {
                                TerrariaUtils.Tiles.SetObjectState(measureData, newState.Value);
                            }
                            else
                            {
                                args.Player.SendTileSquare(location);
                            }
                        }
                        else if (
                            hitBlockType == AdvancedCircuits.BlockType_ORGate ||
                            hitBlockType == AdvancedCircuits.BlockType_ANDGate ||
                            hitBlockType == AdvancedCircuits.BlockType_XORGate
                            )
                        {
                            if (
                                !args.Player.HasBuildPermission(location.X, location.Y) || (
                                    this.PluginCooperationHandler.IsProtectorAvailable &&
                                    this.PluginCooperationHandler.Protector_CheckProtected(args.Player, location, false)
                                    ))
                            {
                                player.SendErrorMessage("This gate is protected.");
                                player.SendTileSquare(location);
                                return(result);
                            }

                            PaintColor paint = (PaintColor)TerrariaUtils.Tiles[location].color();
                            if (paint == AdvancedCircuits.Paint_Gate_TemporaryState)
                            {
                                player.SendErrorMessage("The gate is painted {0}, there's no point in initializing it.", AdvancedCircuits.Paint_Gate_TemporaryState);
                                args.Player.SendTileSquare(location);
                                return(result);
                            }

                            GateStateMetadata gateState;
                            if (!this.WorldMetadata.GateStates.TryGetValue(location, out gateState))
                            {
                                gateState = new GateStateMetadata();
                                this.WorldMetadata.GateStates.Add(location, gateState);
                            }

                            List <DPoint> gatePortLocations = new List <DPoint>(AdvancedCircuits.EnumerateComponentPortLocations(location, new DPoint(1, 1)));
                            for (int i = 0; i < 4; i++)
                            {
                                ITile gatePort = TerrariaUtils.Tiles[gatePortLocations[i]];
                                if (!gatePort.active() || gatePort.type != (int)AdvancedCircuits.BlockType_InputPort)
                                {
                                    continue;
                                }

                                if (newState == null)
                                {
                                    if (gateState.PortStates[i] == null)
                                    {
                                        gateState.PortStates[i] = true;
                                    }
                                    else
                                    {
                                        gateState.PortStates[i] = !gateState.PortStates[i];
                                    }
                                }
                                else
                                {
                                    gateState.PortStates[i] = newState.Value;
                                }
                            }

                            player.SendSuccessMessage("The states of this gate's ports are now:");
                            this.SendGatePortStatesInfo(args.Player, gateState);
                            args.Player.SendTileSquare(location);
                        }
                        else if (tile.active() && tile.type == (int)AdvancedCircuits.BlockType_InputPort)
                        {
                            foreach (DPoint adjacentTileLocation in AdvancedCircuits.EnumerateComponentPortLocations(location, new DPoint(1, 1)))
                            {
                                ITile adjacentTile = TerrariaUtils.Tiles[adjacentTileLocation];
                                if (!adjacentTile.active() || !AdvancedCircuits.IsLogicalGate(adjacentTile.type))
                                {
                                    continue;
                                }

                                if (
                                    !args.Player.HasBuildPermission(adjacentTileLocation.X, adjacentTileLocation.Y) || (
                                        this.PluginCooperationHandler.IsProtectorAvailable &&
                                        this.PluginCooperationHandler.Protector_CheckProtected(args.Player, adjacentTileLocation, false)
                                        ))
                                {
                                    player.SendErrorMessage("This gate is protected.");
                                    player.SendTileSquare(location);
                                    return(result);
                                }

                                PaintColor paint = (PaintColor)TerrariaUtils.Tiles[location].color();
                                if (paint == AdvancedCircuits.Paint_Gate_TemporaryState)
                                {
                                    player.SendErrorMessage("The gate is painted {0}, there's no point in initializing it.", AdvancedCircuits.Paint_Gate_TemporaryState);
                                    args.Player.SendTileSquare(location);
                                    return(result);
                                }

                                GateStateMetadata gateState;
                                if (!this.WorldMetadata.GateStates.TryGetValue(adjacentTileLocation, out gateState))
                                {
                                    gateState = new GateStateMetadata();
                                    this.WorldMetadata.GateStates.Add(adjacentTileLocation, gateState);
                                }

                                int portIndex;
                                switch (AdvancedCircuits.DirectionFromTileLocations(adjacentTileLocation, location))
                                {
                                case Direction.Up:
                                    portIndex = 0;
                                    break;

                                case Direction.Down:
                                    portIndex = 1;
                                    break;

                                case Direction.Left:
                                    portIndex = 2;
                                    break;

                                case Direction.Right:
                                    portIndex = 3;
                                    break;

                                default:
                                    return(result);
                                }

                                if (newState == null)
                                {
                                    if (gateState.PortStates[portIndex] == null)
                                    {
                                        gateState.PortStates[portIndex] = true;
                                    }
                                    else
                                    {
                                        gateState.PortStates[portIndex] = !gateState.PortStates[portIndex];
                                    }
                                }
                                else
                                {
                                    gateState.PortStates[portIndex] = newState.Value;
                                }

                                player.SendSuccessMessage("The states of this gate's ports are now:");
                                this.SendGatePortStatesInfo(args.Player, gateState);
                                args.Player.SendTileSquare(location);
                                return(result);
                            }

                            player.SendErrorMessage($"The state of \"{TerrariaUtils.Tiles.GetBlockTypeName(hitBlockType, 0)}\" can not be changed.");
                            player.SendTileSquare(location);
                        }

                        return(result);
                    }

                    return(new CommandInteractionResult {
                        IsHandled = false, IsInteractionCompleted = false
                    });
                };
                interaction.TimeExpiredCallback = (player) => {
                    player.SendErrorMessage("Waited too long, no component will be toggled.");
                };

                args.Player.SendSuccessMessage("Hit an object to change its state.");
                return(true);
            }

            return(false);
        }
Пример #26
0
        public static void WorldRegen(CommandArgs args)
        {
            string cmd = "help";

            if (args.Parameters.Count > 0)
            {
                cmd = args.Parameters[0].ToLower();
            }
            switch (cmd)
            {
            case "time":
                TimeSpan NextRegen = WorldRegeneration.WorldRegenCheck - DateTime.UtcNow.AddSeconds(-WorldRegeneration.Config.RegenerationInterval);
                args.Player.SendInfoMessage("World Regeneration will be in{0}{1}{2}.", NextRegen.Hours > 0 ? NextRegen.Hours == 1 ? " " + NextRegen.Hours + " Hour" : " " + NextRegen.Hours + " Hours" : "", NextRegen.Minutes > 0 ? NextRegen.Minutes == 1 ? " " + NextRegen.Minutes + " Minute" : " " + NextRegen.Minutes + " Minutes" : "", NextRegen.Seconds > 0 ? NextRegen.Seconds == 1 ? " " + NextRegen.Seconds + " Second" : " " + NextRegen.Seconds + " Seconds" : "");
                break;

            case "force":
                int time = 300;
                if (args.Parameters.Count == 2 && args.Parameters[1] == "1")
                {
                    time = 60;
                }
                args.Player.SendInfoMessage("You forced World Regeneration.");
                WorldRegeneration.WorldRegenCheck = DateTime.UtcNow.AddSeconds(-WorldRegeneration.Config.RegenerationInterval + time + 1);
                break;

            case "list":
                if (args.Parameters.Count > 2)
                {
                    args.Player.SendErrorMessage("Invalid syntax! Proper syntax: /worldregen list [page]");
                    return;
                }

                int page;
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out page))
                {
                    return;
                }

                var schematics = from s in Directory.EnumerateFiles("worldregen", "world-*.twd")
                                 select s.Substring(17, s.Length - 21);

                PaginationTools.SendPage(args.Player, page, PaginationTools.BuildLinesFromTerms(schematics),
                                         new PaginationTools.Settings
                {
                    HeaderFormat = "Worlds ({0}/{1}):",
                    FooterFormat = "Type /worldregen list {0} for more."
                });
                args.Player.SendInfoMessage("Last World Regenerated: {0}.", WorldRegeneration.lastWorldID);
                break;

            default:
            {
                int pageNumber;
                int pageParamIndex = 0;
                if (args.Parameters.Count > 1)
                {
                    pageParamIndex = 1;
                }

                if (cmd != "help")
                {
                    if (!PaginationTools.TryParsePageNumber(args.Parameters, pageParamIndex, args.Player, out pageNumber))
                    {
                        args.Player.SendErrorMessage("Proper syntax: /search <option> <name>");
                        return;
                    }
                }
                else
                {
                    pageNumber = 1;
                }

                List <string> lines = new List <string> {
                    "time - Information on next world regeneration.",
                    "force [1] - Force the world regeneration to 5 minutes, or last minute.",
                    "list - List available world IDs.",
                };
                PaginationTools.SendPage(
                    args.Player, pageNumber, lines,
                    new PaginationTools.Settings
                    {
                        HeaderFormat = "Available [c/ffffff:World Regen] Sub-Commands ({0}/{1}):",
                        FooterFormat = "Type {0}worldregen {{0}} for more sub-commands.".SFormat(TShockAPI.Commands.Specifier)
                    }
                    );
                return;
            }
            }
        }
Пример #27
0
        private static void DieMobCommand(CommandArgs args)
        {
            if (args.Parameters.Count > 0 && args.Parameters[0].ToLower() == "reload")
            {
                if (ReadConfig())
                {
                    args.Player.SendMessage("DieMob config reloaded.", Color.BurlyWood);
                }
                else
                {
                    args.Player.SendErrorMessage("Error reading config. Check log for details.");
                }
                return;
            }
            else if (args.Parameters.Count > 0 && args.Parameters[0].ToLower() == "list")
            {
                for (int r = 0; r < RegionList.Count; r++)
                {
                    var regManReg = TShock.Regions.GetRegionByName(RegionList[r].TSRegion.Name);
                    if (RegionList[r].TSRegion == null || regManReg == null || regManReg.Name == "")
                    {
                        db.Query("DELETE FROM DieMobRegions WHERE Region=@0 AND WorldID=@1", RegionList[r].TSRegion.Name, Main.worldID);
                        RegionList.RemoveAt(r);
                    }
                }

                int pageNumber;

                if (args.Parameters.Count < 2)
                {
                    pageNumber = 1;
                }
                else if (!int.TryParse(args.Parameters[1], out pageNumber))
                {
                    args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}dm list <page number>", (args.Silent ? TShock.Config.CommandSilentSpecifier : TShock.Config.CommandSpecifier));
                }

                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
                {
                    return;
                }
                IEnumerable <string> Regions = from region in RegionList
                                               where region.TSRegion != null
                                               select string.Format("{0} @ X: {1}, Y: {2}", region.TSRegion.Name, region.TSRegion.Area.X,
                                                                    region.TSRegion.Area.Y);

                PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(Regions),
                                         new PaginationTools.Settings
                {
                    HeaderFormat = "DieMob Regions ({0}/{1}):",
                    FooterFormat = "Type /dm list {0} for more."
                });
                return;
            }
            else if (args.Parameters.Count > 1 && args.Parameters[0].ToLower() == "info")
            {
                DieMobRegion reg = GetRegionByName(args.Parameters[1]);
                if (reg == null)
                {
                    args.Player.SendMessage(String.Format("Region {0} not found on DieMob list", args.Parameters[1]), Color.Red);
                }
                else
                {
                    args.Player.SendMessage(String.Format("DieMob region: {0}", reg.TSRegion.Name), Color.DarkOrange);
                    args.Player.SendMessage(String.Format("Type: {0}", reg.Type.ToString()), Color.LightSalmon);
                    args.Player.SendMessage(String.Format("Affects friendly NPCs: {0}", reg.AffectFriendlyNPCs ? "True" : "False"), Color.LightSalmon);
                    args.Player.SendMessage(String.Format("Affects statue spawned mobs: {0}", reg.AffectStatueSpawns ? "True" : "False"), Color.LightSalmon);
                    args.Player.SendMessage(String.Format("Replacing {0} mobs. Type '{1}dm replacemobsinfo RegionName [pageNum]' to get a list.", reg.ReplaceMobs.Count, (args.Silent ? TShock.Config.CommandSilentSpecifier : TShock.Config.CommandSpecifier)), Color.LightSalmon);
                }
                return;
            }
            else if (args.Parameters.Count > 1 && (args.Parameters[0].ToLower() == "replacemobsinfo" || args.Parameters[0].ToLower() == "rminfo"))
            {
                DieMobRegion reg = GetRegionByName(args.Parameters[1]);
                if (reg == null)
                {
                    args.Player.SendErrorMessage("Region {0} not found on DieMob list", args.Parameters[1]);
                }
                else
                {
                    int page = 0;
                    if (args.Parameters.Count > 2)
                    {
                        int.TryParse(args.Parameters[2], out page);
                    }
                    if (page <= 0)
                    {
                        page = 1;
                    }
                    int startIndex = (page - 1) * 6;
                    args.Player.SendMessage(String.Format("{0} mob replacements page {1}:", reg.TSRegion.Name, page), Color.LightSalmon);
                    for (int i = startIndex; i < reg.ReplaceMobs.Count; i++)
                    {
                        if (i < startIndex + 6)
                        {
                            int key = reg.ReplaceMobs.Keys.ElementAt(i);
                            args.Player.SendMessage(String.Format("[{0}] From: {1}  To: {2}", i + 1, key, reg.ReplaceMobs[key]), Color.BurlyWood);
                        }
                    }
                }
                return;
            }
            else if (args.Parameters.Count > 0 && args.Parameters[0].ToLower() == "mod")
            {
                if (args.Parameters.Count > 1)
                {
                    DieMobRegion region = GetRegionByName(args.Parameters[1]);
                    if (region == null)
                    {
                        args.Player.SendErrorMessage("Region {0} not found on DieMob list", args.Parameters[1]);
                        return;
                    }
                    if (args.Parameters.Count > 2)
                    {
                        switch (args.Parameters[2].ToLower())
                        {
                        case "type":
                        {
                            if (args.Parameters.Count > 3 && (args.Parameters[3].ToLower() == "kill" || args.Parameters[3].ToLower() == "repel" ||
                                                              args.Parameters[3].ToLower() == "passive"))
                            {
                                if (args.Parameters[3].ToLower() == "repel")
                                {
                                    region.Type = RegionType.Repel;
                                    args.Player.SendMessage(String.Format("Region {0} is now repeling mobs", region.TSRegion.Name), Color.LightSalmon);
                                }
                                else if (args.Parameters[3].ToLower() == "passive")
                                {
                                    region.Type = RegionType.Passive;
                                    args.Player.SendMessage(String.Format("Region {0} is now passive", region.TSRegion.Name), Color.LightSalmon);
                                }
                                else
                                {
                                    region.Type = RegionType.Kill;
                                    args.Player.SendMessage(String.Format("Region {0} is now killing mobs", region.TSRegion.Name), Color.LightSalmon);
                                }
                                Diemob_Update(region);
                                return;
                            }
                            break;
                        }

                        case "affectfriendlynpcs":
                        {
                            if (args.Parameters.Count > 3 && (args.Parameters[3].ToLower() == "true" || args.Parameters[3].ToLower() == "false"))
                            {
                                if (args.Parameters[3].ToLower() == "true")
                                {
                                    region.AffectFriendlyNPCs = true;
                                    args.Player.SendMessage(String.Format("Region {0} is now affecting friendly NPCs", region.TSRegion.Name),
                                                            Color.LightSalmon);
                                }
                                else
                                {
                                    region.AffectFriendlyNPCs = false;
                                    args.Player.SendMessage(String.Format("Region {0} is no longer affecting friendly NPCs", region.TSRegion.Name),
                                                            Color.LightSalmon);
                                }
                                Diemob_Update(region);
                                return;
                            }
                            break;
                        }

                        case "affectstatuespawns":
                        {
                            if (args.Parameters.Count > 3 && (args.Parameters[3].ToLower() == "true" || args.Parameters[3].ToLower() == "false"))
                            {
                                if (args.Parameters[3].ToLower() == "true")
                                {
                                    region.AffectStatueSpawns = true;
                                    args.Player.SendMessage(String.Format("Region {0} is now affecting statue spawned mobs", region.TSRegion.Name),
                                                            Color.LightSalmon);
                                }
                                else
                                {
                                    region.AffectStatueSpawns = false;
                                    args.Player.SendMessage(String.Format("Region {0} is no longer affecting statue spawned mobs", region.TSRegion.Name),
                                                            Color.LightSalmon);
                                }
                                Diemob_Update(region);
                                return;
                            }
                            break;
                        }

                        case "replacemobs":
                        {
                            if (args.Parameters.Count > 4 && (args.Parameters[3].ToLower() == "add" || args.Parameters[3].ToLower() == "del"))
                            {
                                int fromMobID, toMobID;
                                if (args.Parameters[3].ToLower() == "add" && args.Parameters.Count > 5 && int.TryParse(args.Parameters[4], out fromMobID) &&
                                    int.TryParse(args.Parameters[5], out toMobID))
                                {
                                    if (region.ReplaceMobs.ContainsKey(fromMobID))
                                    {
                                        args.Player.SendMessage(String.Format("Region {0} already is already converting mobID {1} to mob {2}",
                                                                              region.TSRegion.Name, fromMobID, region.ReplaceMobs[fromMobID]), Color.LightSalmon);
                                        return;
                                    }
                                    region.ReplaceMobs.Add(fromMobID, toMobID);
                                    args.Player.SendMessage(String.Format("Region {0} is now converting mobs with id {1} to mobs {2}", region.TSRegion.Name,
                                                                          fromMobID, toMobID), Color.LightSalmon);
                                    Diemob_Update(region);
                                    return;
                                }
                                else if (args.Parameters[3].ToLower() == "del" && int.TryParse(args.Parameters[4], out fromMobID))
                                {
                                    if (region.ReplaceMobs.ContainsKey(fromMobID))
                                    {
                                        region.ReplaceMobs.Remove(fromMobID);
                                    }
                                    args.Player.SendMessage(String.Format("Region {0} is no longer converting mobs with id {1}", region.TSRegion.Name, fromMobID),
                                                            Color.LightSalmon);
                                    Diemob_Update(region);
                                    return;
                                }
                            }
                            break;
                        }
                        }
                    }
                }
                args.Player.SendMessage("{0}dm mod RegionName option arguments".SFormat(args.Silent ? TShock.Config.CommandSilentSpecifier : TShock.Config.CommandSpecifier), Color.DarkOrange);
                args.Player.SendMessage("Options:", Color.LightSalmon);
                args.Player.SendMessage("type - args: kill [default] / repel / passive", Color.LightSalmon);
                args.Player.SendMessage("affectfriendlynpcs - args: true / false [default]", Color.LightSalmon);
                args.Player.SendMessage("affectstatuespawns - args: true / false [default]", Color.LightSalmon);
                args.Player.SendMessage("replacemobs - args: add fromMobID toMobID / del fromMobID", Color.LightSalmon);
                return;
            }
            else if (args.Parameters.Count > 1)
            {
                var region = TShock.Regions.GetRegionByName(args.Parameters[1]);
                if (region != null && region.Name != "")
                {
                    if (args.Parameters[0].ToLower() == "add")
                    {
                        if (RegionList.Select(r => r.TSRegion).Contains(region))
                        {
                            args.Player.SendMessage(String.Format("Region '{0}' is already on the DieMob list", region.Name), Color.LightSalmon);
                            return;
                        }
                        if (!DieMob_Add(region.Name))
                        {
                            args.Player.SendErrorMessage("Error adding '{0}' to DieMob list. Check log for details", region.Name);
                            return;
                        }
                        RegionList.Add(new DieMobRegion(region));
                        args.Player.SendMessage(String.Format("Region '{0}' added to DieMob list", region.Name), Color.BurlyWood);
                        return;
                    }
                    else if (args.Parameters[0].ToLower() == "del")
                    {
                        if (!RegionList.Exists(r => r.TSRegion.Name == region.Name))
                        {
                            args.Player.SendMessage(String.Format("Region '{0}' is not on the DieMob list", region.Name), Color.LightSalmon);
                            return;
                        }
                        DieMob_Delete(region.Name);
                        args.Player.SendMessage(String.Format("Region '{0}' deleted from DieMob list", region.Name), Color.BurlyWood);
                        return;
                    }
                    return;
                }
                else
                {
                    args.Player.SendErrorMessage($"Region '{args.Parameters[1]}' not found.");
                    return;
                }
            }
            args.Player.SendMessage("Syntax: {0}diemob [add | del] RegionName - Creates / Deletes DieMob region based on pre-existing region".SFormat(args.Silent ? TShock.Config.CommandSilentSpecifier : TShock.Config.CommandSpecifier), Color.LightSalmon);
            args.Player.SendMessage("Syntax: {0}diemob list [page number] - Lists DieMob regions".SFormat(args.Silent ? TShock.Config.CommandSilentSpecifier : TShock.Config.CommandSpecifier), Color.LightSalmon);
            args.Player.SendMessage("Syntax: {0}diemob reload - Reloads config.json file".SFormat(args.Silent ? TShock.Config.CommandSilentSpecifier : TShock.Config.CommandSpecifier), Color.LightSalmon);
            args.Player.SendMessage("Syntax: {0}diemob mod RegionName - Modifies a DieMob region".SFormat(args.Silent ? TShock.Config.CommandSilentSpecifier : TShock.Config.CommandSpecifier), Color.LightSalmon);
            args.Player.SendMessage("Syntax: {0}diemob info RegionName - Displays info for a DieMob region".SFormat(args.Silent ? TShock.Config.CommandSilentSpecifier : TShock.Config.CommandSpecifier), Color.LightSalmon);
        }
Пример #28
0
        void TeamDo(CommandArgs e)
        {
            if (e.Parameters.Count == 0)
            {
                e.Player.SendErrorMessage("Invalid syntax! Proper syntax: /team <command>. Type /team help for all commands.");
            }
            else
            {
                switch (e.Parameters[0])
                {
                case "kick":
                    if (CommandIsValid(e, Permissions.kick, 2, "kick <team> [reason]"))
                    {
                        if (e.Parameters[1].Length == 0)
                        {
                            e.Player.SendErrorMessage("Missing team name.");
                        }
                        else
                        {
                            string reason = e.Parameters.Count > 2 ? String.Join(" ", e.Parameters.Skip(2)) : "Misbehavior.";
                            var    team   = TeamColorToID(e.Parameters[1], e.Player);
                            foreach (TSPlayer player in TShock.Players)
                            {
                                if (player != null && (team == player.Team || team == 5))
                                {
                                    TShock.Utils.Kick(player, reason, !e.Player.RealPlayer, true, e.Player.Name);
                                }
                            }
                            TShock.Utils.Broadcast(string.Format("{0} was kicked for '{1}'", TeamIDToColor(team), reason.ToLower()), Color.Green);
                        }
                    }
                    break;

                case "ban":
                    if (CommandIsValid(e, Permissions.ban, 2, "ban <team> [reason]"))
                    {
                        string reason = e.Parameters.Count > 2 ? String.Join(" ", e.Parameters.Skip(2)) : "Misbehavior.";
                        var    team   = TeamColorToID(e.Parameters[1], e.Player);
                        foreach (TSPlayer player in TShock.Players)
                        {
                            if (player != null && (team == player.Team || team == 5) && (!player.Group.HasPermission(Permissions.immunetoban) || e.Player.RealPlayer))
                            {
                                var user     = TShock.Users.GetUserByID(player.Index);
                                var knownIps = JsonConvert.DeserializeObject <List <string> >(user.KnownIps);
                                TShock.Bans.AddBan(knownIps.Last(), user.Name, user.UUID, reason, false, e.Player.User.Name);
                            }
                        }
                        TShock.Utils.Broadcast(string.Format("{0} was banned for '{1}'", TeamIDToColor(team), reason.ToLower()), Color.Green);
                    }
                    break;

                case "tempban":
                    if (CommandIsValid(e, Permissions.ban, 3, "tempban <team> <time> [reason]"))
                    {
                        int time;
                        if (!TShock.Utils.TryParseTime(e.Parameters[2], out time))
                        {
                            e.Player.SendErrorMessage("Invalid time string! Proper format: _d_h_m_s, with at least one time specifier.");
                            e.Player.SendErrorMessage("For example, 1d and 10h-30m+2m are both valid time strings, but 2 is not.");
                            return;
                        }
                        string reason = e.Parameters.Count > 3 ? String.Join(" ", e.Parameters.Skip(3)) : "Misbehavior.";
                        var    team   = TeamColorToID(e.Parameters[1], e.Player);
                        foreach (TSPlayer player in TShock.Players)
                        {
                            if (player != null && (team == player.Team || team == 5) && (!player.Group.HasPermission(Permissions.immunetoban) || e.Player.RealPlayer))
                            {
                                if (TShock.Bans.AddBan(player.IP, player.Name, player.UUID, reason, false, e.Player.Name, DateTime.UtcNow.AddSeconds(time).ToString("s")))
                                {
                                    player.Disconnect(String.Format("Banned: {0}", reason));
                                }
                            }
                        }
                        TShock.Utils.Broadcast(string.Format("{0} was banned for '{1}'", TeamIDToColor(team), reason.ToLower()), Color.Green);
                    }
                    break;

                case "mute":
                    if (CommandIsValid(e, Permissions.mute, 2, "mute <team> [reason]"))
                    {
                        string reason = e.Parameters.Count > 3 ? String.Join(" ", e.Parameters.Skip(3)) : "Misbehavior.";
                        var    team   = TeamColorToID(e.Parameters[1], e.Player);
                        foreach (TSPlayer player in TShock.Players)
                        {
                            if (player != null && (team == player.Team || team == 5) && !player.Group.HasPermission(Permissions.mute))
                            {
                                player.mute = true;
                            }
                        }
                        TShock.Utils.Broadcast(string.Format("{0} was muted for '{1}'", TeamIDToColor(team), reason.ToLower()), Color.Green);
                    }
                    break;

                case "unmute":
                    if (CommandIsValid(e, Permissions.mute, 2, "mute <team>"))
                    {
                        var team = TeamColorToID(e.Parameters[1], e.Player);
                        foreach (TSPlayer player in TShock.Players)
                        {
                            if (player != null && (team == player.Team || team == 5))
                            {
                                player.mute = false;
                            }
                        }
                        TShock.Utils.Broadcast(string.Format("{0} was unmuted by {1}.", TeamIDToColor(team), e.Player.Name), Color.Green);
                    }
                    break;

                case "tempgroup":
                    if (CommandIsValid(e, Permissions.settempgroup, 3, "tempgroup <team> <new group>"))
                    {
                        var team = TeamColorToID(e.Parameters[1], e.Player);
                        if (!TShock.Groups.GroupExists(e.Parameters[2]))
                        {
                            e.Player.SendErrorMessage(string.Format("Could not find group {0}", e.Parameters[2]));
                        }
                        else
                        {
                            var g = TShock.Utils.GetGroup(e.Parameters[2]);
                            foreach (TSPlayer player in TShock.Players)
                            {
                                if (player != null && (team == player.Team || team == 5))
                                {
                                    player.tempGroup = g;
                                    player.SendSuccessMessage(string.Format("Your group has temporarily been changed to {0}", g.Name));
                                }
                            }
                            e.Player.SendSuccessMessage(string.Format("You have changed {0}'s group to {1}", TeamIDToColor(team, false), g.Name));
                        }
                    }
                    break;

                case "usergroup":
                    if (CommandIsValid(e, Permissions.managegroup, 3, "usergroup <team> <new group>"))
                    {
                        var team = TeamColorToID(e.Parameters[1], e.Player);
                        if (!TShock.Groups.GroupExists(e.Parameters[2]))
                        {
                            e.Player.SendErrorMessage(string.Format("Could not find group {0}", e.Parameters[2]));
                        }
                        else
                        {
                            var g = TShock.Utils.GetGroup(e.Parameters[2]);
                            foreach (TSPlayer player in TShock.Players)
                            {
                                if (player != null && (team == player.Team || team == 5))
                                {
                                    player.Group = g;
                                    player.SendSuccessMessage(string.Format("Your group has been changed to {0}", g.Name));
                                }
                            }
                            e.Player.SendSuccessMessage(string.Format("You have changed {0}'s group to {1}", TeamIDToColor(team, false), g.Name));
                        }
                    }
                    break;

                case "give":
                case "g":
                    if (CommandIsValid(e, Permissions.item, 3, "give <item type/id> <team> [item amount] [prefix id/name]"))
                    {
                        if (e.Parameters[1].Length == 0)
                        {
                            e.Player.SendErrorMessage("Missing item name/id.");
                        }
                        else if (e.Parameters[2].Length == 0)
                        {
                            e.Player.SendErrorMessage("Missing team name.");
                        }
                        else
                        {
                            int    itemAmount = 0;
                            int    prefix     = 0;
                            var    items      = TShock.Utils.GetItemByIdOrName(e.Parameters[1]);
                            string plStr      = e.Parameters[2];
                            if (e.Parameters.Count == 4)
                            {
                                int.TryParse(e.Parameters[3], out itemAmount);
                            }
                            else if (e.Parameters.Count == 5)
                            {
                                int.TryParse(e.Parameters[3], out itemAmount);
                                var prefixIds = TShock.Utils.GetPrefixByIdOrName(e.Parameters[4]);
                                if (items[0].accessory && prefixIds.Contains(42))
                                {
                                    prefixIds.Remove(42);
                                    prefixIds.Remove(76);
                                    prefixIds.Add(76);
                                }
                                else if (!items[0].accessory && prefixIds.Contains(42))
                                {
                                    prefixIds.Remove(76);
                                }
                                if (prefixIds.Count == 1)
                                {
                                    prefix = prefixIds[0];
                                }
                            }

                            if (items.Count == 0)
                            {
                                e.Player.SendErrorMessage("Invalid item type!");
                            }
                            else if (items.Count > 1)
                            {
                                TShock.Utils.SendMultipleMatchError(e.Player, items.Select(i => i.Name));
                            }
                            else
                            {
                                var item = items[0];
                                if (item.type >= 1 && item.type < Main.maxItemTypes)
                                {
                                    var team = TeamColorToID(e.Parameters[2], e.Player);
                                    foreach (TSPlayer player in TShock.Players)
                                    {
                                        if (player != null && (team == player.Team || team == 5) && (player.InventorySlotAvailable || (item.type > 70 && item.type < 75) || item.ammo > 0 || item.type == 58 || item.type == 184))
                                        {
                                            if (itemAmount == 0 || itemAmount > item.maxStack)
                                            {
                                                itemAmount = item.maxStack;
                                            }
                                            player.GiveItem(item.type, item.Name, item.width, item.height, itemAmount, prefix);
                                            if (player != e.Player)
                                            {
                                                player.SendSuccessMessage(string.Format("{0} gave you {1} {2}(s).", e.Player.Name, itemAmount, item.Name));
                                            }
                                        }
                                    }
                                    e.Player.SendSuccessMessage(string.Format("Gave {0} {1} {2}(s).", TeamIDToColor(team, false), itemAmount, item.Name));
                                }
                                else
                                {
                                    e.Player.SendErrorMessage("Invalid item type!");
                                }
                            }
                        }
                    }
                    break;

                case "tphere":
                    if (CommandIsValid(e, Permissions.tpothers, 2, "tphere <team>"))
                    {
                        var team = TeamColorToID(e.Parameters[1], e.Player);
                        foreach (TSPlayer player in TShock.Players)
                        {
                            if (player != null && player.Active && !player.Dead && player.Team == team && player != e.Player)
                            {
                                player.Teleport(e.TPlayer.position.X, e.TPlayer.position.Y);
                                player.SendSuccessMessage(String.Format("You were teleported to {0}.", e.Player.Name));
                            }
                        }
                        e.Player.SendSuccessMessage("Teleported {0} to yourself.", TeamIDToColor(team, false));
                    }
                    break;

                case "gbuff":
                case "buffplayer":
                    if (CommandIsValid(e, Permissions.buffplayer, 3, "gbuff <team> <buff id/name> [time(seconds)]"))
                    {
                        var team = TeamColorToID(e.Parameters[1], e.Player);
                        int id   = 0;
                        int time = 60;
                        if (!int.TryParse(e.Parameters[2], out id))
                        {
                            var found = TShock.Utils.GetBuffByName(e.Parameters[2]);
                            if (found.Count == 0)
                            {
                                e.Player.SendErrorMessage("Invalid buff name!");
                            }
                            else if (found.Count > 1)
                            {
                                //TShock.Utils.SendMultipleMatchError(e.Player, found.Select(b => Main.buffName[b]));
                                TShock.Utils.SendMultipleMatchError(e.Player, found.Select(b => Lang.GetBuffName(b)));
                            }
                            else
                            {
                                id = found[0];
                            }
                        }
                        if (e.Parameters.Count == 4)
                        {
                            int.TryParse(e.Parameters[3], out time);
                        }
                        if (id > 0 && id < Main.maxBuffTypes)
                        {
                            if (time < 0 || time > short.MaxValue)
                            {
                                time = 60;
                            }
                            foreach (TSPlayer player in TShock.Players)
                            {
                                if (player != null && player.Active && !player.Dead && player.Team == team)
                                {
                                    player.SetBuff(id, time * 60);
                                    if (player != e.Player)
                                    {
                                        player.SendSuccessMessage(string.Format("{0} has buffed you with {1}({2}) for {3} seconds!",
                                                                                e.Player.Name, TShock.Utils.GetBuffName(id),
                                                                                TShock.Utils.GetBuffDescription(id), (time)));
                                    }
                                }
                            }
                            e.Player.SendSuccessMessage(string.Format("You have buffed {0} with {1}({2}) for {3} seconds!",
                                                                      TeamIDToColor(team, false), TShock.Utils.GetBuffName(id),
                                                                      TShock.Utils.GetBuffDescription(id), (time)));
                        }
                        else
                        {
                            e.Player.SendErrorMessage("Invalid buff ID!");
                        }
                    }
                    break;

                case "heal":
                    if (CommandIsValid(e, Permissions.heal, 2, "heal <team>"))
                    {
                        var team = TeamColorToID(e.Parameters[1], e.Player);
                        foreach (TSPlayer player in TShock.Players)
                        {
                            if (player != null && player.Active && !player.Dead && player.Team == team)
                            {
                                player.Heal();
                                if (player != e.Player)
                                {
                                    player.SendSuccessMessage(string.Format("{0} just healed you!", e.Player.Name));
                                }
                            }
                        }
                        e.Player.SendSuccessMessage(String.Format("You just healed {0}.", TeamIDToColor(team, false)));
                    }
                    break;

                case "kill":
                    if (CommandIsValid(e, Permissions.kill, 2, "kill <team>"))
                    {
                        var team = TeamColorToID(e.Parameters[1], e.Player);
                        foreach (TSPlayer player in TShock.Players)
                        {
                            if (player != null && player.Active && !player.Dead && player.Team == team)
                            {
                                player.DamagePlayer(999999);
                            }
                        }
                        TSPlayer.All.SendInfoMessage("{0} killed {1}.", e.Player.Name, TeamIDToColor(team, false));
                    }
                    break;

                case "slap":
                    if (CommandIsValid(e, Permissions.slap, 2, "slap <team> [damage]"))
                    {
                        var team   = TeamColorToID(e.Parameters[1], e.Player);
                        int damage = 5;
                        if (e.Parameters.Count == 3)
                        {
                            int.TryParse(e.Parameters[2], out damage);
                        }
                        if (!e.Player.Group.HasPermission(Permissions.kill))
                        {
                            damage = TShock.Utils.Clamp(damage, 15, 0);
                        }
                        foreach (TSPlayer player in TShock.Players)
                        {
                            if (player != null && player.Active && !player.Dead && player.Team == team)
                            {
                                player.DamagePlayer(damage);
                            }
                        }
                        TSPlayer.All.SendInfoMessage("{0} slapped {1} for {2} damage.", e.Player.Name, TeamIDToColor(team, false), damage);
                    }
                    break;

                case "playing":
                case "online":
                case "who":
                    if (CommandIsValid(e, "", 2, "who <team> [pagenumber]"))
                    {
                        var team       = TeamColorToID(e.Parameters[1], e.Player);
                        int pageNumber = 1;
                        if (e.Parameters.Count > 2)
                        {
                            int.TryParse(e.Parameters[2], out pageNumber);
                        }
                        var plrs = new List <string>();
                        foreach (TSPlayer player in TShock.Players)
                        {
                            if (player != null && player.Active && player.Team == team)
                            {
                                plrs.Add(player.Name);
                            }
                        }
                        e.Player.SendSuccessMessage("Online Players ({0}/{1})", plrs.Count, TShock.Config.MaxSlots);
                        PaginationTools.SendPage(e.Player, pageNumber, plrs,
                                                 new PaginationTools.Settings {
                            IncludeHeader = false,
                            FooterFormat  = string.Format("Type /team who {0} {{0}} for more.", TeamIDToColor(team))
                        }
                                                 );
                    }
                    break;

                case "sendwarp":
                    if (CommandIsValid(e, Permissions.tpothers, 3, "sendwarp <team> <warpname>"))
                    {
                        var team = TeamColorToID(e.Parameters[1], e.Player);
                        var warp = TShock.Warps.Find(e.Parameters[2]);
                        if (warp.Position != Point.Zero)
                        {
                            foreach (TSPlayer player in TShock.Players)
                            {
                                if (player != null && player.Active && !player.Dead && player.Team == team)
                                {
                                    if (player.Teleport(warp.Position.X * 16, warp.Position.Y * 16) && player != e.Player)
                                    {
                                        player.SendSuccessMessage(String.Format("{0} warped you to {1}.", e.Player.Name, e.Parameters[2]));
                                    }
                                }
                            }
                            e.Player.SendSuccessMessage(String.Format("You warped {0} to {1}.", TeamIDToColor(team, false), e.Parameters[2]));
                        }
                        else
                        {
                            e.Player.SendErrorMessage("Specified warp not found.");
                        }
                    }
                    break;

                /*
                 * case "annoy":
                 *  break;
                 *
                 * case "confuse":
                 *  break;
                 *
                 * case "rocket":
                 *  break;
                 *
                 * case "firework":
                 *  break;
                 *
                 * case "overridessc":
                 * case "ossc":
                 *  break;*/

                case "help": {
                    int pageNumber;
                    if (!PaginationTools.TryParsePageNumber(e.Parameters, 1, e.Player, out pageNumber))
                    {
                        return;
                    }
                    var commands = new List <string> {
                        "kick", "ban", "tempban", "usergroup", "tempgroup", "give", "tphere", "mute", "unmute", "sendwarp", "gbuff", "heal",
                        "kill", "slap", "playing"
                    };
                    PaginationTools.SendPage(e.Player, pageNumber, PaginationTools.BuildLinesFromTerms(commands),
                                             new PaginationTools.Settings {
                            HeaderFormat = "Team Commands ({0}/{1}):",
                            FooterFormat = "Type /team help {0} for more commands."
                        }
                                             );
                }
                break;
                }
            }
        }
Пример #29
0
        /// <summary>Fired when CIDR Ban command is used</summary>
        /// <param name="args">CommandArgs object</param>
        private void CIDRBanCommand(CommandArgs args)
        {
            //Creates TSPlayer player object for easy access
            TSPlayer player = args.Player;
            //Creates subcmd as shortcut for sub-command used (args.Parameters[0])
            string subcmd = args.Parameters.Count == 0 ? "help" : args.Parameters[0].ToLower();

            //Checks which sub-command is used
            switch (subcmd)
            {
            case "help":
                //Displays CIDR Bans Plugin's information
                player.SendInfoMessage("CIDR Bans Plugin");
                player.SendInfoMessage("Description: Allows banning CIDR ranges");
                player.SendInfoMessage("Syntax: {0}cidrban <add/addtemp/del/list> [arguments]", Commands.Specifier);
                player.SendInfoMessage("Type {0}help cidrban for more info.", Commands.Specifier);
                break;

            case "add":
                //Checks if player has put in CIDR range
                if (args.Parameters.Count < 2)
                {
                    player.SendErrorMessage("Invalid syntax! Proper syntax: {0}cidrban add <range> [reason]", Commands.Specifier);
                    return;
                }
                //Checks if player's CIDR range input is correct
                if (!Regex.IsMatch(args.Parameters[1], rangeregex))
                {
                    player.SendErrorMessage("Invalid CIDR range string! Proper format: 0-255.0-255.0-255.0-255/0-32");
                    return;
                }
                //If player hasn't specified reason, set default reason
                if (args.Parameters.Count < 3)
                {
                    args.Parameters.Add("Manually added IP address ban.");
                }
                //For reason with spaces without use of quotation marks, put into one string
                args.Parameters[2] = String.Join(" ", args.Parameters.GetRange(2, args.Parameters.Count - 2));
                //Add CIDR range into database
                if (cidrbans.AddCIDRBan(args.Parameters[1], args.Parameters[2], player.Name, DateTime.UtcNow.ToString("s")))
                {
                    player.SendSuccessMessage("Banned range {0} for '{1}'.", args.Parameters[1], args.Parameters[2]);
                }
                //If it fails, inform player
                else
                {
                    player.SendErrorMessage("Adding range {0} into database failed.", args.Parameters[1]);
                }
                break;

            case "addtemp":
                //Checks if player has put in CIDR range and time
                if (args.Parameters.Count < 3)
                {
                    player.SendErrorMessage("Invalid syntax! Proper syntax: {0}cidrban addtemp <range> <time> [reason]", Commands.Specifier);
                    return;
                }
                //Checks if player's CIDR range input is correct
                if (!Regex.IsMatch(args.Parameters[1], rangeregex))
                {
                    player.SendErrorMessage("Invalid CIDR range string! Proper format: 0-255.0-255.0-255.0-255/0-32");
                    return;
                }
                //Creates int exp object to store expiration time in seconds
                int exp;
                //Parse input argument into exp object
                if (!TShock.Utils.TryParseTime(args.Parameters[2], out exp))
                {
                    //If fails, inform player
                    args.Player.SendErrorMessage("Invalid time string! Proper format: _d_h_m_s, with at least one time specifier.");
                    args.Player.SendErrorMessage("For example, 1d and 10h-30m+2m are both valid time strings, but 2 is not.");
                    return;
                }
                //If player hasn't specified reason, set default reason
                if (args.Parameters.Count < 4)
                {
                    args.Parameters.Add("Manually added IP address ban.");
                }
                //For reason with spaces without use of quotation marks, put into one string
                args.Parameters[3] = String.Join(" ", args.Parameters.GetRange(3, args.Parameters.Count - 3));
                //Add CIDR range into database
                if (cidrbans.AddCIDRBan(args.Parameters[1], args.Parameters[3], player.Name,
                                        DateTime.UtcNow.ToString("s"), DateTime.UtcNow.AddSeconds(exp).ToString("s")))
                {
                    player.SendSuccessMessage("Banned range {0} for '{1}'.", args.Parameters[1], args.Parameters[3]);
                }
                //If it fails, inform player
                else
                {
                    player.SendErrorMessage("Adding range {0} into database failed.", args.Parameters[1]);
                }
                break;

            case "del":
                //Checks if player has put in either CIDR range or IP
                if (args.Parameters.Count < 2)
                {
                    player.SendErrorMessage("Invalid syntax! Proper syntax: {0}cidrban del <ip/range>", Commands.Specifier);
                    return;
                }
                //Checks if input is CIDR range
                if (Regex.IsMatch(args.Parameters[1], rangeregex))
                {
                    //Removes ban from database
                    if (cidrbans.DelCIDRBanByRange(args.Parameters[1]))
                    {
                        player.SendSuccessMessage("Unbanned range {0}.", args.Parameters[1]);
                    }
                    //If it fails, inform player
                    else
                    {
                        player.SendErrorMessage("Removing range {0} from database failed.", args.Parameters[1]);
                    }
                    return;
                }
                //Checks if input is IP
                if (Regex.IsMatch(args.Parameters[1], ipregex))
                {
                    //List of string for removed CIDR ranges
                    List <string> removed = cidrbans.DelCIDRBanByIP(args.Parameters[1]);
                    //If no CIDR ranges are removed, inform player that it fails
                    if (removed.Count == 0)
                    {
                        player.SendErrorMessage("Removing range {0} from database failed.", args.Parameters[1]);
                        return;
                    }
                    //Inform player amount of ranges removed and which
                    player.SendSuccessMessage("Removed {0} range{1} from the database:", removed.Count, removed.Count == 1 ? "" : "s");
                    player.SendInfoMessage(String.Join(", ", removed));
                    return;
                }
                //If player's input doesn't match either range or IP, inform player
                player.SendErrorMessage("Invalid syntax! Proper syntax: {0}cidrban del <ip/range>", Commands.Specifier);
                player.SendErrorMessage("IP proper format: 0-255.0-255.0-255.0-255");
                player.SendErrorMessage("CIDR range proper format : 0-255.0-255.0-255.0-255/0-32");
                break;

            case "list":
                //PageNumber integer to use with TShock's built-in PaginationTools
                int pagenumber;
                if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pagenumber))
                {
                    return;
                }
                //List of all CIDR Ban Informations
                List <CIDRBan> list = cidrbans.GetCIDRBanList();
                //Creates list of CIDR ranges
                var namelist = from ban in list
                               select ban.CIDR;
                //Inform player, allows selecting page
                PaginationTools.SendPage(player, pagenumber, PaginationTools.BuildLinesFromTerms(namelist),
                                         new PaginationTools.Settings
                {
                    HeaderFormat           = "CIDR Range Bans ({0}/{1}):",
                    FooterFormat           = "Type {0}ban list {{0}} for more.".SFormat(Commands.Specifier),
                    NothingToDisplayString = "There are currently no CIDR range bans."
                });
                break;

            default:
                player.SendErrorMessage("Invalid subcommand. Type {0}help cidrban for information.", Commands.Specifier);
                break;
            }
        }
Пример #30
0
        private void BindGlobalCMD(CommandArgs args)
        {
            string Parameter = (args.Parameters.Count == 0) ? "help" : args.Parameters[0].ToLower();

            switch (Parameter)
            {
            case "add":
            case "del":
            {
                if (!BTExtensions.IsAdmin(args.Player))
                {
                    return;
                }
                BTExtensions.ManageGlobalBinds(args);
                break;
            }

            case "list":
            {
                int page = 1;
                if ((args.Parameters.Count > 1) &&
                    (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out page)))
                {
                    return;
                }

                var GBinds = (from BTGlobalBind b in GlobalBinds
                              where args.Player.HasPermission(b.Permission)
                              select(string.Format("Item: [i:{0}]. Name: {1}. Commands: {2}. Permission: {3}. Awaiting: {4}. Looping: {5}. Slot: {6}. Prefix: {7}.",
                                                   b.ItemID,
                                                   b.Name,
                                                   string.Join("; ", b.Commands),
                                                   b.Permission,
                                                   b.Awaiting,
                                                   b.Looping,
                                                   ((b.Slot == -1) ? "Any" : (b.Slot == 58) ? "Cursor" : "Hotbar-" + (b.Slot + 1)),
                                                   ((b.Prefix == -1) ? "Any" : (b.Prefix == 0) ? "None" : Lang.prefix[b.Prefix].Value)))).ToList();

                PaginationTools.SendPage(args.Player, page, GBinds,
                                         new PaginationTools.Settings
                    {
                        HeaderFormat           = "Global binds ({0}/{1}):",
                        FooterFormat           = "Type {0}bgl list b {{0}} for more info.".SFormat(TShock.Config.CommandSpecifier),
                        NothingToDisplayString = "There are currently no global binds you allowed to use."
                    }
                                         );
                break;
            }

            case "help":
            {
                List <string> Help = new List <string>
                {
                    string.Format("{0}bgl list [page]", TShock.Config.CommandSpecifier),
                };
                if (args.Player.HasPermission("bindtools.admin"))
                {
                    List <string> Help2 = new List <string>
                    {
                        string.Format("{0}bgl add [Name] [ItemID] [Permission] [SlotID] [PrefixID] [Looping] [Awaiting] commands; separated; by semicolon", TShock.Config.CommandSpecifier),
                        string.Format("{0}bgl del [Name]", TShock.Config.CommandSpecifier),
                        "SlotID: -1 for any; 1-10 - hotbar; 100 for cursor",
                        "PrefixID: -1 for any; Looping: true/false; Awaiting: true/false",
                    };
                    Help.AddRange(Help2);
                }
                int page = 1;
                if ((args.Parameters.Count > 1) &&
                    (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out page)))
                {
                    return;
                }
                PaginationTools.SendPage(args.Player, page, Help,
                                         new PaginationTools.Settings
                    {
                        HeaderFormat = "BindGlobal help ({0}/{1}):",
                        FooterFormat = "Type {0}bgl help {{0}} for more info.".SFormat(TShock.Config.CommandSpecifier)
                    }
                                         );
                break;
            }
            }
        }