private void PvPItemBans(CommandArgs args) { List <int> bannedItemsList = new List <int>(); bannedItemsList.AddRange(cfg.weaponBans); bannedItemsList.AddRange(cfg.armorBans); bannedItemsList.AddRange(cfg.accsBans); int pageNumber; if (!PaginationTools.TryParsePageNumber(args.Parameters, 0, args.Player, out pageNumber)) { return; } IEnumerable <string> itemNames = from itemBan in bannedItemsList select TShock.Utils.GetItemById(itemBan).Name; PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(itemNames, maxCharsPerLine: 75), new PaginationTools.Settings { HeaderFormat = "The following items cannot be used in PvP:", FooterFormat = "Type /pvpitembans {0} for more.", NothingToDisplayString = "There are currently no banned items." }); }
public static void ListMessages(CommandArgs args) { if (args.Parameters.Count < 2) { throw new CommandException("Invalid usage! Usage: /autobc messages list <broadcast name> "); } string broadcastName = args.Parameters[1]; 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); int pageParamIndex = 3; int pageNumber; if (!PaginationTools.TryParsePageNumber(args.Parameters, pageParamIndex, args.Player, out pageNumber)) { return; } PaginationTools.SendPage(args.Player, pageNumber, broadcast.Messages.Select((e, index) => $"[{index}] " + e).ToList(), new PaginationTools.Settings { HeaderFormat = "Messages ({0}/{1}):", FooterFormat = $"Type /autobc messages list \"{broadcastName}\" {{0}} for more.", MaxLinesPerPage = 4 }); }
void classList(CommandArgs e) { int pageNumber = 1; if (e.Parameters.Count > 0) { int.TryParse(e.Parameters[0], out pageNumber); } if (pageNumber <= 0) { e.Player.SendErrorMessage("The page number must be greater than zero."); } else { var files = Directory.GetFiles(Path.Combine(TShock.SavePath, "Classes")).Where(x => !x.ToLower().Contains("analytics")); List <string> newFiles = new List <string>(); foreach (string file in files) { newFiles.Add(Path.GetFileName(file)); } PaginationTools.SendPage(e.Player, pageNumber, PaginationTools.BuildLinesFromTerms(newFiles), new PaginationTools.Settings { HeaderFormat = "Files ({0}/{1}):", FooterFormat = "Type /classlist {0} for more." }); } }
private void Help(CommandArgs args) { List <string> contextCommandDescs = new List <string>(); for (int i = 0; i < Contexts.Count; i++) { string aliases = ""; for (int j = 1; j < Contexts[i].Names.Length; j++) { aliases += $"{Contexts[i].Names[j]}, "; } aliases.Remove(aliases.Length - 2, 2); contextCommandDescs.Add("{0} ({1}) - {2}".SFormat(Contexts[i].Names[0], aliases, Contexts[i].Description)); } int pageNumberCon = 1; if (args.Parameters.Count > 0) { int pageParamIndexCon = 0; if (!PaginationTools.TryParsePageNumber(args.Parameters, pageParamIndexCon, args.Player, out pageNumberCon)) { return; } } PaginationTools.SendPage( args.Player, pageNumberCon, contextCommandDescs, new PaginationTools.Settings { HeaderFormat = "Available contexts command ({0}/{1}):", FooterFormat = "Type {0}/re context {{0}} for more contexts.".SFormat(TShock.Config.CommandSpecifier) } ); }
private static void SendInvalidSyntax(CommandArgs e) { var help = new Dictionary <string, string> { { "prefix", "Sets the player's chat prefix" }, { "suffix", "Sets the player's chat suffix" }, { "color", "Sets the player's chat color" }, { "remove", "Removes the player's (pre/suf)fix or chat color" }, { "reset", "Resets the player's chat information" }, { "purge", "Removes all empty entries from the database" }, { "read", "Outputs the player's chat information" } }; if (!PaginationTools.TryParsePageNumber(e.Parameters, 1, e.Player, out int pageNum)) { if (!help.ContainsKey(e.Parameters[1])) { e.Player.SendErrorMessage("Invalid command name or page provided."); return; } e.Player.SendInfoMessage($"Sub-command: {e.Parameters[1]}"); e.Player.SendInfoMessage($"Help: {help[e.Parameters[1]]}"); } else { PaginationTools.SendPage(e.Player, pageNum, help.Keys.Select(p => $"{p} - {help[p]}"), help.Count, new PaginationTools.Settings() { HeaderFormat = $"UserSpecificFunctions Help ({{0}}/{{1}})", FooterFormat = $"Type {Commands.Specifier}us help {{0}} for more." }); } }
public static void SendUic <T>(TSPlayer receiver, T player, int page) { if (player is SPlayer) { var ply = player as SPlayer; if (ply.TsPlayer.IsLoggedIn) { var uixInfo = new List <string>(); var time1 = DateTime.Now.Subtract(DateTime.Parse(ply.firstLogin)); uixInfo.Add(string.Format("UIC info for {0}", ply.Name)); uixInfo.Add(string.Format("First login: {0} ({1} ago)", ply.firstLogin, time1.TimeSpanPlayed())); uixInfo.Add("Last seen: Now"); uixInfo.Add(string.Format("Overall play time: {0}", ply.TimePlayed())); uixInfo.Add(string.Format("Logged in {0} times since registering", ply.loginCount)); PaginationTools.SendPage(receiver, page, uixInfo, new PaginationTools.Settings { HeaderFormat = "User Information [Page {0} of {1}]", HeaderTextColor = Color.Lime, LineTextColor = Color.White, FooterFormat = string.Format("/uix {0} {1} for more", ply.Name, page + 1), FooterTextColor = Color.Lime }); } else { receiver.SendErrorMessage("{0} is not logged in", ply.Name); } } else { var ply = player as StoredPlayer; var uixInfo = new List <string>(); var time1 = DateTime.Now.Subtract(DateTime.Parse(ply.firstLogin)); uixInfo.Add(string.Format("UIC info for {0}", ply.name)); uixInfo.Add(string.Format("First login: {0} ({1} ago)", ply.firstLogin, time1.TimeSpanPlayed())); uixInfo.Add(string.Format("Last seen: {0}", DateTime.Now.Subtract(DateTime.Parse(ply.lastSeen)).TimeSpanPlayed())); uixInfo.Add(string.Format("Overall play time: {0}", ply.TimePlayed())); uixInfo.Add(string.Format("Logged in {0} times since registering", ply.loginCount)); PaginationTools.SendPage(receiver, page, uixInfo, new PaginationTools.Settings { HeaderFormat = "User Information [Page {0} of {1}]", HeaderTextColor = Color.Lime, LineTextColor = Color.White, FooterFormat = string.Format("/uix {0} {1} for more", ply.name, page + 1), FooterTextColor = Color.Lime }); } }
public static void CommandNickColor(TShockAPI.CommandArgs args) { int money = SurvivalCore.SrvPlayers[args.Player.Index].Money; string text = "0:0=1"; if (args.Parameters.Count > 0) { text = args.Parameters[0].ToLower(); } if (text == "list") { List <string> list = new List <string>(); foreach (string key in Colors.Keys) { list.Add($"[c/{Colors[key]}:{key}]"); } args.Player.SendMessage($"[c/00ff00:Lista dostepnych kolorow:]", new Color(0, 0, 0)); PaginationTools.SendPage(args.Player, 0, PaginationTools.BuildLinesFromTerms(list, null, ", ", 140), new PaginationTools.Settings { IncludeHeader = false, LineTextColor = new Color(255, 255, 255), IncludeFooter = false, NothingToDisplayString = "Error 404." }); return; } if (!Colors.ContainsKey(text)) { args.Player.SendErrorMessage("Nie znaleziono podanego koloru."); args.Player.SendInfoMessage($"Wpisz /ncolor list, aby otrzymac liste dostepnych kolorow."); return; } int cost = 14500; cost = Utils.CostCalc(args.Player, cost); if (money < cost) { args.Player.SendErrorMessage("Nie stac cie na zmiane koloru nicku. Koszt {0} €", cost); return; } object[] data = new object[2] { cost, text }; Chat.AddAcceptation((byte)args.Player.Index, Action_CommandNick, data); string msg = string.Format(ChatFormat, ( SurvivalCore.SrvPlayers[args.Player.Index].PrefixItem == -1) ? PowelderAPI.Utils.GetGroupItem(args.Player.Group.Name) : SurvivalCore.SrvPlayers[args.Player.Index].PrefixItem, PowelderAPI.Utils.GetGroupColor(args.Player.Group.Name), (args.Player.Group.Name == "Xedlefix" || args.Player.Group.Name == "Iwobos") ? "Zalozyciel" : args.Player.Group.Name, Colors[text], args.Player.Name, "Przykladowa wiadomosc."); args.Player.SendMessage(msg, Color.White); args.Player.SendInfoMessage($"Czy zgadzasz sie na zmiane? Wpisz [c/66ff66:/tak] lub [c/ff6666:/nie] Koszt {cost} €"); }
private void DoRest(CommandArgs args) { string subCommand = "help"; if (args.Parameters.Count > 0) { subCommand = args.Parameters[0]; } switch (subCommand.ToLower()) { case "listusers": if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out int pageNumber)) { return; } var restUsersTokens = new Dictionary <string, int>(); foreach (SecureRest.TokenData tokenData in Restful.Instance.Api.Tokens.Values) { if (restUsersTokens.ContainsKey(tokenData.Username)) { restUsersTokens[tokenData.Username]++; } else { restUsersTokens.Add(tokenData.Username, 1); } } var restUsers = new List <string>(restUsersTokens.Select(ut => $"{ut.Key} ({ut.Value} tokens)")); PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(restUsers), new PaginationTools.Settings { NothingToDisplayString = "There are currently no active REST users.", HeaderFormat = "Active REST Users ({0}/{1}):", FooterFormat = $"Type {TShockAPI.Commands.Specifier}rest listusers {{0}} for more." } ); break; case "destroytokens": Restful.Instance.Api.Tokens.Clear(); args.Player.SendSuccessMessage("All REST tokens have been destroyed."); break; default: args.Player.SendInfoMessage("Available REST Sub-Commands:"); args.Player.SendMessage("listusers - Lists all REST users and their current active tokens.", Color.White); args.Player.SendMessage("destroytokens - Destroys all current REST tokens.", Color.White); break; } }
public void SendHelpText(CommandArgs args, string error = null) { if (error != null) { Utils.ShowErrorMessage(error); } List <string> helpText = new List <string>(); int pageParamIndex = 1; int pageNumber; if (args.Parameters.Count > 1 && args.Parameters[0] == "help" && !int.TryParse(args.Parameters[1], out int num)) { pageParamIndex = 2; string commandName = args.Parameters[1]; var subcmd = Subcommands.FirstOrDefault(s => s.Names.Contains(args.Parameters[1])); if (subcmd == null) { throw new CommandException($"Invalid subcommand! Try {RShockAPI.Config.CommandPrefix}{commandName} help for more info."); } helpText = subcmd.HelpDesc.Count() == 0 ? new List <string>() { subcmd.HelpText } : subcmd.HelpDesc.ToList(); } else { helpText = GetHelpText(args).ToList(); } if (helpText.Count == 0) { Utils.ShowInfoMessage("The command does not have any help description!"); return; } if (!PaginationTools.TryParsePageNumber(args.Parameters, pageParamIndex, out pageNumber)) { return; } PaginationTools.SendPage(pageNumber, helpText, new PaginationTools.Settings { HeaderFormat = "Commands ({0}/{1}):", FooterFormat = $"Type /{Names.First()} help {{0}} for more. \nType /{Names.First()} help <command name> for command description.", MaxLinesPerPage = 4 }); }
public void RegionInfo(Region region, int page = 1) { 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( Sender, page, lines, new PaginationTools.Settings { HeaderFormat = string.Format("Information About Region \"{0}\" ({{0}}/{{1}}):", region.Name), FooterFormat = string.Format("Type {0}easy-region info {1} {{0}} for more information.", TextOptions.CommandPrefix, region.Name) } ); }
void DoSignInfo(CommandArgs args) { int pageNumber; if (!PaginationTools.TryParsePageNumber(args.Parameters, 0, args.Player, out pageNumber)) { pageNumber = 1; } PaginationTools.SendPage(args.Player, pageNumber, Help.Info, new PaginationTools.Settings() { IncludeHeader = false, FooterFormat = $"Type {Commands.Specifier}sign {{0}} for more info." }); }
public void Invoke(CommandArgs args) { int num; if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out num)) { return; } List <string> strs = _cmds.Select(x => string.Format("{0} - {1}.", x.Value.Usage, x.Value.Description)).ToList(); PaginationTools.Settings setting = new PaginationTools.Settings(); setting.HeaderFormat = "Buff Ban Sub-Commands ({0}/{1}):"; setting.FooterFormat = StringExt.SFormat("Type {0}banbuff help {{0}} for more sub-commands.", TShockAPI.Commands.Specifier); PaginationTools.SendPage(args.Player, num, strs, setting); }
void ListPlugins(List <TerrariaPlugin> plugins, TSPlayer receiver, List <string> args) { if (receiver is TSServerPlayer) { // Get rid of the annoying console colon Console.WriteLine(); // Assume console, use a string table TableHelper.PrintLine(); TableHelper.PrintRow("Name", "Author", "Version", "Configuration"); TableHelper.PrintLine(); foreach (TerrariaPlugin p in plugins) { TableHelper.PrintRow(p.Name, p.Author, p.Version.ToString(), GetAssemblyConfiguration(p.GetType().Assembly)); } TableHelper.PrintLine(); } else if (receiver.RealPlayer) { // Use TShock Pagination List <string> lines = PaginationTools.BuildLinesFromTerms(plugins.Select(p => p.Name)); int pageNum; if (!PaginationTools.TryParsePageNumber(args, 1, receiver, out pageNum)) { return; } PaginationTools.SendPage(receiver, pageNum, lines, new PaginationTools.Settings { HeaderFormat = "Plugin List ({0}/{1}):", FooterFormat = $"Type {Commands.Specifier}plugin <find/list> {{0}} for more.", NothingToDisplayString = "No plugins were found." }); } else { // Assume outside source, send raw comma-separated list receiver.SendInfoMessage($"Plugin count: {plugins.Count}"); receiver.SendInfoMessage(String.Join(", ", plugins.Select(p => p.Name))); } }
private void PvPProjBans(CommandArgs args) { int pageNumber; if (!PaginationTools.TryParsePageNumber(args.Parameters, 0, args.Player, out pageNumber)) { return; } PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(cfg.projBans, maxCharsPerLine: 75), new PaginationTools.Settings { HeaderFormat = "The following projectiles cannot be used in PvP:", FooterFormat = "Type /pvpprojbans {0} for more.", NothingToDisplayString = "There are currently no banned projectiles." }); }
public void Invoke(CommandArgs args) { int num; if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out num)) { return; } IEnumerable <string> buffBans = from BuffBan in _buffManager.BuffBans select BuffBan.Name; List <string> strs = PaginationTools.BuildLinesFromTerms(buffBans, null, ", ", 80); PaginationTools.Settings setting = new PaginationTools.Settings(); setting.HeaderFormat = "Buff Bans ({0}/{1}):"; setting.FooterFormat = StringExt.SFormat("Type {0}banbuff list {{0}} for more.", TShockAPI.Commands.Specifier); setting.NothingToDisplayString = "There are currently no banned buffs."; PaginationTools.SendPage(args.Player, num, strs, setting); }
void DoSignFiles(CommandArgs args) { int pageNumber; var files = FileTools.ListFiles(); var lines = PaginationTools.BuildLinesFromTerms(files); if (!PaginationTools.TryParsePageNumber(args.Parameters, 0, args.Player, out pageNumber)) { pageNumber = 1; } PaginationTools.SendPage(args.Player, pageNumber, lines, new PaginationTools.Settings() { HeaderFormat = "Available Files ({0}/{1}):", FooterFormat = "Type {0}signfiles {{0}} for more files.".SFormat(Commands.Specifier), NothingToDisplayString = "No files available." }); }
public void ListWarpplates(CommandArgs args) { int pageNumber; if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber)) { return; } var wpNames = Manager.ListAllWarpplates(); PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(wpNames), new PaginationTools.Settings { HeaderFormat = "Warpplates ({0}/{1}):", FooterFormat = "Type {0}lwp {{0}} for more.".SFormat(TShock.Config.CommandSpecifier), NothingToDisplayString = "There are currently no warpplates defined." }); }
private void PvPBuffBans(CommandArgs args) { int pageNumber; if (!PaginationTools.TryParsePageNumber(args.Parameters, 0, args.Player, out pageNumber)) { return; } IEnumerable <string> buffNames = from buffBan in cfg.buffBans select TShock.Utils.GetBuffName(buffBan); PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(buffNames, maxCharsPerLine: 75), new PaginationTools.Settings { HeaderFormat = "The following buffs cannot be used in PvP:", FooterFormat = "Type /pvpbuffbans {0} for more.", NothingToDisplayString = "There are currently no banned buffs." }); }
private static void ListPlayerPermissions(CommandArgs args) { if (args.Parameters.Count < 2 || args.Parameters.Count > 3) { args.Player.SendErrorMessage("Invalid syntax: {0}permission list <player name> [page]", TShock.Config.CommandSpecifier); return; } List <User> users = TShock.Users.GetUsersByNameEx(args.Parameters[1]); if (users.Count == 0) { args.Player.SendErrorMessage("Invalid player!"); return; } else if (users.Count > 1) { TShock.Utils.SendMultipleMatchError(args.Player, users.Select(p => p.Name)); return; } else if (Instance.USFDatabase.GetPlayer(users[0].ID) == null || !Instance.USFDatabase.GetPlayer(users[0].ID).Permissions.Any()) { args.Player.SendErrorMessage("This player has no permissions to list."); return; } else { int pageNum; if (!PaginationTools.TryParsePageNumber(args.Parameters, 2, args.Player, out pageNum)) { return; } List <string> permissionList = Instance.USFDatabase.GetPlayer(users[0].ID).Permissions; PaginationTools.SendPage(args.Player, pageNum, PaginationTools.BuildLinesFromTerms(permissionList), new PaginationTools.Settings { HeaderFormat = "{0} permissions:".SFormat(users[0].Name.SuffixPossesion()), FooterFormat = "Type {0}permission list {1} {{0}} for more.".SFormat(TShock.Config.CommandSilentSpecifier, users[0].Name), NothingToDisplayString = "This player has no permissions to list." }); } }
public static void ListFlags(CommandArgs args) { int pageParamIndex = 1; int pageNumber; List <string> options = PaginationTools.BuildLinesFromTerms(TweakOptions); if (!PaginationTools.TryParsePageNumber(args.Parameters, pageParamIndex, args.Player, out pageNumber)) { return; } PaginationTools.SendPage(args.Player, pageNumber, options, new PaginationTools.Settings { HeaderFormat = "Flags ({0}/{1}):", FooterFormat = $"Type /autobc listflags {{0}} for more.", MaxLinesPerPage = 4 }); }
public static void Stats(CommandArgs args) { if (!args.Player.IsLoggedIn) { args.Player.SendErrorMessage(VocationPlugin.Resources.ERR_NOT_LOGGED_IN); return; } int index = Plugin.Config.Warrior.FindIndex(v => v.PlayerName == args.Player.Name); if (index == -1) { args.Player.SendErrorMessage(VocationPlugin.Resources.ERR_NO_VOCATION); return; } Vocation character = Vocation.getVocation(index, Plugin.Config.settings[index].currentVocation); try { int pageNumber; if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber)) { return; } var lines = new List <string> { string.Format(VocationPlugin.Resources.INFO_STAT_LEVEL, character.Level, character.RemainingXp, character.RemainingXpPercent), string.Format(VocationPlugin.Resources.INFO_STAT_ATTACK, "Magic", character.magic.Level, character.magic.getAttackLevelXp(character.MagicAttackMultiplier, XpFormat.Percent)), string.Format(VocationPlugin.Resources.INFO_STAT_ATTACK, "Melee", character.melee.Level, character.melee.getAttackLevelXp(character.MeleeAttackMultiplier, XpFormat.Percent)), string.Format(VocationPlugin.Resources.INFO_STAT_ATTACK, "Ranged", character.ranged.Level, character.ranged.getAttackLevelXp(character.RangedAttackMultiplier, XpFormat.Percent)) }; PaginationTools.SendPage(args.Player, pageNumber, lines, new PaginationTools.Settings { HeaderFormat = args.Player.Name + " stats:" }); } catch (Exception e) { args.Player.SendErrorMessage(e.Message); return; } }
void ShowClasses(TSPlayer player, bool showHelp, int pageNumber = 1) { List <string> classNames = new List <string>(); foreach (Config.PlayerClass clas in Config.contents.playerClasses) { if (canHaveDuplicates || !clas.taken) { classNames.Add(clas.name); } } if (showHelp) { player.SendInfoMessage("Choose a class with /class."); } PaginationTools.SendPage(player, pageNumber, PaginationTools.BuildLinesFromTerms(classNames), new PaginationTools.Settings { HeaderFormat = "Classes ({0}/{1}):", FooterFormat = "Type /class list {0} for more." }); }
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." }); }
/// <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; } }
private void ClassAccess(CommandArgs args) { TSPlayer player = args.Player; #region help if (args.Parameters.Count == 0 || args.Parameters[0] == "help") { player.SendErrorMessage("Aliases: /class, /cs"); player.SendErrorMessage("/class list <category>"); player.SendErrorMessage("/class select <class name>"); player.SendErrorMessage("/class preview <class name>"); player.SendErrorMessage("/class random <category>"); player.SendErrorMessage("/class stop"); player.SendErrorMessage("If a class name is not specified, this command will attempt to use the most recently used class from /cwm select."); player.SendErrorMessage("/class stop will attempt to restore your inventory and set you to not playing or previewing any class."); return; } #endregion #region list if (args.Parameters[0].ToLower() == "list") { int page = 1; bool categoryExists = false; string category; List <string> results = new List <string>(); PaginationTools.Settings settings = new PaginationTools.Settings { HeaderFormat = "Class Wars Classes: ", FooterFormat = "type /class list {{0}}", NothingToDisplayString = "There are no classes presently defined." }; if (args.Parameters.Count > 1) { if (!int.TryParse(args.Parameters[1], out page)) { categoryExists = true; category = args.Parameters[1]; TextInfo TI = new CultureInfo("en-US", false).TextInfo; category = TI.ToTitleCase(category); //sets to title case for minor improvement to pagination appearance later. foreach (CWClass c in CUtil.classes) { if (c.category.ToLower() == category.ToLower()) { results.Add(c.name); } } settings = new PaginationTools.Settings { HeaderFormat = category + " Classes: ", FooterFormat = "type /class list " + category + " {{0}}", NothingToDisplayString = "There are no classes in the " + category + " category." }; } } if (!categoryExists) { foreach (CWClass c in CUtil.classes) { results.Add(c.name); } } results.Sort(); PaginationTools.SendPage(player, page, PaginationTools.BuildLinesFromTerms(results), settings); return; } #endregion #region select if (args.Parameters[0].ToLower() == "select" || args.Parameters[0].ToLower() == "pick" || args.Parameters[0].ToLower() == "sel") { if (args.Parameters.Count == 1 && PInfo.GetClassEdit(player.Name) == "none") { player.SendErrorMessage("Usage: /class select <class name>"); player.SendErrorMessage("Alternatively, select a class using /cwm select before using /class select."); return; } args.Parameters.RemoveAt(0); string className = PInfo.GetClassEdit(player.Name); if (args.Parameters.Count > 0) { string c = string.Join(" ", args.Parameters); int resultType = -100; string results = CUtil.ClassExists(c, ref resultType); switch (resultType) { case -1: player.SendErrorMessage(results); return; case 0: case 1: className = results; break; case 2: player.SendErrorMessage("Multiple classes found: "); player.SendErrorMessage(results); return; } } CUtil.SetClass(player, className, ref PInfo); player.SendSuccessMessage("You have selected " + className + "."); //game logic here, moron. Don't forget it. } #endregion #region preview if (args.Parameters[0].ToLower() == "select" || args.Parameters[0].ToLower() == "pick" || args.Parameters[0].ToLower() == "sel") { if (args.Parameters.Count == 1 && PInfo.GetClassEdit(player.Name) == "none") { player.SendErrorMessage("Usage: /class select <class name>"); player.SendErrorMessage("Alternatively, select a class using /cwm select before using /class select."); return; } args.Parameters.RemoveAt(0); string className = PInfo.GetClassEdit(player.Name); if (args.Parameters.Count > 0) { string c = string.Join(" ", args.Parameters); int resultType = -100; string results = CUtil.ClassExists(c, ref resultType); switch (resultType) { case -1: player.SendErrorMessage(results); return; case 0: case 1: className = results; break; case 2: player.SendErrorMessage("Multiple classes found: "); player.SendErrorMessage(results); return; } } CUtil.SetClass(player, className, ref PInfo); PInfo.SetPreviewing(player.Name, true); player.SendSuccessMessage("You are now previewing " + className + "."); } #endregion #region stop if (args.Parameters[0].ToLower() == "stop") { PInfo.RestoreInv(player); PInfo.SetPlaying(player.Name, "none"); PInfo.SetPreviewing(player.Name, false); CWGame.GTFO(player); player.SendSuccessMessage("Inventory restore attempted, you are no longer playing or previewing a class."); return; } #endregion #region random if (args.Parameters[0].ToLower() == "random") { string category = "none"; List <CWClass> classesToPick = new List <CWClass>(); if (args.Parameters.Count > 1) { args.Parameters.RemoveAt(0); category = string.Join(" ", args.Parameters); foreach (CWClass c in CUtil.classes) { if (c.category.ToLower() == category.ToLower()) { classesToPick.Add(c); } } if (classesToPick.Count == 0) { player.SendErrorMessage("No classes found in category " + category); return; } } else { classesToPick = CUtil.classes; } if (classesToPick.Count == 0) { player.SendErrorMessage("No classes are presently defined."); return; } Random rand = new Random(); TShockAPI.Commands.HandleCommand(player, "/class select " + classesToPick[rand.Next(classesToPick.Count)].name); return; } #endregion }
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; } }
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); }
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; } }
public static void BoostCommand(CommandArgs args) { if (args.Parameters.Count < 1) { args.Player.SendErrorMessage("Uzycie: /boost <nazwa buffa/list>"); } else if (args.Parameters[0].ToLower() == "list") { List <string> list = new List <string>(); foreach (string key in avalibleBuffs.Keys) { list.Add($"{key} - [c/ffff00:{avalibleBuffs[key].Value} €]"); } args.Player.SendMessage($"Lista dostepnych buffow:", Color.Green); PaginationTools.SendPage(args.Player, 0, PaginationTools.BuildLinesFromTerms(list, null, " | ", 140), new PaginationTools.Settings { IncludeHeader = false, LineTextColor = new Color(192, 192, 192), IncludeFooter = false, NothingToDisplayString = "Error 404." }); } else { string buff = string.Join(" ", args.Parameters).ToLower(); if (avalibleBuffs.ContainsKey(buff)) { if (SurvivalCore.SrvPlayers[args.Player.Index].Money < avalibleBuffs[buff].Value && !args.Player.HasPermission("isGracz+++")) { args.Player.SendErrorMessage($"Nie stac cie na wykupienie boosta na serwerze. Koszt {avalibleBuffs[buff].Value} €"); return;; } if ((SurvivalCore.SrvPlayers[args.Player.Index].BoostCooldown - DateTime.Now).Seconds > 0) { args.Player.SendErrorMessage($"Nastepny boost bedzie mozliwy za {PowelderAPI.Utils.ExpireCountDown(SurvivalCore.SrvPlayers[args.Player.Index].BoostCooldown)}"); return;; } if (SurvivalCore.BoostBuffType != 0) { args.Player.SendErrorMessage($"Aktualnie jest aktywny juz jeden boost. Minie on za {PowelderAPI.Utils.ExpireCountDown(SurvivalCore.BoostBuffEndTime)}"); return;; } if (!args.Player.HasPermission("isGracz+++")) { SurvivalCore.SrvPlayers[args.Player.Index].Money -= avalibleBuffs[buff].Value; } SurvivalCore.SrvPlayers[args.Player.Index].BoostCooldown = DateTime.Now.AddDays(2); args.Player.SendSuccessMessage($"Pomyslnie zboostowales serwer buffem {buff} na 2 godziny. Twoj nastepny boost bedzie mozliwy za 48h."); if (!args.Player.HasPermission("isGracz+++")) { args.Player.SendInfoMessage($"Twoj nowy stan konta: {SurvivalCore.SrvPlayers[args.Player.Index].Money} €"); } TSPlayer.All.SendWarningMessage($"{args.Player.Name} obdarowal serwer buffem {buff} na 2 godziny."); SurvivalCore.BoostBuffType = avalibleBuffs[buff].Key; SurvivalCore.BoostBuffEndTime = DateTime.Now.AddHours(2); return; } args.Player.SendErrorMessage("Nie znaleziono podanego buffa. Lista pod /boost list"); } }
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); }