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 ¶
- Constants
- Variables
- func Redact(secret string) string
- type Alarm
- type AuthToken
- type Clan
- func (cl Clan) Chat(ctx context.Context) ([]ClanMessage, error)
- func (cl Clan) Info(ctx context.Context) (*ClanInfo, error)
- func (cl Clan) OnChanged(fn func(*ClanInfo)) (remove func())
- func (cl Clan) OnMessage(fn func(ClanMessage)) (remove func())
- func (cl Clan) Send(ctx context.Context, message string) error
- func (cl Clan) SetMotd(ctx context.Context, motd string) error
- type ClanInfo
- type ClanInvite
- type ClanMember
- type ClanMessage
- type ClanRole
- type Client
- func (c *Client) Alarm(id uint64) Alarm
- func (c *Client) Clan() Clan
- func (c *Client) Close() error
- func (c *Client) Connect(ctx context.Context) error
- func (c *Client) Connected() bool
- func (c *Client) Do(ctx context.Context, cost int, fill func(*rustpluspb.AppRequest)) (*rustpluspb.AppResponse, error)
- func (c *Client) Done() <-chan struct{}
- func (c *Client) Entity(id uint64) Entity
- func (c *Client) Err() error
- func (c *Client) Info(ctx context.Context) (ServerInfo, error)
- func (c *Client) Map(ctx context.Context) (Map, error)
- func (c *Client) Markers(ctx context.Context) ([]Marker, error)
- func (c *Client) NexusAuth(ctx context.Context, appKey string) (NexusAuth, error)
- func (c *Client) OnBroadcast(fn func(*rustpluspb.AppBroadcast)) (remove func())
- func (c *Client) OnDisconnected(fn func(err error)) (remove func())
- func (c *Client) OnEntityChanged(fn func(EntityChanged)) (remove func())
- func (c *Client) OnReconnected(fn func()) (remove func())
- func (c *Client) PlayerID() uint64
- func (c *Client) StorageMonitor(id uint64) StorageMonitor
- func (c *Client) Switch(id uint64) Switch
- func (c *Client) Team() Team
- func (c *Client) Time(ctx context.Context) (GameTime, error)
- type Config
- type Entity
- type EntityChanged
- type EntityInfo
- type EntityPayload
- type EntityType
- type GameTime
- type GridCell
- type HandshakeError
- type Item
- type Map
- type MapNote
- type Marker
- type MarkerType
- type Monument
- type NexusAuth
- type Option
- func WithAuthTokenSource(fn func(ctx context.Context) (string, error)) Option
- func WithEventBuffer(n int) Option
- func WithHTTPClient(c *http.Client) Option
- func WithHTTPHeader(key, value string) Option
- func WithLogger(l *slog.Logger) Option
- func WithMaxMessageSize(n int64) Option
- func WithOrigin(origin string) Option
- func WithPanicHandler(fn func(recovered any)) Option
- func WithPingInterval(d time.Duration) Option
- func WithReconnect(p ReconnectPolicy) Option
- func WithRelayURL(u string) Option
- func WithRequestTimeout(d time.Duration) Option
- func WithoutExpiryCheck() Option
- func WithoutRateLimit() Option
- func WithoutReconnect() Option
- type ReconnectPolicy
- type SellOrder
- type ServerError
- type ServerInfo
- type StorageContents
- type StorageMonitor
- type Switch
- type Team
- func (t Team) Chat(ctx context.Context) ([]TeamMessage, error)
- func (t Team) Info(ctx context.Context) (TeamInfo, error)
- func (t Team) Kick(ctx context.Context, steamID uint64) error
- func (t Team) OnChanged(fn func(TeamChanged)) (remove func())
- func (t Team) OnMessage(fn func(TeamMessage)) (remove func())
- func (t Team) Promote(ctx context.Context, steamID uint64) error
- func (t Team) Send(ctx context.Context, message string) error
- type TeamChanged
- type TeamInfo
- type TeamMember
- type TeamMessage
- type Vector4
Examples ¶
Constants ¶
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 ¶
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.
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 ¶
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 ¶
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()
}
Output:
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 ¶
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.
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 ¶
Info returns the clan. It returns ErrNoClan (or a nil info) when the player is not in a clan.
func (Clan) OnChanged ¶
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.
type ClanInfo ¶
type ClanInfo struct {
ID int64
Name string
Created time.Time
Creator uint64
Motd string
MotdTimestamp time.Time
MotdAuthor uint64
Logo []byte
Color int32
Roles []ClanRole
Members []ClanMember
Invites []ClanInvite
MaxMemberCount int32
Score int64
}
ClanInfo describes the player's clan.
type ClanInvite ¶
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 ¶
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
CanSetLogo 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 ¶
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 ¶
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)
}
Output:
func (*Client) Close ¶
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 ¶
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) 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) Err ¶
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 ¶
Map returns the map image and monuments. The response is large; avoid calling it often.
func (*Client) Markers ¶
Markers returns the dynamic markers currently on the map: players, vending machines, cargo ship, helicopters and so on.
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 ¶
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) StorageMonitor ¶
func (c *Client) StorageMonitor(id uint64) StorageMonitor
StorageMonitor returns a handle to the storage monitor with the given entity ID.
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.
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) 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 ¶
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.
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.
const ( EntitySwitch EntityType = EntityType(rustpluspb.AppEntityType_Switch) EntityAlarm EntityType = EntityType(rustpluspb.AppEntityType_Alarm) EntityStorageMonitor EntityType = EntityType(rustpluspb.AppEntityType_StorageMonitor) )
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).
type GridCell ¶ added in v0.2.0
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
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
type HandshakeError ¶
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 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 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 MarkerType ¶
type MarkerType int32
MarkerType is the kind of a map marker.
const ( MarkerUndefined MarkerType = MarkerType(rustpluspb.AppMarkerType_Undefined) MarkerPlayer MarkerType = MarkerType(rustpluspb.AppMarkerType_Player) MarkerExplosion MarkerType = MarkerType(rustpluspb.AppMarkerType_Explosion) MarkerVendingMachine MarkerType = MarkerType(rustpluspb.AppMarkerType_VendingMachine) MarkerCH47 MarkerType = MarkerType(rustpluspb.AppMarkerType_CH47) MarkerCargoShip MarkerType = MarkerType(rustpluspb.AppMarkerType_CargoShip) MarkerCrate MarkerType = MarkerType(rustpluspb.AppMarkerType_Crate) MarkerGenericRadius MarkerType = MarkerType(rustpluspb.AppMarkerType_GenericRadius) MarkerPatrolHelicopter MarkerType = MarkerType(rustpluspb.AppMarkerType_PatrolHelicopter) MarkerTravellingVendor MarkerType = MarkerType(rustpluspb.AppMarkerType_TravellingVendor) )
func (MarkerType) String ¶
func (t MarkerType) String() string
type Option ¶
type Option func(*options)
Option configures a Client.
func WithAuthTokenSource ¶
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()
}
Output:
func WithEventBuffer ¶
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 ¶
WithHTTPClient sets the HTTP client used for the WebSocket handshake (for proxies or custom TLS settings).
func WithHTTPHeader ¶
WithHTTPHeader adds a header to the WebSocket handshake request.
func WithLogger ¶
WithLogger sets the logger. By default the client logs nothing.
func WithMaxMessageSize ¶
WithMaxMessageSize sets the maximum size of a single incoming message. The default is 32 MiB.
func WithOrigin ¶
WithOrigin overrides the Origin header sent to the relay.
func WithPanicHandler ¶
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 ¶
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 ¶
WithRelayURL overrides the relay base URL. The server ID is appended to it. Mostly useful for tests.
func WithRequestTimeout ¶
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)
}
}
Output:
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) OnChanged ¶
OnChanged registers a handler called with the switch state whenever it changes, and right after subscribing.
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) 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.
type TeamChanged ¶
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).
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 ¶
TeamMessage is a team chat message.
Source Files
¶
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). |