mcwss

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 11, 2023 License: MIT Imports: 20 Imported by: 0

README

mcwss

A documentation and implementation of the Minecraft Bedrock Edition websocket protocol.

Minecraft Websockets

Minecraft has websocket connection commands that may be used to connect to a websocket server. These commands are /connect and /wsserver. Both these commands have the same effect. Once connected to a websocket, the connection will last until the server closes it or until the player completely exits the game. The connection will last when a player merely leaves a world, and will thus last when joining a server. Websockets in Minecraft can be used for simple command communication between a player and a server. Additionally, the server can choose to listen for certain events sent by the client and act upon receiving them.

In order to be able to execute the /connect and /wsserver commands, cheats must be enabled. This means that connecting on third party servers is not possible, and only on the dedicated server when cheats are enabled. It is possible to connect on a singleplayer world and join a server after that, but commands executed by the websocket server will not work. Events will still be sent by the client however.

In the settings tab, there is also a setting that enables/disables encrypted websockets. mcwss implements encryption between websockets, so changing this setting will not have an effect on the behaviour of mcwss.

Getting Started

Prerequisites

mcwss is a Go library. To use it, Go must be installed. The library may be downloaded using go get github.com/sandertv/mcwss.

Usage
package main

import (
	"github.com/sandertv/mcwss"
)

func main() {
    // Create a new server using the default configuration. To use specific configuration, pass a *wss.Config{} in here.
    server := mcwss.NewServer(nil)
    
    server.OnConnection(func(player *mcwss.Player){
      // Called when a player connects to the server.
    })
    server.OnDisconnection(func(player *mcwss.Player){
      // Called when a player disconnects from the server.
    })
    // Run the server. (blocking)
    server.Run()
}

The server may now be connected to by joining a singleplayer game and executing the command /connect localhost:8000/ws.

Documentation

https://godoc.org/github.com/Sandertv/mcwss

Documentation

Overview

Package mcwss implements a websocket server to be used with Minecraft Bedrock Edition. It aims to implement most of the protocol and abstraction around it to achieve and easy to use API for interacting with the client.

When using mcwss.NewServer(nil), the default configuration is used. Once the server is ran, (Server.Run()) your client may connect to it using `/connect localhost:8000/ws'. The client will remain connected to the websocket until it either connects to a new one or closes the entire game, or when the websocket server chooses to forcibly close the connection.

After connecting to a websocket server in a world that has cheats enabled, it is possible to join (online) games, like Mineplex, or other single player worlds, that do not have cheats enabled. Executing commands or other actions that would modify the world are not available on those servers, but events will still be sent by the client as expected.

Index

Constants

View Source
const MinecraftWSEncryptSubprotocol = "com.microsoft.minecraft.wsencrypt"

MinecraftWSEncryptSubprotocol is the subprotocol used for encrypted websocket connections in Minecraft.

Variables

This section is empty.

Functions

This section is empty.

Types

type Agent

type Agent struct {
	// contains filtered or unexported fields
}

Agent is the agent of a player. The agent is an entity that can be created and controlled using websockets.

func NewAgent

func NewAgent(player *Player) *Agent

NewAgent returns a new agent for the player passed.

func (*Agent) Attack

func (agent *Agent) Attack(direction mctype.Direction)

Attack makes the agent attack up to one block in a given direction.

func (*Agent) DestroyBlock

func (agent *Agent) DestroyBlock(direction mctype.Direction)

DestroyBlock makes the agent destroy a block in a direction. The agent can break any block, regardless of whether the block is breakable in survival mode or not. Bedrock, water etc. can be broken.

func (*Agent) Move

func (agent *Agent) Move(direction mctype.Direction, metres int)

Move moves the agent in a given direction for a given amount of metres.

func (*Agent) Position

func (agent *Agent) Position(f func(position mctype.Position))

Position requests the position of the agent and passes it into the function passed when a response is received.

func (*Agent) Rotation

func (agent *Agent) Rotation(f func(yRotation float64))

Rotation requests the rotation of the agent and passes it into the function passed when a response is received.

func (*Agent) TillBlock

func (agent *Agent) TillBlock(direction mctype.Direction)

TillBlock makes the agent till a block in a given direction using a hoe. Tilling does not appear to work in non-edu mode, and seems to often crash the game instead.

func (*Agent) TurnLeft

func (agent *Agent) TurnLeft()

TurnLeft turns the agent 90 degrees to the left.

func (*Agent) TurnRight

func (agent *Agent) TurnRight()

TurnRight turns the agent 90 degrees to the right.

func (*Agent) UseHeldItem

func (agent *Agent) UseHeldItem(direction mctype.Direction)

UseHeldItem makes the agent place its held item, provided it is a block, in a given direction.

type Config

type Config struct {
	// HandlerPattern is the handler pattern on which the websocket server may be found. By default, this
	// value is '/ws'.
	HandlerPattern string
	// Address is the address+port on which the websocket server is running. By default, this is ':8000'.
	Address string
}

Config is the configuration of the websocket server.

type Player

type Player struct {
	*websocket.Conn

	event.Properties

	sync.Mutex
	// contains filtered or unexported fields
}

Player is a player connected to the websocket server.

func NewPlayer

func NewPlayer(conn *websocket.Conn) *Player

NewPlayer returns an initialised player for a websocket connection.

func (*Player) Agent

func (player *Player) Agent() *Agent

Agent returns the controllable agent entity of the player.

func (*Player) CloseChat

func (player *Player) CloseChat()

CloseChat closes the chat window of a player if the player has it open. This command is available also on third party servers.

func (*Player) CloseConnection

func (player *Player) CloseConnection()

CloseConnection closes the socket connection with the player. The player will be closed shortly after this method is called.

func (*Player) Connected

func (player *Player) Connected() bool

Connected checks if a player is currently connected. If not, the reference to this player should be released as soon as possible.

func (*Player) EduInformation

func (player *Player) EduInformation(f func(info *command.EduClientInfo))

EduInformation requests information about the player (specifically education edition related, but education edition needs not to be enabled) and calls the function passed when a response is received.

func (*Player) EnableDebug

func (player *Player) EnableDebug()

EnableDebug enables debug messages for a player. It will output messages about missing fields in events and related.

func (*Player) Exec

func (player *Player) Exec(commandLine string, callback interface{})

Exec sends a command string with a callback that can process the output of the command. The callback passed must have one input argument, being the container of the output. This may be done using either a pointer to a struct, or a map, like so:

player.Exec("getlocalplayername", func(response *command.LocalPlayerName){}) player.Exec("getlocalplayername", func(response map[string]interface{}){})

Nil may also be passed if no callback needs to be executed.

func (*Player) ExecAs

func (player *Player) ExecAs(commandLine string, callback func(statusCode int))

ExecAs sends a command string as if it were sent by the player itself with a callback that can process the output of the command. The callback passed must have one input argument, being the container of the output. The output of the command is captured by the player, not by the websocket server. Only a status code is captured by the server that indicates if the command was successful.

func (*Player) Name

func (player *Player) Name() string

Name returns the name of the player.

func (*Player) OnAwardAchievement

func (player *Player) OnAwardAchievement(handler func(event *event.AwardAchievement))

OnAwardAchievement listens to achievements awarded to the player. Note that achievements are not awarded in worlds that have cheats enabled.

func (*Player) OnBlockBroken

func (player *Player) OnBlockBroken(handler func(event *event.BlockBroken))

OnBlockBroken subscribes to blocks broken by the player.

func (*Player) OnBlockPlaced

func (player *Player) OnBlockPlaced(handler func(event *event.BlockPlaced))

OnBlockPlaced subscribes to blocks placed by the player.

func (*Player) OnBookEdited

func (player *Player) OnBookEdited(handler func(event *event.BookEdited))

OnBookEdited subscribes to edits by the player to a book after closing it.

func (*Player) OnEndOfDay

func (player *Player) OnEndOfDay(handler func(event *event.EndOfDay))

OnEndOfDay subscribes to events called when the end of a day was reached naturally. (without commands)

func (*Player) OnGameRulesLoaded

func (player *Player) OnGameRulesLoaded(handler func(event *event.GameRulesLoaded))

OnGameRulesLoaded listens for the game rules to be loaded for a player. This happens when the player joins a game, regardless whether it's multi-player or single-player.

func (*Player) OnGameRulesUpdated

func (player *Player) OnGameRulesUpdated(handler func(event *event.GameRulesUpdated))

OnGameRulesUpdated listens for game rule updates for a player. This event is called whenever a specific game rule is changed.

func (*Player) OnItemAcquired

func (player *Player) OnItemAcquired(handler func(event *event.ItemAcquired))

OnItemAcquired listens to items acquired by the player, for example by picking items up or by getting items from a chest.

func (*Player) OnItemCrafted

func (player *Player) OnItemCrafted(handler func(event *event.ItemCrafted))

OnItemCrafted subscribes to items crafted by the player.

func (*Player) OnItemDropped

func (player *Player) OnItemDropped(handler func(event *event.ItemDropped))

OnItemDropped listens for items dropped on the ground by the player.

func (*Player) OnItemEquipped

func (player *Player) OnItemEquipped(handler func(event *event.ItemEquipped))

OnItemEquipped listens for items equipped by the player. This includes armour, pumpkins, elytras and other items that may be worn.

func (*Player) OnItemInteracted

func (player *Player) OnItemInteracted(handler func(event *event.ItemInteracted))

OnItemInteracted subscribes to interactions made using items by the player.

func (*Player) OnItemNamed

func (player *Player) OnItemNamed(handler func(event *event.ItemNamed))

OnItemNamed listens for items named by a player using an anvil.

func (*Player) OnItemSmelted

func (player *Player) OnItemSmelted(handler func(event *event.ItemSmelted))

OnItemSmelted listens for items smelted by the player and taken out of the inventory.

func (*Player) OnItemUsed

func (player *Player) OnItemUsed(handler func(event *event.ItemUsed))

OnItemUsed subscribes to items used by the player.

func (*Player) OnMobBorn

func (player *Player) OnMobBorn(handler func(event *event.MobBorn))

OnMobBorn listens for entities born by the player feeding two entities.

func (*Player) OnMobInteracted

func (player *Player) OnMobInteracted(handler func(event *event.MobInteracted))

OnMobInteracted subscribes to events called when the player interacts with a mob, in a way that has actually has a result.

func (*Player) OnMobKilled

func (player *Player) OnMobKilled(handler func(event *event.MobKilled))

OnMobKilled listens for entities that were killed by the entity. Note that indirect killing methods such as drowning an entity, hitting off an edge, suffocating it etc. does not trigger the event.

func (*Player) OnPlayerMessage

func (player *Player) OnPlayerMessage(handler func(event *event.PlayerMessage))

OnPlayerMessage subscribes to player messages sent and received by the client.

func (*Player) OnScreenChanged

func (player *Player) OnScreenChanged(handler func(event *event.ScreenChanged))

OnScreenChanged listens for the screen of the player being changed. Note that this is not sent every time anything is changed on the screen, but rather when a player switches to a completely different screen.

func (*Player) OnScriptLoaded

func (player *Player) OnScriptLoaded(handler func(event *event.ScriptLoaded))

OnScriptLoaded listens for scripts that are loaded by the player.

func (*Player) OnScriptRan

func (player *Player) OnScriptRan(handler func(event *event.ScriptRan))

OnScriptRan listens for scripts that are ran immediately after they are loaded. This event is called once immediately hen the player spawns, even though the script might still be running after that.

func (*Player) OnSignInToXBOXLive

func (player *Player) OnSignInToXBOXLive(handler func(event *event.SignInToXBOXLive))

OnSignInToXBOXLive listens for the player signing into XBOX Live.

func (*Player) OnSignOutOfXBOXLive

func (player *Player) OnSignOutOfXBOXLive(handler func(event *event.SignOutOfXBOXLive))

OnSignOutOfXBOXLive listens for the player signing out of XBOX Live.

func (*Player) OnSignedBookOpened

func (player *Player) OnSignedBookOpened(handler func(event *event.SignedBookOpened))

OnSignedBookOpened subscribes to signed books opened by the player.

func (*Player) OnSlashCommandExecuted

func (player *Player) OnSlashCommandExecuted(handler func(event *event.SlashCommandExecuted))

OnSlashCommandExecuted listens for commands executed by a player that actually existed. Unknown commands do not result in this event being called.

func (*Player) OnStartWorld

func (player *Player) OnStartWorld(handler func(event *event.StartWorld))

OnStartWorld subscribes to events called when the player starts a world by clicking it in the main menu. It includes both servers and singleplayer worlds. The event provides no information about the world.

func (*Player) OnTeleported

func (player *Player) OnTeleported(handler func(event *event.PlayerTeleported))

OnTeleported listens for teleportations done by the player, such as using the /tp command or throwing an ender pearl.

func (*Player) OnTransform

func (player *Player) OnTransform(handler func(event *event.PlayerTransform))

OnTransform subscribes to transformations done to the player, usually sent by means such as teleporting.

func (*Player) OnTravelled

func (player *Player) OnTravelled(handler func(event *event.PlayerTravelled))

OnTravelled subscribes to the player travelling to places.

func (*Player) OnVehicleExited

func (player *Player) OnVehicleExited(handler func(event *event.VehicleExited))

OnVehicleExited listens for the player exiting a vehicle such as a minecart or a horse.

func (*Player) OnWorldGenerated

func (player *Player) OnWorldGenerated(handler func(event *event.WorldGenerated))

OnWorldGenerated subscribes to events called when a player generates a new singleplayer world.

func (*Player) OnWorldLoaded

func (player *Player) OnWorldLoaded(handler func(event *event.WorldLoaded))

OnWorldLoaded subscribes to events called when the player loads a world. This happens both when joining servers and singleplayer worlds, and happens directly after the StartGamePacket is called. The event supplies some of the data of this packet.

func (*Player) Position

func (player *Player) Position(f func(position mctype.Position))

Position requests the position of a player and calls the function passed when a response is received, containing the position of the player.

func (*Player) Rotation

func (player *Player) Rotation(f func(rotation float64))

Rotation requests the Y-Rotation (yaw) of a player and calls the function passed when a response is received, containing the rotation of the player.

func (*Player) Say

func (player *Player) Say(message string, parameters ...interface{})

Say broadcasts a message as the player to all players in the world of the player.

func (*Player) SendMessage

func (player *Player) SendMessage(message string, parameters ...interface{})

SendMessage sends a message that only the player receives. Its behaviour is synonymous with fmt.Sprintf(), putting all parameters in the string using formatting identifiers.

func (*Player) Tell

func (player *Player) Tell(message string, parameters ...interface{})

Tell tells the player a private message. Its behaviour is synonymous with fmt.Sprintf(), putting all parameters in the string using formatting identifiers.

func (*Player) UnsubscribeFrom

func (player *Player) UnsubscribeFrom(eventName event.Name)

UnsubscribeFrom unsubscribes from events with the event name passed. The handler used to handle the event will no longer be called.

func (*Player) UnsubscribeFromAll

func (player *Player) UnsubscribeFromAll()

UnsubscribeFromAll unsubscribes from all events previously listened on. No more events will be received.

func (*Player) World

func (player *Player) World() *World

World returns the world of the player.

func (*Player) WriteJSON

func (player *Player) WriteJSON(v interface{}) error

WriteJSON adds a packet to the packet stack, after which will be written as JSON to the websocket connection.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is the main entry-point of the mcwss package. It allows interfacing with clients connected to it and provides methods to ease the use.

func NewServer

func NewServer(config *Config) *Server

NewServer initialises and returns a new server. If the configuration passed in was non-nil, that configuration is used. If nil is passed, the default configuration is used. (see config.go/defaultConfig())

func (*Server) OnConnection

func (server *Server) OnConnection(handler func(player *Player))

OnConnection sets a handler to handle new connections from players. This method must be used to interact with players connected.

func (*Server) OnDisconnection

func (server *Server) OnDisconnection(handler func(player *Player))

OnDisconnection sets a handler to handle disconnections from players. Note that when setting the handler, sending packets to the player will not arrive.

func (*Server) Run

func (server *Server) Run() error

Run runs the server and blocks the current goroutine until the server is stopped.

type World

type World struct {
	// contains filtered or unexported fields
}

World represents a world a player has joined. This might be either a singleplayer world, or a multiplayer server. Multiworld servers are treated as if they had only one world.

func NewWorld

func NewWorld(player *Player) *World

NewWorld returns a new world representing the world the player passed is in.

func (*World) Broadcast

func (world *World) Broadcast(message string, parameters ...interface{})

Broadcast broadcasts a message with optional parameters (operates using fmt.Sprintf) to all players in the world. The message is prefixed with '[External]'.

func (*World) DestroyBlock

func (world *World) DestroyBlock(position mctype.BlockPosition)

DestroyBlock destroys a block at the position passed. It will show the block breaking particles and sounds that would normally be sent when destroying a block.

func (*World) SetBlock

func (world *World) SetBlock(position mctype.BlockPosition, block string, dataValue byte)

SetBlock sets a block at a given position. It uses the data value, provided it is a value of 0-15. If not, the function panics.

func (*World) SpawnParticle

func (world *World) SpawnParticle(particle string, position mctype.Position)

SpawnParticle spawns a particle with a given name into the world at the position passed.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL