Convert Figma logo to code with AI

PrismarineJS logonode-minecraft-protocol

Parse and serialize minecraft packets, plus authentication and encryption.

1,218
238
1,218
101

Top Related Projects

Create Minecraft bots with a powerful, stable, and high level JavaScript API.

Brigadier is a command parser & dispatcher, designed and developed for Minecraft: Java Edition.

A lightweight, fast and extensible game server for Minecraft

BungeeCord, the 6th in a generation of server portal suites. Efficiently proxies and maintains connections and transport between multiple Minecraft servers.

Quick Overview

The node-minecraft-protocol project is a Node.js library that provides a low-level implementation of the Minecraft protocol, allowing developers to create custom Minecraft clients, servers, and tools. It supports a wide range of Minecraft versions and can be used to build a variety of Minecraft-related applications.

Pros

  • Cross-Version Compatibility: The library supports a wide range of Minecraft versions, making it suitable for building applications that need to work with different versions of the game.
  • Extensibility: The library is designed to be modular and extensible, allowing developers to easily add new features and functionality as needed.
  • Active Development: The project is actively maintained and developed, with regular updates and bug fixes.
  • Comprehensive Documentation: The project has detailed documentation that covers a wide range of topics, making it easier for developers to get started and understand how to use the library.

Cons

  • Complexity: The library can be quite complex, especially for developers who are new to Minecraft or low-level network programming.
  • Performance: Depending on the use case, the library may not be the most performant option, as it is a general-purpose implementation of the Minecraft protocol.
  • Limited Abstraction: The library provides a low-level implementation of the Minecraft protocol, which may not be suitable for developers who are looking for a higher-level abstraction.
  • Steep Learning Curve: Developers who are new to Minecraft or network programming may find the learning curve for this library to be quite steep.

Code Examples

Here are a few examples of how to use the node-minecraft-protocol library:

  1. Creating a Minecraft Client:
const mc = require('minecraft-protocol');

const client = mc.createClient({
  host: 'example.com', // optional
  port: 25565,        // optional
  username: 'player', // email and password are required for online mode
  password: 'secret'  // password is required for online mode
});

client.on('login', () => {
  console.log('Logged in!');
});

client.on('error', (err) => {
  console.log('Error:', err.toString());
});
  1. Creating a Minecraft Server:
const mc = require('minecraft-protocol');

const server = mc.createServer({
  'online-mode': true, // optional
  encryption: true,    // optional
  host: '0.0.0.0',      // optional
  port: 25565,         // optional
  version: '1.16.5'    // required
});

server.on('login', (client) => {
  console.log(`${client.username} joined the game!`);

  client.on('chat', (message) => {
    console.log(`${client.username}: ${message}`);
    server.broadcast(`${client.username}: ${message}`);
  });
});

server.on('error', (err) => {
  console.log('Error:', err.toString());
});
  1. Parsing Minecraft Packets:
const mc = require('minecraft-protocol');

const client = mc.createClient({
  host: 'example.com',
  port: 25565,
  username: 'player',
  password: 'secret'
});

client.on('packet', (data, meta) => {
  console.log(`Received packet: ${meta.name}`);
  console.log(data);
});

Getting Started

To get started with the node-minecraft-protocol library, follow these steps:

  1. Install the library using npm:
npm install minecraft-protocol
  1. Import the library in your JavaScript file:
const mc = require('minecraft-protocol');
  1. Create a Minecraft client or server using the provided methods:
const client = mc.createClient({
  host: 'example.com',
  port: 25565,
  username: 'player',
  password: 'secret'
});

// or

const server = mc.createServer({
  'online-mode': true,
  encryption: true,
  host: '0.0.0.0',
  port: 25565,

Competitor Comparisons

Create Minecraft bots with a powerful, stable, and high level JavaScript API.

Pros of mineflayer

  • Higher-level abstraction, providing a more user-friendly API for bot creation
  • Built-in functionality for common bot tasks like pathfinding and inventory management
  • Extensive plugin system for extending functionality

Cons of mineflayer

  • Potentially slower performance due to higher-level abstractions
  • May have a steeper learning curve for developers familiar with raw protocol handling

Code Comparison

mineflayer:

const mineflayer = require('mineflayer')
const bot = mineflayer.createBot({ username: 'player' })

bot.on('chat', (username, message) => {
  if (message === 'hello') bot.chat('Hi!')
})

node-minecraft-protocol:

const mc = require('minecraft-protocol')
const client = mc.createClient({ username: 'player' })

client.on('chat', (packet) => {
  if (packet.message === 'hello') {
    client.write('chat', { message: 'Hi!' })
  }
})

The mineflayer example demonstrates its higher-level API, handling chat events and responses more intuitively. The node-minecraft-protocol example shows its lower-level approach, dealing directly with packet handling and writing.

Both libraries are part of the PrismarineJS ecosystem and can be used together, with mineflayer built on top of node-minecraft-protocol for those needing a more abstracted approach to Minecraft bot development.

Brigadier is a command parser & dispatcher, designed and developed for Minecraft: Java Edition.

Pros of brigadier

  • Official Minecraft command parsing library developed by Mojang
  • Lightweight and focused solely on command parsing and dispatching
  • Supports multiple programming languages (Java, C#, etc.)

Cons of brigadier

  • Limited to command parsing, doesn't handle network protocol
  • Less community-driven development and contributions
  • Narrower scope compared to node-minecraft-protocol

Code Comparison

brigadier (Java):

LiteralArgumentBuilder<CommandSource> command = LiteralArgumentBuilder.<CommandSource>literal("foo")
    .then(RequiredArgumentBuilder.<CommandSource, Integer>argument("bar", IntegerArgumentType.integer())
        .executes(c -> {
            // Command logic here
            return 1;
        }));

node-minecraft-protocol (JavaScript):

client.on('chat', (packet) => {
  const message = packet.message;
  if (message === '/foo') {
    client.write('chat', { message: 'Command executed!' });
  }
});

Summary

brigadier is Mojang's official command parsing library, offering a lightweight and focused solution for Minecraft command handling. It supports multiple languages but is limited to command parsing. node-minecraft-protocol, on the other hand, is a community-driven project that provides a more comprehensive solution for interacting with the Minecraft protocol, including networking and various game features. The choice between the two depends on the specific requirements of your project and the level of integration needed with the Minecraft ecosystem.

A lightweight, fast and extensible game server for Minecraft

Pros of cuberite

  • Written in C++, offering potentially better performance for server hosting
  • Designed as a full server implementation, providing more control over game mechanics
  • Supports plugins written in Lua, allowing for easier server customization

Cons of cuberite

  • Limited to server-side implementation, not suitable for client-side development
  • May have less frequent updates compared to node-minecraft-protocol
  • Smaller community and ecosystem compared to Node.js-based solutions

Code comparison

node-minecraft-protocol (JavaScript):

const mc = require('minecraft-protocol');
const client = mc.createClient({
  host: "localhost",
  port: 25565,
  username: "player"
});

cuberite (C++):

#include "Globals.h"
#include "Server.h"

int main()
{
    cServer Server;
    Server.Start();
    return 0;
}

node-minecraft-protocol focuses on providing a flexible protocol implementation for both client and server development in JavaScript, while cuberite is a complete server implementation in C++ with a focus on performance and customization through Lua plugins. node-minecraft-protocol may be more suitable for rapid prototyping and cross-platform development, whereas cuberite might be preferred for dedicated server hosting and performance-critical applications.

BungeeCord, the 6th in a generation of server portal suites. Efficiently proxies and maintains connections and transport between multiple Minecraft servers.

Pros of BungeeCord

  • Robust and widely-used proxy server for Minecraft
  • Supports multiple Minecraft versions and server types
  • Extensive plugin ecosystem for customization

Cons of BungeeCord

  • Java-based, which may have a steeper learning curve for some developers
  • Primarily focused on server-side functionality, not client-side interactions
  • May require more resources to run compared to lightweight alternatives

Code Comparison

BungeeCord (Java):

@EventHandler
public void onServerConnect(ServerConnectEvent event) {
    event.getPlayer().sendMessage(new TextComponent("Connecting to server..."));
}

node-minecraft-protocol (JavaScript):

client.on('login', (data) => {
  console.log('Logged in to server');
});

Summary

BungeeCord is a powerful, server-side proxy solution for Minecraft, offering extensive customization through plugins and support for multiple server types. It's well-established in the Minecraft server community but requires Java knowledge.

node-minecraft-protocol, on the other hand, is a JavaScript library focused on client-side interactions with Minecraft servers. It's more lightweight and accessible for web developers but may lack some of the advanced server management features of BungeeCord.

The choice between these two depends on your specific needs: server management and proxying (BungeeCord) or client-side interactions and bot development (node-minecraft-protocol).

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

minecraft protocol

NPM version Build Status Discord Gitter Irc

Try it on gitpod

Parse and serialize minecraft packets, plus authentication and encryption.

Features

  • Supports Minecraft PC version 1.7.10, 1.8.8, 1.9 (15w40b, 1.9, 1.9.1-pre2, 1.9.2, 1.9.4), 1.10 (16w20a, 1.10-pre1, 1.10, 1.10.1, 1.10.2), 1.11 (16w35a, 1.11, 1.11.2), 1.12 (17w15a, 17w18b, 1.12-pre4, 1.12, 1.12.1, 1.12.2), and 1.13 (17w50a, 1.13, 1.13.1, 1.13.2-pre1, 1.13.2-pre2, 1.13.2), 1.14 (1.14, 1.14.1, 1.14.3, 1.14.4) , 1.15 (1.15, 1.15.1, 1.15.2) and 1.16 (20w13b, 20w14a, 1.16-rc1, 1.16, 1.16.1, 1.16.2, 1.16.3, 1.16.4, 1.16.5), 1.17 (21w07a, 1.17, 1.17.1), 1.18 (1.18, 1.18.1 and 1.18.2), 1.19 (1.19, 1.19.1, 1.19.2, 1.19.3, 1.19.4), 1.20 (1.20, 1.20.1, 1.20.2, 1.20.3 and 1.20.4)
  • Parses all packets and emits events with packet fields as JavaScript objects.
  • Send a packet by supplying fields as a JavaScript object.
  • Client
    • Authenticating and logging in
    • Encryption
    • Compression
    • Both online and offline mode
    • Respond to keep-alive packets
    • Follow DNS service records (SRV)
    • Ping a server for status
  • Server
    • Online/Offline mode
    • Encryption
    • Compression
    • Handshake
    • Keep-alive checking
    • Ping status
  • Robust test coverage.
  • Optimized for rapidly staying up to date with Minecraft protocol updates.

Want to contribute on something important for PrismarineJS ? go to https://github.com/PrismarineJS/mineflayer/wiki/Big-Prismarine-projects

Third Party Plugins

node-minecraft-protocol is pluggable.

Projects Using node-minecraft-protocol

  • mineflayer - Create minecraft bots with a stable, high level API.
  • mcserve - Runs and monitors your minecraft server, provides real-time web interface, allow your users to create bots.
  • flying-squid - Create minecraft servers with a high level API, also a minecraft server by itself.
  • pakkit - A GUI tool to monitor Minecraft packets in real time, allowing you to view their data and interactively edit and resend them.
  • minecraft-packet-debugger - A tool to capture Minecraft packets in a buffer then view them in a browser.
  • aresrpg - An open-source mmorpg minecraft server.
  • SteveProxy - Proxy for Minecraft with the ability to change the gameplay using plugins.
  • and several thousands others

Installation

npm install minecraft-protocol

Documentation

Usage

Echo client example

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))
});

Set auth to offline if the server is in offline mode. If auth is set to microsoft, you will be prompted to login to microsoft.com with a code in your browser. After signing in on your browser, the client will automatically obtain and cache authentication tokens (under your specified username) so you don't have to sign-in again.

To switch the account, update the supplied username. By default, cached tokens will be stored in your user's .minecraft folder, or if profilesFolder is specified, they'll instead be stored there. For more information on bot options see the API doc.

Note: SRV records will only be looked up if the port is unspecified or set to 25565 and if the host is a valid non-local domain name.

Client example joining a Realm

Example to connect to a Realm that the authenticating account is owner of or has been invited to:

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'
})

Hello World server example

For a more up to date example, see examples/server/server.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,
    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: 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' })
  }
})

Testing

  • Ensure your system has the java executable in PATH.
  • MC_SERVER_JAR_DIR=some/path/to/store/minecraft/server/ MC_USERNAME=email@example.com MC_PASSWORD=password npm test

Debugging

You can enable some protocol debugging output using DEBUG environment variable:

DEBUG="minecraft-protocol" node [...]

On Windows:

set DEBUG=minecraft-protocol
node your_script.js

Contribute

Please read https://github.com/PrismarineJS/prismarine-contribute

History

See history

Related

  • node-rcon can be used to access the rcon server in the minecraft server
  • map-colors can be used to convert any image into a buffer of minecraft compatible colors

NPM DownloadsLast 30 Days