rustplus

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 23 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

rustplus

Go Reference CI Go version

A Go client for the Rust+ companion API of the game Rust.

With it, bots and services can:

  • control the smart devices of a base;
  • read and send team and clan chat messages;
  • follow the map and server events;
  • receive Rust+ push notifications: pairing, alarms, deaths, teammate logins.

[!NOTE] This is an unofficial library, not affiliated with Facepunch Studios. The Rust+ protocol is undocumented and may change without notice.

Features

  • Server: server information, in-game time, the map with monuments, map markers (players, vending machines, cargo ship, helicopters, CH47).
  • Team: members, their positions and status, chat, sending messages, promoting a leader, kicking members.
  • Clan: information, chat, messages, message of the day.
  • Smart devices: switches, alarms and storage monitors. Each kind has its own typed handle: turning on and off, state, container contents, tool cupboard upkeep, managing the device's push notifications.
  • Real-time events: team and clan messages, team and clan changes, device changes, connection loss and recovery.
  • Push notifications: registering a push device, server and device pairing, Smart Alarm triggers, player deaths, teammate logins.
  • Low-level access: Do and OnBroadcast work with raw protobuf messages (package rustpluspb) for anything not yet wrapped in the typed API.

Why rustplus

  • Resilient connection. The client reconnects on its own with exponential backoff. Event handlers and device subscriptions are restored, and requests made during an outage wait for the connection. Only a request that certainly never reached the server is sent again, so an action such as a chat message is never performed twice.
  • Server limits respected up front. The built-in rate limiter mirrors the game server's limit and serves requests strictly in order. Instead of failing with rate_limit, requests wait for their turn, and an expensive map request does not get stuck behind a stream of small ones.
  • Typed API. Methods are grouped by subject: c.Team(), c.Clan(), device handles c.Switch(id), c.Alarm(id), c.StorageMonitor(id). A switch cannot be mistaken for a storage box, and server responses are plain Go types with time.Time, not protobuf.
  • Clear errors. Server and connection errors are checked with errors.Is, and every error has a single, unambiguous meaning.
  • Safe for concurrent code. A Client can be used from many goroutines. A panic in an event handler does not crash the bot. Connect, Close, Done and Err manage the lifecycle.
  • Production ready. Structured logging with log/slog at levels from Error to Debug, context.Context on every request, default timeouts, no global state.
  • Few dependencies, thorough tests. The only third-party dependencies are coder/websocket and protobuf. Tests run on virtual time (testing/synctest) over an in-memory network and with the race detector.

Installation

go get github.com/roreng/rustplus

Requires Go 1.26 or newer.

Quick start

package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"os/signal"

	"github.com/roreng/rustplus"
)

// Replace these with your own values; see "Connection details" below.
const (
	serverID    = "089941d9-064e-4628-9c60-eaeb01a943e8"
	playerID    = 76561198000000001
	playerToken = -123456789
	authToken   = "your Rust+ auth token"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()

	c, err := rustplus.New(rustplus.Config{
		ServerID:    serverID,
		PlayerID:    playerID,
		PlayerToken: playerToken,
		AuthToken:   authToken,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	// Handlers are registered before Connect, so no event is missed.
	c.Team().OnMessage(func(m rustplus.TeamMessage) {
		fmt.Printf("%s: %s\n", m.Name, m.Message)
	})

	if err := c.Connect(ctx); err != nil {
		log.Fatal(err)
	}

	info, err := c.Info(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Server: %s (%d/%d players, %d queued)\n", info.Name, info.Players, info.MaxPlayers, info.QueuedPlayers)

	select {
	case <-ctx.Done(): // Ctrl+C
	case <-c.Done(): // stopped for good, e.g. the auth token was rejected
		log.Fatal(c.Err())
	}
}

rustplus.Dial(ctx, cfg) combines New and Connect in a single call. Use it when no handlers need to be registered before connecting.

Connection details

rustplus.Config field What it is Where to get it
ServerID server identifier (GUID) the id field of the pairing notification
PlayerID the player's Steam64 ID the playerId field of the pairing notification
PlayerToken the server pairing token the playerToken field of the pairing notification
AuthToken Rust+ token, valid for about 14 days signing in to Rust+ with Steam

The pairing notification arrives when the player presses "Pair" in the Rust+ menu in game. The push package receives it, and ServerPairing.Config(authToken) returns a ready-to-use rustplus.Config.

The auth token expires after about 14 days. To let a long-running bot pick up a new token without a restart, pass it as a function. The client calls it before every connection:

c, err := rustplus.New(cfg, rustplus.WithAuthTokenSource(func(ctx context.Context) (string, error) {
	return loadAuthToken(ctx) // from the application's own storage
}))

Usage

Server
info, err := c.Info(ctx)       // name, players, map size, wipe time
t, err := c.Time(ctx)          // in-game time: t.Clock(), t.IsDay()
markers, err := c.Markers(ctx) // players, vending machines, cargo ship...
m, err := c.Map(ctx)           // JPEG of the map and monuments; a large response

cell, ok := info.Grid(x, y)    // grid cell such as "G12" for a position; no request
Team and clan
team, err := c.Team().Info(ctx)
for _, m := range team.Members {
	fmt.Println(m.Name, m.Online, m.Alive)
}

err = c.Team().Send(ctx, "Hello, team!")

c.Team().OnChanged(func(tc rustplus.TeamChanged) {
	fmt.Println("team now has", len(tc.Team.Members), "members")
})

c.Clan().OnMessage(func(m rustplus.ClanMessage) {
	fmt.Println(m.Name, m.Message)
})
Smart devices

Device handles are lightweight values that can be kept in a bot's own structs.

lights := c.Switch(123456)
if err := lights.On(ctx); err != nil {
	log.Println(err)
}

c.Alarm(777).OnTriggered(func() {
	_ = lights.On(ctx)
	_ = c.Team().Send(ctx, "Raid alarm!")
})

box, err := c.StorageMonitor(555).Contents(ctx)
if err == nil {
	fmt.Println(len(box.Items), "stacks, upkeep until", box.ProtectionExpiry)
}
  • Type checking. A device handle checks the device's kind. For example, Switch(id).State on a storage box returns rustplus.ErrWrongType.
  • Change subscriptions. The server reports changes only for devices the client has queried. OnChanged subscribes the device by itself. The handler first receives the current state and then only the changes of its own device, including after a reconnect.
Events

Handlers are called one at a time on a goroutine owned by the client, in the order events arrive. A handler may make requests and call Close. Long work is best moved to a separate goroutine so that it does not delay the following events. Every On… method returns a function that removes the handler.

Event Where
team or clan chat message c.Team().OnMessage, c.Clan().OnMessage
team or clan change c.Team().OnChanged, c.Clan().OnChanged
device change OnChanged on a device handle, Alarm.OnTriggered, c.OnEntityChanged for all devices
connection loss and recovery c.OnDisconnected, c.OnReconnected
raw server message c.OnBroadcast
Push notifications

The push package registers a push device on behalf of the Rust+ app and receives the account's notifications. Persist the device data (push.Device) so that the next run does not need to register again.

dev, err := push.NewDevice(ctx, authToken)
if err != nil {
	log.Fatal(err)
}

err = push.Listen(ctx, dev, func(n push.Notification) {
	switch ev := n.Event.(type) {
	case push.ServerPairing:
		cfg := ev.Config(authToken) // ready for rustplus.New
		fmt.Println("paired with", ev.Name, cfg.ServerID)
	case push.EntityPairing:
		fmt.Println("paired", ev.EntityName, ev.EntityID)
	case push.Alarm:
		fmt.Println("alarm:", ev.Title, ev.Message)
	case push.PlayerDeath, push.TeamLogin:
		fmt.Println(n.Title, n.Message)
	}
})
  • Recovery after a failure. If registration was interrupted, Device.Complete performs only the missing steps and does not create a second device.
  • New token. After signing in to Rust+ again, push.Link(ctx, dev, newToken) is enough; the device stays the same.
  • Redelivery. The listener reconnects on its own. Listener.PersistentIDs together with push.WithPersistentIDs keep notifications from arriving again after a restart.
  • Several bots on one account. Each device is registered under its own ID, so bots do not take each other's notifications.
Reconnection and errors

When the connection drops, the client reconnects on its own: the delay starts at 1 second and grows up to 1 minute. The policy can be tuned with WithReconnect or disabled with WithoutReconnect. The client stops for good only when the connection cannot be restored: the relay rejected the token, the server was not found, the token expired, or the attempts ran out. Then c.Done() is closed and c.Err() reports the reason.

if err := c.Switch(id).On(ctx); err != nil {
	switch {
	case errors.Is(err, rustplus.ErrNotFound):
		// the device was destroyed or unpaired
	case errors.Is(err, rustplus.ErrConnectionLost):
		// sent, but the connection dropped before the answer; it may have taken effect
	case errors.Is(err, context.DeadlineExceeded):
		// no answer in time
	}
}
Error Meaning
ErrAuthRejected the relay rejected the auth token; sign in to Rust+ again
ErrAuthTokenExpired the auth token has expired
ErrServerNotFound the relay does not know this server
ErrConnectionLost the request was sent, but the connection dropped before the answer
ErrNotConnected, ErrClosed Connect has not been called yet, or the client is closed
ErrNotFound, ErrWrongType, ErrNoTeam, ErrNotLeader, … errors returned by the game server
Configuration
Option Default Purpose
WithAuthTokenSource(fn) — get the auth token from a function before every connection
WithLogger(l) no logging *slog.Logger for the client's logs
WithRequestTimeout(d) 15 s timeout for a request without its own deadline
WithReconnect(p), WithoutReconnect() 1 s to 1 min, unlimited attempts reconnection policy
WithPingInterval(d) 30 s connection liveness check
WithEventBuffer(n) 4096 size of the event queue for handlers
WithPanicHandler(fn) logged what to do when a handler panics
WithoutRateLimit() enabled disable the built-in rate limiter
WithHTTPClient(c) default HTTP client for connecting, for example through a proxy

Limitations

  • Cameras are not supported.
  • The Rust+ protocol is unofficial. Changes on Facepunch's side may cause outages until a new version of the library is released.
  • The game server limits the request rate: a burst of 25 requests, then 3 per second per player. The built-in rate limiter accounts for this, but it caps the bot's throughput.

Examples

  • examples/simple is a complete program. It connects to a server, prints the server and the team members, and answers !time in team chat. It reads its settings from the RUSTPLUS_SERVER_ID, RUSTPLUS_PLAYER_ID, RUSTPLUS_PLAYER_TOKEN and RUSTPLUS_AUTH_TOKEN variables:

    go run ./examples/simple
    
  • Examples for individual functions are in the package documentation.

Development

Development works with Go 1.26 or newer.

go test -race ./...

Regenerating the protobuf code requires protoc; the protoc-gen-go version is pinned in go.mod:

go install tool
go generate ./rustpluspb ./internal/fcm/fcmpb

CI checks formatting, go vet, go fix, staticcheck, tests with the race detector on Go 1.26 and the latest Go release, and that the generated code is up to date.

The change history is in CHANGELOG.md.

Acknowledgements

The Rust+ protocol is undocumented. The workings of the relay, push notification registration and request limits could be reconstructed thanks to open community projects: rustplus.js, rustplus.py, push-receiver and rustplusplus.

License

MIT.

The Google protocol schemas in proto/fcm and the code generated from them come from Chromium and are distributed under the BSD-3-Clause license.

Documentation

Overview

Package rustplus is a client for the Rust+ companion API of the game Rust.

Clients connect to the Facepunch companion relay at wss://companion-rust.facepunch.com/socket/<server id> and authenticate with a Rust+ auth token passed through the "rustplus.auth.v1" WebSocket subprotocol. This package implements that transport and a typed API on top of the protobuf protocol (see package rustpluspb).

The values needed to connect come from the in-game pairing notification (server id, player id and player token) and from signing in to Rust+ with Steam (the auth token, valid for about 14 days). The library stores none of them: the application loads them from its own storage, and can supply the auth token through WithAuthTokenSource so that a renewed token is picked up on reconnect:

cfg := rustplus.Config{ServerID: id, PlayerID: playerID, PlayerToken: playerToken}
c, err := rustplus.New(cfg, rustplus.WithAuthTokenSource(loadToken))
if err != nil { ... }
defer c.Close()

c.Team().OnMessage(func(m rustplus.TeamMessage) {
	fmt.Println(m.Name, m.Message)
})
if err := c.Connect(ctx); err != nil { ... }

info, err := c.Info(ctx)

Dial combines New and Connect for clients that need no handlers before the first connection.

Methods by subject

  • the server itself, directly on Client: Info, Time, Map, Markers;
  • map grid cells such as "G12" for positions: ServerInfo.Grid, GridAt;
  • the player's team, through Client.Team: chat, members, events;
  • the player's clan, through Client.Clan;
  • smart devices, through typed handles: Client.Switch, Client.Alarm, Client.StorageMonitor, or the generic Client.Entity.

Connection management (New, Connect, Close, Done, OnDisconnected, ...) and the raw Do and OnBroadcast stay on Client.

The client reconnects automatically with exponential backoff when the connection drops (see WithReconnect, OnDisconnected, OnReconnected).

Errors returned by the game server can be matched with errors.Is against ErrNotFound, ErrRateLimit and the other ServerError values. A Client throttles requests on its side to stay within the server's rate limits.

Camera control is not supported.

Index

Examples

Constants

View Source
const DefaultRelayURL = "wss://companion-rust.facepunch.com/socket/"

DefaultRelayURL is the base URL of the Facepunch companion relay, through which every client connects to a game server.

Variables

View Source
var (
	// ErrClosed is returned by requests made on a closed client.
	ErrClosed = errors.New("rustplus: client closed")
	// ErrNotConnected is returned by requests made before Connect succeeded.
	ErrNotConnected = errors.New("rustplus: not connected; call Connect first")
	// ErrAlreadyConnected is returned by Connect after it has succeeded once;
	// the client reconnects by itself from then on.
	ErrAlreadyConnected = errors.New("rustplus: already connected")
	// ErrInvalidConfig is returned by Dial when Config is incomplete.
	ErrInvalidConfig = errors.New("rustplus: invalid config")
	// ErrInvalidAuthToken is returned when the auth token cannot be parsed.
	ErrInvalidAuthToken = errors.New("rustplus: invalid auth token")
	// ErrAuthTokenExpired is returned by Dial when the auth token has expired.
	// Sign in to Rust+ again to get a new token.
	ErrAuthTokenExpired = errors.New("rustplus: auth token expired")
	// ErrAuthRejected means the relay rejected the auth token (HTTP 403).
	ErrAuthRejected = errors.New("rustplus: auth token rejected by relay")
	// ErrServerNotFound means the relay does not know the server ID (HTTP 404).
	ErrServerNotFound = errors.New("rustplus: server not found on relay")
	// ErrConnectionLost is returned by a request whose connection dropped
	// before the response arrived (the request may or may not have taken
	// effect), and by Err when the client could not reconnect.
	ErrConnectionLost = errors.New("rustplus: connection lost")
	// ErrUnexpectedResponse means the server answered with a response that
	// does not match the request.
	ErrUnexpectedResponse = errors.New("rustplus: unexpected response")
)

Connection and configuration errors.

View Source
var (
	ErrNotFound       = &ServerError{Code: "not_found"}
	ErrRateLimit      = &ServerError{Code: "rate_limit"}
	ErrNoTeam         = &ServerError{Code: "no_team"}
	ErrNoClan         = &ServerError{Code: "no_clan"}
	ErrNotLeader      = &ServerError{Code: "not_leader"}
	ErrNoPlayer       = &ServerError{Code: "no_player"}
	ErrAccessDenied   = &ServerError{Code: "access_denied"}
	ErrBanned         = &ServerError{Code: "banned"}
	ErrMessageNotSent = &ServerError{Code: "message_not_sent"}
	ErrWrongType      = &ServerError{Code: "wrong_type"}
)

Errors reported by the game server. Use errors.Is to match them against an error returned by a request:

if errors.Is(err, rustplus.ErrNotFound) { ... }

Functions

func Redact

func Redact(secret string) string

Redact masks a secret for display: the first four characters followed by "…(redacted)", or "(empty)".

Example

Secrets are masked when printed or logged.

package main

import (
	"fmt"

	"github.com/roreng/rustplus"
)

func main() {
	cfg := rustplus.Config{ServerID: "sid", PlayerID: 1, PlayerToken: -42, AuthToken: "eyJzdGVhbUlkIjoiMSJ9.signature"}
	fmt.Println(cfg)
	fmt.Println(rustplus.Redact("eyJzdGVhbUlkIjoiMSJ9"))
}
Output:
rustplus.Config{ServerID:"sid" PlayerID:1 PlayerToken:(redacted) AuthToken:eyJz…(redacted)}
eyJz…(redacted)

Types

type Alarm

type Alarm struct{ Entity }

Alarm is a handle to a smart alarm.

func (Alarm) OnChanged

func (a Alarm) OnChanged(fn func(active bool)) (remove func())

OnChanged registers a handler called with the alarm state whenever it changes, and right after subscribing.

func (Alarm) OnTriggered

func (a Alarm) OnTriggered(fn func()) (remove func())

OnTriggered registers a handler called whenever the alarm reports being active, including when it is already active right after subscribing.

Unlike the alarm's push notification, which the game server sends at most every few minutes, this follows every state change the server broadcasts while the client is connected.

Example

Device handles are cheap values: keep them in the bot's own structs.

package main

import (
	"context"
	"log"

	"github.com/roreng/rustplus"
)

func main() {
	ctx := context.Background()
	c, err := rustplus.Dial(ctx, rustplus.Config{ /* ... */ })
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	turrets := c.Switch(123456)
	c.Alarm(777).OnTriggered(func() {
		if err := turrets.On(ctx); err != nil {
			log.Println("turrets:", err)
		}
		_ = c.Team().Send(ctx, "Raid! Turrets are on.")
	})
	<-c.Done()
}

func (Alarm) State

func (a Alarm) State(ctx context.Context) (active bool, err error)

State reports whether the alarm is currently active. It fails with ErrWrongType if the device is not an alarm.

type AuthToken

type AuthToken struct {
	// Raw is the token exactly as it is sent to the relay.
	Raw string
	// SteamID is the Steam64 ID of the account the token belongs to.
	SteamID uint64
	// Version is the token format version.
	Version int
	// IssuedAt is when the token was issued.
	IssuedAt time.Time
	// ExpiresAt is when the token stops being accepted by the relay.
	ExpiresAt time.Time
}

AuthToken is a parsed Rust+ companion auth token.

The token is issued by Facepunch after a Steam login in the Rust+ app and is valid for about 14 days. Its format is base64(json payload) "." signature, where the payload carries the owner's Steam ID and the issue and expiry timestamps.

func ParseAuthToken

func ParseAuthToken(raw string) (AuthToken, error)

ParseAuthToken parses a Rust+ auth token. Tokens copied from a URL (containing percent escapes) are unescaped first. The signature is not verified: only the relay can do that.

func (AuthToken) Expired

func (t AuthToken) Expired(now time.Time) bool

Expired reports whether the token has expired at time now.

func (AuthToken) GoString

func (t AuthToken) GoString() string

GoString implements fmt.GoStringer (%#v) with the token redacted.

func (AuthToken) LogValue

func (t AuthToken) LogValue() slog.Value

LogValue implements slog.LogValuer with the token redacted.

func (AuthToken) String

func (t AuthToken) String() string

String implements fmt.Stringer: the owner and validity, not the token.

type Clan

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

Clan gives access to the player's clan: its info, chat and events. Obtain it with Client.Clan; it is a small value, cheap to copy.

func (Clan) Chat

func (cl Clan) Chat(ctx context.Context) ([]ClanMessage, error)

Chat returns the recent clan chat messages.

func (Clan) Info

func (cl Clan) Info(ctx context.Context) (*ClanInfo, error)

Info returns the clan. It returns ErrNoClan (or a nil info) when the player is not in a clan.

func (Clan) OnChanged

func (cl Clan) OnChanged(fn func(*ClanInfo)) (remove func())

OnChanged registers a handler for clan changes. The ClanInfo is nil when the player is no longer in a clan.

func (Clan) OnMessage

func (cl Clan) OnMessage(fn func(ClanMessage)) (remove func())

OnMessage registers a handler for new clan chat messages.

func (Clan) Send

func (cl Clan) Send(ctx context.Context, message string) error

Send posts a message to clan chat as the player.

func (Clan) SetMotd

func (cl Clan) SetMotd(ctx context.Context, motd string) error

SetMotd sets the clan's message of the day.

type ClanInfo

type ClanInfo struct {
	ID             int64
	Name           string
	Created        time.Time
	Creator        uint64
	Motd           string
	MotdTimestamp  time.Time
	MotdAuthor     uint64
	Color          int32
	Roles          []ClanRole
	Members        []ClanMember
	Invites        []ClanInvite
	MaxMemberCount int32
	Score          int64
}

ClanInfo describes the player's clan.

type ClanInvite

type ClanInvite struct {
	SteamID   uint64
	Recruiter uint64
	Time      time.Time
}

ClanInvite is a pending clan invitation.

type ClanMember

type ClanMember struct {
	SteamID  uint64
	RoleID   int32
	Joined   time.Time
	LastSeen time.Time
	Notes    string
	Online   bool
}

ClanMember is a member of a clan.

type ClanMessage

type ClanMessage struct {
	ClanID  int64
	SteamID uint64
	Name    string
	Message string
	Time    time.Time
}

ClanMessage is a clan chat message. ClanID is set for broadcasts only.

type ClanRole

type ClanRole struct {
	ID                   int32
	Rank                 int32
	Name                 string
	CanSetMotd           bool
	CanInvite            bool
	CanKick              bool
	CanPromote           bool
	CanDemote            bool
	CanSetPlayerNotes    bool
	CanAccessLogs        bool
	CanAccessScoreEvents bool
}

ClanRole is a role and its permissions.

type Client

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

Client is a connection to a Rust server through the Facepunch companion relay. It is safe for concurrent use.

When the connection drops, the client reconnects with exponential backoff (see WithReconnect). Event handlers stay registered across reconnects, and devices queried with EntityInfo are subscribed again. Requests made while disconnected wait for the connection to come back, within their context. Requests in flight when the connection drops fail with ErrConnectionLost and are not retried, since they may already have taken effect.

The client stops for good after Close, when the relay rejects the credentials, or when reconnection gives up. Done is closed once it has fully stopped, including any event handler still running; Err then reports why.

func Dial

func Dial(ctx context.Context, cfg Config, opts ...Option) (*Client, error)

Dial creates a client and connects it: New followed by Connect. Use New and Connect separately to register event handlers before the first connection, so that no event is missed.

func New

func New(cfg Config, opts ...Option) (*Client, error)

New creates a client without connecting it. Register event handlers, then call Connect. Configuration and auth token problems are reported here; nothing touches the network.

Example

Register handlers between New and Connect so that no event is missed.

package main

import (
	"context"
	"fmt"
	"log"
	"log/slog"
	"os"

	"github.com/roreng/rustplus"
)

func main() {
	ctx := context.Background()
	cfg := rustplus.Config{
		ServerID:    "089941d9-064e-4628-9c60-eaeb01a943e8", // from the pairing notification
		PlayerID:    76561198000000001,
		PlayerToken: -123456789,
		AuthToken:   os.Getenv("RUSTPLUS_AUTH_TOKEN"),
	}
	c, err := rustplus.New(cfg, rustplus.WithLogger(slog.Default()))
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	c.Team().OnMessage(func(m rustplus.TeamMessage) {
		fmt.Printf("%s: %s\n", m.Name, m.Message)
	})
	c.OnDisconnected(func(err error) { log.Println("connection lost:", err) })

	if err := c.Connect(ctx); err != nil {
		log.Fatal(err)
	}
	info, err := c.Info(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(info.Name, info.Players, "/", info.MaxPlayers)
}

func (*Client) Alarm

func (c *Client) Alarm(id uint64) Alarm

Alarm returns a handle to the smart alarm with the given entity ID.

func (*Client) Clan

func (c *Client) Clan() Clan

Clan returns the player's clan.

func (*Client) Close

func (c *Client) Close() error

Close closes the connection and stops reconnecting. It returns once the network goroutines have exited and no further events will be dispatched, but it does not wait for an event handler that is already running, so it is safe to call from a handler. To wait until that handler has returned as well, wait on Done:

c.Close()
<-c.Done()

func (*Client) Connect

func (c *Client) Connect(ctx context.Context) error

Connect makes the first connection to the relay. Requests made before it fail with ErrNotConnected. If Connect fails, it may be called again; after it succeeds the client reconnects on its own and further calls return ErrAlreadyConnected. Close aborts a Connect in progress.

func (*Client) Connected

func (c *Client) Connected() bool

Connected reports whether the client currently has a live connection.

func (*Client) Do

func (c *Client) Do(ctx context.Context, cost int, fill func(*rustpluspb.AppRequest)) (*rustpluspb.AppResponse, error)

Do sends a raw request and returns the raw response, for requests this package does not wrap. Seq, PlayerId and PlayerToken are filled in by the client; fill sets the rest. cost is the rate-limit cost (usually 1).

func (*Client) Done

func (c *Client) Done() <-chan struct{}

Done returns a channel that is closed when the client has stopped for good and all of its goroutines, event handlers included, have returned.

func (*Client) Entity

func (c *Client) Entity(id uint64) Entity

Entity returns a handle to the device with the given entity ID.

func (*Client) Err

func (c *Client) Err() error

Err returns why the client stopped: ErrClosed after Close, or the error that made reconnection impossible. It returns nil while running, also while reconnecting. Once Done is closed, Err is non-nil.

func (*Client) Info

func (c *Client) Info(ctx context.Context) (ServerInfo, error)

Info returns information about the server.

func (*Client) Map

func (c *Client) Map(ctx context.Context) (Map, error)

Map returns the map image and monuments. The response is large; avoid calling it often.

func (*Client) Markers

func (c *Client) Markers(ctx context.Context) ([]Marker, error)

Markers returns the dynamic markers currently on the map: players, vending machines, cargo ship, helicopters and so on.

func (*Client) NexusAuth

func (c *Client) NexusAuth(ctx context.Context, appKey string) (NexusAuth, error)

NexusAuth requests Nexus credentials for the given app key.

func (*Client) OnBroadcast

func (c *Client) OnBroadcast(fn func(*rustpluspb.AppBroadcast)) (remove func())

OnBroadcast registers a handler that receives every raw broadcast, before the typed handlers.

func (*Client) OnDisconnected

func (c *Client) OnDisconnected(fn func(err error)) (remove func())

OnDisconnected registers a handler called with the reason when the connection drops. Unless reconnection is disabled, the client then reconnects in the background.

func (*Client) OnEntityChanged

func (c *Client) OnEntityChanged(fn func(EntityChanged)) (remove func())

OnEntityChanged registers a handler for changes of every smart device the client is subscribed to. For a single device, use the OnChanged method of its handle, which also subscribes to it.

func (*Client) OnReconnected

func (c *Client) OnReconnected(fn func()) (remove func())

OnReconnected registers a handler called each time the client has reconnected after a dropped connection. The connection made by Dial is not reported.

func (*Client) PlayerID

func (c *Client) PlayerID() uint64

PlayerID returns the Steam ID requests are issued as.

func (*Client) StorageMonitor

func (c *Client) StorageMonitor(id uint64) StorageMonitor

StorageMonitor returns a handle to the storage monitor with the given entity ID.

func (*Client) Switch

func (c *Client) Switch(id uint64) Switch

Switch returns a handle to the smart switch with the given entity ID.

func (*Client) Team

func (c *Client) Team() Team

Team returns the player's team.

func (*Client) Time

func (c *Client) Time(ctx context.Context) (GameTime, error)

Time returns the in-game time.

type Config

type Config struct {
	// ServerID is the relay ID of the server (the "id" field of the
	// pairing notification), e.g. "089941d9-064e-4628-9c60-eaeb01a943e8".
	ServerID string
	// PlayerID is the Steam64 ID of the player ("playerId").
	PlayerID uint64
	// PlayerToken is the per-server pairing token ("playerToken").
	PlayerToken int32
	// AuthToken is the Rust+ companion auth token obtained by signing in
	// to Rust+ with Steam. It is valid for about 14 days. It may be left
	// empty when WithAuthTokenSource is used.
	AuthToken string
}

Config identifies the server and the player to connect as. All values come from the in-game pairing notification and the Rust+ login.

The library does not store these values: load them from wherever the application keeps its secrets. Config redacts the tokens when printed or logged.

func (Config) GoString

func (c Config) GoString() string

GoString implements fmt.GoStringer (%#v) with the tokens redacted.

func (Config) LogValue

func (c Config) LogValue() slog.Value

LogValue implements slog.LogValuer with the tokens redacted.

func (Config) String

func (c Config) String() string

String implements fmt.Stringer with the tokens redacted.

type Entity

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

Entity is a handle to a paired smart device of any kind. Prefer the typed handles Switch, Alarm and StorageMonitor; use Entity when the kind is not known in advance. Handles are small values, cheap to copy and safe to keep, for example in a bot's own structs.

The server reports a device's changes only to clients that queried it. The handles take care of that: a device is subscribed the first time it is queried or an OnChanged handler is registered for it, and subscribed again after every reconnect.

func (Entity) ID

func (e Entity) ID() uint64

ID returns the device's entity ID.

func (Entity) Info

func (e Entity) Info(ctx context.Context) (EntityInfo, error)

Info returns the device's kind and state, and subscribes to its changes.

func (Entity) Notifications

func (e Entity) Notifications(ctx context.Context) (bool, error)

Notifications reports whether push notifications are enabled for the device (smart alarms, storage monitors).

func (Entity) OnChanged

func (e Entity) OnChanged(fn func(EntityPayload)) (remove func())

OnChanged registers a handler for this device's changes and subscribes to them. Right after subscribing, the handler also receives the device's current state.

func (Entity) SetNotifications

func (e Entity) SetNotifications(ctx context.Context, enabled bool) error

SetNotifications enables or disables push notifications for the device.

type EntityChanged

type EntityChanged struct {
	EntityID uint64
	Payload  EntityPayload
}

EntityChanged is broadcast when a device the client queried changes.

type EntityInfo

type EntityInfo struct {
	Type    EntityType
	Payload EntityPayload
}

EntityInfo is the state of a smart device (AppEntityInfo).

type EntityPayload

type EntityPayload struct {
	Value            bool
	Items            []Item
	Capacity         int32
	HasProtection    bool
	ProtectionExpiry time.Time
}

EntityPayload is the state of a smart device. Value is used by switches and alarms; Items, Capacity and protection fields by storage monitors.

type EntityType

type EntityType int32

EntityType is the kind of a paired smart device.

func (EntityType) String

func (t EntityType) String() string

type GameTime

type GameTime struct {
	DayLengthMinutes float32
	TimeScale        float32
	Sunrise          float32
	Sunset           float32
	Time             float32
}

GameTime is the in-game time of day (AppTime). Hours are in [0, 24).

func (GameTime) Clock

func (t GameTime) Clock() string

Clock formats the in-game time as HH:MM.

func (GameTime) IsDay

func (t GameTime) IsDay() bool

IsDay reports whether the sun is up.

type GridCell added in v0.2.0

type GridCell struct {
	Column int
	Row    int
}

GridCell is a cell of the in-game map grid, such as "G12". Column 0 is "A", 25 is "Z", 26 is "AA"; row 0 is the top row, as on the in-game map.

func GridAt added in v0.2.0

func GridAt(mapSize uint32, x, y float32) (cell GridCell, ok bool)

GridAt returns the grid cell that contains the world position (x, y) on a map of the given size (ServerInfo.MapSize). Positions use the Rust+ coordinates found in TeamMember, Marker, MapNote and Monument: metres from the bottom-left corner of the map.

ok is false for positions outside the map, such as the ocean beyond its edge.

Example

Convert a position from Rust+ (team members, markers, map notes) to the grid cell shown on the in-game map. In a bot the map size comes from Client.Info, and ServerInfo.Grid does the same with it.

package main

import (
	"fmt"

	"github.com/roreng/rustplus"
)

func main() {
	const mapSize = 4750 // ServerInfo.MapSize
	if cell, ok := rustplus.GridAt(mapSize, 3162, 2077); ok {
		fmt.Println(cell)
	}
	_, ok := rustplus.GridAt(mapSize, -50, 2077) // in the ocean
	fmt.Println(ok)
}
Output:
V18
false

func (GridCell) String added in v0.2.0

func (g GridCell) String() string

String returns the cell as the game labels it, e.g. "G12" or "AA3".

type HandshakeError

type HandshakeError struct {
	StatusCode int
	Err        error
}

HandshakeError is returned by Dial when the relay refuses the WebSocket upgrade. It unwraps to ErrAuthRejected or ErrServerNotFound where the status code identifies the reason.

func (*HandshakeError) Error

func (e *HandshakeError) Error() string

func (*HandshakeError) Unwrap

func (e *HandshakeError) Unwrap() error

type Item

type Item struct {
	ItemID    int32
	Quantity  int32
	Blueprint bool
}

Item is a stack of items in a storage container.

type Map

type Map struct {
	Width       uint32
	Height      uint32
	JPG         []byte
	OceanMargin int32
	Monuments   []Monument
	Background  string
}

Map is the server map image with its monuments (AppMap).

type MapNote

type MapNote struct {
	Type        int32
	X, Y        float32
	Icon        int32
	ColourIndex int32
	Label       string
}

MapNote is a marker a player placed on the map.

type Marker

type Marker struct {
	ID         uint64
	Type       MarkerType
	X, Y       float32
	SteamID    uint64
	Rotation   float32
	Radius     float32
	Color1     Vector4
	Color2     Vector4
	Alpha      float32
	Name       string
	OutOfStock bool
	SellOrders []SellOrder
}

Marker is a dynamic marker on the map: players, vending machines, cargo ship, helicopters and so on (AppMarker).

type Monument

type Monument struct {
	Token        string
	X, Y         float32
	IsCustomName bool
}

Monument is a named location on the map.

type NexusAuth

type NexusAuth struct {
	ServerID    string
	PlayerToken int32
}

NexusAuth is the result of a Nexus authentication request.

type Option

type Option func(*options)

Option configures a Client.

func WithAuthTokenSource

func WithAuthTokenSource(fn func(ctx context.Context) (string, error)) Option

WithAuthTokenSource sets a function the client calls for the auth token before every connection attempt, the first one and each reconnect. It takes precedence over Config.AuthToken.

Use it for long-running bots: the token expires after about 14 days, and with a source the client picks up a renewed token from the application's own storage without being recreated. While the source returns an expired or rejected token, the client keeps retrying with backoff instead of stopping, waiting for the application to renew it.

The function is called from the client's goroutines; it must be safe for concurrent use and should honour ctx.

Example

With a token source the client fetches the auth token before every connection, so a renewed token is picked up on the next reconnect.

package main

import (
	"context"
	"log"
	"os"

	"github.com/roreng/rustplus"
)

func main() {
	source := func(ctx context.Context) (string, error) {
		// Read from wherever the application keeps secrets.
		return os.Getenv("RUSTPLUS_AUTH_TOKEN"), nil
	}
	c, err := rustplus.New(rustplus.Config{
		ServerID: "089941d9-064e-4628-9c60-eaeb01a943e8",
		PlayerID: 76561198000000001,
	}, rustplus.WithAuthTokenSource(source))
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()
}

func WithEventBuffer

func WithEventBuffer(n int) Option

WithEventBuffer sets how many broadcasts may wait for handlers; when the queue is full the oldest event is dropped. Zero means unbounded. The default is 4096.

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient sets the HTTP client used for the WebSocket handshake (for proxies or custom TLS settings).

func WithHTTPHeader

func WithHTTPHeader(key, value string) Option

WithHTTPHeader adds a header to the WebSocket handshake request.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the logger. By default the client logs nothing.

func WithMaxMessageSize

func WithMaxMessageSize(n int64) Option

WithMaxMessageSize sets the maximum size of a single incoming message. The default is 32 MiB.

func WithOrigin

func WithOrigin(origin string) Option

WithOrigin overrides the Origin header sent to the relay.

func WithPanicHandler

func WithPanicHandler(fn func(recovered any)) Option

WithPanicHandler sets the function called with the value recovered when an event handler panics. By default the panic and its stack trace are logged at error level (to slog.Default if no logger is set).

func WithPingInterval

func WithPingInterval(d time.Duration) Option

WithPingInterval sets how often the client pings the relay to detect a dead connection. Zero disables pings. The default is 30s.

func WithReconnect

func WithReconnect(p ReconnectPolicy) Option

WithReconnect sets the reconnection policy. Zero fields take their defaults from DefaultReconnectPolicy().

func WithRelayURL

func WithRelayURL(u string) Option

WithRelayURL overrides the relay base URL. The server ID is appended to it. Mostly useful for tests.

func WithRequestTimeout

func WithRequestTimeout(d time.Duration) Option

WithRequestTimeout sets the timeout applied to a request whose context has no deadline. Zero disables it. The default is 15s.

func WithoutExpiryCheck

func WithoutExpiryCheck() Option

WithoutExpiryCheck makes Dial skip the local auth token expiry check and leave the decision to the relay.

func WithoutRateLimit

func WithoutRateLimit() Option

WithoutRateLimit disables the client-side rate limiter. The server enforces its own limits and answers "rate_limit" when they are exceeded.

func WithoutReconnect

func WithoutReconnect() Option

WithoutReconnect disables reconnection: the client stops (Done is closed) as soon as the connection drops.

type ReconnectPolicy

type ReconnectPolicy struct {
	// InitialDelay is the delay before the first attempt. Default 1s.
	InitialDelay time.Duration
	// MaxDelay caps the delay between attempts. Default 1m.
	MaxDelay time.Duration
	// MaxAttempts is how many failed attempts in a row are tolerated
	// before the client gives up. Zero means retry forever.
	MaxAttempts int
	// DialTimeout bounds a single connection attempt. Default 15s.
	DialTimeout time.Duration
	// contains filtered or unexported fields
}

ReconnectPolicy controls how a Client reconnects after the connection drops. The delay before attempt n is InitialDelay * 2^(n-1), capped at MaxDelay, with ±20% jitter.

func DefaultReconnectPolicy

func DefaultReconnectPolicy() ReconnectPolicy

DefaultReconnectPolicy returns the policy used unless WithReconnect is given: retry forever with 1s..1m exponential backoff and a 15s dial timeout. Each call returns a new copy.

type SellOrder

type SellOrder struct {
	ItemID                     int32
	Quantity                   int32
	CurrencyID                 int32
	CostPerItem                int32
	AmountInStock              int32
	ItemIsBlueprint            bool
	CurrencyIsBlueprint        bool
	ItemCondition              float32
	ItemConditionMax           float32
	PriceMultiplier            float32
	ReceivedQuantityMultiplier float32
}

SellOrder is an offer in a vending machine.

type ServerError

type ServerError struct {
	// Code is the raw error string, e.g. "not_found".
	Code string
}

ServerError is an error returned by the game server in AppResponse.error.

func (*ServerError) Error

func (e *ServerError) Error() string

func (*ServerError) Is

func (e *ServerError) Is(target error) bool

Is makes two ServerErrors with the same code compare equal.

type ServerInfo

type ServerInfo struct {
	Name           string
	HeaderImage    string
	URL            string
	Map            string
	MapSize        uint32
	WipeTime       time.Time
	Players        uint32
	MaxPlayers     uint32
	QueuedPlayers  uint32
	Seed           uint32
	Salt           uint32
	LogoImage      string
	Nexus          string
	NexusID        int32
	NexusZone      string
	CamerasEnabled bool
}

ServerInfo describes the game server (AppInfo).

func (ServerInfo) Grid added in v0.2.0

func (s ServerInfo) Grid(x, y float32) (GridCell, bool)

Grid returns the grid cell that contains the world position (x, y) on the server's map; see GridAt.

info, err := c.Info(ctx)
...
if cell, ok := info.Grid(member.X, member.Y); ok {
	fmt.Println(member.Name, "is in", cell) // "is in G12"
}

type StorageContents

type StorageContents struct {
	Items    []Item
	Capacity int32
	// HasProtection and ProtectionExpiry are set for a tool cupboard:
	// whether upkeep is paid and until when.
	HasProtection    bool
	ProtectionExpiry time.Time
}

StorageContents is what a storage monitor reports about its container.

type StorageMonitor

type StorageMonitor struct{ Entity }

StorageMonitor is a handle to a storage monitor.

func (StorageMonitor) Contents

func (m StorageMonitor) Contents(ctx context.Context) (StorageContents, error)

Contents returns the monitored container's contents. It fails with ErrWrongType if the device is not a storage monitor.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"log"

	"github.com/roreng/rustplus"
)

func main() {
	ctx := context.Background()
	c, err := rustplus.Dial(ctx, rustplus.Config{ /* ... */ })
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	box, err := c.StorageMonitor(555).Contents(ctx)
	switch {
	case errors.Is(err, rustplus.ErrNotFound):
		fmt.Println("the monitor was destroyed or unpaired")
	case errors.Is(err, rustplus.ErrWrongType):
		fmt.Println("entity 555 is not a storage monitor")
	case err != nil:
		log.Fatal(err)
	default:
		fmt.Println(len(box.Items), "stacks, upkeep until", box.ProtectionExpiry)
	}
}

func (StorageMonitor) OnChanged

func (m StorageMonitor) OnChanged(fn func(StorageContents)) (remove func())

OnChanged registers a handler called with the contents whenever they change, and right after subscribing.

type Switch

type Switch struct{ Entity }

Switch is a handle to a smart switch.

func (Switch) Off

func (s Switch) Off(ctx context.Context) error

Off turns the switch off.

func (Switch) On

func (s Switch) On(ctx context.Context) error

On turns the switch on.

func (Switch) OnChanged

func (s Switch) OnChanged(fn func(on bool)) (remove func())

OnChanged registers a handler called with the switch state whenever it changes, and right after subscribing.

func (Switch) Set

func (s Switch) Set(ctx context.Context, on bool) error

Set turns the switch on or off.

func (Switch) State

func (s Switch) State(ctx context.Context) (on bool, err error)

State reports whether the switch is on. It fails with ErrWrongType if the device is not a switch.

type Team

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

Team gives access to the player's team: members, chat and events. Obtain it with Client.Team; it is a small value, cheap to copy.

func (Team) Chat

func (t Team) Chat(ctx context.Context) ([]TeamMessage, error)

Chat returns the recent team chat messages.

func (Team) Info

func (t Team) Info(ctx context.Context) (TeamInfo, error)

Info returns the team's members, leader and map notes.

func (Team) Kick

func (t Team) Kick(ctx context.Context, steamID uint64) error

Kick removes a member from the team. The player must be the leader.

func (Team) OnChanged

func (t Team) OnChanged(fn func(TeamChanged)) (remove func())

OnChanged registers a handler for team changes: members joining, leaving, dying, moving, going online or offline.

func (Team) OnMessage

func (t Team) OnMessage(fn func(TeamMessage)) (remove func())

OnMessage registers a handler for new team chat messages. See the Client documentation for how handlers are run.

func (Team) Promote

func (t Team) Promote(ctx context.Context, steamID uint64) error

Promote makes another team member the team leader.

func (Team) Send

func (t Team) Send(ctx context.Context, message string) error

Send posts a message to team chat as the player.

type TeamChanged

type TeamChanged struct {
	PlayerID uint64
	Team     TeamInfo
}

TeamChanged is broadcast when the team composition or state changes.

type TeamInfo

type TeamInfo struct {
	LeaderSteamID  uint64
	Members        []TeamMember
	MapNotes       []MapNote
	LeaderMapNotes []MapNote
}

TeamInfo is the player's team (AppTeamInfo).

func (TeamInfo) Member

func (t TeamInfo) Member(steamID uint64) (TeamMember, bool)

Member returns the team member with the given Steam ID.

type TeamMember

type TeamMember struct {
	SteamID   uint64
	Name      string
	X, Y      float32
	Online    bool
	Alive     bool
	SpawnTime time.Time
	DeathTime time.Time
}

TeamMember is a member of the player's team.

type TeamMessage

type TeamMessage struct {
	SteamID uint64
	Name    string
	Message string
	Color   string
	Time    time.Time
}

TeamMessage is a team chat message.

type Vector4

type Vector4 struct{ X, Y, Z, W float32 }

Vector4 is a four-component vector, used for marker colours (RGBA).

Directories

Path Synopsis
examples
simple command
Command simple connects to a Rust server, prints what it knows about the server and the team, and answers "!time" in team chat.
Command simple connects to a Rust server, prints what it knows about the server and the team, and answers "!time" in team chat.
internal
fcm
Package fcm is a client for Firebase Cloud Messaging that registers as an Android app and receives push messages over Google's MCS protocol (mtalk.google.com:5228), the way an Android device does.
Package fcm is a client for Firebase Cloud Messaging that registers as an Android app and receives push messages over Google's MCS protocol (mtalk.google.com:5228), the way an Android device does.
fcm/fcmpb
Package fcmpb contains the Go types generated from the Google checkin and MCS protocol definitions (proto/fcm).
Package fcmpb contains the Go types generated from the Google checkin and MCS protocol definitions (proto/fcm).
ratelimit
Package ratelimit implements a reserving token bucket.
Package ratelimit implements a reserving token bucket.
testnet
Package testnet provides an in-memory HTTP server for tests.
Package testnet provides an in-memory HTTP server for tests.
Package push receives Rust+ push notifications: server and device pairing, smart alarms, deaths and team logins.
Package push receives Rust+ push notifications: server and device pairing, smart alarms, deaths and team logins.
Package rustpluspb contains the Go types generated from the Rust+ companion protocol definition (proto/rustplus.proto).
Package rustpluspb contains the Go types generated from the Rust+ companion protocol definition (proto/rustplus.proto).

Jump to

Keyboard shortcuts

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