### Install node-minecraft-protocol Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/README.md Install the node-minecraft-protocol package using npm. ```bash npm install minecraft-protocol ``` -------------------------------- ### mc.createServer(options) Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Creates a Minecraft server instance and starts listening for connections. It handles automatic client login and validation against Mojang's authentication services. ```APIDOC ## mc.createServer(options) ### Description Returns a `Server` instance and starts listening. All clients will be automatically logged in and validated against mojang's auth. ### Method `createServer` ### Parameters #### Options Object - **port** (number) - Optional - Default to 25565 - **host** (string) - Optional - Default to undefined (listen to all available ipv4 and ipv6 addresses) - **kickTimeout** (number) - Optional - Default to 10000 (10s), kick client that doesn't answer to keepalive after that time - **checkTimeoutInterval** (number) - Optional - Default to 4000 (4s), send keepalive packet at that period - **online-mode** (boolean) - Optional - Default to true - **beforePing** (function) - Optional - Allows customization of the server's response to a client ping. Takes `response` and `client` arguments. Can optionally take a `callback`. If `false` is returned, the connection is terminated. - **beforeLogin** (function) - Optional - Allows customization of the client before the `success` packet is sent. Must be synchronous. - **motd** (string) - Optional - Default to "A Minecraft server" - **motdMsg** (object) - Optional - A JSON object of the chat message to use instead of `motd`. Can be built using [prismarine-chat](https://github.com/PrismarineJS/prismarine-chat) and calling .toJSON(). Not used with legacy pings. - **maxPlayers** (number) - Optional - Default to 20 - **keepAlive** (boolean) - Optional - Send keep alive packets, default to true - **version** (string|boolean) - Optional - The version of the server, defaults to the latest version. Set to `false` to enable dynamic cross version support. - **fallbackVersion** (string) - Optional - The version to use as a fallback if the client version isn't supported. Only works with dynamic cross version support. - **favicon** (string) - Optional - The favicon to set, base64 encoded. - **customPackets** (object) - Optional - An object indexed by version/state/direction/name for custom packets. - **errorHandler** (function) - Optional - Overrides the default error handler for client errors. Takes `Client` and `error` arguments. The default kicks the client. - **hideErrors** (boolean) - Optional - Do not display errors, default to false. - **agent** (object) - Optional - An http agent for setting proxy settings for yggdrasil authentication confirmation. - **validateChannelProtocol** (boolean) - Optional - Whether or not to enable protocol validation for custom protocols using plugin channels. Defaults to true. - **enforceSecureProfile** (boolean) - Optional - Kick clients that do not have chat signing keys from Mojang (1.19+). - **generatePreview** (function) - Optional - Function to generate chat previews. Takes the raw message string and should return the message preview as a string. (1.19-1.19.2). - **socketType** (string) - Optional - Either `tcp` or `ipc`. Switches from a tcp connection to a ipc socket connection (or named pipes on windows). With the `ipc` option `host` becomes the path off the ipc connection. - **Server** (class) - Optional - A custom server class to use instead of the default one. ### Response Returns a `Server` instance. ``` -------------------------------- ### Connect to a Realm Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/README.md Example for connecting to a Minecraft Realm. The `realms` option allows specifying a function to pick a realm from a list. ```js const mc = require('minecraft-protocol'); const client = mc.createClient({ realms: { pickRealm: (realms) => realms[0] // Function which recieves an array of joined/owned Realms and must return a single Realm. Can be async }, auth: 'microsoft' }) ``` -------------------------------- ### `listening` event Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Called when the server starts listening for incoming connections, indicating it is ready to accept clients. ```APIDOC ## `listening` event ### Description Called when the server is listening for connections. This means that the server is ready to accept incoming connections. ``` -------------------------------- ### mc.defaultVersion Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Gets the default Minecraft version that the library will use if not specified. ```APIDOC ## mc.defaultVersion The current default minecraft version. ``` -------------------------------- ### Registering a Client Channel Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Use this method to register a new channel with a specified name and protodef type definition. The register packet is sent if 'custom' is true. This starts emitting channel events on the client. ```javascript client.registerChannel(name, typeDefinition, custom) ``` -------------------------------- ### server.favicon Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Gets or sets the favicon that appears next to the server in the Minecraft client's multiplayer list. ```APIDOC ## server.favicon ### Description A base64 data string representing the favicon that will appear next to the server on the mojang client's multiplayer list. ### Usage ```javascript // Get favicon const currentFavicon = server.favicon; // Set favicon (must be a base64 data string) server.favicon = 'data:image/png;base64,...'; ``` ``` -------------------------------- ### server.motd Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Gets or sets the Message of the Day (MOTD) that is displayed when a player pings the server. ```APIDOC ## server.motd ### Description The motd that is sent to the player when he is pinging the server. ### Usage ```javascript // Get MOTD const currentMotd = server.motd; // Set MOTD server.motd = 'Welcome to my server!'; ``` ``` -------------------------------- ### client.registerChannel Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Registers a custom channel with a specified name and Protodef type definition. If `custom` is true, a register packet is sent. This method also starts emitting channel events on the client object. ```APIDOC ## client.registerChannel(name, typeDefinition, [custom]) ### Description Registers a channel `name` using the protodef `typeDefinition` and sending the register packet if `custom` is true. Starts emitting channel events of the given name on the client object. ### Parameters #### Path Parameters - **name** (string) - Required - The name of the channel to register. - **typeDefinition** (object) - Required - The Protodef type definition for the channel. - **custom** (boolean) - Optional - If true, sends a register packet. ``` -------------------------------- ### mc.createClient(options) Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Creates a `Client` instance and initiates the login process. This method allows for extensive configuration of connection and authentication parameters. ```APIDOC ## mc.createClient(options) Returns a `Client` instance and perform login. `options` is an object containing the properties : * username * port : default to 25565 * auth : the type of account to use, either `microsoft`, `mojang`, `offline` or `function (client, options) => void`. defaults to 'offline'. * password : can be omitted * (microsoft account) leave this blank to use device code auth. If you provide a password, we try to do username and password auth, but this does not always work. * (mojang account) If provided, we auth with the username and password. If this is blank, and `profilesFolder` is specified, we auth with the tokens there instead. If neither `password` or `profilesFolder` are specified, we connect in offline mode. * host : default to localhost * session : An object holding clientToken, accessToken and selectedProfile. Generated after logging in using username + password with mojang auth or after logging in using microsoft auth. `clientToken`, `accessToken` and `selectedProfile: {name: '', id: ''}` can be set inside of `session` when using createClient to login with a client and access Token instead of a password. `session` is also emitted by the `Client` instance with the event 'session' after successful authentication. * clientToken : generated if a password is given or can be set when when using createClient * accessToken : generated if a password or microsoft account is given or can be set when using createBot * selectedProfile : generated if a password or microsoft account is given. Can be set as a object with property `name` and `id` that specifies the selected profile. * name : The selected profiles in game name needed for logging in with access and client Tokens. * id : The selected profiles uuid in short form (without `-`) needed for logging in with access and client Tokens. * authServer : auth server, default to https://authserver.mojang.com * sessionServer : session server, default to https://sessionserver.mojang.com * keepAlive : send keep alive packets : default to true * closeTimeout : end the connection after this delay in milliseconds if server doesn't answer to ping, default to `120*1000` * noPongTimeout : after the server opened the connection, wait for a default of `5*1000` after pinging and answers without the latency * checkTimeoutInterval : default to `30*1000` (30s), check if keepalive received at that period, disconnect otherwise. * version : 1.8 or 1.9 or false (to auto-negotiate): default to 1.8 * customPackets (optional) : an object index by version/state/direction/name, see client_custom_packet for an example * hideErrors : do not display errors, default to false * skipValidation : do not try to validate given session, defaults to false * stream : a stream to use as connection * connect : a function taking the client as parameter and that should client.setSocket(socket) and client.emit('connect') when appropriate (see the proxy examples for an example of use) * agent : a http agent that can be used to set proxy settings for yggdrasil authentication (see proxy-agent on npm) * fakeHost : (optional) hostname to send to the server in the set_protocol packet * profilesFolder : optional * (mojang account) the path to the folder that contains your `launcher_profiles.json`. defaults to your minecraft folder if it exists, otherwise the local directory. set to `false` to disable managing profiles * (microsoft account) the path to store authentication caches, defaults to .minecraft * onMsaCode(data) : (optional) callback called when signing in with a microsoft account with device code auth. `data` is an object documented [here](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-device-code#device-authorization-response) * id : a numeric client id used for referring to multiple clients in a server * validateChannelProtocol (optional) : whether or not to enable protocol validation for custom protocols using plugin channels. Defaults to true * disableChatSigning (optional) : Don't try obtaining chat signing keys from Mojang (1.19+) * realms : An object which should contain one of the following properties: `realmId` or `pickRealm`. When defined will attempt to join a Realm without needing to specify host/port. **The authenticated account must either own the Realm or have been invited to it** * realmId : The id of the Realm to join. * pickRealm(realms) : A function which will have an array of the user Realms (joined/owned) passed to it. The function should return a Realm. * Client : You can pass a custom client class to use instead of the default one, which would allow you to create completely custom communication. Also note that you can use the `stream` option instead where you can supply custom duplex, but this will still use serialization/deserialization of packets. ``` -------------------------------- ### Create a Basic Minecraft Server Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/README.md Sets up a basic Minecraft server that logs players in and sends a 'Hello, world!' chat message. Requires 'prismarine-nbt' for advanced chat formatting. ```js const mc = require('minecraft-protocol') const nbt = require('prismarine-nbt') const server = mc.createServer({ 'online-mode': true, // optional encryption: true, // optional host: '0.0.0.0', // optional port: 25565, // optional version: '1.18' }) const mcData = require('minecraft-data')(server.version) function chatText (text) { return mcData.supportFeature('chatPacketsUseNbtComponents') ? nbt.comp({ text: nbt.string(text) }) : JSON.stringify({ text }) } server.on('playerJoin', function(client) { const loginPacket = mcData.loginPacket client.write('login', { ...loginPacket, enforceSecureChat: false, entityId: client.id, hashedSeed: [0, 0], maxPlayers: server.maxPlayers, viewDistance: 10, reducedDebugInfo: false, enableRespawnScreen: true, isDebug: false, isFlat: false }) client.write('position', { x: 0, y: 255, z: 0, yaw: 0, pitch: 0, flags: 0x00 }) const message = { translate: 'chat.type.announcement', with: [ 'Server', 'Hello, world!' ] } if (mcData.supportFeature('signedChat')) { client.write('player_chat', { plainMessage: message, signedChatContent: '', unsignedChatContent: chatText(message), type: mcData.supportFeature('chatTypeIsHolder') ? { chatType: 1 } : 0, senderUuid: 'd3527a0b-bc03-45d5-a878-2aafdd8c8a43', // random senderName: JSON.stringify({ text: 'me' }), senderTeam: undefined, timestamp: Date.now(), salt: 0n, signature: mcData.supportFeature('useChatSessions') ? undefined : Buffer.alloc(0), previousMessages: [], filterType: 0, networkName: JSON.stringify({ text: 'me' }) }) } else { client.write('chat', { message: JSON.stringify({ text: message }), position: 0, sender: 'me' }) } }) ``` -------------------------------- ### Proxy Command Line Usage Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/examples/proxy/README.md This shows the basic command structure for running the proxy server, including available options for packet dumping and filtering. ```bash usage: node proxy.js [...] options: --dump name print to stdout messages with the specified name. --dump-all print to stdout all messages, except those specified with -x. -x name do not print messages with this name. name a packet name as defined in protocol.json examples: node proxy.js --dump-all -x keep_alive -x update_time -x entity_velocity -x rel_entity_move -x entity_move_look -x entity_velocity -x rel_entity_move -x entity_move_look -x entity_teleport -x entity_head_rotation -x position localhost 1.8 print all messages except for some of the most prolific. node examples/proxy.js --dump open_window --dump close_window --dump set_slot --dump window_items --dump craft_progress_bar --dump transaction --dump close_window --dump window_click --dump set_creative_slot --dump enchant_item localhost 1.8 print messages relating to inventory management. ``` -------------------------------- ### client.connect(port, host) Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Initiates a connection to a Minecraft server. This method is typically called automatically by the `createClient` function. ```APIDOC ## client.connect(port, host) Used by the [Client Class](https://github.com/PrismarineJS/node-minecraft-protocol/blob/d9d01c8be4921bb38e7b59d9c18afd771615ba22/src/client.js) to connect to a server, done by createClient automatically ``` -------------------------------- ### mc.Server(version,[customPackets]) Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Creates a server instance for a specific version of Minecraft. It can optionally accept custom packets. ```APIDOC ## mc.Server(version,[customPackets]) ### Description Creates a server instance for `version` of minecraft. Optionally accepts `customPackets`. ### Parameters * **version** (string) - The Minecraft version to support. * **customPackets** (object) - Optional. An object containing custom packet definitions. ``` -------------------------------- ### mc.Client Constructor Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Creates a new Minecraft client instance. It can be configured as either a server-side or client-side client, and supports specifying the Minecraft protocol version. ```APIDOC ## mc.Client(isServer, version, [customPackets]) Create a new client, if `isServer` is true then it is a server-side client, otherwise it's a client-side client. Takes a minecraft `version` as second argument. ``` -------------------------------- ### Enable Protocol Debugging (Windows) Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/README.md On Windows, use the `set` command to enable protocol debugging by setting the `DEBUG` environment variable to `minecraft-protocol` before executing your Node.js script. ```batch set DEBUG=minecraft-protocol node your_script.js ``` -------------------------------- ### `connection` event Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Emitted when a client connects to the server, before any login process begins. It provides the Client object. ```APIDOC ## `connection` event ### Description Called when a client connects, but before any login has happened. Takes a `Client` parameter. ### Parameters * **client** (Client) - The client object representing the new connection. ``` -------------------------------- ### Run Tests with Environment Variables Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/README.md To run tests, ensure the `java` executable is in your system's PATH. Set the `MC_SERVER_JAR_DIR`, `MC_USERNAME`, and `MC_PASSWORD` environment variables before running the npm test command. ```bash MC_SERVER_JAR_DIR=some/path/to/store/minecraft/server/ MC_USERNAME=email@example.com MC_PASSWORD=password npm test ``` -------------------------------- ### mc.supportedVersions Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Retrieves a list of all versions of Minecraft that are supported by the library. ```APIDOC ## mc.supportedVersions The supported minecraft versions. ``` -------------------------------- ### Enable Protocol Debugging (Linux/macOS) Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/README.md Enable detailed protocol debugging output by setting the `DEBUG` environment variable to `minecraft-protocol` before running your Node.js script. ```bash DEBUG="minecraft-protocol" node [...] ``` -------------------------------- ### client.end(reason, fullReason) Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Ends the client's connection. You can provide a simple `reason` string or a more detailed `fullReason` object, which can represent a chat message. ```APIDOC ## client.end(reason, fullReason) Ends the connection with `reason` or `fullReason` If `fullReason` is not defined, then the `reason` will be used. `fullReason` is a JSON object, which represents [chat](https://wiki.vg/Chat) message. ``` -------------------------------- ### WalkerBot Implementation Source: https://github.com/prismarinejs/node-minecraft-protocol/wiki/Walking-in-straight-line This snippet demonstrates how to create a Minecraft client, handle chat commands to control movement, and continuously update the bot's position to walk in a straight line. Use this for basic automated movement tasks. ```javascript //var mc = require('minecraft-protocol'); var mc = require('../'); var client = mc.createClient({ host: "cmc.im", port: 25565, username: "yourusername", password: "yourpassword", }); function x() { position.x += 0.26; refreshposition(); } var currTimeout = null; function startTimeout() { if (currTimeout == null) { console.log("Starting"); currTimeout = setInterval(x, 50); } else { console.log("Already started"); } } function stopTimeout() { if (currTimeout != null) { console.log("Stopping"); clearTimeout(currTimeout); currTimeout = null; } else { console.log("Already stopped"); } } client.on('connect',function() { console.log('Stuff to do when you recieve the connect packet!') }); client.on('chat', function(packet) { console.log(JSON.stringify(packet.message)); if (packet.message.indexOf("stop") > -1) stopTimeout(); if (packet.message.indexOf("start") > -1) startTimeout(); }); var position = { x: 0, y: 0, z: 0, }; client.on('position', function(packet) { console.log(packet); position.x = packet.x; position.y = packet.y; position.z = packet.z; refreshposition(); startTimeout(); }); function refreshposition() { if (client.state === "play") { //console.log(position); client.write('position', { x: position.x, stance: position.y - 1.62, y: position.y, z: position.z, onGround: false }); } } ``` -------------------------------- ### `login` event Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Emitted when a client has successfully logged into the server. It provides the Client object. ```APIDOC ## `login` event ### Description Called when a client is logged in against server. Takes a `Client` parameter. ### Parameters * **client** (Client) - The client object representing the logged-in player. ``` -------------------------------- ### Create Protocol Serializer Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Returns a protocol serializer for the given state, direction, and version. Use this to serialize packet data. ```javascript const mc = require('minecraft-protocol'); const states = require('minecraft-protocol').states; const serializer = mc.createSerializer({ state: states.HANDSHAKING, isServer: false, version: '1.16.1' }); ``` -------------------------------- ### Pinging a Minecraft Server Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Pings a Minecraft server to retrieve information. Options for host, port, and version can be specified. Returns a promise or uses a callback. ```javascript mc.ping(options, callback) ``` -------------------------------- ### client.registerChannel(name, typeDefinition, custom) Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Registers a new plugin channel with a specified name and type definition. This allows for custom packet handling for specific plugins. ```APIDOC ## client.registerChannel(name, typeDefinition, custom) Registers a plugin channel with the given `name` and protodef `typeDefinition` ``` -------------------------------- ### Create Protocol Deserializer Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Returns a protocol deserializer for the given state, direction, and version. Use this to parse incoming packet data. ```javascript const mc = require('minecraft-protocol'); const states = require('minecraft-protocol').states; const deserializer = mc.createDeserializer({ state: states.HANDSHAKING, isServer: false, packetsToParse: { packet: true }, version: '1.16.1' }); ``` -------------------------------- ### client.write(name, params) Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Writes a packet to the connected Minecraft server or client. The packet is identified by its `name` and its data is provided in `params`. ```APIDOC ## client.write(name, params) write a packet ``` -------------------------------- ### Troubleshoot FetchError: Socket closed Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/examples/client_socks_proxy/README.md This error typically indicates that the SOCKS5 proxy itself is not working or is not configured correctly. ```text FetchError: request to https://authserver.mojang.com/authenticate failed, reason: Socket closed - The Proxy is not working ``` -------------------------------- ### Troubleshoot SocksClientError: connect ECONNREFUSED Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/examples/client_socks_proxy/README.md This error signifies that the connection attempt to the specified proxy address failed, likely because the proxy server is unreachable or not listening on the expected port. ```text SocksClientError: connect ECONNREFUSED - The Connection to the proxy Failed ``` -------------------------------- ### client.verifyMessage(packet) Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Verifies if a player's chat message packet was signed with their Mojang provided key. This is handled internally in newer versions. ```APIDOC ## client.verifyMessage(packet) : boolean ### Description (1.19-1.19.2) Verifies if player's chat message packet was signed with their Mojang provided key. Handled internally (and thus deprecated) in 1.19.3 and above. ### Parameters * **packet** (object) - The chat message packet to verify. ### Returns * (boolean) - True if the message is verified, false otherwise. ``` -------------------------------- ### mc.createSerializer Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Creates a protocol serializer for a given state, direction, and version. ```APIDOC ## mc.createSerializer({ state = states.HANDSHAKING, isServer = false , version}) Returns a minecraft protocol [serializer](https://github.com/roblabla/ProtoDef#serializerprotomaintype) for these parameters. ``` -------------------------------- ### Test SOCKS5 Proxy Connection with Curl Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/examples/client_socks_proxy/README.md Use this command to verify your SOCKS5 proxy is functioning correctly before attempting to use it with the client. It checks if the proxy forwards your connection to an external IP address service. ```bash curl -x "socks5://:" "http://ifconfig.me" ``` -------------------------------- ### Client Properties Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Provides access to various properties of the Minecraft client, including its state, network socket, UUID, username, session details, and protocol information. ```APIDOC ### client.state The internal state that is used to figure out which protocol state we are in during packet parsing. This is one of the protocol.states. ### client.isServer True if this is a connection going from the server to the client, False if it is a connection from client to server. ### client.socket Returns the internal nodejs Socket used to communicate with this client. ### client.uuid A string representation of the client's UUID. Note that UUIDs are unique for each players, while playerNames, as of 1.7.7, are not unique and can change. ### client.username The user's username. ### client.session The user's session, as returned by the Yggdrasil system. (only client-side) ### client.profile The player's profile, as returned by the Yggdrasil system. (only server-side) ### client.latency The latency of the client, in ms. Updated at each keep alive. ### client.customPackets An object index by version/state/direction/name, see client_custom_packet for an example ### client.protocolVersion The client's protocol version ### client.version The client's version, as a string ``` -------------------------------- ### Verifying a Player Chat Packet (1.19+) Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Verifies a player's chat packet against their public key, used for security on version 1.19 and above. ```javascript client.verifyMessage(publicKey: Buffer | KeyObject, packet) ``` -------------------------------- ### server.writeToClients(clients, name, params) Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Writes a packet to multiple clients efficiently by encoding it only once. ```APIDOC ## server.writeToClients(clients, name, params) ### Description Write a packet to all `clients` but encode it only once. ### Parameters * **clients** (array) - An array of client objects to send the packet to. * **name** (string) - The name of the packet to write. * **params** (object) - The parameters for the packet. ``` -------------------------------- ### client.writeRaw(buffer) Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Writes a raw buffer directly as a packet. This is useful for sending custom or pre-formatted packet data. ```APIDOC ## client.writeRaw(buffer) write a raw buffer as a packet ``` -------------------------------- ### server.clients Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md A JavaScript object that maps client IDs to their respective Client objects. ```APIDOC ## server.clients ### Description Javascript object mapping a `Client` from a clientId. ### Usage ```javascript const client = server.clients[clientId]; ``` ``` -------------------------------- ### client.chat Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Sends a chat message to the Minecraft server. Supports message signing for versions 1.19 and above. ```APIDOC ## client.chat(message) ### Description Send a chat message to the server, with signing on 1.19+. ### Parameters #### Path Parameters - **message** (string) - Required - The chat message to send. ``` -------------------------------- ### Signing a Chat Message (1.19+) Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Generates a signature for a chat message, required for sending to the server on version 1.19 and above. Includes optional parameters for timestamp, salt, preview, and acknowledgements. ```javascript client.signMessage(message: string, timestamp: BigInt, salt?: number, preview?: string, acknowledgements?: Buffer[]) : Buffer ``` -------------------------------- ### server.playerCount Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Retrieves the current number of players connected to the server. ```APIDOC ## server.playerCount ### Description The amount of players currently present on the server. ### Usage ```javascript const count = server.playerCount; ``` ``` -------------------------------- ### Troubleshoot SocksClientError: Proxy connection timed out Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/examples/client_socks_proxy/README.md A timeout error suggests that the destination address is incorrect or unreachable, or that the proxy server is not responding within the expected timeframe. ```text SocksClientError: Proxy connection timed out - Destination Address is wrong/not reachable. Or the Proxy is not working ``` -------------------------------- ### Event Listeners Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Defines various events that can be listened to, allowing developers to react to different occurrences within the client's lifecycle, such as packet reception, connection status, errors, and chat messages. ```APIDOC ### `packet` event Called with every packet parsed. Takes four paramaters, the JSON data we parsed, the packet metadata (name, state), the buffer (raw data) and the full buffer (includes surplus data and may include the data of following packets on versions below 1.8) ### `raw` event Called with every packet, but as a buffer. Takes two params, the buffer and the packet metadata (name, state) ### `connect` event when the socket connects to the server, this is emitted ### `end` event Called when the client's connection is disconnected. Takes the reason as parameter ### `session` event Called when user authentication is resolved. Takes session data as parameter. ### `state` event Called when the protocol changes state. Takes the new state and old state as parameters. ### `playerJoin` event Emitted after the player enters the PLAY protocol state and can send and recieve game packets ### `error` event Called when an error occurs within the client. Takes an Error as parameter. ### `playerChat` event Called when a chat message from another player arrives. The emitted object contains: * formattedMessage -- (JSON) the chat message preformatted, if done on server side * plainMessage -- (Plaintext) the chat message without formatting (for example no ` message` ; instead `message`), on version 1.19+ * unsignedContent -- (JSON) unsigned formatted chat contents ; should only be present when the message is modified and server has chat previews disabled - only on version 1.19 - 1.19.2 * type -- the message type - on 1.19, which format string to use to render message ; below, the place where the message is displayed (for example chat or action bar) * sender -- the UUID of the player sending the message * senderTeam -- scoreboard team of the player (pre 1.19) * senderName -- Name of the sender * targetName -- Name of the target (for outgoing commands like /tell). Only in 1.19.2+ * verified -- true if message is signed, false if not signed, undefined on versions prior to 1.19 ### `systemChat` event Called when a system chat message arrives. A system chat message is any message not sent by a player. The emitted object contains: * formattedMessage -- (JSON) the chat message preformatted * positionId -- the chat type of the message. 1 for system chat and 2 for actionbar See the [chat example](https://github.com/PrismarineJS/node-minecraft-protocol/blob/master/examples/client_chat/client_chat.js#L1) for usage. ### per-packet events Check out the [minecraft-data docs](https://prismarinejs.github.io/minecraft-data/?v=1.8&d=protocol) to know the event names and data field names. ``` -------------------------------- ### client.setSocket(socket) Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Replaces the client's internal network socket with a provided one. This allows for custom network configurations or integrations. ```APIDOC ## client.setSocket(socket) Sets the client's connection socket. ``` -------------------------------- ### mc.ping Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Pings a Minecraft server to retrieve information about it. It can be used with either a promise-based approach or a callback function. Options for host, port, and version can be provided. ```APIDOC ## mc.ping(options, callback) ### Description Ping a minecraft server and return a promise or use an optional callback containing the information about it. ### Parameters #### Path Parameters - **options** (object) - Optional - An object containing connection options. - **host** (string) - Optional - The hostname or IP address of the server (defaults to 'localhost'). - **port** (number) - Optional - The port of the server (defaults to 25565). - **version** (string) - Optional - The Minecraft version to use for the ping (defaults to the most recent version). - **callback** (function) - Optional - A callback function to handle the results or errors. ### Returns - `promise( ).then(pingResult).catch(err)`: A promise that resolves with ping results or rejects with an error. - `callback(err, pingResults)`: If a callback is provided, it will be called with an error (if any) and the ping results. ``` -------------------------------- ### client.writeChannel(channel, params) Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Writes data to a registered plugin channel. This is used for communication with plugins that utilize custom channels. ```APIDOC ## client.writeChannel(channel, params) Write to [Plugin Channels](https://wiki.vg/Plugin_channels) ``` -------------------------------- ### mc.createDeserializer Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Creates a protocol deserializer for a given state, direction, and version, with options for parsing specific packets. ```APIDOC ## mc.createDeserializer({ state = states.HANDSHAKING, isServer = false, packetsToParse = {"packet": true}, version }) Returns a minecraft protocol [deserializer](https://github.com/roblabla/ProtoDef#parserprotomaintype) for these parameters. ``` -------------------------------- ### `playerJoin` event Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Emitted after a player joins and enters the PLAY protocol state, allowing them to send and receive game packets. This event is crucial for newer Minecraft versions (1.20.2+) after the login and CONFIG state. ```APIDOC ## `playerJoin` event ### Description Emitted after a player joins and enters the PLAY protocol state and can send and recieve game packets. This is emitted after the `login` event. On 1.20.2 and above after we emit the `login` event, the player will enter a CONFIG state, as opposed to the PLAY state (where game packets can be sent), so you must instead now wait for `playerJoin`. ### Parameters * **client** (Client) - The client object representing the player who has joined. ``` -------------------------------- ### mc.states Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Provides access to the different states within the Minecraft protocol. ```APIDOC ## mc.states The minecraft protocol states. ``` -------------------------------- ### `close` event Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Called when the server stops listening for incoming connections. ```APIDOC ## `close` event ### Description Called when the server is no longer listening to incoming connections. ``` -------------------------------- ### client.verifyMessage Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Verifies a player's chat packet against their public key, specifically for Minecraft version 1.19 and above. This function helps ensure the authenticity of messages received from other players. ```APIDOC ## client.verifyMessage(publicKey: Buffer | KeyObject, packet) : boolean ### Description (1.19) Verifies a player chat packet sent by another player against their public key. ### Parameters #### Path Parameters - **publicKey** (Buffer | KeyObject) - Required - The public key to verify against. - **packet** (object) - Required - The chat packet to verify. ``` -------------------------------- ### Echo Chat Messages Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/README.md Connects to a Minecraft server and echoes back any chat messages received. Ensure the server is running and accessible. ```js const mc = require('minecraft-protocol'); const client = mc.createClient({ host: "localhost", // optional port: 25565, // set if you need a port that isn't 25565 username: 'Bot', // username to join as if auth is `offline`, else a unique identifier for this account. Switch if you want to change accounts // version: false, // only set if you need a specific version or snapshot (ie: "1.8.9" or "1.16.5"), otherwise it's set automatically // password: '12345678' // set if you want to use password-based auth (may be unreliable). If specified, the `username` must be an email }); client.on('playerChat', function (ev) { // Listen for chat messages and echo them back. const content = ev.formattedMessage ? JSON.parse(ev.formattedMessage) : ev.unsignedChat ? JSON.parse(ev.unsignedContent) : ev.plainMessage const jsonMsg = JSON.parse(packet.message) if (ev.senderName === client.username) return client.chat(JSON.stringify(content)) }); ``` -------------------------------- ### server.maxPlayers Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Retrieves the maximum number of players allowed on the server. ```APIDOC ## server.maxPlayers ### Description The maximum amount of players allowed on the server. ### Usage ```javascript const max = server.maxPlayers; ``` ``` -------------------------------- ### server.onlineModeExceptions Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md A plain JavaScript object used to specify usernames that should be exempt from online mode checks. ```APIDOC ## server.onlineModeExceptions ### Description This is a plain old JavaScript object. Add a key with the username you want to be exempt from online mode or offline mode (whatever mode the server is in). Make sure the entries in this object are all lower case. ### Usage ```javascript server.onlineModeExceptions.add('username'); ``` ``` -------------------------------- ### client.signMessage Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Generates a digital signature for a chat message, intended for use in Minecraft versions 1.19 and later. This is crucial for authenticating chat messages sent to the server. ```APIDOC ## client.signMessage(message: string, timestamp: BigInt, salt?: number, preview?: string, acknowledgements?: Buffer[]) : Buffer ### Description (1.19) Generate a signature for a chat message to be sent to server. ### Parameters #### Path Parameters - **message** (string) - Required - The chat message to sign. - **timestamp** (BigInt) - Required - The timestamp of the message. - **salt** (number) - Optional - A salt value for the signature. - **preview** (string) - Optional - A preview of the message. - **acknowledgements** (Buffer[]) - Optional - Acknowledgements for the message. ``` -------------------------------- ### Sending a Chat Message Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Sends a chat message to the server. Message signing is enabled for versions 1.19 and later. ```javascript client.chat(message) ``` -------------------------------- ### Troubleshoot Connection Refused: Blocked by CloudFront/CloudFlare Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/examples/client_socks_proxy/README.md If you encounter this error, it means the IP address of your SOCKS5 proxy has been identified and blocked by services like Cloudflare or CloudFront, preventing further connections. ```text Connection Refused: Blocked by CloudFront/CloudFlare - Proxy Ip has been banned/block by Cloudflare. ``` -------------------------------- ### client.unregisterChannel(name) Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Unregisters a previously registered plugin channel by its name. ```APIDOC ## client.unregisterChannel(name) Unregisters a plugin channel. ``` -------------------------------- ### Troubleshoot SocksClientError: Socket closed Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/examples/client_socks_proxy/README.md A general socket error, this often means the proxy is bad or is actively refusing the connection. ```text SocksClientError: Socket closed - General Socket error Bad Proxy/Proxy refuses the connection ``` -------------------------------- ### client.logSentMessageFromPeer(packet) Source: https://github.com/prismarinejs/node-minecraft-protocol/blob/master/docs/API.md Logs a sent message from a peer, which is necessary for maintaining chat chain integrity. ```APIDOC ## client.logSentMessageFromPeer(packet) ### Description (1.19.1+) You must call this function when the server receives a message from a player and that message gets broadcast to other players in player_chat packets. This function stores these packets so the server can then verify a player's lastSeenMessages field in inbound chat packets to ensure chain integrity. For more information, see [chat.md](chat.md). ### Parameters * **packet** (object) - The packet containing the message from a peer. ```