### Register Custom Command (JavaScript) Source: https://github.com/hosttale-project/simplescripting/blob/main/DESCRIPTION.md Example of registering a custom command named 'greet' using the SimpleScripting API. It takes a player name as an argument and sends a greeting message. ```javascript Commands.register() .setName('greet') .setDescription('Greet a player') .addRequiredStringArg('player', 'Player to greet') .setHandler(function(ctx) { var target = Players.getByNameFuzzy(ctx.getArgAsString('player')); if (target) { MessageHelper.send(target, Colors.GOLD + 'Hello from ' + Players.getUsername(ctx.getPlayer()) + '!'); ctx.sendMessage(Colors.GREEN + 'Greeting sent!'); } else { ctx.sendMessage(Colors.RED + 'Player not found!'); } }); ``` -------------------------------- ### Listen to Player Join Event (JavaScript) Source: https://github.com/hosttale-project/simplescripting/blob/main/DESCRIPTION.md An example of listening to the 'playerJoin' event. When a player joins, it retrieves player information and broadcasts a join message. ```javascript Events.on('playerJoin', function(event) { var player = Players.getByUuid(event.playerUuid); MessageHelper.broadcast(Colors.YELLOW + Players.getUsername(player) + ' has joined the server!'); }); ``` -------------------------------- ### Utils Library Examples (JavaScript) Source: https://github.com/hosttale-project/simplescripting/blob/main/README.md Demonstrates various utility functions available in the Utils library for common tasks. This includes retrieving player objects from context, formatting time and positions, managing cooldowns with a tracker, and implementing teleportation with a warmup period. ```javascript // Get player from command context var player = Utils.getPlayerFromContext(ctx); // Format time var text = Utils.formatTime(3661); // "1h 1m 1s" // Format position var pos = Utils.formatPosition(100.5, 64, -200.3); // "100.5, 64, -200.3" // Create cooldown tracker var cooldowns = Utils.createCooldownTracker('db_file', 'feature_name'); cooldowns.setCooldown(playerId, 'action'); if (cooldowns.isOnCooldown(playerId, 'action', 60)) { var remaining = cooldowns.getRemainingSeconds(playerId, 'action', 60); } // Teleport with warmup Utils.teleportWithWarmup(player, location, warmupSeconds, 'destination name', callback); ``` -------------------------------- ### Rank-Based Configuration (JavaScript) Source: https://github.com/hosttale-project/simplescripting/blob/main/DESCRIPTION.md Allows defining custom settings for different player ranks, overriding default configurations. For example, 'vip' and 'admin' ranks have different home limits. ```javascript var RANKS = { default: { // Uses default settings }, vip: { homes: { maxHomes: 5, cooldownSeconds: 3 } }, admin: { homes: { maxHomes: 10, cooldownSeconds: 0 } } }; ``` -------------------------------- ### JavaScript Custom Warp System Example Source: https://context7.com/hosttale-project/simplescripting/llms.txt A comprehensive JavaScript script that implements a custom warp system. It allows administrators to set warps and all players to use them, featuring commands for setting, using, and listing warps, along with permission checks, cooldowns, and warmups. ```javascript /** * Custom Warp System * Allows admins to set warps and all players to use them. */ (function() { 'use strict'; var DB_FILE = 'warps'; var cooldowns = Utils.createCooldownTracker('cooldowns', 'warp'); // Get all warps function getWarps() { var data = DB.get(DB_FILE, 'all_warps'); return data ? JSON.parse(data) : {}; } // Save all warps function saveWarps(warps) { DB.save(DB_FILE, 'all_warps', JSON.stringify(warps)); } // /setwarp - Admin only Commands.register() .setName('setwarp') .setDescription('Create a server warp') .addRequiredStringArg('name', 'Warp name') .setHandler(function(ctx) { var player = Utils.getPlayerFromContext(ctx); if (!player) return; if (!Permissions.has(player, 'warps.admin')) { ctx.sendMessage('&cYou need warps.admin permission.'); return; } var warpName = ctx.getArgAsString('name').toLowerCase(); var location = Players.getFullLocation(player); if (!location) { ctx.sendMessage('&cCould not get your location.'); return; } var warps = getWarps(); warps[warpName] = { x: location.x, y: location.y, z: location.z, pitch: location.pitch, yaw: location.yaw, worldName: location.worldName, createdBy: Players.getUsername(player), createdAt: java.lang.System.currentTimeMillis() }; saveWarps(warps); ctx.sendMessage(Colors.GREEN + 'Warp \'' + warpName + '\' created!'); Logger.info(Players.getUsername(player) + ' created warp: ' + warpName); }); // /warp - All players Commands.register() .setName('warp') .setDescription('Teleport to a server warp') .addRequiredStringArg('name', 'Warp name') .setHandler(function(ctx) { var player = Utils.getPlayerFromContext(ctx); if (!player) return; var playerId = Players.getUuidString(player); var warpName = ctx.getArgAsString('name').toLowerCase(); var warps = getWarps(); if (!warps[warpName]) { ctx.sendMessage('&cWarp \'' + warpName + '\' not found.'); ctx.sendMessage('&7Available warps: ' + Object.keys(warps).join(', ')); return; } var cooldownSeconds = Config.getPlayerSetting(playerId, 'warps.cooldownSeconds'); if (cooldowns.isOnCooldown(playerId, 'use', cooldownSeconds)) { var remaining = cooldowns.getRemainingSeconds(playerId, 'use', cooldownSeconds); ctx.sendMessage('&eWait ' + remaining + ' seconds.'); return; } cooldowns.setCooldown(playerId, 'use'); var warmupSeconds = Config.getPlayerSetting(playerId, 'warps.warmupSeconds'); Utils.teleportWithWarmup(player, warps[warpName], warmupSeconds, warpName, function() { Logger.info(Players.getUsername(player) + ' warped to: ' + warpName); }); }); // /warps - List all warps Commands.register() .setName('warps') .setDescription('List all server warps') .setHandler(function(ctx) { var warps = getWarps(); var names = Object.keys(warps); if (names.length === 0) { ctx.sendMessage('&eNo warps available.'); return; } ctx.sendMessage(Colors.GOLD + '=== Server Warps (' + names.length + ') ==='); for (var i = 0; i < names.length; i++) { var name = names[i]; var warp = warps[name]; ctx.sendMessage('&f ' + name + ' &7- ' + Utils.formatPosition(warp.x, warp.y, warp.z)); } }); Logger.info('Warp system loaded!'); })(); ``` -------------------------------- ### Basic Custom Script Template (JavaScript) Source: https://github.com/hosttale-project/simplescripting/blob/main/README.md Provides a fundamental template for creating custom scripts in JavaScript. It includes registering commands, handling command execution, and listening for player events. This template serves as a starting point for adding new functionalities to the server. ```javascript /** * My Custom Script * Description of what it does. */ (function() { 'use strict'; // Register a command Commands.register() .setName('mycommand') .setDescription('Does something cool') .setHandler(function(ctx) { var player = Utils.getPlayerFromContext(ctx); if (!player) return; ctx.sendMessage(Colors.GREEN + 'Hello, ' + Players.getUsername(player) + '!'); }); // Listen to events Events.on('playerJoin', function(event) { var player = Players.getByUuid(event.playerUuid); if (player) { MessageHelper.send(player, Colors.GOLD + 'Welcome to the server!'); } }); Logger.info('My custom script loaded!'); })(); ``` -------------------------------- ### Use Simple Key-Value Database with DB API Source: https://github.com/hosttale-project/simplescripting/blob/main/README.md A simple key-value database for storing and retrieving data. Supports saving, getting, deleting, and checking for the existence of keys. Can store stringified JSON data. Dependencies: None. ```javascript // Save data DB.save('myfile', 'key', 'value'); // Get data var value = DB.get('myfile', 'key'); // Delete data DB.delete('myfile', 'key'); // Check existence var exists = DB.has('myfile', 'key'); // Example: Save JSON data var homes = { home1: { x: 100, y: 64, z: 200 } }; DB.save('player_homes', playerId, JSON.stringify(homes)); // Load JSON data var data = DB.get('player_homes', playerId); var homes = data ? JSON.parse(data) : {}; ``` -------------------------------- ### Send and Broadcast Messages with MessageHelper API Source: https://context7.com/hosttale-project/simplescripting/llms.txt The MessageHelper API simplifies sending messages to individual players and broadcasting to all online players. It supports Minecraft color codes for styled text. Messages can be sent directly to a player object or through a command context. An example demonstrates a formatted welcome message for new players and a broadcast announcement. ```javascript // Send message to a specific player MessageHelper.send(player, 'Hello, world!'); MessageHelper.send(player, '&aGreen text with color codes'); MessageHelper.send(player, Colors.GOLD + 'Using Colors constants'); // Broadcast to all online players MessageHelper.broadcast('Server announcement!'); MessageHelper.broadcast(Colors.RED + Colors.BOLD + 'Important notice!'); // Send from command context ctx.sendMessage('&aCommand executed successfully!'); ctx.sendMessage(Colors.RED + 'Error: Something went wrong'); // Example: Formatted welcome message Events.on('playerJoin', function(event) { var player = Players.getByUuid(event.uuid); if (player) { MessageHelper.send(player, ''); MessageHelper.send(player, Colors.GOLD + '=== Welcome to the Server ==='); MessageHelper.send(player, Colors.YELLOW + 'Hello, ' + Colors.WHITE + event.username + Colors.YELLOW + '!'); MessageHelper.send(player, Colors.GRAY + 'Use /help for available commands'); MessageHelper.send(player, ''); // Announce to others MessageHelper.broadcast(Colors.GREEN + event.username + ' has joined!'); } }); ``` -------------------------------- ### Register Custom Server Command with Arguments and Aliases (JavaScript) Source: https://context7.com/hosttale-project/simplescripting/llms.txt Registers a new server command named 'greet' using the Commands API. This command accepts required and optional string and integer arguments, supports aliases ('hello', 'hi'), and includes a handler function to process player interactions and messages. It demonstrates argument retrieval, player lookup, and message sending. ```javascript Commands.register() .setName('greet') .setDescription('Greet a player with a custom message') .addRequiredStringArg('player', 'Target player name') .addOptionalStringArg('message', 'Custom greeting message') .addOptionalIntArg('times', 'Number of times to repeat') .addAlias('hello') .addAlias('hi') .setHandler(function(ctx) { // Get the executing player var player = ctx.getPlayer(); if (!player) { ctx.sendMessage('&cThis command can only be used by players.'); return; } // Get arguments with defaults var targetName = ctx.getArgAsString('player'); var message = ctx.getArgAsString('message', 'Hello'); var times = ctx.getArgAsInt('times', 1); // Find target player (fuzzy matching) var target = Players.getByNameFuzzy(targetName); if (!target) { ctx.sendMessage('&cPlayer '' + targetName + '' not found.'); return; } // Send greeting var senderName = Players.getUsername(player); for (var i = 0; i < times; i++) { MessageHelper.send(target, Colors.GOLD + message + ' from ' + senderName + '!'); } ctx.sendMessage('&aGreeting sent to ' + Players.getUsername(target) + '!'); }); ``` -------------------------------- ### Build Plugin (Bash) Source: https://github.com/hosttale-project/simplescripting/blob/main/README.md Command to build the plugin using Gradle. This command compiles the project and packages it into a JAR file. The resulting JAR file can then be found in the 'build/libs/' directory. ```bash ./gradlew build ``` -------------------------------- ### Teleport API: Player and Coordinate Teleportation Source: https://context7.com/hosttale-project/simplescripting/llms.txt Provides methods for teleporting players to specific coordinates, other players, or across worlds. Supports thread-safe operations and includes functions for getting player locations and saving them. ```javascript // Teleport to coordinates (thread-safe version for use from scheduler/events) Teleport.teleportFromAnyThread(player, 100, 64, 200, 0, 90, 'default'); // Parameters: player, x, y, z, pitch, yaw, worldName // Teleport to coordinates in current world Teleport.teleport(player, 100, 64, 200); // Teleport with rotation Teleport.teleportWithRotation(player, 100, 64, 200, 0, 90, 'default'); // Teleport to another player var target = Players.getByNameFuzzy('Steve'); if (target) { Teleport.teleportToPlayer(player, target); } // Get player's current location var loc = Teleport.getPlayerLocation(player); if (loc) { // Save for later use var locationData = { x: loc.x, y: loc.y, z: loc.z, pitch: loc.pitch, yaw: loc.yaw, worldName: loc.worldName }; DB.save('saved_locations', 'spawn', JSON.stringify(locationData)); } // Teleport with warmup using Utils helper Utils.teleportWithWarmup(player, { x: 100, y: 64, z: 200, pitch: 0, yaw: 90, worldName: 'default' }, 5, 'spawn point', function() { Logger.info('Teleport complete!'); }); ``` -------------------------------- ### Logger API Source: https://context7.com/hosttale-project/simplescripting/llms.txt The Logger API provides console logging at different severity levels for debugging and monitoring scripts. It supports info, warning, error, and debug levels, along with structured logging and error handling examples. ```APIDOC ## Logger API ### Description Provides console logging at different severity levels for debugging and monitoring scripts. ### Methods - `Logger.info(message)`: Logs an informational message. - `Logger.warning(message)`: Logs a warning message. - `Logger.error(message)`: Logs an error message. - `Logger.debug(message)`: Logs a debug message (only shown if debug is enabled). ### Examples ```javascript // Log at different levels Logger.info('Script loaded successfully'); Logger.warning('Configuration not found, using defaults'); Logger.error('Failed to save player data'); Logger.debug('Debug: Processing player ' + playerId); // Structured logging function logCommand(player, command, args) { Logger.info('[CMD] ' + Players.getUsername(player) + ' executed /' + command + ' ' + args.join(' ')); } // Error handling with logging function loadPlayerData(playerId) { try { var data = DB.get('player_data', playerId); if (data) { return JSON.parse(data); } Logger.warning('No data found for player: ' + playerId); return null; } catch (e) { Logger.error('Failed to load player data: ' + e.message); return null; } } ``` ``` -------------------------------- ### Directory Structure Source: https://github.com/hosttale-project/simplescripting/blob/main/DESCRIPTION.md Illustrates the typical directory structure for a SimpleScripting project, including folders for mods, libraries, databases, and assets. ```text universe/SimpleScripting/ ├── mods/ # Your JavaScript files │ ├── lib/ # Shared libraries (loaded first) │ │ ├── utils.js # Common utilities │ │ └── config.js # Configuration │ ├── homes.js # Home system │ ├── warps.js # Warp system │ └── ... # Your custom scripts! ├── db/ # Database files (auto-created) └── assets/ # Assets folder ├── config/ # Config files ├── lang/ # Language files └── ui/ # UI definitions ``` -------------------------------- ### Register Custom Commands with SimpleScripting (JavaScript) Source: https://github.com/hosttale-project/simplescripting/blob/main/README.md Demonstrates how to register custom commands using the SimpleScripting Commands API. This includes setting command names, descriptions, aliases, arguments (required and optional), and defining the command handler function. The handler receives a context object for accessing arguments and sending messages. ```javascript Commands.register() .setName('mycommand') .setDescription('My custom command') .addRequiredStringArg('name', 'Player name') .addOptionalIntArg('count', 'Number of items') .addAlias('mc') .setHandler(function(ctx) { var name = ctx.getArgAsString('name'); var count = ctx.getArgAsInt('count') || 1; ctx.sendMessage('Hello ' + name + '! Count: ' + count); }); ``` -------------------------------- ### Permissions API Source: https://github.com/hosttale-project/simplescripting/blob/main/README.md APIs for checking and managing player permissions. ```APIDOC ## Permissions API ### Description APIs for checking and managing player permissions. ### Methods - `Permissions.has(player, permissionNode)`: Checks if a player has a specific permission node. - `Permissions.hasSender(context, permissionNode)`: Checks if the sender in a command context has a specific permission node. - `Permissions.require(player, permissionNode, errorMessage)`: Checks if a player has a permission node, sending an error message if they don't. - `Permissions.isAdmin(player)`: Checks if a player is an administrator. - `Permissions.requirePlayer(context)`: Ensures the command sender is a player, returning the player object or null. ``` -------------------------------- ### Config Library: Accessing All Ranks and Defaults Source: https://context7.com/hosttale-project/simplescripting/llms.txt Provides methods to retrieve a list of all defined player ranks and to access the entire default configuration object. This is useful for administrative tasks, debugging, or understanding the base configuration structure. ```javascript // Get all defined ranks var allRanks = Config.getAllRanks(); // ['default', 'vip', 'admin'] // Access default configuration var defaults = Config.defaults; Logger.info('Default home limit: ' + defaults.homes.maxHomes); Logger.info('Default RTP distance: ' + defaults.rtp.minDistance + '-' + defaults.rtp.maxDistance); ``` -------------------------------- ### Access World and Block Info with Worlds API Source: https://github.com/hosttale-project/simplescripting/blob/main/README.md Interact with worlds and blocks, including getting worlds by name, retrieving world names, and asynchronously checking block properties like type, air, solid, and liquid. Also supports finding safe teleport locations and the highest solid block. Dependencies: None. ```javascript // Get a world by name var world = Worlds.getWorld('default'); // Get world name var name = Worlds.getWorldName(world); // Get block info (async) Worlds.getBlock(world, x, y, z, function(block) { // block.type - block type string // block.isAir - true if air // block.isSolid - true if solid // block.isLiquid - true if liquid // block.x, block.y, block.z - coordinates }); // Quick checks (async) Worlds.isAir(world, x, y, z, function(isAir) { /* ... */ }); Worlds.isSolid(world, x, y, z, function(isSolid) { /* ... */ }); Worlds.isLiquid(world, x, y, z, function(isLiquid) { /* ... */ }); // Find safe teleport Y (async) Worlds.findSafeTeleportY(world, x, z, function(safeY) { if (safeY !== null) { // Found safe location at safeY } }); // Get highest solid block Y (async) Worlds.getHighestSolidY(world, x, z, function(y) { // y is the highest solid block }); ``` -------------------------------- ### Utils Library: Custom Warmup Manager Source: https://context7.com/hosttale-project/simplescripting/llms.txt A manager for creating custom warmup sequences for player actions. It allows defining a duration, success callback, cancellation callback, and a message to display during the warmup. This is useful for implementing custom timed events. ```javascript // Warmup manager for custom teleports var warmupManager = Utils.createWarmupManager(); warmupManager.start(player, 3, function() { /* onComplete */ }, function() { /* onCancel */ }, 'Teleporting in 3 seconds...' ); ``` -------------------------------- ### Utils Library Source: https://context7.com/hosttale-project/simplescripting/llms.txt The Utils library provides common utility functions for cooldowns, warmups, time formatting, location management, and player context handling. ```APIDOC ## Utils Library ### Description Provides common utility functions for cooldowns, warmups, time formatting, location management, and player context handling. ### Functions - `Utils.formatTime(seconds)`: Formats time in seconds into a human-readable string (e.g., "1h 1m 1s"). - `Utils.formatPosition(x, y, z)`: Formats position coordinates into a string (e.g., "100, 64, -200"). - `Utils.formatLocation(locationObject)`: Formats a location object into a string (e.g., "100, 64, 200"). - `Utils.getPlayerFromContext(ctx)`: Retrieves a player object from the command context, with validation. - `Utils.createCooldownTracker(storageKey, type)`: Creates a cooldown tracker instance. - `setCooldown(playerId, type)`: Sets a cooldown for a player. - `isOnCooldown(playerId, type, duration)`: Checks if a player is on cooldown. - `getRemainingSeconds(playerId, type, duration)`: Gets the remaining cooldown time in seconds. - `clearCooldown(playerId, type)`: Clears a player's cooldown. - `Utils.saveLocation(storageKey, locationName, locationObject)`: Saves a location object. - `Utils.loadLocation(storageKey, locationName)`: Loads a location object. - `Utils.teleportWithWarmup(player, location, warmupSeconds, cooldownType, onCompleteCallback)`: Teleports a player with a warmup period that can be canceled by movement. - `Utils.createWarmupManager()`: Creates a warmup manager instance. - `start(player, duration, onCompleteCallback, onCancelCallback, message)`: Starts a warmup process. ### Examples ```javascript // Time formatting var timeStr = Utils.formatTime(3661); // "1h 1m 1s" var timeStr2 = Utils.formatTime(45); // "45s" var timeStr3 = Utils.formatTime(120); // "2m" // Position formatting var posStr = Utils.formatPosition(100.5, 64.0, -200.3); // "100, 64, -200" var locStr = Utils.formatLocation({x: 100, y: 64, z: 200}); // "100, 64, 200" // Get player from command context with validation var player = Utils.getPlayerFromContext(ctx); if (!player) return; // Error message already sent // Cooldown tracking var cooldowns = Utils.createCooldownTracker('cooldowns', 'home'); // Set cooldown cooldowns.setCooldown(playerId, 'teleport'); // Check cooldown (60 second cooldown) if (cooldowns.isOnCooldown(playerId, 'teleport', 60)) { var remaining = cooldowns.getRemainingSeconds(playerId, 'teleport', 60); ctx.sendMessage('&eWait ' + remaining + ' seconds before teleporting again.'); return; } // Clear cooldown cooldowns.clearCooldown(playerId, 'teleport'); // Save/load locations Utils.saveLocation('locations', 'spawn', { x: 0, y: 64, z: 0, pitch: 0, yaw: 0, worldName: 'default' }); var spawn = Utils.loadLocation('locations', 'spawn'); if (spawn) { Logger.info('Spawn is at ' + Utils.formatLocation(spawn)); } // Teleport with warmup (movement cancels teleport) Utils.teleportWithWarmup(player, location, 5, 'home', function() { Logger.info('Teleport complete'); }); // Warmup manager for custom teleports var warmupManager = Utils.createWarmupManager(); warmupManager.start(player, 3, function() { /* onComplete */ }, function() { /* onCancel */ }, 'Teleporting in 3 seconds...' ); ``` ``` -------------------------------- ### Config Library: Player Rank and Setting Management Source: https://context7.com/hosttale-project/simplescripting/llms.txt Manages player ranks and retrieves rank-specific configuration settings. It allows setting a player's rank and accessing settings that apply to that rank or the player's effective settings considering their rank. This facilitates tiered features and permissions. ```javascript // Player rank management var playerRank = Config.getPlayerRank(playerId); // Returns: 'default' Config.setPlayerRank(playerId, 'vip'); // Get rank-specific settings var vipMaxHomes = Config.getRankSetting('vip', 'homes.maxHomes'); // Set rank-specific settings Config.setRankSetting('vip', 'homes.maxHomes', 10); Config.setRankSetting('admin', 'homes.cooldownSeconds', 0); // Get player's effective setting (considers their rank) var playerMaxHomes = Config.getPlayerSetting(playerId, 'homes.maxHomes'); ``` -------------------------------- ### Rank-Based Configuration (JavaScript) Source: https://github.com/hosttale-project/simplescripting/blob/main/README.md Illustrates how to define rank-specific settings in JavaScript, allowing for custom limits and cooldowns based on player ranks. This enables a tiered system where different ranks have access to different feature configurations. The 'default' rank uses the global DEFAULTS. ```javascript var RANKS = { default: { // Uses DEFAULTS }, vip: { homes: { maxHomes: 5, cooldownSeconds: 3 } }, admin: { homes: { maxHomes: 10, cooldownSeconds: 0, warmupSeconds: 0 } } }; ``` -------------------------------- ### MessageHelper API Source: https://github.com/hosttale-project/simplescripting/blob/main/README.md APIs for sending messages to players. ```APIDOC ## MessageHelper API ### Description APIs for sending messages to players. ### Methods - `MessageHelper.send(player, message)`: Sends a message to a specific player. - `MessageHelper.broadcast(message)`: Broadcasts a message to all online players. ``` -------------------------------- ### Utils Library: Teleportation with Warmup Source: https://context7.com/hosttale-project/simplescripting/llms.txt This function facilitates teleportation with a configurable warmup period. During the warmup, player movement will cancel the teleport. It also includes a callback for when the teleport is complete. This adds a layer of safety and user feedback. ```javascript // Teleport with warmup (movement cancels teleport) Utils.teleportWithWarmup(player, location, 5, 'home', function() { Logger.info('Teleport complete'); }); ``` -------------------------------- ### Events API Source: https://github.com/hosttale-project/simplescripting/blob/main/README.md Listen to various server and player events using the Events API. ```APIDOC ## Events API ### Description Listen to various server and player events. ### Method `Events.on(eventName: string, handler: function(event))` `Events.once(eventName: string, handler: function(event))` `Events.off(eventName: string, handler: function(event))` ### Event Names - `playerJoin`: Called when a player joins the server. - `playerQuit`: Called when a player quits the server. - `playerDeath`: Called when a player dies. - `playerRespawn`: Called when a player respawns. - `playerMove`: Called when a player moves (0.1 block threshold). - `playerChangeWorld`: Called when a player changes world. - `playerChat`: Called when a player chats (cancellable). - `playerCommand`: Called when a player runs a command (cancellable). - `tick`: Called every server tick. ### Event Data (example for `playerMove`) - `event.x`: New X position. - `event.y`: New Y position. - `event.z`: New Z position. ### Event Data (example for `playerChat`) - `event.message`: The chat message. - `event.cancel()`: Prevents the message from being displayed. ### Request Example ```javascript // Player joins the server Events.on('playerJoin', function(event) { var player = Players.getByUuid(event.playerUuid); MessageHelper.broadcast(Players.getUsername(player) + ' joined!'); }); // Player chats (cancellable) Events.on('playerChat', function(event) { if (event.message.startsWith('/ignore')) { event.cancel(); // Prevent the message from being sent } }); // Listen once Events.once('playerJoin', function(event) { // Called only for the first join }); // Remove listener var handler = function(event) { /* ... */ }; Events.on('playerJoin', handler); Events.off('playerJoin', handler); ``` ``` -------------------------------- ### Commands API Source: https://github.com/hosttale-project/simplescripting/blob/main/README.md Register custom commands with arguments, aliases, and handlers using the Commands API. ```APIDOC ## Commands API ### Description Register custom commands with arguments, aliases, and handlers. ### Method `Commands.register()` ### Parameters #### Command Registration Methods - `setName(name: string)` - Sets the command name. - `setDescription(description: string)` - Sets the command description. - `addRequiredStringArg(name: string, description: string)` - Adds a required string argument. - `addOptionalStringArg(name: string, description: string)` - Adds an optional string argument. - `addRequiredIntArg(name: string, description: string)` - Adds a required integer argument. - `addOptionalIntArg(name: string, description: string)` - Adds an optional integer argument. - `addRequiredDoubleArg(name: string, description: string)` - Adds a required double argument. - `addOptionalDoubleArg(name: string, description: string)` - Adds an optional double argument. - `addAlias(alias: string)` - Adds an alias for the command. - `setHandler(handler: function(ctx))` - Sets the function to be executed when the command is run. #### Command Context (ctx) - `ctx.getArgAsString(name: string): string` - Get string argument. - `ctx.getArgAsInt(name: string): number` - Get integer argument. - `ctx.getArgAsDouble(name: string): number` - Get double argument. - `ctx.sendMessage(message: string)` - Send message to command sender. - `ctx.isPlayer(): boolean` - Check if sender is a player. - `ctx.getPlayer()` - Get player entity (if sender is a player). ### Request Example ```javascript Commands.register() .setName('mycommand') .setDescription('My custom command') .addRequiredStringArg('name', 'Player name') .addOptionalIntArg('count', 'Number of items') .addAlias('mc') .setHandler(function(ctx) { var name = ctx.getArgAsString('name'); var count = ctx.getArgAsInt('count') || 1; ctx.sendMessage('Hello ' + name + '! Count: ' + count); }); ``` ``` -------------------------------- ### Default Plugin Configuration (JavaScript) Source: https://github.com/hosttale-project/simplescripting/blob/main/README.md Shows the default configuration settings for various plugin features in JavaScript. This object defines parameters such as maximum homes, cooldown periods, warmup durations, and teleportation limits. These defaults can be overridden in custom configurations. ```javascript // Default settings var DEFAULTS = { homes: { maxHomes: 3, cooldownSeconds: 5, warmupSeconds: 3 }, warps: { cooldownSeconds: 5, warmupSeconds: 3 }, spawn: { cooldownSeconds: 10, warmupSeconds: 5 }, tpa: { timeoutSeconds: 60, cooldownSeconds: 10, warmupSeconds: 3 }, back: { cooldownSeconds: 10, warmupSeconds: 3, historySize: 5 }, rtp: { minDistance: 100, maxDistance: 5000, maxAttempts: 10, cooldownSeconds: 300, warmupSeconds: 5 } }; ``` -------------------------------- ### Handle Player Events with SimpleScripting (JavaScript) Source: https://github.com/hosttale-project/simplescripting/blob/main/README.md Illustrates how to listen to various player and server events using the SimpleScripting Events API. This includes registering event handlers for player joins, quits, deaths, movement, chat, command execution, and server ticks. Event handlers receive an event object containing relevant data, and some events can be cancelled. ```javascript // Player joins the server Events.on('playerJoin', function(event) { var player = Players.getByUuid(event.playerUuid); MessageHelper.broadcast(Players.getUsername(player) + ' joined!'); }); // Player quits Events.on('playerQuit', function(event) { Logger.info('Player quit: ' + event.playerUuid); }); // Player dies Events.on('playerDeath', function(event) { var player = Players.getByUuid(event.playerUuid); // Save death location for /back command }); // Player respawns Events.on('playerRespawn', function(event) { // Welcome back message }); // Player moves (0.1 block threshold) Events.on('playerMove', function(event) { // event.x, event.y, event.z - new position }); // Player changes world Events.on('playerChangeWorld', function(event) { // event.fromWorld, event.toWorld }); // Player chats (cancellable) Events.on('playerChat', function(event) { // event.message // event.cancel() - prevent the message }); // Player runs a command (cancellable) Events.on('playerCommand', function(event) { // event.command - the command string // event.cancel() - prevent execution }); // Server tick Events.on('tick', function(event) { // Called every server tick }); // Listen once Events.once('playerJoin', function(event) { // Called only for the first join }); // Remove listener var handler = function(event) { /* ... */ }; Events.on('playerJoin', handler); Events.off('playerJoin', handler); ``` -------------------------------- ### DB API Source: https://github.com/hosttale-project/simplescripting/blob/main/README.md A simple key-value database API for storing and retrieving data. ```APIDOC ## DB API ### Description A simple key-value database API for storing and retrieving data. ### Methods - `DB.save(fileName, key, value)`: Saves a value to a specified file and key. - `DB.get(fileName, key)`: Retrieves a value from the specified file and key. - `DB.delete(fileName, key)`: Deletes a value from the specified file and key. - `DB.has(fileName, key)`: Checks if a value exists for the specified file and key. ``` -------------------------------- ### Players API Source: https://github.com/hosttale-project/simplescripting/blob/main/README.md APIs for finding and managing players within the game. ```APIDOC ## Players API ### Description APIs for finding and managing players within the game. ### Methods - `Players.getByName(username)`: Finds a player by exact username. - `Players.getByNameFuzzy(username)`: Finds a player by fuzzy username match. - `Players.getByUuid(uuid)`: Finds a player by their UUID. - `Players.getOnlinePlayers()`: Returns a list of all online players. - `Players.getUsername(player)`: Gets the username of a player object. - `Players.getUuidString(player)`: Gets the UUID string of a player object. - `Players.getPosition(player)`: Gets the position (x, y, z) of a player. - `Players.getRotation(player)`: Gets the rotation (pitch, yaw) of a player. - `Players.getFullLocation(player)`: Gets the full location (x, y, z, pitch, yaw, worldName) of a player. - `Players.getWorld(player)`: Gets the world a player is currently in. ``` -------------------------------- ### Utils Library: Time and Position Formatting Source: https://context7.com/hosttale-project/simplescripting/llms.txt The Utils library provides functions to format time durations into human-readable strings and to format numerical coordinates into string representations. These are useful for displaying information to players or for logging purposes. ```javascript // Time formatting var timeStr = Utils.formatTime(3661); // "1h 1m 1s" var timeStr2 = Utils.formatTime(45); // "45s" var timeStr3 = Utils.formatTime(120); // "2m" // Position formatting var posStr = Utils.formatPosition(100.5, 64.0, -200.3); // "100, 64, -200" var locStr = Utils.formatLocation({x: 100, y: 64, z: 200}); // "100, 64, 200" ``` -------------------------------- ### Minecraft Colors API Usage (JavaScript) Source: https://github.com/hosttale-project/simplescripting/blob/main/README.md Demonstrates how to use the Colors API in JavaScript to format chat messages with various colors and styles. It utilizes predefined color constants and formatting options like bold, italic, and underline. The RESET constant is crucial for preventing subsequent messages from inheriting the applied formatting. ```javascript ctx.sendMessage(Colors.GREEN + 'Success!' + Colors.RESET); ctx.sendMessage(Colors.RED + 'Error!' + Colors.RESET); ctx.sendMessage(Colors.BOLD + Colors.GOLD + 'Important!' + Colors.RESET); ``` -------------------------------- ### Default Configuration Settings (JavaScript) Source: https://github.com/hosttale-project/simplescripting/blob/main/DESCRIPTION.md Defines default settings for various game features like homes, warps, tpa, and rtp. These values can be overridden by rank-specific configurations. ```javascript var DEFAULTS = { homes: { maxHomes: 3, cooldownSeconds: 5, warmupSeconds: 3 }, warps: { cooldownSeconds: 5, warmupSeconds: 3 }, tpa: { timeoutSeconds: 60, cooldownSeconds: 10, warmupSeconds: 3 }, rtp: { minDistance: 100, maxDistance: 5000, cooldownSeconds: 300 } // ... and more! }; ``` -------------------------------- ### Config Library Source: https://context7.com/hosttale-project/simplescripting/llms.txt The Config library provides centralized configuration management with defaults, database persistence, and rank-based settings. ```APIDOC ## Config Library ### Description Provides centralized configuration management with defaults, database persistence, and rank-based settings. ### Functions - `Config.get(path)`: Retrieves a configuration value from the specified path. - `Config.getDefault(path)`: Retrieves the default configuration value for the specified path. - `Config.set(path, value)`: Sets a configuration value at the specified path. - `Config.reset(path)`: Resets a configuration value to its default. - `Config.getPlayerRank(playerId)`: Gets the rank of a player. - `Config.setPlayerRank(playerId, rank)`: Sets the rank of a player. - `Config.getRankSetting(rank, path)`: Retrieves a configuration value specific to a rank. - `Config.setRankSetting(rank, path, value)`: Sets a configuration value for a specific rank. - `Config.getPlayerSetting(playerId, path)`: Retrieves the effective configuration value for a player, considering their rank. - `Config.getAllRanks()`: Returns an array of all defined ranks. - `Config.defaults`: An object containing all default configuration values. ### Examples ```javascript // Get configuration values var maxHomes = Config.get('homes.maxHomes'); // Returns: 3 (default) var cooldown = Config.get('homes.cooldownSeconds'); // Returns: 5 (default) // Get default values directly var defaultWarmup = Config.getDefault('spawn.warmupSeconds'); // Returns: 3 // Set configuration values Config.set('homes.maxHomes', 5); Config.set('rtp.maxDistance', 10000); // Reset to default Config.reset('homes.maxHomes'); // Player rank management var playerRank = Config.getPlayerRank(playerId); // Returns: 'default' Config.setPlayerRank(playerId, 'vip'); // Get rank-specific settings var vipMaxHomes = Config.getRankSetting('vip', 'homes.maxHomes'); // Set rank-specific settings Config.setRankSetting('vip', 'homes.maxHomes', 10); Config.setRankSetting('admin', 'homes.cooldownSeconds', 0); // Get player's effective setting (considers their rank) var playerMaxHomes = Config.getPlayerSetting(playerId, 'homes.maxHomes'); // Get all defined ranks var allRanks = Config.getAllRanks(); // ['default', 'vip', 'admin'] // Access default configuration var defaults = Config.defaults; Logger.info('Default home limit: ' + defaults.homes.maxHomes); Logger.info('Default RTP distance: ' + defaults.rtp.minDistance + '-' + defaults.rtp.maxDistance); ``` ``` -------------------------------- ### Colors API Source: https://context7.com/hosttale-project/simplescripting/llms.txt Provides Minecraft color codes and formatting constants for styling messages. ```APIDOC ## Colors API ### Description Provides Minecraft color codes and formatting constants for styling messages. ### Constants **Basic Colors:** - `Colors.BLACK`, `Colors.DARK_BLUE`, `Colors.DARK_GREEN`, `Colors.DARK_AQUA`, `Colors.DARK_RED`, `Colors.DARK_PURPLE`, `Colors.GOLD`, `Colors.GRAY`, `Colors.DARK_GRAY`, `Colors.BLUE`, `Colors.GREEN`, `Colors.AQUA`, `Colors.RED`, `Colors.LIGHT_PURPLE`, `Colors.YELLOW`, `Colors.WHITE` **Formatting:** - `Colors.BOLD`, `Colors.ITALIC`, `Colors.UNDERLINE`, `Colors.STRIKETHROUGH`, `Colors.RESET` ### Example Usage ```javascript // Basic colors ctx.sendMessage(Colors.BLACK + 'Black'); ctx.sendMessage(Colors.DARK_BLUE + 'Dark Blue'); ctx.sendMessage(Colors.DARK_GREEN + 'Dark Green'); ctx.sendMessage(Colors.DARK_AQUA + 'Dark Aqua'); ctx.sendMessage(Colors.DARK_RED + 'Dark Red'); ctx.sendMessage(Colors.DARK_PURPLE + 'Dark Purple'); ctx.sendMessage(Colors.GOLD + 'Gold'); ctx.sendMessage(Colors.GRAY + 'Gray'); ctx.sendMessage(Colors.DARK_GRAY + 'Dark Gray'); ctx.sendMessage(Colors.BLUE + 'Blue'); ctx.sendMessage(Colors.GREEN + 'Green'); ctx.sendMessage(Colors.AQUA + 'Aqua'); ctx.sendMessage(Colors.RED + 'Red'); ctx.sendMessage(Colors.LIGHT_PURPLE + 'Light Purple'); ctx.sendMessage(Colors.YELLOW + 'Yellow'); ctx.sendMessage(Colors.WHITE + 'White'); // Formatting ctx.sendMessage(Colors.BOLD + 'Bold text' + Colors.RESET); ctx.sendMessage(Colors.ITALIC + 'Italic text' + Colors.RESET); ctx.sendMessage(Colors.UNDERLINE + 'Underlined text' + Colors.RESET); ctx.sendMessage(Colors.STRIKETHROUGH + 'Strikethrough text' + Colors.RESET); // Combined formatting ctx.sendMessage(Colors.RED + Colors.BOLD + 'Important Error!' + Colors.RESET); ctx.sendMessage(Colors.GOLD + Colors.ITALIC + 'Fancy announcement' + Colors.RESET); // Alternative: Use & codes in strings ctx.sendMessage('&aGreen &bAqua &cRed &6Gold'); ctx.sendMessage('&l&cBold Red'); ``` ``` -------------------------------- ### Config Library: Accessing Configuration Values Source: https://context7.com/hosttale-project/simplescripting/llms.txt The Config library allows retrieval of configuration settings, including nested values and defaults. It supports accessing general settings and specific default values directly. These values are typically used to control game mechanics and features. ```javascript // Get configuration values var maxHomes = Config.get('homes.maxHomes'); // Returns: 3 (default) var cooldown = Config.get('homes.cooldownSeconds'); // Returns: 5 (default) // Get default values directly var defaultWarmup = Config.getDefault('spawn.warmupSeconds'); // Returns: 3 ``` -------------------------------- ### Scheduler API Source: https://github.com/hosttale-project/simplescripting/blob/main/README.md APIs for scheduling delayed and repeating tasks. ```APIDOC ## Scheduler API ### Description APIs for scheduling delayed and repeating tasks. ### Methods - `Scheduler.runLater(callback, delayTicks)`: Runs a function after a specified delay in ticks (20 ticks = 1 second). - `Scheduler.runLaterMs(callback, delayMs)`: Runs a function after a specified delay in milliseconds. - `Scheduler.runRepeating(callback, intervalTicks)`: Runs a function repeatedly at a specified interval in ticks. - `Scheduler.runRepeatingMs(callback, intervalMs)`: Runs a function repeatedly at a specified interval in milliseconds. - `Scheduler.cancel(taskId)`: Cancels a scheduled task using its ID. - `Scheduler.cancelAll()`: Cancels all scheduled tasks. ``` -------------------------------- ### Teleport API Source: https://github.com/hosttale-project/simplescripting/blob/main/README.md APIs for safely teleporting players to different locations. ```APIDOC ## Teleport API ### Description APIs for safely teleporting players to different locations. ### Methods - `Teleport.teleport(player, world, x, y, z)`: Teleports a player to specified coordinates in a given world. - `Teleport.teleportWithRotation(player, world, x, y, z, pitch, yaw)`: Teleports a player to specified coordinates with a specific rotation. - `Teleport.teleportToPlayer(player, targetPlayer)`: Teleports one player to the location of another player. - `Teleport.getPlayerLocation(player)`: Gets the current location (x, y, z, pitch, yaw, worldName) of a player. ``` -------------------------------- ### Worlds API Source: https://github.com/hosttale-project/simplescripting/blob/main/README.md APIs for accessing world and block information. ```APIDOC ## Worlds API ### Description APIs for accessing world and block information. ### Methods - `Worlds.getWorld(worldName)`: Gets a world object by its name. - `Worlds.getWorldName(world)`: Gets the name of a world object. - `Worlds.getBlock(world, x, y, z, callback)`: Asynchronously gets block information at specified coordinates. The callback receives a block object with properties like `type`, `isAir`, `isSolid`, `isLiquid`, and coordinates. - `Worlds.isAir(world, x, y, z, callback)`: Asynchronously checks if a block at the coordinates is air. - `Worlds.isSolid(world, x, y, z, callback)`: Asynchronously checks if a block at the coordinates is solid. - `Worlds.isLiquid(world, x, y, z, callback)`: Asynchronously checks if a block at the coordinates is liquid. - `Worlds.findSafeTeleportY(world, x, z, callback)`: Asynchronously finds a safe Y coordinate for teleportation at given X and Z coordinates. - `Worlds.getHighestSolidY(world, x, z, callback)`: Asynchronously finds the Y coordinate of the highest solid block at given X and Z coordinates. ``` -------------------------------- ### Listen to Player Death Event and Save Location (JavaScript) Source: https://github.com/hosttale-project/simplescripting/blob/main/DESCRIPTION.md Demonstrates listening to the 'playerDeath' event. Upon player death, it saves the player's location to the database for potential use with a '/back' command. ```javascript Events.on('playerDeath', function(event) { var player = Players.getByUuid(event.playerUuid); var loc = Players.getFullLocation(player); // Save death location for /back command DB.save('death_locations', event.playerUuid, JSON.stringify(loc)); }); ```