GitHubComeçar

A referência da API é gerada a partir dos comentários de documentação Go no código-fonte e está escrita em inglês.

package presence

import "github.com/nsgo-dev/game/pkg/presence"

Visão geral

Package presence reports what the player is doing (level, game mode, party size, timestamps, artwork, and custom localization tokens) to Steam and Discord friend lists through a single provider-neutral API.

Architecture

A game builds an Activity describing the player's current state and passes it to a Manager configured with one or more Provider implementations:

  • Discord speaks Discord's local IPC v1 protocol directly over Unix domain sockets on macOS and Linux or named pipes on Windows, in pure Go with no cgo.
  • Steam calls Steamworks' flat C rich presence API (ISteamFriends::SetRichPresence and ClearRichPresence) by dynamically loading the Steamworks shared library through purego on desktop targets, with no hand-written C.

On platforms without desktop IPC or Steamworks (web, iOS, Android) or when Discord or Steam is not running, the providers return ErrUnavailable. A Manager fans updates out to every configured provider, deduplicates unchanged states, optionally throttles rapid updates via ManagerConfig.MinInterval, and degrades gracefully when one provider is unavailable while another succeeds.

Changing levels

Games typically set their mode, party, and artwork once with Manager.Update and update the current level as the player progresses with Manager.SetLevel:

mgr := presence.NewManager(
	presence.ManagerConfig{},
	presence.NewSteam(presence.SteamConfig{}),
	discordProvider,
)
defer mgr.Close()

_ = mgr.Update(ctx, presence.Activity{
	Mode:      "Campaign",
	Level:     "Forest 1-2",
	PartyID:   "squad-42",
	PartySize: 2,
	PartyMax:  4,
})
_ = mgr.SetLevel(ctx, "Cavern 2-1")

Both Discord and Steam accept injectable transports (DiscordConfig.Dial and SteamConfig.Driver) so tests can verify the exact wire frames and Steamworks key-value mutations deterministically without running Discord or Steam.

Índice

Constantes

const (
	// SteamMaxKeys is the maximum number of simultaneous rich presence keys
	// Steamworks allows for the local user (k_cchMaxRichPresenceKeys).
	SteamMaxKeys = 30
	// SteamMaxKeyLength is the maximum UTF-8 byte length of a Steam rich
	// presence key (excluding the NUL terminator).
	SteamMaxKeyLength = 63
	// SteamMaxValueLength is the maximum UTF-8 byte length of a Steam rich
	// presence value (excluding the NUL terminator).
	SteamMaxValueLength = 255
)

Steam rich presence limits from Steamworks' isteamfriends.h. Steamworks defines k_cchMaxRichPresenceKeyLength = 64 and k_cchMaxRichPresenceValueLength = 256 including the trailing NUL byte.

const DefaultMinInterval = 4 * time.Second

DefaultMinInterval is the recommended minimum interval between presence updates when throttling rapid state transitions for desktop clients such as Discord (which rate-limits SET_ACTIVITY bursts).

const DiscordMaxTextLength = 128

DiscordMaxTextLength is the maximum UTF-8 byte length Discord accepts for rich presence text fields such as details, state, and asset hover text.

Variáveis

var (
	// ErrUnavailable reports that a rich presence platform or local daemon is
	// not running, its shared library is absent, or the current target platform
	// does not support the provider.
	ErrUnavailable = errors.New("presence: provider unavailable")

	// ErrClosed reports that a Provider or Manager has already been closed.
	ErrClosed = errors.New("presence: closed")

	// ErrInvalidConfig reports that a provider configuration is missing a
	// required field or contains an invalid setting.
	ErrInvalidConfig = errors.New("presence: invalid configuration")
)
var (
	// ErrSteamKeyInvalid reports a Steam rich presence key that is empty,
	// contains a NUL byte, or exceeds SteamMaxKeyLength bytes.
	ErrSteamKeyInvalid = errors.New("presence: invalid steam rich presence key")

	// ErrSteamTooManyKeys reports an Activity that maps to more than
	// SteamMaxKeys Steam rich presence keys.
	ErrSteamTooManyKeys = errors.New("presence: too many steam rich presence keys")
)

Tipos

type Activity struct {
	// Level names the current level, stage, map, or area (for example "Forest 1-2").
	Level string
	// Mode names the current game mode (for example "Campaign", "Co-op", or "Ranked").
	Mode string
	// Details is the primary summary line shown in presence UIs. When empty,
	// providers derive it from Mode and Level.
	Details string
	// Status is the secondary state line shown in presence UIs (Discord's
	// "state" field and Steam's "status" key). When empty, providers derive a
	// readable string from Level and Mode.
	Status string

	// PartyID identifies the player's current party or lobby. Maps to Discord's
	// party.id and Steam's "steam_player_group" key.
	PartyID string
	// PartySize is the current number of players in the party (0 if solo).
	// Maps to Discord's party.size[0] and Steam's "steam_player_group_size" key.
	PartySize int
	// PartyMax is the maximum capacity of the party (0 if unspecified).
	// Maps to Discord's party.size[1].
	PartyMax int

	// StartTime marks when the current activity began (shown as elapsed time on
	// Discord).
	StartTime time.Time
	// EndTime marks when the current activity ends (shown as remaining time on
	// Discord).
	EndTime time.Time

	// LargeImage is the Discord artwork asset key or URL for the large icon.
	LargeImage string
	// LargeText is the hover tooltip for LargeImage.
	LargeText string
	// SmallImage is the Discord artwork asset key or URL for the small badge icon.
	SmallImage string
	// SmallText is the hover tooltip for SmallImage.
	SmallText string

	// JoinSecret is an opaque session join token. Maps to Discord's
	// secrets.join and Steam's "connect" key when Custom["connect"] is unset.
	JoinSecret string

	// Custom holds additional provider-specific key-value pairs, primarily for
	// Steam rich presence localization tokens such as "steam_display",
	// "connect", "steam_player_group", "steam_player_group_size", or custom
	// token parameters.
	Custom map[string]string
}

Activity describes what the player is currently doing in the game.

All fields are optional. Providers translate the populated fields into their native representation: Discord's SET_ACTIVITY payload and Steam's ISteamFriends rich presence key-value table.

func (a Activity) Clone() Activity

Clone returns a copy of a with an independent Custom map so later mutations do not alias stored state.

func (a Activity) Equal(b Activity) bool

Equal reports whether a and b represent the same rich presence state.

func (a Activity) Summary() string

Summary returns a single human-readable status string derived from a, using Status if set, otherwise Details, otherwise combining Mode and Level.

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

Discord publishes rich presence updates to a locally running Discord desktop client using Discord's local IPC v1 protocol in pure Go (no cgo).

Connections are established lazily on the first Set or Clear call (or eagerly via Discord.Connect). If Discord is not running or the current target has no desktop IPC transport, Set and Clear return ErrUnavailable. If an active IPC connection drops mid-session, Discord automatically attempts a single reconnect and handshake before returning an error.

All methods on Discord are safe for concurrent use.

func NewDiscord(cfg DiscordConfig) (*Discord, error)

NewDiscord constructs a Discord rich presence provider. It returns ErrInvalidConfig if cfg.ClientID is empty or whitespace.

func (d *Discord) Clear(ctx context.Context) error

Clear removes the current Discord rich presence by sending SET_ACTIVITY with activity set to null.

func (d *Discord) Close() error

Close closes the Discord IPC connection and marks the provider closed.

func (d *Discord) Connect(ctx context.Context) error

Connect eagerly opens the local Discord IPC connection and performs the v1 handshake if not already connected.

func (d *Discord) Name() string

Name returns "discord".

func (d *Discord) Set(ctx context.Context, activity Activity) error

Set publishes activity to the local Discord client via SET_ACTIVITY.

type DiscordConfig struct {
	// ClientID is the Discord Application ID from the Discord Developer Portal.
	// Required.
	ClientID string

	// PID is the process ID reported in SET_ACTIVITY commands. When zero or
	// negative, os.Getpid() is used.
	PID int

	// Dial opens the local Discord IPC transport. When nil, the platform
	// default is used (Unix domain sockets discord-ipc-0..9 on macOS and Linux,
	// named pipes \\.\pipe\discord-ipc-0..9 on Windows, and ErrUnavailable on
	// mobile and web targets).
	Dial func(ctx context.Context) (io.ReadWriteCloser, error)
}

DiscordConfig configures a Discord local IPC rich presence provider.

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

Manager fans rich presence updates out to one or more Provider backends (for example Steam and Discord simultaneously), deduplicates unchanged activities, optionally throttles bursts via ManagerConfig.MinInterval, and degrades gracefully when a platform daemon is unavailable.

All methods on Manager are safe for concurrent use.

func NewManager(cfg ManagerConfig, providers ...Provider) *Manager

NewManager constructs a Manager that fans out updates to providers. Nil entries in providers are ignored.

func (m *Manager) Activity() (Activity, bool)

Activity returns a copy of the latest desired activity and whether rich presence is currently active.

func (m *Manager) Clear(ctx context.Context) error

Clear removes active rich presence on all configured providers and cancels any pending throttled update.

func (m *Manager) Close() error

Close closes every configured provider and marks the Manager as closed. Subsequent calls to Close are no-ops and return nil.

func (m *Manager) Flush(ctx context.Context) error

Flush immediately pushes any pending coalesced update regardless of ManagerConfig.MinInterval.

func (m *Manager) Pending() bool

Pending reports whether a rate-limited update is currently waiting to be pushed by Manager.Poll or Manager.Flush.

func (m *Manager) Poll(ctx context.Context) error

Poll pushes a coalesced pending update if ManagerConfig.MinInterval has elapsed since the previous push. Games using MinInterval can call Poll from their update loop or periodic tick.

func (m *Manager) SetLevel(ctx context.Context, level string) error

SetLevel updates the Level field of the current activity while preserving its other fields (such as Mode, party, assets, timestamps, and Custom keys), then pushes the update to all configured providers.

func (m *Manager) SetMode(ctx context.Context, mode string) error

SetMode updates the Mode field of the current activity while preserving its other fields, then pushes the update to all configured providers.

func (m *Manager) SetParty(ctx context.Context, id string, size, max int) error

SetParty updates the PartyID, PartySize, and PartyMax fields of the current activity while preserving its other fields, then pushes the update to all configured providers.

func (m *Manager) Update(ctx context.Context, activity Activity) error

Update publishes activity to all configured providers.

If activity equals the last applied state (and no earlier update is pending), Update is a no-op and returns nil. When ManagerConfig.MinInterval is positive and has not yet elapsed since the previous push, Update coalesces activity as pending and returns nil; call Manager.Poll once the interval elapses or Manager.Flush to push immediately.

If at least one provider succeeds and the remaining providers return ErrUnavailable, Update returns nil so a missing optional client (such as Discord not running) does not fail the update. If all providers return ErrUnavailable, Update returns ErrUnavailable. Any non-unavailable provider errors are joined and returned while still updating all other providers.

type ManagerConfig struct {
	// MinInterval enforces a minimum duration between consecutive provider
	// pushes. When zero, every distinct update is pushed immediately. When
	// positive, updates arriving within MinInterval of the last push are
	// coalesced and kept pending until Poll is called after MinInterval elapses
	// or Flush is called.
	MinInterval time.Duration

	// Now returns the current time for MinInterval throttling. When nil,
	// time.Now is used.
	Now func() time.Time

	// OnError, if non-nil, is called whenever an individual provider returns an
	// error during Update, SetLevel, Clear, Poll, or Flush (including
	// ErrUnavailable). It is invoked without holding the Manager's internal
	// lock.
	OnError func(provider string, err error)
}

ManagerConfig configures a Manager.

type Provider interface {
	// Set publishes activity to the platform.
	Set(ctx context.Context, activity Activity) error
	// Clear removes any active rich presence from the platform.
	Clear(ctx context.Context) error
	// Close releases platform resources held by the provider.
	Close() error
}

Provider publishes rich presence state to a single platform (such as Steam or Discord).

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

Steam publishes rich presence updates through Steamworks' ISteamFriends::SetRichPresence and ClearRichPresence flat C API using purego (no cgo or hand-written C).

Steam maps an Activity into Steam rich presence keys:

  • "status": derived from Activity.Summary() (Status, Details, Mode - Level, Level, or Mode)
  • "level": Activity.Level when non-empty (usable by Steam localization tokens as %level%)
  • "mode": Activity.Mode when non-empty (usable by Steam localization tokens as %mode%)
  • "steam_player_group": Activity.PartyID when non-empty
  • "steam_player_group_size": strconv.Itoa(Activity.PartySize) when PartySize > 0
  • "connect": Activity.JoinSecret when non-empty
  • "steam_display": SteamConfig.DisplayToken when configured and presence is non-empty
  • Activity.Custom entries override or add keys; setting a key to "" omits it.

Removed keys from a previous Set call are deleted via SetRichPresence(key, "") without clearing unchanged keys, avoiding friend-list flicker.

All methods on Steam are safe for concurrent use.

func NewSteam(cfg SteamConfig) *Steam

NewSteam constructs a Steam rich presence provider. If cfg.Driver is nil, Steam loads the Steamworks shared library lazily on the first Set or Clear call so games can construct Steam unconditionally on every target.

func (s *Steam) Clear(ctx context.Context) error

Clear clears all Steam rich presence keys for the local user.

func (s *Steam) Close() error

Close releases the underlying SteamDriver (if opened) and marks the provider closed.

func (s *Steam) Name() string

Name returns "steam".

func (s *Steam) Set(ctx context.Context, activity Activity) error

Set publishes activity to Steam's ISteamFriends rich presence table.

type SteamConfig struct {
	// LibraryPath overrides the shared library path loaded on desktop targets
	// (for example a custom path to libsteam_api.dylib, libsteam_api.so, or
	// steam_api64.dll). When empty, standard library names beside the game
	// executable and on the system loader path are tried.
	LibraryPath string

	// DisplayToken sets the default "steam_display" localization token (for
	// example "#Status_InLevel") when Activity.Custom["steam_display"] is not
	// set and the activity produces at least one rich presence key.
	DisplayToken string

	// AutoInit, when true, calls SteamAPI_Init if ISteamFriends is not yet
	// initialized when opening the Steamworks library, and calls
	// SteamAPI_Shutdown on Close if Steam initialized it. Leave false when the
	// game initializes Steamworks elsewhere.
	AutoInit bool

	// Driver overrides dynamic purego loading with a custom or mock
	// SteamDriver.
	Driver SteamDriver
}

SteamConfig configures a Steam rich presence provider.

type SteamDriver interface {
	// SetRichPresence corresponds to ISteamFriends::SetRichPresence(key, value).
	// Passing an empty value deletes the key.
	SetRichPresence(key, value string) bool
	// ClearRichPresence corresponds to ISteamFriends::ClearRichPresence().
	ClearRichPresence()
	// Close releases any dynamic library handles owned by the driver.
	Close() error
}

SteamDriver is the low-level binding to Steamworks ISteamFriends rich presence functions.

By default, NewSteam dynamically loads the Steamworks shared library via purego on desktop platforms (macOS, Linux, and Windows) and returns ErrUnavailable on mobile/web targets or when the library or Steam client is absent. Tests and custom integrations can inject a SteamDriver through SteamConfig.Driver.