Skip to content
rorengPublic

About

Go client for the Rust+ companion API: typed API, smart devices, events, automatic reconnection and push notifications

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.

About

Go client for the Rust+ companion API: typed API, smart devices, events, automatic reconnection and push notifications

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages