diff --git a/README.md b/README.md index 1778d2a..05d9390 100644 --- a/README.md +++ b/README.md @@ -3,260 +3,26 @@ scriptserver [![](http://i.imgur.com/zhptNme.png)](https://github.com/garrettjoecox/scriptserver) -[![Gitter chat](https://img.shields.io/gitter/room/ScriptServer/Lobby.svg)](https://gitter.im/ScriptServer/Lobby) ![Total Downloads](https://img.shields.io/npm/dt/scriptserver.svg) - -## What's ScriptServer? -A configurable Minecraft server wrapper written in Node.js. -Using a combination of RCON and the output of the server console it allows you to do some pretty cool things. -Though, this is the engine of ScriptServer, and is honestly pretty bare. -The modules are where the magic happens (check 'Published Modules' down below). - -The ScriptServer engine does 3 things: - - Starts the Minecraft server as a child process, using the specified jar & arguments - - Provides an interface to send commands, use their results, and make use of other things that are displayed in the server console. - - Initializes a simple module loader for ScriptServer modules. - -## What version of Minecraft does it work with? - -Because it relies on the RCON interface and the format of the output log, it should work with pretty much any version of Minecraft dating back to 2012. It should continue to work for all future releases and snapshots as long as the logging format doesn't drastically change, and they don't drop RCON support. (Both unlikely) - -## Getting Started - -#### Prerequisites -- [NodeJS](https://nodejs.org/en/) (^8.0.0 recommended) -- Somewhat of a familiarity with NodeJS is recommended. - -#### Setup -While inside the root of your Minecraft server directory, run `npm install scriptserver`. Then create a javascript file to run the server, I usually go with `server.js`. Paste in the following: - -```javascript -const ScriptServer = require('scriptserver'); - -const server = new ScriptServer({ - core: { - jar: 'minecraft_server.jar', - args: ['-Xmx2G'], - rcon: { - port: '25575', - password: 'password' - } - } -}); - -server.start(); -``` - -When initializing your ScriptServer instance all it takes is an optional config object, which is automatically set to `server.config`, and accessible by third party modules. Read each module's README to check for configuration options. - -The options in the `core` config are used by the ScriptServer engine to determine the startup jar, arguments, and RCON configuration. - -**RCON IS NOT ENABLED BY DEFAULT**, you will need to add the following to your `server.properties` to enable it: -``` -enable-rcon=true -rcon.port=25575 -rcon.password=password -``` - -You start your server with `server.start()` - -Finally, you can run the server with node using -```bash -node server.js -``` - -And that's it! - -Seriously. Like I said the engine is pretty bare, especially to users, but in the section 'Creating Modules' I'll explain how developers can utilize the simplicity of this engine. - -For people looking to quickly try this out, I recommend giving [scriptserver-essentials](https://github.com/garrettjoecox/scriptserver-essentials) a try, it provides basic commands like `tpa`, `home`, and `spawn`, as well as a starter kit. - -## Using Modules - -To put 3rd party modules to use, you must first of course `npm install` them, then in your `server.js` initialize them one at a time with `server.use()` - -```javascript -const ScriptServer = require('scriptserver'); - -// Configuration - -const server = new ScriptServer({ - core: { - jar: 'minecraft_server.jar', - args: ['-Xmx2G'] - }, - command: { - prefix: '~' - }, - essentials: { - starterKit: { - enabled: false - } - } -}); - -// Loading modules - -server.use(require('scriptserver-command')) -// or -const ssEssentials = require('scriptserver-essentials'); -server.use(ssEssentials); - -// Start server - -server.start(); -``` - -As for the functionality of the actual module please refer to it's own `README.md` for use. - -## Creating Modules - -As a developer you have a few tools to work with. Below I will explain and use them in examples. - -### 1) server.on(event, callback) - -The server's console output is our main way of getting data from the server to our javascript wrapper. -Every time a log is output the engine emits the `console` event. This sounds useless as first but combining that with RegExp you'd be surprised at how much you can do. - -Because ScriptServer extends the EventsEmitter, 3rd party module creators can utilize the emitter themselves. For instance the `scriptserver-event` module emits the events `chat`, `login`, `logout`, etc. right along side the main `console` event. - -#### Simple ~head command example -```javascript -server.on('console', line => { - // Regex matches when a user types ~head in chat - const result = line.match(/]: <([\w]+)> ~head (.*)/); - if (result) { - // Player that sent command - console.log(result[1]) - // head user is requesting - console.log(result[2]); - // Give the user the player head! - server.send(`give ${result[1]} minecraft:skull 1 3 {SkullOwner:"${result[2]}"}`) - } -}); -``` - -### 2) server.send(command) - -The send method allows you to send commands to the Minecraft server. -See [here](http://minecraft.gamepedia.com/Commands) for a list of available commands. When mixed with ES2015's template strings and Promises, server.send can be a powerful tool. - -#### Using server.send -```javascript -const player = 'ProxySaw'; -// Just like commands you'd type in the server console. -server.send(`give ${player} minecraft:diamond 1`); -server.send(`playsound entity.item.pickup master ${player} ~ ~ ~ 10 1 1`); -server.send(`say ${player} got a diamond!`); -``` - -`server.send` also allows you to use the result of the command through it's returned promise. Similar to the console output, when combined with RegExp this can be extremely useful. - -#### Using server.send promises to get player location - -Sending the following command to the server console: -``` -execute ProxySaw ~ ~ ~ /testforblock ~ ~ ~ minecraft:air 10 -``` -Will result in the following line being output: -``` -[10:32:37] [Server thread/INFO]: The block at 20,74,-161 had the data value of 0 (expected: 10). -``` - -Using the RegExp: `/at\s([-\d]+),([-\d]+),([-\d]+)/` I can pull the coordinates out of that log and use them within my javascript function. - -```javascript -var player = 'ProxySaw'; - -server.send(`execute ${player} ~ ~ ~ /testforblock ~ ~ ~ minecraft:air 10`) - .then(result => { - const coords = result.match(/at\s([-\d]+),([-\d]+),([-\d]+)/); - console.log('X:', coords[0]); - console.log('Y:', coords[1]); - console.log('Z:', coords[2]); - }); -``` - -### 3) server.sendConsole(command) - -sendConsole is a helper method for special use-cases that want/need to bypass the RCON interface, and instead write directly to the server console. The drawback of this, is that there is no direct response to anything sent directly to the console. About 99% of the time you'll likely want to use `server.send` instead. - -### Module Structure -So now that you know how to utilize those tools, it's time to build a module. Whenever a user `.use`'s your module, it simply invokes it with the context of their server, therefor encapsulate all server-side logic in a module.exports function. - -The following was taken from the [scriptserver-command module](https://github.com/garrettjoecox/scriptserver-command). It allows for custom commands to be created using server.command() Read inline comments for breakdown. -```javascript -// The function that is called on server.use(require('scriptserver-command')) -module.exports = function() { - // Invoked with the context of the user's server - const server = this; - // Local storage for commands - const commands = {}; - - // Uses another scriptserver module - server.use(require('scriptserver-event')); - - // Interface for users to add commands - server.command = function(cmd, callback) { - commands[cmd] = commands[cmd] || []; - commands[cmd].push(callback); - } - - // Hooks into chat event to watch for the ~ char, then emits the command event - server.on('chat', event => { - const stripped = event.message.match(/~([\w]+)\s?(.*)/); - if (stripped && commands.hasOwnProperty(stripped[1])) { - server.emit('command', { - player: event.player, - command: stripped[1], - args: stripped[2].split(' '), - timestamp: Date.now() - }); - } - }); - - // Invokes any listeners on the command the player triggered - server.on('command', event => { - if (commands.hasOwnProperty(event.command)) { - commands[event.command].forEach(callback => callback(event)); - } - }); -} -``` - -Now for using the scriptserver-command module, -```javascript -const ScriptServer = require('scriptserver'); -const server = new ScriptServer({ - core: { - jar: 'minecraft_server.jar', - args: ['-Xmx2G'] - }, -}); - -server.use(require('scriptserver-command')); - -server.command('head', event => { - var skull = event.args[0] || event.player - server.send(`give ${event.player} minecraft:skull 1 3 {SkullOwner:"${skull}"}`); -}); - -server.start(); -``` - -And muahlah! In game sending the command `~head` will give yourself your player head or passing in a name `~head Notch` will give you their player head! - -If you run into any issues or questions, read through other published modules(below) or submit an issue and I'll try to help you out! - -## Published Modules -- [scriptserver-essentials](https://github.com/garrettjoecox/scriptserver-essentials) -Some essential server commands like home, tpa, and head. -- [scriptserver-command](https://github.com/garrettjoecox/scriptserver-command) -Provides interface for adding custom server commands. -- [scriptserver-event](https://github.com/garrettjoecox/scriptserver-event) -Interface for hooking onto events like chat, login, and logout. -- [scriptserver-util](https://github.com/garrettjoecox/scriptserver-util) -Multiple helper commands for module developers. -- [scriptserver-json](https://github.com/garrettjoecox/scriptserver-json) -Provides ability to read/write from JSON files. -- [scriptserver-update](https://github.com/garrettjoecox/scriptserver-update) -Lets you restart the server in game, and auto update to snapshot/release channels. +## What's this? +Sciptserver is a minecraft server wrapper, allowing you to write simple plugins using the RCON connection and STDIN/OUT from the java console. This is currently a WIP port to deno, milage may vary. + +## Todo: +- [x] Basic functionality +- [x] Split up java server from rcon connection +- [x] Plugin interface pattern +- [x] Events module +- [x] Command module +- [ ] Utils module + - [ ] isOp + - [ ] isOp + - [ ] getOnline + - [x] tellRaw + - [x] getEntityData + - [x] getDimension + - [x] getLocation + - [x] teleport +- [ ] JSON module +- [ ] Essentials module +- [ ] More user friendly config (deep defaults) +- [ ] README documentation +- [ ] Paper/Spigot flavors \ No newline at end of file diff --git a/command.ts b/command.ts index 873b02c..df323cd 100644 --- a/command.ts +++ b/command.ts @@ -18,7 +18,6 @@ export interface CommandConfig { commands: { [cmd: string]: CommandCallback[]; }; - commandFunc?: (cmd: string, callback: CommandCallback) => void; } declare module "./config.ts" { @@ -31,6 +30,10 @@ declare module "./java_server.ts" { export interface JavaServerEvents { command: CommandCallback; } + + export interface JavaServer { + command: (cmd: string, callback: CommandCallback) => void; + } } const DEFAULT_CONFIG: CommandConfig = { @@ -41,7 +44,7 @@ const DEFAULT_CONFIG: CommandConfig = { export function useCommand(javaServer: JavaServer) { if (javaServer.config?.command?.initialized) { - return javaServer.config.command.commandFunc!; + return; } useEvents(javaServer); @@ -78,15 +81,10 @@ export function useCommand(javaServer: JavaServer) { } }); - javaServer.config.command.commandFunc = ( - cmd: string, - callback: CommandCallback - ) => { + javaServer.command = (cmd: string, callback: CommandCallback) => { cmd = cmd.toLowerCase(); javaServer.config.command.commands[cmd] = javaServer.config.command.commands[cmd] || []; javaServer.config.command.commands[cmd].push(callback); }; - - return javaServer.config.command.commandFunc; } diff --git a/java_server.ts b/java_server.ts index 2df65f3..d05f982 100644 --- a/java_server.ts +++ b/java_server.ts @@ -1,6 +1,7 @@ import { EventEmitter } from "https://deno.land/std@0.93.0/node/events.ts"; import { iter } from "https://deno.land/std@0.93.0/io/util.ts"; import { Config } from "./config.ts"; +import { Buffer } from "https://deno.land/std@0.93.0/node/buffer.ts"; export interface JavaServerConfig { jar: string; @@ -71,6 +72,12 @@ export class JavaServer extends EventEmitter { this.stderrIter(); } + public send(message: string) { + if (!this.process || !this.process.stdin) return; + + this.process.stdin.write(Buffer.from(message + "\n")); + } + private async stdoutIter() { try { if (this.process?.stdout && this.config.javaServer.pipeStdout) { diff --git a/mod.ts b/mod.ts index d196732..8f09988 100644 --- a/mod.ts +++ b/mod.ts @@ -1,24 +1,62 @@ +import { JavaServer } from "./java_server.ts"; +import { RconConnection } from "./rcon_connection.ts"; import { ScriptServer } from "./script_server.ts"; import { useEvents } from "./events.ts"; import { useCommand } from "./command.ts"; +import { useUtils } from "./utils.ts"; -(() => { +// Example of only using the JavaServer & Plugins +() => { try { - const scriptServer = new ScriptServer(); + const javaServer = new JavaServer(); - useEvents(scriptServer.javaServer); - const command = useCommand(scriptServer.javaServer); + useEvents(javaServer); + useCommand(javaServer); + + javaServer.command("head", (event) => { + javaServer.send(`say ${event.player} issued "head" command`); + }); + + javaServer.start(); + } catch (error) { + console.error(error); + } +}; + +// Example of only using the RconConnection & Plugins +() => { + try { + const rconConnection = new RconConnection(); - scriptServer.javaServer.on("command", (event) => { - console.log("command", event); + useUtils(rconConnection); + + rconConnection.on("authenticated", async () => { + await rconConnection.utils.tellRaw("@a", "Hello World"); }); - command("head", (event) => { - console.log("head", event); + rconConnection.connect(); + } catch (error) { + console.error(error); + } +}; + +// Example of using ScriptServer, which is both JavaServer & RconConnection +() => { + try { + const scriptServer = new ScriptServer(); + + useEvents(scriptServer.javaServer); + useCommand(scriptServer.javaServer); + useUtils(scriptServer.rconConnection); + + scriptServer.javaServer.command("spawn", (event) => { + scriptServer.rconConnection.utils.tellRaw("Hello world", event.player, { + color: "red", + }); }); scriptServer.start(); } catch (error) { console.error(error); } -})(); +}; diff --git a/utils.ts b/utils.ts new file mode 100644 index 0000000..ab04198 --- /dev/null +++ b/utils.ts @@ -0,0 +1,127 @@ +import { Config } from "./config.ts"; +import { RconConnection } from "./rcon_connection.ts"; +import get from "https://deno.land/x/denodash@v0.1.3/src/object/get.ts"; + +export type Dimension = + | "minecraft:overworld" + | "minecraft:the_nether" + | "minecraft:the_end"; + +interface Location { + x: number; + y: number; + z: number; + dimension: Dimension; +} + +export interface UtilsConfig { + initialized: boolean; + flavorSpecific: { + default: { + tellRaw: ( + message: string, + target?: string, + options?: Record + ) => void; + getEntityData: ( + target?: string, + path?: string, + scale?: number + ) => Promise; + getDimension: (player: string) => Promise; + getLocation: (player: string) => Promise; + teleport: (target: string, location: Location) => Promise; + }; + }; +} + +declare module "./config.ts" { + export interface Config { + utils: UtilsConfig; + } +} + +declare module "./rcon_connection.ts" { + export interface RconConnection { + utils: UtilsConfig["flavorSpecific"]["default"]; + } +} + +export function useUtils(rconConnection: RconConnection) { + if (rconConnection.config.utils?.initialized) { + return; + } + + rconConnection.config = { + // @ts-ignore + utils: { + initialized: false, + flavorSpecific: { + default: { + tellRaw(message, target = "@a", options = {}) { + options.text = + typeof message === "string" ? message : JSON.stringify(message); + return rconConnection.send( + `tellraw ${target} ${JSON.stringify(options)}` + ); + }, + async getEntityData(target = "@a", path = "", scale) { + let cmd = `data get entity ${target}`; + if (path) { + cmd += ` ${path}`; + } + if (path && scale !== undefined) { + cmd += ` ${scale}`; + } + + const rawResult = await rconConnection.send(cmd); + if (rawResult.match(/^No entity was found$/)) + throw new Error(`Invalid target ${target}`); + const result = rawResult.match( + /^(\w+) has the following entity data: (.+)$/ + )![2]; + + return result; + }, + async getDimension(player) { + const rawDimension = await this.getEntityData(player, "Dimension"); + const dimension = rawDimension.replaceAll('"', ""); + + return dimension; + }, + async getLocation(player) { + const rawLocation = await this.getEntityData(player, "Pos"); + const location = rawLocation.match( + /\[([-\d.]+)d, ([-\d.]+)d, ([-\d.]+)d\]$/ + ); + + return { + x: parseFloat(location![1]), + y: parseFloat(location![2]), + z: parseFloat(location![3]), + }; + }, + async teleport(target, location) { + await rconConnection.send( + `execute in ${location.dimension} run tp ${target} ${location.x} ${location.y} ${location.z}` + ); + await rconConnection.send( + `execute in ${location.dimension} run particle cloud ${location.x} ${location.y} ${location.z} 1 1 1 0.1 100 force` + ); + await rconConnection.send( + `execute in ${location.dimension} run playsound entity.item.pickup master @a ${location.x} ${location.y} ${location.z} 10 1 1` + ); + }, + }, + }, + }, + ...rconConnection.config, + }; + rconConnection.config.utils.initialized = true; + + rconConnection.utils = get( + rconConnection.config.utils, + `flavorSpecific.${rconConnection.config.flavor}`, + rconConnection.config.utils.flavorSpecific.default + ); +}