protected virtual void Dispose(bool disposing) { if (disposing == true) { TShockAPI.Command bankCommand = TShockAPI.Commands.ChatCommands.FirstOrDefault(i => i.Name == "bank" && i.CommandDelegate == Chat_BankCommand); if (bankCommand != null) { TShockAPI.Commands.ChatCommands.Remove(bankCommand); } } }
/// <summary> /// Invokes a command ignoring permissions /// </summary> public static bool RunWithoutPermissions(this TShockAPI.Command cmd, string msg, TShockAPI.TSPlayer ply, List <string> parms) { try { TShockAPI.CommandDelegate cmdDelegateRef = cmd.CommandDelegate; cmdDelegateRef(new TShockAPI.CommandArgs(msg, ply, parms)); } catch (Exception e) { ply.SendErrorMessage("Command failed, check logs for more details."); TShock.Log.Error(e.ToString()); } return(true); }
public void ParseJSCommands() { lock (jsAliases) { foreach (JScriptAliasCommand jCmd in jsAliases) { TShockAPI.Command newCommand = new TShockAPI.Command(jCmd.Permissions, ChatCommand_AliasExecuted, new string[] { jCmd.CommandAlias, "jistalias." + jCmd.CommandAlias }) { AllowServer = true }; TShockAPI.Commands.ChatCommands.Add(newCommand); } } }
protected void ParseCommands() { TShockAPI.Commands.ChatCommands.RemoveAll(i => i.Names.Count(x => x.StartsWith("cmdalias.")) > 0); foreach (AliasCommand aliasCmd in Configuration.CommandAliases) { //The command delegate points to the same function for all aliases, which will generically handle all of them. TShockAPI.Command newCommand = new TShockAPI.Command(aliasCmd.Permissions, ChatCommand_AliasExecuted, new string[] { aliasCmd.CommandAlias, "cmdalias." + aliasCmd.CommandAlias }) { AllowServer = true }; TShockAPI.Commands.ChatCommands.Add(newCommand); } }
/// <summary> /// Creates a javascript alias pointing to a javascript function. /// </summary> internal void CreateAlias(JScriptAliasCommand alias, bool allowServer = true) { TShockAPI.Command newCommand = new TShockAPI.Command(alias.Permissions, ChatCommand_AliasExecuted, new string[] { alias.CommandAlias, "jistalias." + alias.CommandAlias }) { AllowServer = allowServer }; newCommand.DoLog = alias.Silent == false; TShockAPI.Commands.ChatCommands.RemoveAll(i => i.Names.Contains("jistalias." + alias.CommandAlias)); TShockAPI.Commands.ChatCommands.Add(newCommand); jsAliases.RemoveAll(i => i.CommandAlias == alias.CommandAlias); jsAliases.Add(alias); }
protected override void AddCommand(CommandDelegate <TSPlayer> command, string[] names) { CommandDelegate commandDelegate = async(CommandArgs args) => { try { int firstSpace = args.Message.IndexOf(' '); // Get the command text without the command name string rawCommandArguments = firstSpace == -1 ? "" : args.Message.Substring(firstSpace + 1); await command.Invoke(args.Player, rawCommandArguments); } // TShock's command system does its own exception handling, so we have to catch error messages here. catch (CommandParsingException e) { args.Player.SendErrorMessage(e.Message); } catch (CommandExecutionException e) { args.Player.SendErrorMessage(e.Message); } catch (Exception e) { TShock.Log.Error(e.ToString()); args.Player.SendErrorMessage(Context.TextOptions.CommandThrewException); } }; var helpText = command.GetCustomAttribute <HelpText>(); var permissions = command.GetCustomAttribute <CommandPermissions>(); var allowServer = command.GetCustomAttribute <AllowServer>(); var doLog = command.GetCustomAttribute <DoLog>(); var tshockCommand = new TShockAPI.Command(permissions != null ? permissions.Permissions.ToList() : new List <string>(), commandDelegate, names) { HelpText = $"{(helpText != null ? helpText.Documentation : "")} Syntax: {command.SyntaxDocumentation(TSPlayer.Server)}", AllowServer = allowServer != null ? allowServer.Allow : true, DoLog = doLog != null ? doLog.Log : true }; Commands.ChatCommands.Add(tshockCommand); }
public override void Initialize() { if (!File.Exists(SavePath)) { AddDefaultsToConfig(); config.Write(SavePath); } config.Read(SavePath); foreach (EmoteRegex regex in config.Emotes) { Regexes.Add(new Regex(regex.ToString()), regex); } _emoteCmd = new Command("", EmoteCallback, "emotes") { HelpDesc = config.HelpText }; ServerApi.Hooks.ServerChat.Register(this, OnChat, 6); TShockAPI.Hooks.GeneralHooks.ReloadEvent += OnReload; Commands.ChatCommands.Add(_emoteCmd); }
public override void Initialize() { Command viewCommand = new Command(new List<string>(new string[] { "regionvision.regionview", "regionview" }), commandView, new string[] { "regionview", "rv" }); viewCommand.AllowServer = false; viewCommand.HelpDesc = new string[] { "Usage: /rv <region name>", "Shows you the boundary of the specified region" }; Commands.ChatCommands.Add(viewCommand); Command clearCommand = new Command(new List<string>(new string[] { "regionvision.regionview", "regionview" }), commandClear, new string[] { "regionclear", "rc" }); clearCommand.AllowServer = false; clearCommand.HelpDesc = new string[] { "Usage: /rc", "Removes all region borders from your view" }; Commands.ChatCommands.Add(clearCommand); Command viewNearbyCommand = new Command(new List<string>(new string[] { "regionvision.regionviewnear", "regionviewnear" }), commandViewNearby, new string[] { "regionviewnear", "rvn" }); viewNearbyCommand.AllowServer = false; viewNearbyCommand.HelpDesc = new string[] { "Usage: /rvn", "Turns on or off automatic showing of regions near you" }; Commands.ChatCommands.Add(viewNearbyCommand); GetDataHandlers.TileEdit += TShockAPI.HandlerList<GetDataHandlers.TileEditEventArgs>.Create(OnTileEdit, HandlerPriority.High, false); TShockAPI.Hooks.RegionHooks.RegionCreated += RegionHooks_RegionCreated; TShockAPI.Hooks.RegionHooks.RegionDeleted += RegionHooks_RegionDeleted; ServerApi.Hooks.ServerJoin.Register(this, onPlayerJoin); ServerApi.Hooks.ServerLeave.Register(this, onPlayerLeave); TShockAPI.Hooks.PlayerHooks.PlayerCommand += onPlayerCommand; refreshTimer.AutoReset = false; refreshTimer.Elapsed += refreshTimer_Elapsed; }
/// <summary> /// Invokes a command delegate. /// </summary> /// <param name="command">The command.</param> /// <param name="msg">The command text.</param> /// <param name="tsPlayer">The command issuer.</param> /// <param name="args">The parsed text.</param> /// <returns>True or false.</returns> private static bool RunCommand(Command command, string msg, TSPlayer tsPlayer, List<string> args) { try { CommandDelegate commandD = command.CommandDelegate; commandD(new CommandArgs(msg, tsPlayer, args)); } catch (Exception ex) { tsPlayer.SendErrorMessage("Command failed, check logs for more details."); TShock.Log.Error(ex.ToString()); } return true; }
protected Command RegisterCommand( string[] names, CommandDelegate commandExec, Func<CommandArgs,bool> commandHelpExec = null, string requiredPermission = null, bool allowServer = true, bool doLog = true ) { Contract.Requires<ObjectDisposedException>(!this.IsDisposed); Contract.Requires<ArgumentNullException>(names != null); Contract.Requires<ArgumentNullException>(commandExec != null); CommandDelegate actualCommandExec; if (commandHelpExec != null) { actualCommandExec = (args) => { if (args.ContainsParameter("help", StringComparison.InvariantCultureIgnoreCase)) if (commandHelpExec(args)) return; commandExec(args); }; } else { actualCommandExec = commandExec; } Command command; if (requiredPermission != null) command = new Command(requiredPermission, actualCommandExec, names); else command = new Command(actualCommandExec, names); TShockAPI.Commands.ChatCommands.Add(command); command.AllowServer = allowServer; command.DoLog = doLog; return command; }
protected void DeregisterCommand(Command tshockCommand) { Contract.Requires<ArgumentNullException>(tshockCommand != null); if (!TShockAPI.Commands.ChatCommands.Contains(tshockCommand)) throw new InvalidOperationException("Command is not registered."); }
private void initDiscordCommands() { // Note: ParameterType.Unparsed catches all remaining text as a single optional parameter Client.GetService <CommandService>().CreateCommand("do") .Alias("execute", "run") .Description("Executes a TShock command.") .Parameter("command", ParameterType.Required) .Parameter("parameters", ParameterType.Unparsed) .Do(async e => { BridgeUser player = await Client.LoadUser(e.User); if (!player.IsLoggedIn) { await e.User.SendMessage("You must be logged in to use TShock commands.\n" + $"Message me with `{Config.BotPrefix}login <username> <password>` using your TShock credentials to begin."); return; } // Blacklist commands which must be run through their discord command counterparts var blacklist = new List <string> { "login", "logout" }; if (blacklist.Contains(e.GetArg("command"))) { await e.Channel.SendMessage($"This is a discord command, so use `{Config.BotPrefix}{e.GetArg("command")}` (without the `{Config.BotPrefix}do` prefix) instead."); return; } TSCommand command = Commands.ChatCommands.Find(c => !c.Names.Contains("login") && !c.Names.Contains("logout") && c.Names.Contains(e.GetArg("command"))); if (command == null && !player.AwaitingResponse.ContainsKey(e.GetArg("command"))) { await e.Channel.SendMessage($"`{e.GetArg("command")}` is not a TShock command."); return; } var sb = new StringBuilder(); if (!e.GetArg("command").StartsWith(Commands.Specifier) && !e.GetArg("command").StartsWith(Commands.Specifier)) { sb.Append(Commands.Specifier); } // Temporarily set their command channel so that messages end in the right place player.CommandChannel = e.Channel; // Disable auto flush to reduce consumption of the discord API for multiple messages player.AutoFlush = false; if (Commands.HandleCommand(player, sb.Append(e.GetArg("command")).Append(' ').Append(e.GetArg("parameters")).ToString())) { await player.FlushMessages(); } else { await e.Channel.SendMessage("Command failed, check logs for details."); } player.AutoFlush = true; player.CommandChannel = null; }); #region Account Commands Client.GetService <CommandService>().CreateCommand("login") .Description("Log in to a TShock user account to use its permissions when using the `do` command.") .Parameter("username", ParameterType.Required) .Parameter("password", ParameterType.Required) .Do(async e => { BridgeUser player = await Client.LoadUser(e.User); if (e.Channel != e.User.PrivateChannel) { // Delete the message await e.Message.Delete(); } if (player.IsLoggedIn) { await e.Channel.SendMessage($"You are already logged in. Use `{Config.BotPrefix}logout` first if you wish to log in to a different account."); return; } string username = e.GetArg("username"); string password = e.GetArg("password"); TShockAPI.DB.User user = TShock.Users.GetUserByName(username); if (user == null) { await e.Channel.SendMessage("A user by that name does not exist."); } else if (!user.VerifyPassword(password)) { await e.Channel.SendMessage("Invalid password!"); } else { await Logins.SetData(e.User, user); player = await Logins.Authenticate(e.User.Id); await e.Channel.SendMessage($"Authenticated as {player.Name} successfully."); } }); Client.GetService <CommandService>().CreateCommand("logout") .Description("Log out of your current TShock user account.") .Do(async e => { BridgeUser player = await Client.LoadUser(e.User); if (!player.IsLoggedIn) { await e.Channel.SendMessage("You are not logged in."); return; } await Logins.RemoveData(e.User.Id); await Logins.Authenticate(e.User.Id); await e.Channel.SendMessage("You have been successfully logged out of your account."); }); #endregion #region Administrative Commands Client.GetService <CommandService>().CreateCommand("echo") .Alias("bc", "say") .Description("Make this bot say something.") .Parameter("text", ParameterType.Unparsed) .AddCheck((c, u, ch) => !ch.IsPrivate) .AddCheck((cmd, user, channel) => user.ServerPermissions.Administrator) .Do(async e => await e.Channel.SendMessage(e.GetArg("text") ?? "Hi!")); Client.GetService <CommandService>().CreateCommand("addbot") .Description("Add another connected Discord Bridge bot to the list of ServerBots for multi-server broadcasting.") .Parameter("name", ParameterType.Required) .AddCheck((cmd, user, channel) => user.ServerPermissions.Administrator) .Do(async e => { User botUser = Client.CurrentServer.FindUsers(e.GetArg("name"), true).FirstOrDefault(); if (botUser == null && (botUser = Client.CurrentServer.Users.FirstOrDefault(u => u.Nickname.Equals(e.GetArg("name"), StringComparison.OrdinalIgnoreCase))) == null) { await e.Channel.SendMessage($"User `{e.GetArg("name")}` is not on this server."); return; } if (!botUser.IsBot) { await e.Channel.SendMessage($"`{e.GetArg("name")}` is not a bot."); return; } string mention = String.IsNullOrWhiteSpace(botUser.Nickname) ? botUser.Mention : botUser.NicknameMention; if (Config.AddBot(botUser.Id)) { await e.Channel.SendMessage($"Added {mention} to the broadcasting list."); } else { await e.Channel.SendMessage($"{mention} is already on the broadcast list."); } }); #endregion }