wrapper

package module
v0.0.0-...-d0f2f64 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2022 License: MIT Imports: 19 Imported by: 0

README ¶

Why is this fork a thing?

  • Starting the server in 1.18 works (Mojang added a random message in 1.18 that basically just say "watch out, servers starting now" which the original repo can't yet handle.)
  • Auto-Stop Server (Allows the wrapper to automatically stop the server, if the server is empty for a given duration)
  • Whitelist Stuff (print current whitelist, add to- and remove from whitelist)
  • Playerlist ( List() ) will now not only return a list of currently connected player, but also their position (updated twice a minute)
  • I added lots of missing death-messages (haven't gotten around to testing on this though)

Thanks to wlwanpan for the heavy lifting, which allowed me to add the stuff I personally needed within a couple of hours. (original readme starts here)

minecraft-wrapper

Minecraft Gopher

What is minecraft-wrapper?

Wrapper is a Go package that wraps a Minecraft Server (JE) and interacts with it by pushing in commands and reading the server logs. This package is meant to provide nicer APIs for your Go program to manage your minecraft server.

Installation

go get github.com/ByteSizedMarius/go-minecraft-wrapper

Usage

  • Starting the server and listening to game events:
wpr := wrapper.NewDefaultWrapper("server.jar", 1024, 1024)
wpr.Start()
defer wpr.Stop()

// Listening to game events...
for {
  select {
  case ev := <-wpr.GameEvents():
    log.Println(ev.String())
  }
}
  • Broadcast a "Hello" message once the server is loaded:
wpr := wrapper.NewDefaultWrapper("server.jar", 1024, 1024)
wpr.Start()
defer wpr.Stop()

<-wpr.Loaded()
wpr.Say("Hello")
  • Retrieving a player position from the /data get command:
out, err := wpr.DataGet("entity", PLAYER_NAME|PLAYER_UUID)
if err != nil {
	...
}
fmt.Println(out.Pos) // [POS_X, POS_Y, POS_Z]
  • Save the game and Tell a game admin "admin-player", when the server is overloading.
wpr := wrapper.NewDefaultWrapper("server.jar", 1024, 1024)
wpr.Start()
defer wpr.Stop()
<-wpr.Loaded()

for {
  select {
  case ev := <-wpr.GameEvents():
    if ev.String() == events.ServerOverloaded {
      if err := wpr.SaveAll(true); err != nil {
        ...
      }
      broadcastMsg := fmt.Sprintf("Server is overloaded and lagging by %sms", ev.Data["lag_time"])
      err := wpr.Tell("admin-player", broadcastMsg)
      ...
    }
  }
}

For more example, go to the examples dir from this repo (more will be added soon).

Note: This package is developed and tested on Minecraft 1.16, though most functionalities (Start, Stop, Seed, ...) works across all versions. Commands like /data get was introduced in version 1.13 and might not work for earlier versions. âš 

Overview

Minecraft Wrapper Overview

If you are interested, you can visit this Medium article to learn some of the basic inner working of the wrapper.

Commands 🚧

The following apis/commands are from the official minecraft gamepedia list of commands unless otherwise specified.

Note: this list might be incomplete...

GameEvents 🚧

List of game events and their respective data...

Minecraft resources

Help and contributions

Feel free to drop a PR, file an issue or proposal of changes you want to have.

Documentation ¶

Index ¶

Constants ¶

View Source
const (
	// MarketOpenTick is the mc time at which a villagers begin their workday,
	// hence are open for item trading.
	MarketOpenTick int64 = 2000
	// MarketCloseTick is the mc time at which villagers end their workday
	// and begin socializing, trading is not available at this point.
	MarketCloseTick int64 = 9000
	// GameTickPerSecond is the minecraft game server tick runs at a fixed
	// rate of 20 ticks per second.
	GameTickPerSecond int = 20
	// ClockSyncInterval is the interval where the wrapper clock will sync with the
	// game tick rate. The wrapper and game tick can be skewed when the game lags.
	ClockSyncInterval time.Duration = 30 * time.Second
)
View Source
const (
	WrapperOffline  = "offline"
	WrapperOnline   = "online"
	WrapperStarting = "starting"
	WrapperStopping = "stopping"
	WrapperSaving   = "saving"
)

Variables ¶

View Source
var (
	// ErrWrapperResponseTimeout is returned when a command fails to receive
	// its respective event from the server logs within some timeframe. Hence
	// no output could be decoded for the command.
	ErrWrapperResponseTimeout = errors.New("response timeout")
	// ErrWrapperNotOnline is returned when a commad is called but the wrapper
	// is not 'online'. The minecraft server is not loaded and ready to process
	// any commands.
	ErrWrapperNotOnline = errors.New("not online")
	// ErrPlayerNotFound is returned when a targetted command failed to process
	// due to the player not being connected to the server.
	ErrPlayerNotFound = errors.New("player not found")
	// ErrUnknownItem is returned when an item operation is called with an
	// invalid item type or structure.
	ErrUnknownItem = errors.New("unknown item")
)

Functions ¶

This section is empty.

Types ¶

type Abilities ¶

type Abilities map[string]float64

type Attribute ¶

type Attribute struct {
	Name string
	Base float64
}

type BanListType ¶

type BanListType string
const (
	BanIPs     BanListType = "ips"
	BanPlayers BanListType = "players"
)

type Brain ¶

type Brain map[string]map[string]interface{}

type Console ¶

type Console interface {
	Start() error
	Kill() error
	WriteCmd(string) error
	ReadLine() (string, error)
}

type DataGetOutput ¶

type DataGetOutput struct {
	Brain                  Brain
	HurtByTimestamp        int
	SleepTimer             int
	SpawnForced            int
	Attributes             []Attribute
	Invulnerable           int
	FallFlying             int
	PortalCooldown         int
	AbsorptionAmount       float64
	Abilities              Abilities
	FallDistance           float64
	RecipeBook             RecipeBook
	DeathTime              int
	XpSeed                 int
	XpTotal                int
	UUID                   []interface{} // Technically []int, cc issue in decoder.go#Lexer.buildStr()
	PlayerGameType         int
	SeenCredits            int
	Motion                 []float64
	Health                 float64
	FoodSaturationLevel    float64
	Air                    int
	OnGround               int
	Dimension              string
	Rotation               []float64
	XpLevel                int
	Score                  int
	Pos                    []float64
	PreviousPlayerGameType int
	Fire                   int
	XpP                    float64
	EnderItems             []interface{}
	DataVersion            int
	FoodLevel              int
	FoodExhaustionLevel    float64
	HurtTime               int // TODO: support native time.Time?
	SelectedItemSlot       int
	Inventory              Inventory
	FoodTickTimer          int
}

DataGetOutput represents the structured data logged from the '/data get entity' command. Some fields might not be of the right or precise type since the decoder will coerse any value to either a string, int or float64 for simplicity.

type ExperienceType ¶

type ExperienceType string
const (
	Levels ExperienceType = "levels"
	Points ExperienceType = "points"
)

type GameDifficulty ¶

type GameDifficulty string
const (
	Easy     GameDifficulty = "easy"
	Hard     GameDifficulty = "hard"
	Normal   GameDifficulty = "normal"
	Peaceful GameDifficulty = "peaceful"
)

type GameMode ¶

type GameMode string
const (
	Survival  GameMode = "survival"
	Creative  GameMode = "creative"
	Adventure GameMode = "adventure"
	Spectator GameMode = "spectator"
)

type Inventory ¶

type Inventory []map[string]interface{}

type JavaExec ¶

type JavaExec interface {
	Stdout() io.ReadCloser
	Stdin() io.WriteCloser
	Start() error
	Kill() error
}

type LogParser ¶

type LogParser func(string, int) (events.Event, events.EventType)

LogParser is an interface func to decode any server log line to its respective event type. The returned events must be either: - Cmd: event holds data to be returned to a user command. - State: event affects the state of the wrapper. - Game: event related to in-game events, like a player died... - Nil: event that hold no value and usually ignored/

type Player ¶

type Player struct {
	Name       string
	Dimension  string
	UUID       string
	POS        Pos
	LastUpdate time.Time
}

type Pos ¶

type Pos struct {
	X string
	Y string
	Z string
}

type RecipeBook ¶

type RecipeBook struct {
	Recipes                             []string
	ToBeDisplayed                       []string
	IsBlastingFurnaceFilteringCraftable int
	IsSmokerGuiOpen                     int
	IsFilteringCraftable                int
	IsFurnaceGuiOpen                    int
	IsGuiOpen                           int
	IsFurnaceFilteringCraftable         int
	IsBlastingFurnaceGuiOpen            int
	IsSmokerFilteringCraftable          int
}

type Wrapper ¶

type Wrapper struct {
	// Version is the minecraft server version being wrapped.
	// The Version is detected and set from the log line:
	// "Starting minecraft server version [X.X.X]""
	Version string
	// contains filtered or unexported fields
}

Wrapper is the minecraft-wrapper core struct, representing an instance of a minecraft server (JE). It is used to manage and interact with the java process by proxying its stdin and stdout via the Console interface.

func NewDefaultWrapper ¶

func NewDefaultWrapper(server string, initial, max int) *Wrapper

NewDefaultWrapper returns a new instance of the Wrapper. This is the main method to use for your wrapper but if you wish to read and parse your own log lines to events, see 'NewWrapper'. This

func NewWrapper ¶

func NewWrapper(c Console, p LogParser) *Wrapper

func (*Wrapper) AutoStop ¶

func (w *Wrapper) AutoStop(after time.Duration)

func (*Wrapper) BanIP ¶

func (w *Wrapper) BanIP(ip, reason string) error

BanIP adds the input IP address to the servers blacklisted IPs list.

func (*Wrapper) BanList ¶

func (w *Wrapper) BanList(t BanListType) ([]string, error)

func (*Wrapper) DataGet ¶

func (w *Wrapper) DataGet(t, id string) (*DataGetOutput, error)

DataGet returns the Go struct representation of an 'entity' or 'block' or 'storage'. The data is originally stored in a NBT format.

func (*Wrapper) DeOp ¶

func (w *Wrapper) DeOp(player string) error

DeOp removes a given player from the operator list.

func (*Wrapper) DefaultGameMode ¶

func (w *Wrapper) DefaultGameMode(mode GameMode) error

DefaultGameMode sets the default game mode for new players joining.

func (*Wrapper) Difficulty ¶

func (w *Wrapper) Difficulty(d GameDifficulty) error

Difficulty changes the game difficulty level of the world.

func (*Wrapper) ExperienceAdd ¶

func (w *Wrapper) ExperienceAdd(target string, xp int32, xpType ExperienceType) error

ExperienceAdd adds a given amount of experience either: - levels or - points to the provided player.

func (*Wrapper) ExperienceQuery ¶

func (w *Wrapper) ExperienceQuery(target string, xpType ExperienceType) (int, error)

ExperienceQuery returns the amount of experience of the provided player. The 'target' arg should be a single target, multi-targets query might fail.

func (*Wrapper) ForceLoadRemoveAll ¶

func (w *Wrapper) ForceLoadRemoveAll() error

ForceLoadRemoveAll removes the constant force loads on all chunks in the dimension.

func (*Wrapper) GameEvents ¶

func (w *Wrapper) GameEvents() <-chan events.GameEvent

GameEvents returns a receive-only channel of game related event. For example: - Player joined, left, died, was banned. - Game updates like game mode changes. - Player sends messages...

func (*Wrapper) Give ¶

func (w *Wrapper) Give(target, item string, count int) error

Give give a target player entity some given items.

func (*Wrapper) Kick ¶

func (w *Wrapper) Kick(target, reason string) error

Kick kicks the provided player from the server. If a reason is provided, the message will display on the players screen when disconnected.

func (*Wrapper) Kill ¶

func (w *Wrapper) Kill() error

Kill the java process, use with caution since it will not trigger a save game. Kill manually perform some cleanup task and hard reset the state to 'offline'.

func (*Wrapper) List ¶

func (w *Wrapper) List() []Player

List returns a list of connected players on the server.

func (*Wrapper) Loaded ¶

func (w *Wrapper) Loaded() <-chan bool

func (*Wrapper) Reload ¶

func (w *Wrapper) Reload() error

Reload reloads the server datapack.

func (*Wrapper) SaveAll ¶

func (w *Wrapper) SaveAll(flush bool) error

SaveAll marks all chunks and player data to be saved to the data storage device. When flush is true, the marked data are saved immediately.

func (*Wrapper) SaveOff ¶

func (w *Wrapper) SaveOff() error

SaveOff disables automatic saving by preventing the server from writing to the world files.

func (*Wrapper) SaveOn ¶

func (w *Wrapper) SaveOn() error

SaveOn enables automatic saving. The server is allowed to write to the world files.

func (*Wrapper) Say ¶

func (w *Wrapper) Say(msg string) error

Say sends the given message in the minecraft in-game chat.

func (*Wrapper) Seed ¶

func (w *Wrapper) Seed() (int, error)

Seed returns the world seed.

func (*Wrapper) SetIdleTimeout ¶

func (w *Wrapper) SetIdleTimeout(minutes uint32) error

SetIdleTimeout sets the default timeout in minutes after which idle players are kicked out of the server.

func (*Wrapper) Start ¶

func (w *Wrapper) Start() error

Start will initialize the minecraft java process and start orchestrating the wrapper machine.

func (*Wrapper) State ¶

func (w *Wrapper) State() string

State returns the current state of the server, it can be one of: 'offline', 'online', 'starting' or 'stopping'.

func (*Wrapper) Stop ¶

func (w *Wrapper) Stop() error

Stop pipes a 'stop' command to the minecraft java process.

func (*Wrapper) Tell ¶

func (w *Wrapper) Tell(target, msg string) error

Tell sends a message to a specific target in the server.

func (*Wrapper) Tick ¶

func (w *Wrapper) Tick() int

Tick returns the current minecraft game tick, which runs at a fixed rate of 20 ticks per second, src: https://minecraft.gamepedia.com/Tick.

func (*Wrapper) WhitelistAdd ¶

func (w *Wrapper) WhitelistAdd(player string) (events.GameEvent, error)

func (*Wrapper) WhitelistList ¶

func (w *Wrapper) WhitelistList() (events.GameEvent, error)

func (*Wrapper) WhitelistRemove ¶

func (w *Wrapper) WhitelistRemove(player string) (events.GameEvent, error)

Directories ¶

Path Synopsis

Jump to

Keyboard shortcuts

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