### Example: Creating a Lavalink client with options Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/configuration.md Shows how to create a new DisGoLink client with custom options: a 30-second HTTP timeout, a track start listener, and a plugin. The userID must be a snowflake.ID. ```go lavalinkClient := disgolink.New(userID, disgolink.WithLogger(slog.Default()), disgolink.WithHTTPClient(&http.Client{Timeout: 30 * time.Second}), disgolink.WithListenerFunc(onTrackStart), disgolink.WithPlugins(myPlugin), ) ``` -------------------------------- ### BestNode Example Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/client.md Example of getting the best node and checking for nil when no nodes are connected. ```go node := lavalinkClient.BestNode() if node == nil { /* no connected nodes */ } ``` -------------------------------- ### Quick wiring example for disgolink Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/client.md Shows the minimal steps to wire up disgolink: create a client with a listener, add a node, get a player, update it with a track, and close the client. The AddNode call returns an error that may be ErrNodeAlreadyExists; see errors.md and configuration.md for details. ```go lavalinkClient := disgolink.New(userID, disgolink.WithListenerFunc(onReady)) node, err := lavalinkClient.AddNode(ctx, disgolink.NodeConfig{ Name: "test", Address: "localhost:2333", Password: "pw" }) player := lavalinkClient.Player(guildID) err := player.Update(ctx, disgolink.WithTrack(track)) lavalinkClient.Close() ``` -------------------------------- ### Version usage example Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/rest-client.md Example call to Version, printing the node version. ```go version, err := node.Rest.Version(ctx) fmt.Println("node version:", version) ``` -------------------------------- ### Update usage example Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/player.md Example of updating the player with a track and volume option. ```go err := player.Update(ctx, disgolink.WithTrack(track), disgolink.WithVolume(80)) ``` -------------------------------- ### Install DisGoLink v4 with go get Source: https://github.com/disgoorg/disgolink/blob/v4/README.md Install the DisGoLink v4 library using the Go module system. ```sh go get github.com/disgoorg/disgolink/v4 ``` -------------------------------- ### WithHTTPClient usage example Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/config.md Example of using WithHTTPClient to create a client with a 30 second timeout. ```go lavalinkClient := disgolink.New(userID, disgolink.WithHTTPClient(&http.Client{ Timeout: 30 * time.Second, })) ``` -------------------------------- ### WithPlugins usage example Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/config.md Example of using WithPlugins to add a sponsorBlockPlugin to the client. ```go lavalinkClient := disgolink.New(userID, disgolink.WithPlugins(sponsorBlockPlugin)) ``` -------------------------------- ### Play a track with player.Update Source: https://github.com/disgoorg/disgolink/blob/v4/README.md Get or create a player for a guild and play a track. The toPlay variable comes from the result handler in the loading example. ```go player := lavalinkClient.Player("guild_id") // This will either return an existing or new player // toPlay is from result handler in the example above err := player.Update(context.TODO(), lavalink.WithTrack(*toPlay)) ``` -------------------------------- ### Iterate Nodes Example Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/client.md Example of iterating over all nodes and printing their name and status. ```go for node := range lavalinkClient.Nodes() { fmt.Println(node.Config.Name, node.Status()) } ``` -------------------------------- ### Position usage example Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/player.md Example of retrieving and formatting the player's position in minutes and seconds. ```go position := player.Position() fmt.Printf("%d:%02d", position.Minutes(), position.SecondsPart()) ``` -------------------------------- ### AddNode Example Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/client.md Example of adding a node with a NodeConfig. The method blocks until the node connects, using the retry/backoff behavior of Node.Open. ```go node, err := lavalinkClient.AddNode(ctx, disgolink.NodeConfig{ Name: "test", Address: "localhost:2333", Password: "youshallnotpass", Secure: false, }) if err != nil { /* handle */ } ``` -------------------------------- ### Iterate Players Example Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/client.md Example of iterating over all players and printing the guild ID for each. ```go for player := range lavalinkClient.Players() { fmt.Println("player for guild", player.GuildID) } ``` -------------------------------- ### LoadTracksHandler usage example Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/rest-client.md Example call to LoadTracksHandler with a search query and a handler constructed via disgolink.NewTrackLoadingResultHandler. ```go node.Rest.LoadTracksHandler(ctx, "ytsearch:Never Gonna Give You Up", disgolink.NewTrackLoadingResultHandler(...)) ``` -------------------------------- ### Example plugin registration Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/plugin.md Creates a plugin implementing Plugin, EventPlugin, and PluginEventHandler, then registers it on a new client via WithPlugins. ```go var myPlugin = &pluginImpl{ NameImpl: "myplugin", VersionImpl: "1.0.0", // pluginImpl implements Plugin, EventPlugin and PluginEventHandler } lavalinkClient := disgolink.New(userID, disgolink.WithPlugins(myPlugin)) ``` -------------------------------- ### Usage Example Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/lavalink/load-result.md Example of using LoadTracks and type-switching on the LoadResult.Data field to handle different result types. ```APIDOC ## Usage Example ### Description Demonstrates how to call LoadTracks and handle the different LoadResultData types. ### Code ```go result, err := node.Rest.LoadTracks(ctx, "spsearch:some song") if err == nil { switch d := result.Data.(type) { case lavalink.Track: fmt.Println("track:", d.Info.Title) case lavalink.Playlist: fmt.Println("playlist:", d.Info.Name, len(d.Tracks)) case lavalink.Search: fmt.Println("search:", len(d), "tracks") case lavalink.Empty: fmt.Println("no matches") case lavalink.Exception: fmt.Println("error:", d.Error()) } } ``` ``` -------------------------------- ### Full example - advanced update Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/player-update.md Advanced update combining multiple options in a single Player.Update call. ```go err := player.Update(ctx, disgolink.WithEncodedTrack(track.Encoded), disgolink.WithPosition(lavalink.Duration(0)), disgolink.WithVolume(100), disgolink.WithPaused(false), disgolink.WithNoReplace(false), ) if err != nil { /* handle */ } ``` -------------------------------- ### Track.WithUserData usage example Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/lavalink/models-media.md Example of calling WithUserData to attach user data to a track, using a map with a requested_by key. ```go track, err := track.WithUserData(map[string]string{"requested_by": userID}) ``` -------------------------------- ### Usage example with LoadTracks and type switch Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/lavalink/load-result.md Example of using RestClient.LoadTracks to load tracks and switching on the concrete type of the result's Data field to handle each case. ```go result, err := node.Rest.LoadTracks(ctx, "spsearch:some song") if err == nil { switch d := result.Data.(type) { case lavalink.Track: fmt.Println("track:", d.Info.Title) case lavalink.Playlist: fmt.Println("playlist:", d.Info.Name, len(d.Tracks)) case lavalink.Search: fmt.Println("search:", len(d), "tracks") case lavalink.Empty: fmt.Println("no matches") case lavalink.Exception: fmt.Println("error:", d.Error()) } } ``` -------------------------------- ### Filter preset from _examples/disgo/handlers.go Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/lavalink/README.md Defines a bass boost equalizer preset and assigns it to the filters. The comment '/* ... */' is part of the original example. ```go var bassBoost = &lavalink.Equalizer{ 0: 0.2, 1: 0.15, 2: 0.1, 3: 0.05, 4: 0.0, 5: -0.05, 6: -0.1, 7: -0.1, /* ... */ } filters.Equalizer = bassBoost ``` -------------------------------- ### Duration arithmetic and formatting example Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/lavalink/duration-timestamp.md Shows creating a duration of 2 minutes and 500 ms, then printing its total milliseconds and string representation. Output: 120500 2m500ms. ```go d := lavalink.Duration(2) * lavalink.Minute + lavalink.Duration(500) fmt.Println(d.Milliseconds(), d.String()) // 120500 2m500ms ``` -------------------------------- ### Usage example with LoadTracksHandler Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/load-result.md Example of using NewTrackLoadingResultHandler with Node.Rest.LoadTracksHandler to load a track query and handle each possible outcome. ```APIDOC ## Usage Example ### Description Demonstrates how to use the TrackLoadingResultHandler with the Lavalink REST client to load a track query and handle each possible outcome. ### Example ```go query := "ytsearch:Rick Astley - Never Gonna Give You Up" lavalinkClient.BestNode().Rest.LoadTracksHandler(ctx, query, disgolink.NewTrackLoadingResultHandler( func(track lavalink.Track) { // Loaded a single track toPlay = &track }, func(playlist lavalink.Playlist) { // Loaded a playlist — e.g. play playlist.Tracks[0] }, func(tracks []lavalink.Track) { // Loaded a search result }, func() { // nothing matching the query found }, func(err error) { // something went wrong while loading the track fmt.Println(err) }, )) ``` ``` -------------------------------- ### Error-handling player update with volume (from _examples/disgo/handlers.go) Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/player.md Checks if a player exists for the guild, returns an error message if not, then updates the player's volume. On failure, sends an error message with the error text. This example is from the DisGo example file _examples/disgo/handlers.go. ```go player := b.Lavalink.ExistingPlayer(*event.GuildID()) if player == nil { return event.CreateMessage(discord.MessageCreate{Content: "No player found"}) } if err := player.Update(context.TODO(), disgolink.WithVolume(volume)); err != nil { return event.CreateMessage(discord.MessageCreate{ Content: fmt.Sprintf("Error while setting volume: `%s`", err), }) } ``` -------------------------------- ### Error handling example Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/load-result.md Example of handling errors in the loadFailed callback, replying to a Discord interaction with the error message. ```APIDOC ## Error Handling Example ### Description Shows how to handle errors in the loadFailed callback, using the original error from the REST layer to reply to a Discord interaction. ### Example ```go func(err error) { _, _ = b.Client.Rest.UpdateInteractionResponse(event.ApplicationID(), event.Token(), discord.MessageUpdate{ Content: omit.Ptr(fmt.Sprintf("Error while looking up query: `%s`", err)), }) } ``` ``` -------------------------------- ### WithListenerFunc usage example Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/config.md Recommended way to hook the event stream using WithListenerFunc with onPlayerUpdate and onTrackStart functions. ```go lavalinkClient := disgolink.New(userID, disgolink.WithListenerFunc(onPlayerUpdate), disgolink.WithListenerFunc(onTrackStart), ) func onPlayerUpdate(event *disgolink.PlayerUpdateEvent) { // ... } func onTrackStart(event *disgolink.PlayerTrackStartEvent) { // ... } ``` -------------------------------- ### Add listener at runtime Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/events.md Use AddListeners to register a new listener after the client is created. The example shows a PlayerUpdateEvent listener that prints the guild ID and playback position. ```go lavalinkClient.AddListeners(disgolink.NewListenerFunc(func(event *disgolink.PlayerUpdateEvent) { fmt.Println(event.Player.GuildID, event.State.Position) })) ``` -------------------------------- ### Create Client with New Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/client.md Example of creating a new DisGoLink client with a snowflake ID. The userID is sent as the User-Id WebSocket header and used for session binding. ```go lavalinkClient := disgolink.New(snowflake.ID(1234567890)) ``` -------------------------------- ### Version method signature Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/rest-client.md Signature for the Version method. It returns the raw response body of GET /version as a string. ```go func (c *RestClient) Version(ctx context.Context) (string, error) ``` -------------------------------- ### Fetching server info and stats with RestClient Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/lavalink/server-info.md Example usage of RestClient.Info and RestClient.Stats to fetch server info and stats. Prints the Lavalink version, JVM, plugins, and player statistics. ```go info, err := node.Rest.Info(ctx) if err == nil { fmt.Println("lavalink", info.Version.Semver, "on", info.JVM) for _, pm := range info.Plugins { fmt.Println("plugin:", pm.Name, pm.Version) } } stats, err := node.Rest.Stats(ctx) fmt.Println("players", stats.Players, "playing", stats.PlayingPlayers, "uptime", stats.Uptime) ``` -------------------------------- ### Usage example with LoadTracksHandler Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/load-result.md Shows how to use NewTrackLoadingResultHandler with Node.Rest.LoadTracksHandler. The query uses ytsearch: prefix. Each callback handles a different outcome; the track callback assigns to toPlay. ```go query := "ytsearch:Rick Astley - Never Gonna Give You Up" lavalinkClient.BestNode().Rest.LoadTracksHandler(ctx, query, disgolink.NewTrackLoadingResultHandler( func(track lavalink.Track) { // Loaded a single track toPlay = &track }, func(playlist lavalink.Playlist) { // Loaded a playlist — e.g. play playlist.Tracks[0] }, func(tracks []lavalink.Track) { // Loaded a search result }, func() { // nothing matching the query found }, func(err error) { // something went wrong while loading the track fmt.Println(err) }, )) ``` -------------------------------- ### WithVolume function declaration Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/player-update.md Sets update.Volume (0-1000 scale used in the example commands). ```go func WithVolume(volume int) PlayerUpdateOpt ``` -------------------------------- ### WithTrack function declaration and usage Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/player-update.md Convenience for starting playback: applies WithEncodedTrack(track.Encoded) and WithTrackUserData(track.UserData). ```go func WithTrack(track lavalink.Track) PlayerUpdateOpt ``` ```go err := player.Update(ctx, disgolink.WithTrack(track)) ``` -------------------------------- ### Default config returned by defaultConfig() Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/configuration.md Shows the default configuration values applied by defaultConfig() and the additional logger enrichment after applying options. The logger gets the name=disgolink_client attribute. ```go return &config{ Logger: slog.Default(), HTTPClient: &http.Client{ Timeout: 10 * time.Second, }, } // plus, after applying options: c.Logger = c.Logger.With(slog.String("name", "disgolink_client")) ``` -------------------------------- ### Error-handling callback example Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/load-result.md From _examples/disgo/handlers.go: the loadFailed callback receives the original error from the REST layer (transport/HTTP or marshaled lavalink.Error) and replies to the interaction with it. ```go func(err error) { _, _ = b.Client.Rest.UpdateInteractionResponse(event.ApplicationID(), event.Token(), discord.MessageUpdate{ Content: omit.Ptr(fmt.Sprintf("Error while looking up query: `%s`", err)), }) } ``` -------------------------------- ### New Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/client.md Constructs a new Client with the given bot user ID and optional configuration options. ```APIDOC ## New ### Description Creates a new Client instance with the specified Discord user ID and optional configuration options. ### Method Constructor ### Signature `func New(userID snowflake.ID, opts ...ConfigOpt) *Client` ### Parameters - **userID** (snowflake.ID) - Required - The Discord user ID of the bot (`uint64`). Sent as the `User-Id` WebSocket header and used for session binding. - **opts** (...ConfigOpt) - Optional - Client configuration options; see Configuration options. ### Returns A new `*Client` whose `nodes`, `players`, `listeners`, and `plugins` collections start empty. `logger` and `httpClient` come from the configuration; if no options are passed, `defaultConfig()` applies (`slog.Default()` logger and `http.Client{Timeout: 10 * time.Second}`). ### Example ```go lavalinkClient := disgolink.New(snowflake.ID(1234567890)) ``` ``` -------------------------------- ### config.apply method Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/config.md The apply method applies all options in order and then tags the logger with name=disgolink_client. ```go func (c *config) apply(opts []ConfigOpt) { for _, opt := range opts { opt(c) } c.Logger = c.Logger.With(slog.String("name", "disgolink_client")) } ``` -------------------------------- ### Create a new DisGoLink client Source: https://github.com/disgoorg/disgolink/blob/v4/README.md Create a new Lavalink client instance with a user ID. This is the first step in setting up DisGoLink. ```go import ( "github.com/disgoorg/snowflake/v2" "github.com/disgoorg/disgolink/v4/disgolink" ) var userID = snowflake.ID(1234567890) lavalinkClient := disgolink.New(userID) ``` -------------------------------- ### TrackStartEvent Structure Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/lavalink/messages.md Represents the start of a track. Player.OnEvent mirrors the track to the player. ```go type TrackStartEvent struct { Track Track `json:"track"` GuildID snowflake.ID `json:"guildId"` } func (TrackStartEvent) Op() Op { return OpEvent } func (TrackStartEvent) Type() EventType { return EventTypeTrackStart } func (e TrackStartEvent) GetGuildID() snowflake.ID { return e.GuildID } ``` -------------------------------- ### Stats Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/rest-client.md Retrieves statistics about the Lavalink node. Sends a GET request to /v4/stats. ```APIDOC ## GET /v4/stats ### Description Retrieves node statistics. ### Method GET ### Endpoint /v4/stats ### Response #### Success Response (200) - **stats** (lavalink.Stats) - Node statistics object. ``` -------------------------------- ### Consume typed events with disgolink Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/lavalink/messages.md Demonstrates how to initialize a new disgolink client with listener functions for PlayerTrackEndEvent and PlayerTrackStuckEvent. ```go lavalinkClient := disgolink.New(userID, disgolink.WithListenerFunc(func(event *disgolink.PlayerTrackEndEvent) { if event.Reason.MayStartNext() { /* advance queue with event.Player */ } }), disgolink.WithListenerFunc(func(event *disgolink.PlayerTrackStuckEvent) { fmt.Println("track stuck after", event.Threshold) }), ) ``` -------------------------------- ### Enable karaoke filter with disgolink.WithFilters Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/lavalink/filters.md Creates a filter set with karaoke enabled and sends it to the server via player.Update using disgolink.WithFilters. The comment notes this enables karaoke mode. ```go filters := lavalink.Filters{ Karaoke: &lavalink.Karaoke{ Level: 1.0, MonoLevel: 1.0, FilterBand: 380.0, FilterWidth: 10.0 }, } err := player.Update(ctx, disgolink.WithFilters(filters)) // enable karaoke mode ``` -------------------------------- ### Stats method signature Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/rest-client.md Signature for the Stats method. It returns lavalink.Stats from GET /v4/stats. ```go func (c *RestClient) Stats(ctx context.Context) (stats *lavalink.Stats, err error) ``` -------------------------------- ### Info method signature Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/rest-client.md Signature for the Info method. It returns lavalink.Info from GET /v4/info. ```go func (c *RestClient) Info(ctx context.Context) (info *lavalink.Info, err error) ``` -------------------------------- ### TrackEndReason Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/lavalink/messages.md Represents the reason a track ended. Provides a method to determine if the next track should start. ```APIDOC ## TrackEndReason ### Description `TrackEndReason` is a string type that indicates why a track ended. It provides a `MayStartNext()` method to determine if the next track in a queue should start. ### Constants - **TrackEndReasonFinished** (`"finished"`) - The track finished naturally. `MayStartNext()` returns `true`. - **TrackEndReasonLoadFailed** (`"loadFailed"`) - The track failed to load. `MayStartNext()` returns `true`. - **TrackEndReasonStopped** (`"stopped"`) - The track was stopped. `MayStartNext()` returns `false`. - **TrackEndReasonReplaced** (`"replaced"`) - The track was replaced. `MayStartNext()` returns `false`. - **TrackEndReasonCleanup** (`"cleanup"`) - The track was cleaned up. `MayStartNext()` returns `false`. ### Methods - **MayStartNext()** (bool) - Returns `true` if the next track should start (for `finished` and `loadFailed`), otherwise `false`. ### Usage Use `MayStartNext()` in your `onTrackEnd` handler to auto-advance a queue only on reasons that permit it. ### Example ```go type TrackEndReason string const ( TrackEndReasonFinished TrackEndReason = "finished" TrackEndReasonLoadFailed TrackEndReason = "loadFailed" TrackEndReasonStopped TrackEndReason = "stopped" TrackEndReasonReplaced TrackEndReason = "replaced" TrackEndReasonCleanup TrackEndReason = "cleanup" ) ``` ``` -------------------------------- ### DecodeTrack Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/rest-client.md Decodes an encoded track into its full track object. Sends a GET request to /v4/decodetrack. ```APIDOC ## GET /v4/decodetrack ### Description Decodes an encoded track into its full track object. ### Method GET ### Endpoint /v4/decodetrack ### Parameters #### Query Parameters - **track** (string) - Required - The URL-escaped encoded track. ### Response #### Success Response (200) - **track** (lavalink.Track) - The decoded track object. ``` -------------------------------- ### Players Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/rest-client.md Retrieves all players for the current session. Sends a GET request to /v4/sessions/{sessionId}/players. ```APIDOC ## GET /v4/sessions/{sessionId}/players ### Description Retrieves all players for the current session. ### Method GET ### Endpoint /v4/sessions/{sessionId}/players ### Parameters #### Path Parameters - **sessionId** (string) - Required - The session ID. ### Response #### Success Response (200) - **players** (array of lavalink.Player) - List of players. ``` -------------------------------- ### Register listeners at construction Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/events.md Pass listener functions to disgolink.New when creating the client. This is useful for setting up all event handlers at once during initialization. ```go lavalinkClient := disgolink.New(userID, disolink.WithListenerFunc(onReady), disolink.WithListenerFunc(onTrackStart), disolink.WithListenerFunc(onWebSocketClosed), ) ``` -------------------------------- ### AddPlugins method signature Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/client.md Appends one or more plugins. Registering at runtime behaves the same as the WithPlugins config option, except plugins are only notified about nodes/players created after registration. ```go func (c *Client) AddPlugins(plugins ...Plugin) ``` -------------------------------- ### WithTrack Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/player-update.md Convenience option that starts playback by setting both the encoded track and its user data from a lavalink.Track value. ```APIDOC ## WithTrack ### Description Convenience option that starts playback by setting both the encoded track and its user data from a lavalink.Track value. ### Method N/A (Go function) ### Endpoint N/A ### Parameters #### Function Parameters - **track** (lavalink.Track) - Required - The track to play, including its encoded data and user data. ### Request Example ```go err := player.Update(ctx, disgolink.WithTrack(track)) ``` ### Response N/A ``` -------------------------------- ### LoadTracks Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/rest-client.md Loads tracks based on an identifier, such as a search query or URL. Sends a GET request to /v4/loadtracks. ```APIDOC ## GET /v4/loadtracks ### Description Loads tracks based on an identifier, such as a search query or URL. ### Method GET ### Endpoint /v4/loadtracks ### Parameters #### Query Parameters - **identifier** (string) - Required - The track identifier, URL-escaped. ### Response #### Success Response (200) - **result** (lavalink.LoadResult) - The load result, a discriminated union. ``` -------------------------------- ### disgolink.New constructor Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/README.md The only constructor for the DisGoLink client. It applies the default configuration, then the variadic ConfigOpt options, and returns a Client that manages nodes, players, listeners, and plugins. ```go func New(userID snowflake.ID, opts ...ConfigOpt) *Client ``` -------------------------------- ### Player Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/rest-client.md Retrieves a specific player by guild ID. Sends a GET request to /v4/sessions/{sessionId}/players/{guildId}. ```APIDOC ## GET /v4/sessions/{sessionId}/players/{guildId} ### Description Retrieves a specific player by guild ID. ### Method GET ### Endpoint /v4/sessions/{sessionId}/players/{guildId} ### Parameters #### Path Parameters - **sessionId** (string) - Required - The session ID. - **guildId** (snowflake.ID) - Required - The guild ID. ### Response #### Success Response (200) - **player** (lavalink.Player) - The player object. ``` -------------------------------- ### LoadTracks method signature Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/rest-client.md Signature for the LoadTracks method. It returns a lavalink.LoadResult from GET /v4/loadtracks?identifier={url-escaped query}. ```go func (c *RestClient) LoadTracks(ctx context.Context, identifier string) (result *lavalink.LoadResult, err error) ``` -------------------------------- ### Move method signature Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/player.md Migrates the player to another node. No-op if already on the target node; otherwise destroys and recreates the player on the new node. ```go func (p *Player) Move(ctx context.Context, node *Node) error ``` -------------------------------- ### Players method signature Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/rest-client.md Signature for the Players method. It returns a slice of lavalink.Player from GET /v4/sessions/{sessionId}/players. ```go func (c *RestClient) Players(ctx context.Context) (players []lavalink.Player, err error) ``` -------------------------------- ### Construct PlayerUpdate via builder functions Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/lavalink/models-player.md Recommended way to update a player. Uses disgolink.WithVolume and disgolink.WithPaused builder functions passed to player.Update. See player-update.md for more details. ```go err := player.Update(ctx, disgolink.WithVolume(80), disgolink.WithPaused(false)) ``` -------------------------------- ### Building a player update with lavalink.PlayerUpdate Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/lavalink/README.md Constructs a player update with a track, volume, pause, and no-replace flag. Prefer the disgolink.With* builder functions for this purpose. ```go update := lavalink.PlayerUpdate{ Track: &lavalink.PlayerUpdateTrack{Encoded: omit.NewPtr(track.Encoded)}, Volume: &100, Paused: &false, NoReplace: true, } ``` -------------------------------- ### Players type alias Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/lavalink/models-player.md Array alias for Player records, used as the response of GET /v4/sessions/{id}/players. ```go type Players []Player ``` -------------------------------- ### Using NewListenerFunc with AddListeners Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/events.md Creates a listener for PlayerTrackStartEvent and adds it to the client. Only events of that type reach the closure. ```go listener := disgolink.NewListenerFunc(func(event *disgolink.PlayerTrackStartEvent) { // only PlayerTrackStartEvent arrivals reach this closure }) lavalinkClient.AddListeners(listener) ``` -------------------------------- ### Plugin interface Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/plugin.md Base plugin contract: every plugin reports its Name and Version. ```go type Plugin interface { Name() string Version() string } ``` -------------------------------- ### Timestamp Now function and type definition Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/lavalink/duration-timestamp.md Defines the Timestamp type wrapping time.Time and provides Now() to get the current instant. ```go func Now() Timestamp { return Timestamp{ Time: time.Now() } } type Timestamp struct { time.Time } ``` -------------------------------- ### WithNullTrack Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/player-update.md Sets the encoded track to an explicit JSON null, which stops playback. Used by the example's /stop command. ```APIDOC ## WithNullTrack ### Description Sets the encoded track to an explicit JSON null, which stops playback. Used by the example's /stop command. ### Method N/A (Go function) ### Endpoint N/A ### Parameters None ### Request Example ```go err := player.Update(ctx, disgolink.WithNullTrack()) // stop the current track ``` ### Response N/A ``` -------------------------------- ### Player update helpers: default and apply Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/player-update.md Internal helpers used by Player.Update: defaultPlayerUpdate returns an empty update, and playerUpdateApply applies all options in order. ```go func defaultPlayerUpdate() lavalink.PlayerUpdate { return lavalink.PlayerUpdate{} } func playerUpdateApply(u *lavalink.PlayerUpdate, opts []PlayerUpdateOpt) { for _, opt := range opts { opt(u) } } ``` -------------------------------- ### Register a plugin with disgolink.WithPlugins Source: https://github.com/disgoorg/disgolink/blob/v4/README.md Registers a plugin when creating the DisGoLink client. The plugin is passed via `disgolink.WithPlugins`. ```go lavalinkClient := disgolink.New(userID, disgolink.WithPlugins(yourPlugin)) ``` -------------------------------- ### TrackStartEvent Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/lavalink/messages.md Represents a track starting to play. The Player.OnEvent method mirrors the track to the player's current track field. ```APIDOC ## TrackStartEvent ### Description A track began playing. `Player.OnEvent` mirrors `p.Track = &e.Track`. ### Fields - **Track** (Track) - The track that started playing. - **GuildID** (snowflake.ID) - The ID of the guild where the track started. ### Methods - **Op()** (Op) - Returns `OpEvent`. - **Type()** (EventType) - Returns `EventTypeTrackStart`. - **GetGuildID()** (snowflake.ID) - Returns the guild ID. ### Example ```go type TrackStartEvent struct { Track Track `json:"track"` GuildID snowflake.ID `json:"guildId"` } ``` ``` -------------------------------- ### Basic player update with disgolink.WithTrack Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/player.md Updates the player to play the specified track. The Update method is called on the player with the disgolink.WithTrack option. This is the simplest form of updating a player. ```go err := player.Update(ctx, disgolink.WithTrack(*toPlay)) ``` -------------------------------- ### PlayerTrackStartEvent Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/events.md Emitted when a track starts. Contains the track, guild ID, and the affected player. Emitted after player.OnEvent sets player.Track. ```APIDOC ## PlayerTrackStartEvent ### Description Emitted when a track starts. Contains the track, guild ID, and the affected player. Emitted after player.OnEvent sets player.Track. ### Type ```go type PlayerTrackStartEvent struct { *GenericEvent lavalink.TrackStartEvent Player *Player } ``` ### Fields - **Track** (lavalink.Track) - The track that started. - **GuildID** (snowflake.ID) - The guild ID of the player. - **Player** (*Player) - The affected player. ``` -------------------------------- ### Version Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/rest-client.md Retrieves the Lavalink node version. Sends a GET request to /version and returns the raw response body as a string. ```APIDOC ## GET /version ### Description Retrieves the Lavalink node version. ### Method GET ### Endpoint /version ### Response #### Success Response (200) - **body** (string) - The raw response body containing the version. #### Response Example "v4.0.0" ``` -------------------------------- ### Connect to a voice channel with DisGo or DiscordGo Source: https://github.com/disgoorg/disgolink/blob/v4/README.md Connect to a voice channel using DisGo or DiscordGo. The method differs per library. ```go // DisGo err := client.UpdateVoiceState(context.TODO(), guildID, channelID, false, false) // DiscordGo err := session.ChannelVoiceJoinManual(guildID, channelID, false, false) ``` -------------------------------- ### DecodeTrack method signature Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/rest-client.md Signature for the DecodeTrack method. It returns a lavalink.Track from GET /v4/decodetrack?track={url-escaped encoded track}. ```go func (c *RestClient) DecodeTrack(ctx context.Context, encodedTrack string) (track *lavalink.Track, err error) ``` -------------------------------- ### GET /v4/decodetrack?track={encoded} Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/endpoints.md Decodes a single encoded track into a human-readable track object. The encoded track is URL-escaped before being sent. ```APIDOC ## GET /v4/decodetrack?track={encoded} ### Description Decodes a single encoded track into a human-readable track object. The encoded track is URL-escaped before being sent. ### Method GET ### Endpoint /v4/decodetrack?track={encoded} ### Parameters #### Query Parameters - **track** (string) - Required - The encoded track to decode. Must be URL-escaped. ### Response #### Success Response (200) - **lavalink.Track** (object) - The decoded track information. #### Response Example ```json { "encoded": "...", "info": { "title": "...", "author": "...", "length": 0, "identifier": "...", "isStream": false, "uri": "...", "artworkUrl": "...", "isrc": "..." }, "pluginInfo": {} } ``` ``` -------------------------------- ### WithVolume Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/player-update.md Sets the player volume on a 0-1000 scale. ```APIDOC ## WithVolume ### Description Sets the player volume on a 0-1000 scale. ### Method N/A (Go function) ### Endpoint N/A ### Parameters #### Function Parameters - **volume** (int) - Required - The volume level, from 0 to 1000. ### Request Example ```go player.Update(ctx, disgolink.WithVolume(100)) ``` ### Response N/A ``` -------------------------------- ### Player method signature Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/rest-client.md Signature for the Player method. It returns a single lavalink.Player for a guild from GET /v4/sessions/{sessionId}/players/{guildId}. ```go func (c *RestClient) Player(ctx context.Context, guildID snowflake.ID) (player *lavalink.Player, err error) ``` -------------------------------- ### Seeking with duration math using lavalink.Duration Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/lavalink/README.md Computes a duration of 90 seconds and prints its minutes and seconds parts. Outputs '1 30'. ```go position := lavalink.Duration(90) * lavalink.Second fmt.Println(position.Minutes(), position.SecondsPart()) // 1 30 ``` -------------------------------- ### Decode an Encoded Track Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/lavalink/models-media.md Decodes an encoded track using the DecodeTrack method and prints its title, author, and length. This example does not play the track. ```go track, err := node.Rest.DecodeTrack(ctx, someTrack.Encoded) fmt.Println(track.Info.Title, track.Info.Author, track.Info.Length) ``` -------------------------------- ### PluginEventHandler interface Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/plugin.md Lifecycle hooks for node open/close and player create/destroy. ```go type PluginEventHandler interface { OnNodeOpen(node *Node) OnNodeClose(node *Node) OnNewPlayer(player *Player) OnDestroyPlayer(player *Player) } ``` -------------------------------- ### AddNode Source: https://github.com/disgoorg/disgolink/blob/v4/_autodocs/api-reference/client.md Creates a node from the given config, registers it, and blocks until the node connects. ```APIDOC ## AddNode ### Description Creates a node from the given config, registers it under `config.Name`, and blocks until the node connects. See Node.Open for retry/backoff behavior. ### Method Method ### Signature `func (c *Client) AddNode(ctx context.Context, config NodeConfig) (*Node, error)` ### Parameters - **ctx** (context.Context) - Required - Cancellation context for the connect/retry loop. - **config** (NodeConfig) - Required - Node connection settings; see NodeConfig. ### Returns - **\*Node** - The connected node. - **error** - An error if the node could not be added. ### Errors - **ErrNodeAlreadyExists** - A node with the same `config.Name` is already registered. - **fmt.Errorf("failed to open node %s: %w", ...)** - `Node.Open` failed, wrapping the underlying connect error. ### Example ```go node, err := lavalinkClient.AddNode(ctx, disgolink.NodeConfig{ Name: "test", Address: "localhost:2333", Password: "youshallnotpass", Secure: false, }) if err != nil { /* handle */ } ``` ```