public void AddCommands() { var DEL = Delegates.Instance; void add(Command cmd) { Commands.ChatCommands.Add(cmd); } #region Item Classes add(new Command("classes.user.choose", DEL.ChooseClass, "chooseclass") { HelpText = "" }); add(new Command("classes.admin.add", DEL.AddClass, "addclass") { HelpText = "" }); add(new Command("classes.admin.reset", DEL.ResetAll, "resetall") { HelpText = "" }); add(new Command("classes.admin.reset.opt", DEL.ResetOption, "resetopt") { HelpText = "" }); add(new Command("classes.admin.reload", DEL.Reload, "reload") { HelpText = "" }); add(new Command("classes.admin.reset.logout", delegate(CommandArgs e) { removeClass = !removeClass; e.Player.SendSuccessMessage("Player that log out have their class type removed: [" + removeClass + "]"); }, "classlogout") { HelpText = "" }); add(new Command("classes.admin.opt", delegate(CommandArgs e) { canChoose = !canChoose; e.Player.SendSuccessMessage("Players able to choose classes: [" + canChoose + "]"); }, "canchoose") { HelpText = "" }); add(new Command("classes.admin.start", DEL.Start, "match")); add(new Command("classes.admin.help", delegate(CommandArgs e) { var list = PaginationTools.BuildLinesFromTerms(new List <string>() { "chooseclass", "resetall", "resetopt", "reload", "classlogout", "canchoose", "match" }); if (e.Message.Contains(" ")) { int.TryParse(e.Message.Substring(e.Message.IndexOf(" ") + 1), out int page); PaginationTools.SendPage(e.Player, page, list); } else { PaginationTools.SendPage(e.Player, 1, list); } }, "classhelp")); #endregion #region Team Set add(new Command("teamset.admin.set", DEL.PlaceTeam, new string[] { "placeteam", "removeteam" }) { HelpText = "For placing or removing players from teams.", AllowServer = false }); add(new Command("teamset.admin", DEL.Reload, new string[] { "reload" }) { HelpText = "Reloads settings." }); add(new Command("teamset.admin.group", DEL.MakeGroups, new string[] { "teamgroups" }) { HelpText = "Makes general groups for each team color." }); add(new Command("teamset.admin.group", DEL.MakeGroups, new string[] { "teamset" }) { HelpText = "Modifies the associated group for the specified team color." }); add(new Command("teamset.join", DEL.JoinTeam, new string[] { "jointeam", "team" }) // "team" command only used to deny the PvPToggle plugin command /team. { HelpText = "Allows players to join a team if they aren't on one already.", AllowServer = false }); add(new Command("teamset.tp", DEL.TeamSpawn, new string[] { "tspawn" }) { HelpText = "Spawns player to their team-designated spawn point", AllowServer = false }); add(new Command("teamset.admin.tp", DEL.SetSpawn, new string[] { "settspawn" }) { HelpText = "For admins to set team spawns", AllowServer = false }); add(new Command("teamset.admin", delegate(CommandArgs a) { DEL.teamSpawn = !DEL.teamSpawn; a.Player.SendSuccessMessage("Teams being permitted to use /tspawn is [" + DEL.teamSpawn + "]."); }, "teamspawn") { HelpText = "Toggles whether players can use /tspawn to go to team spawn locations." }); add(new Command("teamset.help", delegate(CommandArgs a) { a.Player.SendInfoMessage(string.Format("{0} <index | color>, {1} <name>\n{2}\n{3} automates team group creation parented to group default\n{4} <team color> <group>\n{5} <color | index>\n{6} team spawn switch\n{7} <color> places spawn at your current position\n{8} teleports to team spawn\n{9} switches player on leave being removed from team\n{10} <<1-5>,<1-5>,[<1-5>]...> use 2 or more team indices to autosort into said teams \n{11} <reset | init <#>> Useful for expanding the maximum number of players per team \n{12} <all | team | [username]> Teleport whole everyone, team, or single player to their team spawn \n{13} removes everyone from their teams", "/placeteam", "/removeteam", "/reload", "/teamgroups", "/teamset", "/jointeam", "/tspawn", "/settspawn", "/teamspawn", "/teamleavekick", "/autosort", "/database", "/tpteam", "/resetteams")); }, "teamscrip") { HelpText = "Toggles whether players can use /tspawn to go to team spawn locations." }); // Kicking a player via /kick removed them from their team with this flag set. add(new Command("teamset.admin", delegate(CommandArgs a) { DEL.kickOnLeave = !DEL.kickOnLeave; a.Player.SendSuccessMessage("Players that leave are removed from their designated team [" + DEL.kickOnLeave + "]."); }, "teamleavekick") { HelpText = "Toggles whether players leaving should kick them off their teams." }); add(new Command("teamset.superadmin.db", DEL.MakeDataBase, "database") { HelpText = "Makes the database with which to store maximum player per team only to be used after the INI file is manually set up" }); add(new Command("teamset.admin.sort", DEL.AutoSort, "autosort") { HelpText = "Begins automatically sorting players into the teams that have the least players through use of team indices." }); add(new Command("teamset.admin", DEL.TeleportTeam, "tpteam") { HelpText = "Teleport whole team or single player using /tpteam <all | team <color> | [username]>" }); add(new Command("teamset.admin", delegate(CommandArgs a) { DEL.autoAssignGroup = !DEL.autoAssignGroup; a.Player.SendSuccessMessage("Automatically assigning members upon team join to group set to: [" + DEL.autoAssignGroup + "]."); }, "autoassign") { HelpText = "Flag for automatically assigning members to configured groups upon team join" }); add(new Command("teamset.admin.kick", DEL.KickAll, "resetteams") { HelpText = "Removes all server member's teams" }); add(new Command("teamset.help", delegate(CommandArgs e) { var list = PaginationTools.BuildLinesFromTerms(new List <string>() { "placeteam", "removeteam", "reload", "teamgroups", "teamset", "jointeam", "team", "tspawn", "settspawn", "teamspawn", "teamscrip", "teamleavekick", "database", "autosort", "tpteam", "autoassign", "resetteams" }); if (e.Message.Contains(" ")) { int.TryParse(e.Message.Substring(e.Message.IndexOf(" ") + 1), out int page); PaginationTools.SendPage(e.Player, page, list); } else { PaginationTools.SendPage(e.Player, 1, list); } }, "teamhelp") { HelpText = "Provides help pages for commands" });
public static void ShopUser(CommandArgs args) { TSPlayer player = args.Player; string text = null; string cmd2 = null; string text2 = null; string text3 = null; if (args.Parameters.Count > 0) { text = args.Parameters[0].ToLower(); } if (args.Parameters.Count > 1) { cmd2 = args.Parameters[1]; } else { cmd2 = "*"; } text2 = ((args.Parameters.Count <= 2) ? "1" : args.Parameters[2].ToLower()); if (args.Parameters.Count > 3) { text3 = args.Parameters[3].ToLower(); } switch (text) { default: args.Player.SendMessage("Sklep: ", Color.Green); args.Player.SendInfoMessage("/sklep szukaj <nazwa>"); args.Player.SendInfoMessage("/sklep kup <index/nazwa> <ilosc>"); args.Player.SendInfoMessage("/sklep sprzedaj <index/nazwa> <ilosc>"); break; case "search": case "szukaj": { int result3 = 1; int.TryParse(text2, out result3); List <string> list = new List <string>(); if (cmd2 == null || cmd2 == "*") { foreach (Product product5 in Economy.Products) { list.Add( $"[[c/dddd11:{product5.GetIndex()}]] [i:{product5.GetId()}] ([c/11bb11:K] [c/55bb55:{product5.GetBuy()}] ; [c/D42A2A:S] [c/D45A5A:{product5.GetSell()}])"); } } else if (cmd2.StartsWith("[i") && cmd2.EndsWith("]")) { int count = cmd2.IndexOf(':') + 1; string text4 = cmd2.Remove(0, count); count = text4.IndexOf(']'); text4 = text4.Remove(count); foreach (Product product6 in Economy.Products) { if (product6.GetId().ToString() == text4) { list.Add( $"[[c/dddd11:{product6.GetIndex()}]] [i:{product6.GetId()}] ([c/11bb11:K] [c/55bb55:{product6.GetBuy()}] ; [c/D42A2A:S] [c/D45A5A:{product6.GetSell()}])"); } } } else { foreach (Product product7 in Economy.Products) { if (product7.GetName().ToLower().Contains(cmd2.ToLower())) { list.Add( $"[[c/dddd11:{product7.GetIndex()}]] [i:{product7.GetId()}] ([c/11bb11:K] [c/55bb55:{product7.GetBuy()}] ; [c/D42A2A:S] [c/D45A5A:{product7.GetSell()}])"); } } } args.Player.SendMessage(string.Format("Wyniki dla: \"{0}\"", (cmd2 == null) ? "*" : cmd2), Color.Green); PaginationTools.SendPage(args.Player, result3, PaginationTools.BuildLinesFromTerms(list, null, " | ", 300), new PaginationTools.Settings { IncludeHeader = false, LineTextColor = new Color(192, 192, 192), FooterFormat = string.Format("Wpisz \"/sklep szukaj {0} {1}\", aby zobaczyc nastepna strone", (cmd2 == null) ? "*" : cmd2, result3 + 1), FooterTextColor = Color.Green, NothingToDisplayString = "[c/00ff00:Nie znaleziono zadnego produktu. Wpisz \"/sklep szukaj *\", aby otrzymac pelna liste produktow.]" }); break; } case "buy": case "kup": { if (int.TryParse(cmd2, out int index)) { if (index < 0) { args.Player.SendErrorMessage("Podano wartosc ujemna indexu, mozesz podac tylko dodatnia."); return; } Product product3 = new Product(0, null, 0, 0, 0); if (Economy.Products.Exists(x => x.Index == index)) { product3 = Economy.Products.Find(x => x.Index == index); } if (product3.GetIndex() == 0) { player.SendErrorMessage("Nie znaleziono przedmiotu w sklepie."); break; } if (product3.GetBuy() <= 0) { player.SendErrorMessage("Tego przedmiotu nie mozna zakupic."); break; } Item item3 = TShock.Utils.GetItemByIdOrName(product3.GetId().ToString())[0]; int amount = 1; if (args.Parameters.Count > 1) { int.TryParse(text2, out amount); } if (amount > item3.maxStack) { amount = item3.maxStack; } if (amount < 0) { args.Player.SendErrorMessage("Podano wartosc ujemna ilosci, mozesz podac tylko dodatnia."); return; } int num3 = amount * product3.GetBuy(); int money = SurvivalCore.SrvPlayers[player.Index].Money; if (money < num3) { args.Player.SendErrorMessage("Nie stac cie na zakup {0} w ilosci {1}. Brakuje ci {2} {3}", item3.Name, amount, Math.Abs(money - num3), Economy.Config.ValueName); } else if (args.Player.Dead) { args.Player.SendErrorMessage("Musisz byc zywy, kiedy chcesz cos zakupic."); } else if (args.Player.InventorySlotAvailable || (item3.type > 70 && item3.type < 75) || item3.ammo > 0 || item3.type == 58 || item3.type == 184) { SurvivalCore.SrvPlayers[player.Index].Money -= num3; args.Player.GiveItem(item3.type, amount); args.Player.SendSuccessMessage( $"Pomyslnie zakupiono [i:{item3.type}] w ilosci {amount}. Wydano {num3} {Economy.Config.ValueName}"); args.Player.SendInfoMessage( $"Twoj nowy stan konta: {money - num3:N0} {Economy.Config.ValueName}"); } else { args.Player.SendErrorMessage("Twoj ekwipunek jest pelny."); } break; } Product product4 = new Product(0, null, 0, 0, 0); if (Economy.Products.Exists(x => x.Name == cmd2)) { product4 = Economy.Products.Find(x => x.Name == cmd2); } if (product4.GetIndex() == 0) { player.SendErrorMessage("Nie znaleziono przedmiotu w sklepie."); break; } if (product4.GetBuy() <= 0) { player.SendErrorMessage("Tego przedmiotu nie mozna zakupic."); break; } Item item4 = TShock.Utils.GetItemByIdOrName(product4.GetId().ToString())[0]; int amount3 = 1; if (args.Parameters.Count > 1) { int.TryParse(text2, out amount3); } if (amount3 > item4.maxStack) { amount3 = item4.maxStack; } int num4 = amount3 * product4.GetBuy(); int money2 = SurvivalCore.SrvPlayers[player.Index].Money; if (money2 < num4) { args.Player.SendErrorMessage("Nie stac cie na zakup {0} w ilosci {1}. Brakuje ci {2:N0} {3}", item4.Name, amount3, Math.Abs(money2 - num4), Economy.Config.ValueName); } else if (args.Player.Dead) { args.Player.SendErrorMessage("Musisz byc zywy, kiedy chcesz cos zakupic."); } else if (args.Player.InventorySlotAvailable || (item4.type > 70 && item4.type < 75) || item4.ammo > 0 || item4.type == 58 || item4.type == 184) { SurvivalCore.SrvPlayers[player.Index].Money -= num4; args.Player.GiveItem(item4.type, amount3); args.Player.SendSuccessMessage( $"Pomyslnie zakupiono [i:{item4.type}] w ilosci {amount3}. Wydano {num4:N0} {Economy.Config.ValueName}"); args.Player.SendInfoMessage( $"Twoj nowy stan konta: {money2 - num4:N0} {Economy.Config.ValueName}"); } else { args.Player.SendErrorMessage("Twoj ekwipunek jest pelny."); } break; } case "sell": case "sprzedaj": { if (int.TryParse(cmd2, out int index2)) { if (index2 < 0) { args.Player.SendErrorMessage("Podano wartosc ujemna, mozesz podac tylko dodatnia."); return; } Product product = new Product(0, null, 0, 0, 0); if (Economy.Products.Exists((Product x) => x.Index == index2)) { product = Economy.Products.Find((Product x) => x.Index == index2); } if (product.GetIndex() == 0) { player.SendErrorMessage("Nie znaleziono przedmiotu w sklepie."); break; } if (product.GetSell() <= 0) { player.SendErrorMessage("Tego przedmiotu nie mozna sprzedac."); break; } Item item = TShock.Utils.GetItemByIdOrName(product.GetId().ToString())[0]; int result = 1; if (args.Parameters.Count > 1) { int.TryParse(text2, out result); } if (result > PowelderAPI.Utils.PlayerItemCount(args.Player, item)) { player.SendErrorMessage("Nie masz tylu {0} w ekwipunku.", item.Name); break; } if (result < 0) { args.Player.SendErrorMessage("Podano wartosc ujemna ilosci, mozesz podac tylko dodatnia."); return; } int num = result * product.GetSell(); SurvivalCore.SrvPlayers[player.Index].Money += num; PowelderAPI.Utils.PlayerRemoveItems(args.Player, item, result); args.Player.SendSuccessMessage( $"Pomyslnie sprzedano [i:{item.type}] w ilosci {result}. Zarobiono {num:N0} {Economy.Config.ValueName}"); args.Player.SendInfoMessage( $"Twoj nowy stan konta: {SurvivalCore.SrvPlayers[player.Index].Money:N0} {Economy.Config.ValueName}"); break; } if (cmd2.StartsWith("[i")) { string cmdItems = string.Join("", args.Parameters.Skip(1)); //Prefix only = [i/p59:3094] //Stack only = [i/s43:3094] Dictionary <int, int> items = new Dictionary <int, int>(); //Key: ID, Value: amount while (cmdItems.Contains(":")) { while (cmdItems[0] == ':') { cmdItems = cmdItems.Remove(0, 1); } int indexOfEnd = cmdItems.IndexOf(':'); int amount = 1; if (indexOfEnd > -1) { string arg = cmdItems.Substring(0, indexOfEnd); cmdItems = cmdItems.Remove(0, indexOfEnd); string numberText = ""; if (arg.Contains('p')) { amount = 1; } else { for (int i = 0; i < arg.Length; i++) { if (Char.IsDigit(arg[i])) { numberText += arg[i]; } } if (numberText.Length > 0) { amount = int.Parse(numberText); } } indexOfEnd = cmdItems.IndexOf(']'); try { arg = cmdItems.Substring(0, indexOfEnd); } catch (ArgumentOutOfRangeException) { args.Player.SendErrorMessage("Wystapil blad z formatem itemu."); return; } cmdItems = cmdItems.Remove(0, indexOfEnd + 1); numberText = ""; int id = -1; for (int i = 0; i < arg.Length; i++) { if (Char.IsDigit(arg[i])) { numberText += arg[i]; } } if (numberText.Length > 0) { id = int.Parse(numberText); } if (id > 0) { if (items.ContainsKey(id)) { items[id] += amount; } else { items.Add(id, amount); } if (items.Count > 10) { break; } } } } string finalMessage = ""; foreach (var item in items.Keys) { Product product = new Product(0, null, 0, 0, 0); if (Economy.Products.Exists(x => x.GetId() == item)) { product = Economy.Products.Find(x => x.GetId() == item); } if (product.GetIndex() == 0) { finalMessage += $"[c/ff0000:Nie znaleziono] [i:{item}] [c/ff0000:w sklepie.]\n"; continue; } if (product.GetSell() <= 0) { finalMessage += $"[c/ff0000:Nie mozna sprzedac] [i:{item}][c/ff0000:.]\n"; continue; } Item itemos = TShock.Utils.GetItemByIdOrName(product.GetId().ToString())[0]; if (items[item] > PowelderAPI.Utils.PlayerItemCount(args.Player, itemos)) { finalMessage += $"[c/ff0000:Nie posiadasz] [i:{item}] [c/ff0000:w ilosci {items[item]}.]\n"; continue; } int profit = items[item] * product.GetSell(); SurvivalCore.SrvPlayers[player.Index].Money += profit; PowelderAPI.Utils.PlayerRemoveItems(args.Player, itemos, items[item]); finalMessage += $"Pomyslnie sprzedano [i:{itemos.type}] w ilosci {items[item]}. Zarobiono {profit:N0} {Economy.Config.ValueName}\n"; } args.Player.SendSuccessMessage(finalMessage); args.Player.SendInfoMessage( $"Twoj nowy stan konta: {SurvivalCore.SrvPlayers[player.Index].Money:N0} {Economy.Config.ValueName}"); return; } Product product2 = new Product(0, null, 0, 0, 0); if (Economy.Products.Exists((Product x) => x.Name == cmd2)) { product2 = Economy.Products.Find((Product x) => x.Name == cmd2); } if (product2.GetIndex() == 0) { player.SendErrorMessage("Nie znaleziono przedmiotu w sklepie."); break; } if (product2.GetSell() <= 0) { player.SendErrorMessage("Tego przedmiotu nie mozna sprzedac."); break; } Item item2 = TShock.Utils.GetItemByIdOrName(product2.GetId().ToString())[0]; int result2 = 1; if (args.Parameters.Count > 1) { int.TryParse(text2, out result2); } if (result2 > PowelderAPI.Utils.PlayerItemCount(args.Player, item2)) { player.SendErrorMessage("Nie masz tylu {0} w ekwipunku.", item2.Name); break; } int num2 = result2 * product2.GetSell(); SurvivalCore.SrvPlayers[player.Index].Money += num2; PowelderAPI.Utils.PlayerRemoveItems(args.Player, item2, result2); args.Player.SendSuccessMessage( $"Pomyslnie sprzedano [i:{item2.type}] w ilosci {result2}. Zarobiono {num2:N0} {Economy.Config.ValueName}"); args.Player.SendInfoMessage( $"Twoj nowy stan konta: {SurvivalCore.SrvPlayers[player.Index].Money:N0} {Economy.Config.ValueName}"); break; } } }
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); }
void Craft(CommandArgs args) { Item item; var recData = args.Player.GetRecipeData(true); 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": if (recData.activeRecipe == null) { args.Player.SendErrorMessage("You aren't crafting anything!"); } else { args.Player.SendInfoMessage("Returning dropped items..."); foreach (RecItem itm in recData.droppedItems) { item = new Item(); item.SetDefaults(TShock.Utils.GetItemByIdOrName(itm.name).First().netID); args.Player.GiveItem(item.type, itm.name, item.width, item.height, itm.stack, itm.prefix); args.Player.SendInfoMessage("Returned {0}.", Utils.FormatItem((Item)itm)); } recData.activeRecipe = null; recData.droppedItems.Clear(); args.Player.SendInfoMessage("Successfully quit crafting."); } return; case "-confirm": if (!config.CraftFromInventory) { args.Player.SendErrorMessage("Crafting from inventory is disabled!"); return; } int count = 0; Dictionary <int, bool> finishedGroup = new Dictionary <int, bool>(); Dictionary <int, int> slots = new Dictionary <int, int>(); int ingredientCount = recData.activeIngredients.Count; foreach (Ingredient ing in recData.activeIngredients) { if (!finishedGroup.ContainsKey(ing.group)) { finishedGroup.Add(ing.group, false); } else if (ing.group != 0) { ingredientCount--; } } foreach (Ingredient ing in recData.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 = recData.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, NetworkText.Empty, args.Player.Index, slot.Key); args.Player.TPlayer.inventory[CursorSlot] = dummyItem; NetMessage.SendData((int)PacketTypes.PlayerSlot, -1, -1, NetworkText.Empty, args.Player.Index, CursorSlot); if (!recData.droppedItems.ContainsItem(item.Name, item.prefix)) { recData.droppedItems.Add(new RecItem(item.Name, stack, item.prefix)); } else { recData.droppedItems.GetItem(item.Name, item.prefix).stack += slot.Value; } } } List <Product> lDetPros = Utils.DetermineProducts(recData.activeRecipe.products); foreach (Product pro in lDetPros) { Item product = new Item(); product.SetDefaults(TShock.Utils.GetItemByIdOrName(pro.name).First().netID); product.Prefix(pro.prefix); pro.prefix = product.prefix; args.Player.GiveItem(product.type, product.Name, product.width, product.height, pro.stack, product.prefix); args.Player.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(recData.activeRecipe.name, recData.droppedItems, prods), args.Player.Name); recData.activeRecipe.Clone().ExecuteCommands(args.Player); recData.activeRecipe = null; recData.droppedItems.Clear(); args.Player.SendInfoMessage("Finished crafting."); return; default: if (recData.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.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; } recData.activeIngredients = new List <Ingredient>(rec.ingredients.Count); rec.ingredients.ForEach(i => { recData.activeIngredients.Add(i.Clone()); }); recData.activeRecipe = rec.Clone(); break; } } if (recData.activeRecipe != null) { List <string> inglist = Utils.ListIngredients(recData.activeRecipe.ingredients); if (!args.Silent) { args.Player.SendInfoMessage("The {0} recipe requires {1} to craft. {2}", recData.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; } }
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 player 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.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])); } 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; } } }
private 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.User.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 => { User user = TShock.Users.GetUserByID(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.Users.GetUserByName(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.Users.GetUserByName(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 (ExtManager.ClearAllowUsers(param[1])) { plr.SendSuccessMessage("Region clear member success!"); } else { plr.SendErrorMessage("Region clear member failed!"); } break; #endregion #region giveowner case "giveowner": case "gow": 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.Users.GetUserByName(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 context list case "context": case "con": int pageNumberCon = 1; if (args.Parameters.Count > 1) { int pageParamIndexCon = 1; if (!PaginationTools.TryParsePageNumber(param, pageParamIndexCon, plr, out pageNumberCon)) { return; } } lines = new List <string> { $"{Config.ContextSpecifier}this - get current region.", $"{Config.ContextSpecifier}myname - get account username." }; PaginationTools.SendPage( plr, pageNumberCon, lines, new PaginationTools.Settings { HeaderFormat = "Available contexts command ({0}/{1}):", FooterFormat = "Type {0}/re context {{0}} for more contexts.".SFormat(specifier) } ); 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.", "info <region> - Displays several information about the given region." }; if (Config.ContextAllow) { lines.Add("contexts [page] - Show available contexts command."); } 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; } }
private static void ListConnectedPlayers(CommandArgs args) { bool invalidUsage = args.Parameters.Count > 3; var displayIdsRequested = false; var displaypvp = false; var pageNumber = 1; if (!invalidUsage) { foreach (string parameter in args.Parameters) { if (parameter.Equals("-i", StringComparison.InvariantCultureIgnoreCase)) { displayIdsRequested = true; continue; } if (parameter.Equals("-p", StringComparison.InvariantCultureIgnoreCase)) { displaypvp = true; continue; } if (!int.TryParse(parameter, out pageNumber)) { invalidUsage = true; break; } } } if (invalidUsage) { args.Player.SendErrorMessage("Invalid usage, proper usage: {0}who [-p] [-i] [pagenumber]", Commands.Specifier); return; } if (displayIdsRequested && !args.Player.HasPermission(Permissions.seeids)) { args.Player.SendErrorMessage("You don't have the required permission to list player ids."); return; } Func <string> getParam = () => { if (displayIdsRequested && displaypvp) { return(" -i -p"); } if (displaypvp) { return(" -p"); } return(displayIdsRequested ? " -i" : string.Empty); }; var players = GetPlayers(displaypvp, displayIdsRequested, args.Player.RealPlayer).ToList(); args.Player.SendSuccessMessage("Online Players{2}: ({0}/{1})", players.Count, TShock.Config.MaxSlots, displaypvp ? " (with PvP enabled)" : string.Empty); PaginationTools.SendPage( args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(players, maxCharsPerLine: 140), new PaginationTools.Settings { IncludeHeader = false, LineTextColor = Color.White, FooterTextColor = Color.Green, FooterFormat = string.Format("Type {0}who{1} {{0}} for more.", Commands.Specifier, getParam()) } ); }
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 void PzCmd(CommandArgs args) { var cmd = args.Parameters.Count == 0 ? "HELP" : args.Parameters[0].ToUpperInvariant(); switch (cmd) { case "ADD": #region add if (args.Parameters.Count < 3) { args.Player.SendErrorMessage("语法无效! 正确语法: /pz add <区域名> <存档名> [玩家名]"); return; } var regionName = args.Parameters[1]; var name = args.Parameters[2]; var playerName = args.Parameters.ElementAtOrDefault(3); if (name.Length > 10) { args.Player.SendErrorMessage("存档名的长度不能超过10!"); return; } var region = TShock.Regions.GetRegionByName(regionName); if (region == null) { args.Player.SendErrorMessage("区域名无效!"); return; } TSPlayer player = null; if (!string.IsNullOrWhiteSpace(playerName)) { var players = TSPlayer.FindByNameOrID(playerName); if (players.Count == 0) { args.Player.SendErrorMessage("未找到玩家!"); return; } if (players.Count > 1) { args.Player.SendMultipleMatchError(players.Select(p => p.Name)); return; } player = players[0]; } player = player ?? args.Player; var data = new PlayerData(null); data.CopyCharacter(player); PzRegions.AddRegion(region.ID); PzRegions.AddCharacter(region.ID, name, data); args.Player.SendSuccessMessage("添加区域完毕."); #endregion break; case "LIST": #region list int pageNumber; if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber)) { return; } var names = from pz in PzRegions.PzRegions select TShock.Regions.GetRegionByID(pz.Id).Name + ": " + string.Join(", ", pz.PlayerDatas.Keys); PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(names), new PaginationTools.Settings { HeaderFormat = "应用区域 ({0}/{1}):", FooterFormat = "键入 {0}pz list {{0}} 以获取下一页应用区域.".SFormat(Commands.Specifier), NothingToDisplayString = "当前没有可用应用区域." }); #endregion break; case "REMOVE": #region remove if (args.Parameters.Count == 1) { args.Player.SendErrorMessage("语法无效! 正确语法: /pz remove <区域名>"); return; } regionName = string.Join(" ", args.Parameters.Skip(1)); region = TShock.Regions.GetRegionByName(regionName); if (region == null) { args.Player.SendErrorMessage("区域名无效!"); return; } PzRegions.RemoveRegion(region.ID); args.Player.SendSuccessMessage("删除区域及存档完毕."); #endregion break; case "REMOVECHAR": #region removeChar if (args.Parameters.Count < 3) { args.Player.SendErrorMessage("语法无效! 正确语法: /pz removechar <区域名> <存档名>"); return; } regionName = args.Parameters[1]; name = args.Parameters[2]; region = TShock.Regions.GetRegionByName(regionName); if (region == null) { args.Player.SendErrorMessage("区域名无效!"); return; } PzRegions.RemoveCharacter(region.ID, name); args.Player.SendSuccessMessage("删除存档完毕."); #endregion break; case "DEFAULT": #region default if (args.Parameters.Count < 3) { args.Player.SendErrorMessage("语法无效! 正确语法: /pz default <区域名> <存档名>"); return; } regionName = args.Parameters[1]; name = args.Parameters[2]; region = TShock.Regions.GetRegionByName(regionName); if (region == null) { args.Player.SendErrorMessage("区域名无效!"); return; } var pzregion = PzRegions.GetRegionById(region.ID); if (pzregion == null) { args.Player.SendErrorMessage("该区域并卟是Pz区域!"); return; } if (!pzregion.PlayerDatas.ContainsKey(name)) { args.Player.SendErrorMessage("区域内未找到符合条件的存档!"); return; } PzRegions.SetDefaultCharacter(region.ID, name); args.Player.SendSuccessMessage("设定存档完毕."); #endregion break; case "DELDEFAULT": #region deldefault if (args.Parameters.Count == 1) { args.Player.SendErrorMessage("语法无效! 正确语法: /pz deldefault <区域名>"); return; } regionName = string.Join(" ", args.Parameters.Skip(1)); region = TShock.Regions.GetRegionByName(regionName); if (region == null) { args.Player.SendErrorMessage("区域名无效!"); return; } pzregion = PzRegions.GetRegionById(region.ID); if (pzregion == null) { args.Player.SendErrorMessage("该区域并卟是Pz区域!"); return; } PzRegions.SetDefaultCharacter(region.ID, null); args.Player.SendSuccessMessage("移除默认存档完毕."); #endregion break; case "SHOW": case "RESTORE": args.Player.SendErrorMessage("暂不支持该功能."); break; case "HELP": #region help if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber)) { return; } var help = new[] { "add <区域名> <存档名> [玩家名(默认为自己)] - - 增加区域内存档", "remove <区域名> - - 删除区域内所有存档", "removechar <区域名> <存档名> - - 删除区域内存档", "default <区域名> <存档名> - - 设置单一存档默认值", "deldefault <区域名> - - 删除单一存档默认值", "list [页码] - - 显示所有区域", "help [页码] - - 显示子指令帮助" }; PaginationTools.SendPage(args.Player, pageNumber, help, new PaginationTools.Settings { HeaderFormat = "应用区域指令帮助 ({0}/{1}):", FooterFormat = "键入 {0}pz help {{0}} 以获取下一页应用区域帮助.".SFormat(Commands.Specifier), NothingToDisplayString = "当前没有可用帮助." }); #endregion break; default: args.Player.SendErrorMessage("语法无效! 键入 /pz help 以获取帮助."); return; } }
public static void Command(CommandArgs args) { string text = null; string s = null; if (args.Parameters.Count > 0) { text = args.Parameters[0].ToLower(); } if (args.Parameters.Count > 1) { s = args.Parameters[1].ToLower(); } if (text == "list") { int result = 1; int.TryParse(s, out result); if (result == 0) { result = 1; } List <string> list = new List <string>(); foreach (int key in Recipes.Keys) { list.Add($" [[c/dddd11:{key}]] [i/s{Recipes[key].Result.Amount}:{Recipes[key].Result.Id}] ← {Recipes[key].GetIngredientsString()}"); } PaginationTools.SendPage(args.Player, result, PaginationTools.BuildLinesFromTerms(list, null, ""), new PaginationTools.Settings { HeaderTextColor = new Color(0, 255, 0), FooterTextColor = new Color(128, 128, 128), HeaderFormat = "Lista dostepnych receptur:", MaxLinesPerPage = 4, LineTextColor = new Color(192, 192, 192), FooterFormat = $"Wpisz /wytworz list {result + 1}], aby zobaczyc nastepna strone.", NothingToDisplayString = "Wkrotce pojawia sie jakies receptury" }); return; } int result2 = 1; int.TryParse(s, out result2); if (result2 < 1) { result2 = 1; } if (text == null) { args.Player.SendErrorMessage("Uzycie: /wytworz <indeks> <ilosc>"); args.Player.SendErrorMessage("Uzycie: /wytworz list <strona>"); return; } if (!int.TryParse(text, out int result3)) { args.Player.SendErrorMessage("Podano niepoprawny indeks."); return; } if (!Recipes.ContainsKey(result3)) { args.Player.SendErrorMessage("Nie ma receptury o takim indeksie."); return; } if (TShock.Utils.GetItemById(Recipes[result3].Result.Id).maxStack < result2) { result2 = TShock.Utils.GetItemById(Recipes[result3].Result.Id).maxStack; } if (SurvivalCore.SrvPlayers[args.Player.Index].Money < Recipes[result3].Cost) { args.Player.SendErrorMessage($"Nie stac cie na wytworzenie [i:{Recipes[result3].Result.Id}] w ilosci {result2}. Koszt {Recipes[result3].Cost * result2} €."); return; } if (!Recipes[result3].IsPlayerHaveIngredients(args.Player, result2)) { args.Player.SendErrorMessage("Brakuje wymaganych materialow do stworzenia przedmiotu."); return; } if (!args.Player.InventorySlotAvailable) { args.Player.SendErrorMessage("Twoj ekwipunek jest pelny."); return; } int done = Recipes[result3].Do(args.Player, result2); SurvivalCore.SrvPlayers[args.Player.Index].Money -= Recipes[result3].Cost * done; args.Player.SendSuccessMessage($"Pomyslnie wytworzono [i:{Recipes[result3].Result.Id}] w ilosci {Recipes[result3].Result.Amount * done}."); }
private void GenBounty(CommandArgs args) { var player = Utils.GetPlayer(args.Player.Index); if (args.Parameters.Count < 1) { Utils.InvalidGenBountyUsage(args.Player); return; } if (args.Parameters[0].ToLower() == "-list") { int page; if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out page)) { return; } List <string> allBty = new List <string>(); foreach (Bounty bty in bounties) { allBty.Add(bty.name); } PaginationTools.SendPage(args.Player, page, PaginationTools.BuildLinesFromTerms(allBty), new PaginationTools.Settings { HeaderFormat = "Bounties ({0}/{1}):", FooterFormat = "Type /bty -list {0} for more.", NothingToDisplayString = "There are currently no bounties listed!" }); return; } if (args.Parameters.Count < 2) { Utils.InvalidGenBountyUsage(args.Player); return; } if (!Utils.CheckBountyNameExists(args.Parameters[1])) { args.Player.SendErrorMessage("Invalid bounty!"); return; } for (int i = 0; i < bounties.Count; i++) { if (args.Parameters[1].ToLower() == bounties[i].name.ToLower()) { var subcmd = args.Parameters[0].ToLower(); switch (subcmd) { case "-info": args.Player.SendInfoMessage("Bounty ({0}) was listed by {1} targeting {2}", bounties[i].name, bounties[i].contractor, bounties[i].target); args.Player.SendInfoMessage("with rewards ({0}).", Utils.ItemListToRewardsString(bounties[i].reward)); return; case "-accept": if (bounties[i].hunter.Contains(args.Player.Name)) { args.Player.SendErrorMessage("You have already accepted this bounty!"); return; } if (bounties[i].failures.Contains(args.Player.Name)) { args.Player.SendErrorMessage("You have failed this bounty already!"); args.Player.SendErrorMessage("You can no longer accept this bounty."); return; } if (config.MaxHuntersPerBounty != 0 && bounties[i].hunter.Count >= config.MaxHuntersPerBounty) { args.Player.SendErrorMessage("The maximum number of hunters have accepted this bounty!"); args.Player.SendErrorMessage("Please try again later."); return; } if (config.MaxBountiesPerHunter != 0 && player.activeBounties.Count >= config.MaxBountiesPerHunter) { args.Player.SendErrorMessage("You have taken the maximum number of bounties!"); args.Player.SendErrorMessage("Abandon another bounty to accept this bounty."); return; } player.activeBounties.Add(bounties[i], 0); bounties[i].hunter.Add(args.Player.Name); dbManager.UpdateHunters(bounties[i]); args.Player.SendSuccessMessage("You have accepted \"{0}.\" Your target is \"{1}.\"", bounties[i].name, bounties[i].target); return; case "-abandon": Bounty btyToRemove = null; foreach (Bounty bounty in player.activeBounties.Keys) { if (bounty.name == bounties[i].name) { btyToRemove = bounty; } } if (btyToRemove != null) { player.activeBounties.Remove(btyToRemove); } bounties[i].hunter.Remove(args.Player.Name); dbManager.UpdateHunters(bounties[i]); args.Player.SendInfoMessage("You have abandoned \"{0}.\"", bounties[i].name); return; default: Utils.InvalidGenBountyUsage(args.Player); 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.ContainsPermission(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 void ListConnectedPlayers(CommandArgs args) { var invalidUsage = args.Parameters.Count > 2; var displayIdsRequested = false; var pageNumber = 1; if (!invalidUsage) { foreach (var parameter in args.Parameters) { if (parameter.Equals("-i", StringComparison.InvariantCultureIgnoreCase)) { displayIdsRequested = true; continue; } if (!int.TryParse(parameter, out pageNumber)) { invalidUsage = true; break; } } } if (invalidUsage) { args.Player.SendErrorMessage("Invalid usage, proper usage: {0}who [-i] [pagenumber]", Commands.Specifier); return; } if (displayIdsRequested && !args.Player.HasPermission(Permissions.seeids)) { args.Player.SendErrorMessage("You don't have the required permission to list player ids."); return; } var activePlayers = TShock.Players.Where(p => p != null && (p.Active || _forward.ContainsKey(p.Index))).ToList(); args.Player.SendSuccessMessage($"Total Online Players ({activePlayers.Count()}/{TShock.Config.MaxSlots})"); var players = from p in activePlayers group displayIdsRequested ? $"{p.Name} (IX: {p.Index}{(p.User != null ? ", ID: " + p.User.ID : "")})" : p.Name by _forward[p.Index].Server; var content = new List <string>(); var hiddenPlayers = 0; foreach (var server in players) { if (!args.Player.HasPermission(server.Key.Permission)) { hiddenPlayers += server.Count(); continue; } content.Add($"Players in {server.Key.Name} ({server.Count()}):"); content.AddRange(PaginationTools.BuildLinesFromTerms(server)); } if (hiddenPlayers != 0) { content.Add($"{hiddenPlayers} players in hidden server."); } PaginationTools.SendPage(args.Player, pageNumber, content, new PaginationTools.Settings { IncludeHeader = false, FooterFormat = $"Type {Commands.Specifier}who {(displayIdsRequested ? "-i " : string.Empty)}{{0}} for more." }); }
public static void FakeCommand(CommandArgs args) { string arg0 = args.Parameters.ElementAtOrDefault(0); switch (arg0?.ToLower()) { case "l": case "list": { if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out int page)) { return; } List <string> lines = PaginationTools.BuildLinesFromTerms(FakeProviderAPI.Tile.Providers); PaginationTools.SendPage(args.Player, page, lines, new PaginationTools.Settings() { HeaderFormat = "Fake providers ({0}/{1}):", FooterFormat = "Type '/fake list {0}' for more.", NothingToDisplayString = "There are no fake providers yet." }); break; } case "tp": case "teleport": { if (args.Parameters.Count != 2) { args.Player.SendErrorMessage("/fake tp \"provider name\""); return; } if (!FindProvider(args.Parameters[1], args.Player, out INamedTileCollection provider)) { return; } args.Player.Teleport((provider.X + provider.Width / 2) * 16, (provider.Y + provider.Height / 2) * 16); args.Player.SendSuccessMessage($"Teleported to fake provider '{provider.Name}'."); break; } case "m": case "move": { if (args.Parameters.Count != 4) { args.Player.SendErrorMessage("/fake move \"provider name\" <relative x> <relative y>"); return; } if (!FindProvider(args.Parameters[1], args.Player, out INamedTileCollection provider)) { return; } if (!Int32.TryParse(args.Parameters[2], out int x) || !Int32.TryParse(args.Parameters[3], out int y)) { args.Player.SendErrorMessage("Invalid coordinates."); return; } provider.Move(x, y, true); args.Player.SendSuccessMessage($"Fake provider '{provider.Name}' moved to ({x}, {y})."); break; } case "la": case "layer": { if (args.Parameters.Count != 3) { args.Player.SendErrorMessage("/fake layer \"provider name\" <layer>"); return; } if (!FindProvider(args.Parameters[1], args.Player, out INamedTileCollection provider)) { return; } if (!Int32.TryParse(args.Parameters[2], out int layer)) { args.Player.SendErrorMessage("Invalid layer."); return; } provider.SetLayer(layer, true); args.Player.SendSuccessMessage($"Fake provider '{provider.Name}' layer set to {layer}."); break; } case "i": case "info": { if (args.Parameters.Count != 2) { args.Player.SendErrorMessage("/fake info \"provider name\""); return; } if (!FindProvider(args.Parameters[1], args.Player, out INamedTileCollection provider)) { return; } args.Player.SendInfoMessage( $@"Fake provider '{provider.Name}' ({provider.GetType().Name}) Position and size: {provider.XYWH()} Enabled: {provider.Enabled} Entities: {provider.Entities.Count}"); break; } default: { args.Player.SendSuccessMessage("/fake subcommands:"); args.Player.SendInfoMessage( @"/fake info ""provider name"" /fake tp ""provider name"" /fake move ""provider name"" <relative x> <relative y> /fake list [page]"); break; } } }
public static async void Shop(CommandArgs args) { var regex = new Regex(@"^\w+ (?<Switch>\S+)\S* *(?:""?(?<Object>.+?)""?)?(?: (?<Digit>\d+))?$"); Match match = regex.Match(args.Message); if (!match.Success) { args.Player.SendInfoMessage($"{Tag} Syntax: {specifier}shop [-switch]"); var switches = new List <string>(); if (args.Player.Group.HasPermission(Permissions.Buy)) { switches.Add("-b/buy"); } if (args.Player.Group.HasPermission(Permissions.KitsBuy)) { switches.Add("-k/kits"); } if (args.Player.Group.HasPermission(Permissions.Help)) { switches.Add("-h/help [cmd]"); } if (args.Player.Group.HasPermission(Permissions.Search)) { switches.Add("-s/search"); } if (args.Player.Group.HasPermission(Permissions.Reload)) { switches.Add("-r/reload"); } args.Player.SendInfoMessage($"{Tag} Switches: {String.Join(" ", switches)}."); } else { SItem item; Kit kit; BankAccount account; int digit; switch (match.Groups["Switch"].Value.ToLowerInvariant()) { #region B (Purchase an item) case "-b": case "buy": if (!args.Player.Group.HasPermission(Permissions.Buy)) { args.Player.SendErrorMessage("You do not have access to this command."); return; } string itemName = match.Groups["Object"].Value; if (String.IsNullOrWhiteSpace(itemName)) { args.Player.SendErrorMessage($"{Tag} Invalid syntax! Proper syntax: {specifier}shop -b <item name | ID> [amount]"); return; } if (itemName.Equals("list", StringComparison.OrdinalIgnoreCase)) { IEnumerable <string> dataToPaginate = PaginationTools.BuildLinesFromTerms(Manager.GetItems().Select(i => i.GetName())); digit = 1; if (!String.IsNullOrWhiteSpace(match.Groups["Digit"].Value) && !Int32.TryParse(match.Groups["Digit"].Value, out digit)) { args.Player.SendErrorMessage($"{Tag} Invalid page number!"); return; } PaginationTools.SendPage(args.Player, digit, dataToPaginate.ToList(), new PaginationTools.Settings() { HeaderFormat = $"{Tag} Items ({{0}}/{{1}}):", FooterFormat = $"{Tag} Type {specifier}shop -b list {{0}} for more.", NothingToDisplayString = $"{Tag} No items available." }); return; } List <SItem> matches; try { matches = await Manager.GetMatchingItems(itemName); } catch (InvalidItemException) { args.Player.SendErrorMessage($"{Tag} Invalid item!"); return; } if (matches.Count != 1) { args.Player.SendItemMatches(matches); } else { item = matches[0]; digit = 1; if ((account = await BankMain.Bank.GetAsync(args.Player.User?.Name)) == null) { args.Player.SendErrorMessage($"{Tag} You must have a bank account to use this command."); } else if (!String.IsNullOrWhiteSpace(match.Groups["Digit"].Value) && !Int32.TryParse(match.Groups["Digit"].Value, out digit)) { args.Player.SendErrorMessage($"{Tag} Invalid amount!"); } else if (account.Balance < item.cost * digit) { args.Player.SendErrorMessage($"{Tag} You're {BankMain.FormatMoney(item.cost * digit - account.Balance)} short!"); } else if (!args.Player.InventorySlotAvailable) { args.Player.SendErrorMessage($"{Tag} Your inventory seems full."); } else { try { int stack = item.stack * digit; int cost = item.cost * digit; Item realItem = item.GetItem(); if (realItem.maxStack == 1 && stack > 1) { stack = 1; cost = item.cost; } else if (stack > realItem.maxStack) { args.Player.SendErrorMessage($"{Tag} You can't buy {stack} {realItem.Name} at once."); return; } if (CShop.Config.UseGiveItemSSC) { args.Player.GiveItemSSC(item.netID, stack, item.prefix); } else { args.Player.GiveItem(item.netID, realItem.Name, 2, 3, stack, item.prefix); } await BankMain.Bank.ChangeByAsync(account.AccountName, -cost); BankMain.Log.ItemPurchase(account, new SItem(item.netID, stack, cost, item.prefix)); string prefix = item.prefix > 0 ? item.GetPrefixName() + " " : ""; args.Player.SendSuccessMessage($"{Tag} Bought {stack} {prefix}{item.GetName()} for {BankMain.FormatMoney(cost)}."); } catch (NullReferenceException) { args.Player.SendErrorMessage($"{Tag} Invalid bank account!"); } catch (InvalidOperationException) { args.Player.SendErrorMessage($"{Tag} Error performing transaction. Possible database corruption."); args.Player.SendInfoMessage($"{Tag} Double check if there are multiple accounts with the same ID."); args.Player.SendInfoMessage($"{Tag} You can try syncing the server with the database by using the reload command."); } catch (BankLogException ex) { TShock.Log.Error(ex.ToString()); } } } return; #endregion #region H (Help -.-) case "-h": case "help": if (!args.Player.Group.HasPermission(Permissions.Help)) { args.Player.SendErrorMessage("You do not have access to this command."); return; } string helpString = match.Groups["Object"].Value; var helpLines = new List <string>(); if (String.IsNullOrWhiteSpace(helpString) || helpString.ToLowerInvariant() == "all") { helpLines.Add($"{TShock.Utils.ColorTag("CurrencyShop", new Color(90, 138, 211))} v{Instance.Version}" + $" by {TShock.Utils.ColorTag(Instance.Author, new Color(0, 127, 255))}"); helpLines.Add($"Available commands: {specifier}cshop <switch> [item | kit] [number]"); helpLines.Add("Switches: -b (buy) -k (buy kits) -h [cmd] (help) -s (search) -r (reload)"); helpLines.Add($"Type {specifier}shop -h [switch] for more."); if (args.Player.RealPlayer) { // This color looks like this: http://www.colorcombos.com/images/colors/993366.png helpLines.ForEach(l => args.Player.SendMessage(l, new Color(153, 51, 102))); } else { // Colors break when sending to console :( helpLines.ForEach(l => args.Player.SendInfoMessage(l)); } } else { // Now that I'm sure helpString is not null, let me lower it, for god's sake... helpString = helpString.ToLowerInvariant(); if (helpString.StartsWith("b")) { // Doco buy command helpLines.Add($"{Tag} Syntax: {specifier}shop -b[uy] <item name or id> [amount]"); helpLines.Add($"{Tag} Purchase an item from the shop inventory."); helpLines.Add($"{Tag} If 'amount' is given, it will be multiplied by the item's stack."); helpLines.Add($"{Tag} Type '{specifier}shop -b list' to get a list of all available items."); } else if (helpString.StartsWith("c") || helpString.StartsWith("k")) { // Doco kits command helpLines.Add($"{Tag} Syntax: {specifier}shop -k[it] <list | kit name> [confirm:1]"); helpLines.Add($"{Tag} Get information about one of the available item kits."); helpLines.Add($"{Tag} To buy a kit, type '{specifier}shop -k <kit name> 1' (you can only purchase one kit at once)."); helpLines.Add($"{Tag} Type '{specifier}shop -k list' to get a list of all available kits."); } else if (helpString.StartsWith("s")) { // Doco search command helpLines.Add($"{Tag} Syntax: {specifier}shop -s[earch] [item: | kit:] <text>"); helpLines.Add($"{Tag} Search for an item or kit which name starts with 'text'."); helpLines.Add($"{Tag} If 'text' matches one item, this will also search for any kits containing said item."); helpLines.Add($"{Tag} You can use 'item:' or 'kit:' before 'text' to search only for items or kits, respectively."); } else if (helpString.StartsWith("r")) { //Doco reload command helpLines.Add($"{Tag} Syntax: {specifier}shop -r[eload] <config | inventory>"); helpLines.Add($"{Tag} Reloads CurrencyBank's config file."); } else { args.Player.SendErrorMessage($"{Tag} Invalid switch! Type '{specifier}shop -h all' for a list of switches."); return; } // Finally, send the help data to the player helpLines.ForEach(l => args.Player.SendInfoMessage(l)); } return; #endregion #region K (Purchase a kit) case "-c": case "-k": case "kit": case "kits": if (!args.Player.Group.HasPermission(Permissions.KitsBuy)) { args.Player.SendErrorMessage("You do not have access to this command."); return; } string kitName = match.Groups["Object"].Value; if (String.IsNullOrWhiteSpace(kitName)) { args.Player.SendErrorMessage($"{Tag} Invalid syntax! Proper syntax: {specifier}shop -k <kit name> [confirm:1]"); return; } if (kitName.Equals("list", StringComparison.OrdinalIgnoreCase)) { IEnumerable <string> dataToPaginate = PaginationTools.BuildLinesFromTerms(Manager.GetKits().Select(k => k.name)); digit = 1; if (!String.IsNullOrWhiteSpace(match.Groups["Digit"].Value) && !Int32.TryParse(match.Groups["Digit"].Value, out digit)) { args.Player.SendErrorMessage($"{Tag} Invalid page number!"); return; } PaginationTools.SendPage(args.Player, digit, dataToPaginate.ToList(), new PaginationTools.Settings() { HeaderFormat = $"{Tag} Kits ({{0}}/{{1}}):", FooterFormat = $"{Tag} Type {specifier}shop -k list {{0}} for more.", NothingToDisplayString = $"{Tag} No kits available." }); return; } List <Kit> kitMatches = await Manager.GetMatchingKits(kitName); if (kitMatches.Count != 1) { args.Player.SendKitMatches(kitMatches); } else { kit = kitMatches[0]; if (String.IsNullOrWhiteSpace(match.Groups["Digit"].Value) || !Int32.TryParse(match.Groups["Digit"].Value, out digit) || digit < 1) { // Inform the player about the kit's contents args.Player.SendSuccessMessage($"{Tag} You have selected the kit '{kit.name}'."); args.Player.SendSuccessMessage($"{Tag} Kit's contents:"); string prefix = ""; foreach (SItem i in kit.items) { prefix = i.prefix > 0 ? i.GetPrefixName() + " " : ""; args.Player.SendInfoMessage($"{Tag} - {prefix}{i.GetName()} x{i.stack}"); } args.Player.SendInfoMessage($"{Tag} Type '{specifier}shop -k {kit.name} 1' to confirm your purchase."); } else if ((account = await BankMain.Bank.GetAsync(args.Player.User?.Name)) == null) { args.Player.SendErrorMessage($"{Tag} You must have a bank account to use this command."); } else if (account.Balance < kit.cost) { args.Player.SendErrorMessage($"{Tag} You're {BankMain.FormatMoney(kit.cost - account.Balance)} short!"); } else if (args.Player.GetEmptyInventorySlots().Count < kit.items.Count) { args.Player.SendErrorMessage($"{Tag} You must have {kit.items.Count} free inventory slots to purchase this kit."); } else { try { await BankMain.Bank.ChangeByAsync(account.AccountName, -kit.cost); BankMain.Log.KitPurchase(account, kit); foreach (SItem i in kit.items) { if (CShop.Config.UseGiveItemSSC) { args.Player.GiveItemSSC(i.netID, i.stack, i.prefix); } else { args.Player.GiveItem(i.netID, i.GetName(), 2, 3, i.stack, i.prefix); } } args.Player.SendSuccessMessage($"{Tag} Bought the '{kit.name}' kit for {BankMain.FormatMoney(kit.cost)}."); } catch (NullReferenceException) { args.Player.SendErrorMessage($"{Tag} Invalid bank account!"); } catch (InvalidOperationException) { args.Player.SendErrorMessage($"{Tag} Error performing transaction. Possible database corruption."); args.Player.SendInfoMessage($"{Tag} Double check if there are multiple accounts with the same ID."); args.Player.SendInfoMessage($"{Tag} You can try syncing the server with the database by using the reload command."); } catch (BankLogException ex) { TShock.Log.Error(ex.ToString()); } } } return; #endregion #region R (Reload config / inventory) case "-r": case "reload": if (!args.Player.Group.HasPermission(Permissions.Reload)) { args.Player.SendErrorMessage("You do not have access to this command."); return; } string reloadType = match.Groups["Object"].Value; try { if (String.IsNullOrWhiteSpace(reloadType) || reloadType.ToLower() == "all") { CShop.Config = Config.Read(Path.Combine(TShock.SavePath, "CurrencyBank", "Shop.json")); Manager.Reload(); args.Player.SendSuccessMessage($"{Tag} Reloaded config and inventory!"); } else if (reloadType.ToLower() == "config") { CShop.Config = Config.Read(Path.Combine(TShock.SavePath, "CurrencyBank", "Shop.json")); args.Player.SendSuccessMessage($"{Tag} Reloaded config!"); } else if (reloadType.ToLower().StartsWith("inv")) { Manager.Reload(); args.Player.SendSuccessMessage($"{Tag} Reloaded shop inventory!"); } else { args.Player.SendErrorMessage($"{Tag} Invalid reload type! Available types: config, inventory"); } } catch (Exception ex) { args.Player.SendErrorMessage($"{Tag} Something went wrong while reloading data. Check logs for details."); TShock.Log.Error(ex.ToString()); } return; #endregion #region S (Search for items and categories) case "-s": case "search": if (!args.Player.Group.HasPermission(Permissions.Search)) { args.Player.SendErrorMessage("You do not have access to this command."); return; } string searchString = match.Groups["Object"].Value; if (String.IsNullOrWhiteSpace(searchString)) { args.Player.SendErrorMessage($"{Tag} Invalid syntax! Proper syntax: {specifier}shop -s [search term...]"); return; } /* * Group 1 - Whether the user is looking for an item (term) * Group 2 - Whether the user is looking for a kit (term) * Group 3 - The item/kit to look for (search) */ Regex searchRegex = new Regex(@"^(?:(?<IsItem>i(?:tem)?:)|(?<IsKit>k(?:it)?:))? *(?<Object>.+)$"); Match searchMatch = searchRegex.Match(searchString); bool itemOnly = !String.IsNullOrWhiteSpace(searchMatch.Groups["IsItem"].Value); bool kitOnly = !String.IsNullOrWhiteSpace(searchMatch.Groups["IsKit"].Value); string searchName = searchMatch.Groups["Object"].Value; if (itemOnly) { // List all items on sale starting with the search string args.Player.SendInfoMessage($"{Tag} Searching for all items starting with '{searchName}'..."); try { args.Player.SendItemMatches(await Manager.GetMatchingItems(searchName)); } catch (InvalidItemException) { args.Player.SendSuccessMessage($"{Tag} No items matched."); } } else if (kitOnly) { // List all kits on sale containing an item List <Item> items = TShock.Utils.GetItemByName(searchName); if (items.Count == 1) { // Display all kits containing this item args.Player.SendInfoMessage($"{Tag} Searching for all kits containing the item '{items[0].Name}'..."); args.Player.SendKitMatches(await Manager.KitContains(items[0].netID)); } else { // List all kits on sale starting with the search string args.Player.SendInfoMessage($"{Tag} Searching for all kits starting with '{searchName}'..."); args.Player.SendKitMatches(await Manager.GetMatchingKits(searchName)); } } else { // List everything on sale starting with the search string args.Player.SendInfoMessage($"{Tag} Searching for anything in stock starting with '{searchName}'..."); try { args.Player.SendItemMatches(await Manager.GetMatchingItems(searchName)); } catch (InvalidItemException) { args.Player.SendSuccessMessage($"{Tag} No items matched."); } List <Item> items = TShock.Utils.GetItemByName(searchName); if (items.Count == 1) { args.Player.SendKitMatches(await Manager.KitContains(items[0].netID)); } else { args.Player.SendKitMatches(await Manager.GetMatchingKits(searchName)); } } return; #endregion default: args.Player.SendErrorMessage($"{Tag} Invalid switch!"); args.Player.SendErrorMessage($"{Tag} Valid switches: -b (buy) -k (buy kits) -h [cmd] (help) -s (search) -r (reload)"); return; } } }
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) { args.Player.SendMultipleMatchError(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; } } }
public void regionCommand(CommandArgs args) { switch (args.Parameters.ElementAtOrDefault(0)) { case "add": { if (args.Parameters.Count < 4) { args.Player.SendErrorMessage("Invalid syntax! Correct syntax: /smartregion add <region name> <cooldown> <command or file>"); } else { double cooldown = 0; if (!double.TryParse(args.Parameters[2], out cooldown)) { args.Player.SendErrorMessage("Invalid syntax! Correct syntax: /smartregion add <region name> <cooldown> <command or file>"); return; } string command = string.Join(" ", args.Parameters.GetRange(3, args.Parameters.Count - 3)); if (!TShock.Regions.Regions.Exists(x => x.Name == args.Parameters[1])) { args.Player.SendErrorMessage("The region {0} doesn't exist!", args.Parameters[1]); IEnumerable <string> regionNames = from region_ in TShock.Regions.Regions where region_.WorldID == Main.worldID.ToString() select region_.Name; PaginationTools.SendPage(args.Player, 1, PaginationTools.BuildLinesFromTerms(regionNames), new PaginationTools.Settings { HeaderFormat = "Regions ({0}/{1}):", FooterFormat = "Type {0}region list {{0}} for more.".SFormat(Commands.Specifier), NothingToDisplayString = "There are currently no regions defined." }); } else { string cmdName = ""; for (int i = 1; i < command.Length && command[i] != ' '; i++) { cmdName += command[i]; } Command cmd = Commands.ChatCommands.FirstOrDefault(c => c.HasAlias(cmdName)); if (cmd != null && !cmd.CanRun(args.Player)) { args.Player.SendErrorMessage("You cannot create a smart region with a command you don't have permission to use yourself!"); return; } if (cmd != null && !cmd.AllowServer) { args.Player.SendErrorMessage("Your command must be usable by the server!"); return; } var existingRegion = regions.FirstOrDefault(x => x.region == args.Parameters[1]); var newRegion = new SmartRegion { region = args.Parameters[1], cooldown = cooldown, command = command }; if (existingRegion != null) { players[args.Player.Index].regionToReplace = newRegion; args.Player.SendErrorMessage("The smart region {0} already exists! Type /replace to replace it.", args.Parameters[1]); } else { regions.Add(newRegion); args.Player.SendSuccessMessage("Smart region added!"); saveConfig(); } } } } break; case "remove": { if (args.Parameters.Count != 2) { args.Player.SendErrorMessage("Invalid syntax! Correct syntax: /smartregion remove <regionname>"); } else { var region = regions.FirstOrDefault(x => x.region == args.Parameters[1]); if (region == null) { args.Player.SendErrorMessage("No such smart region exists!"); } else { regions.Remove(region); args.Player.SendSuccessMessage("The smart region {0} was removed!", args.Parameters[1]); saveConfig(); } } } break; case "check": { if (args.Parameters.Count != 2) { args.Player.SendErrorMessage("Invalid syntax! Correct syntax: /smartregion check <regionname>"); } else { var region = regions.FirstOrDefault(x => x.region == args.Parameters[1]); if (region == null) { args.Player.SendInfoMessage("That region doesn't have a command associated with it."); } else { string file = Path.Combine(TShock.SavePath, "SmartRegions", region.command), commands; if (File.Exists(file)) { commands = "s:\n" + File.ReadAllText(file); } else { commands = ":\n" + region.command; } args.Player.SendInfoMessage("The region {0} has a cooldown of {1} second{2} and uses the command{3}", args.Parameters[1], region.cooldown, region.cooldown == 1.0 ? "" : "s", commands); } } } break; case "list": { args.Player.SendInfoMessage("Smart regions ({0}):", regions.Count); int pageNumber = 1; if (args.Parameters.Count > 1) { int.TryParse(args.Parameters[1], out pageNumber); } PaginationTools.SendPage( args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(regions.ConvertAll(x => x.region)), new PaginationTools.Settings { IncludeHeader = false, FooterFormat = string.Format("Type {0}smartregion list {{0}} for more.", Commands.Specifier) } ); } break; default: { args.Player.SendInfoMessage("/smartregion sub-commands:\nadd <region name> <cooldown> <command or file>\nremove <region name>\ncheck <region name>\nlist"); } break; } }
public static void Help(CommandArgs args) { if (args.Parameters.Count > 1) { args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}help <command/page>", TShock.Config.CommandSpecifier); return; } int pageNumber; if (args.Parameters.Count == 0 || int.TryParse(args.Parameters[0], out pageNumber)) { if (!PaginationTools.TryParsePageNumber(args.Parameters, 0, args.Player, out pageNumber)) { return; } IEnumerable <string> cmdNames = from cmd in Commands.ChatCommands where cmd.CanRun(args.Player) && (!args.Player.GetPlayerInfo()?.Permissions.Negated(cmd.Permissions.Any() ? cmd.Permissions[0] : null) ?? true) || (args.Player.GetPlayerInfo() != null && args.Player.GetPlayerInfo().HasPermission(cmd.Permissions.Any() ? cmd.Permissions[0] : null) && (cmd.Name != "auth" || TShock.AuthToken != 0)) orderby cmd.Name select TShock.Config.CommandSpecifier + cmd.Name; PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(cmdNames), new PaginationTools.Settings { HeaderFormat = "Commands ({0}/{1}):", FooterFormat = "Type {0}help {{0}} for more.".SFormat(TShock.Config.CommandSpecifier) }); } else { string commandName = args.Parameters[0].ToLower(); if (commandName.StartsWith(TShock.Config.CommandSpecifier)) { commandName = commandName.Substring(1); } Command command = Commands.ChatCommands.Find(c => c.Names.Contains(commandName)); if (command == null) { args.Player.SendErrorMessage("Invalid command."); return; } if (!command.CanRun(args.Player) && !args.Player.HasPermission(command.Permissions[0])) { args.Player.SendErrorMessage("You do not have access to this command."); return; } args.Player.SendSuccessMessage("{0}{1} help: ", TShock.Config.CommandSpecifier, command.Name); if (command.HelpDesc == null) { args.Player.SendInfoMessage(command.HelpText); return; } foreach (string line in command.HelpDesc) { args.Player.SendInfoMessage(line); } } }