waterlink

package module
v2.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2022 License: MIT Imports: 20 Imported by: 8

README


📖 Table of Contents


📚 Introduction

Waterlink is a Lavalink API wrapper written in Go.


📦 Installation

go get -u github.com/lukasl-dev/waterlink/v2

🍀 Getting started

For the further guides, a Lavalink instance is used, which uses the following application.yml configuration:

server:
  port: 2333
  address: 0.0.0.0
lavalink:
  server:
    password: "youshallnotpass"

Creating a client
creds := waterlink.Credentials{
  Authorization: "youshallnotpass",
}

client, err := waterlink.NewClient("http://localhost:2333", creds)
Loading tracks
res, err := client.LoadTracks(query.Of("https://www.youtube.com/watch?v=dQw4w9WgXcQ"))
res, err := client.LoadTracks(query.YouTube("Never Gonna Give You Up"))
res, err := client.LoadTracks(query.SoundCloud("Never Gonna Give You Up"))
Decoding a single track
info, err := client.DecodeTrack(
  "QAAAoQIAPFJpY2sgQXN0bGV5IC0gTmV2ZXIgR29ubmEgR2l2ZSBZb3UgVXAgKE9mZmljaWFsIE11c2ljIFZpZGVvKQALUmljayBBc3RsZXkAAAAAAANACAALZFF3NHc5V2dYY1EAAQAraHR0cHM6Ly93d3cueW91dHViZS5jb20vd2F0Y2g/dj1kUXc0dzlXZ1hjUQAHeW91dHViZQAAAAAAAAAA",
)
Decoding multiple tracks
tracks, err := client.DecodeTracks([]string{
  "QAAAoQIAPFJpY2sgQXN0bGV5IC0gTmV2ZXIgR29ubmEgR2l2ZSBZb3UgVXAgKE9mZmljaWFsIE11c2ljIFZpZGVvKQALUmljayBBc3RsZXkAAAAAAANACAALZFF3NHc5V2dYY1EAAQAraHR0cHM6Ly93d3cueW91dHViZS5jb20vd2F0Y2g/dj1kUXc0dzlXZ1hjUQAHeW91dHViZQAAAAAAAAAA",
})

Opening a connection

The opts parameter is optional. In this example, it is used to register an EventHandler. If this is not needed, omit it.

creds := waterlink.Credentials{
  Authorization: "youshallnotpass", // password of the Lavalink instance
  UserID:        0,                 // id of the bot user
}

opts := waterlink.ConnectionOptions{
  EventHandler: waterlink.EventHandlerFunc(func(evt interface{}) {
    fmt.Printf("%s received\n", reflect.TypeOf(evt))
  }),
}

conn, err := waterlink.Open("ws://localhost:2333", creds, opts)

To restore a past session, its resume key can be defined in the credentials.

See Configuring session resuming

creds := waterlink.Credentials{
  Authorization: "youshallnotpass", // password of the Lavalink instance
  UserID:        0,                 // id of the bot user
  ResumeKey:     "myResumeKey",     // the resume key of the previous session
}
🦷 Configuring session resuming

Configures a resume key with a timeout of 5 minutes.

err := conn.ConfigureResuming("myResumeKey", 5*time.Minute)
❌ Disabling session resuming
err := conn.DisableResuming()
📜 Getting a guild

A guild is necessary to access its audio player. The function does not check whether the bot user is on this guild.

g := conn.Guild(0) // id of the guild to access

A guild can be obtained via its own ID with the use of a connection.

See Getting a guild

Destroying its player
err := g.Destroy()
Updating its voice server

This function is primarily performed inside a 3rd party libraries' event listener.

See Examples

err := g.UpdateVoice("session", "token", "endpoint")
Playing a track

The params parameter is optional. It can be used to specify more information. If this is not needed, omit it.

params := waterlink.PlayParams{
  StartTime: 0,
  EndTime:   0,
  Volume:    0,
  NoReplace: false,
  Pause:     false,
}
err := g.PlayTrack(t, params) // `t` is the preloaded track to play
Stopping the playback
err := g.Stop()
Pausing/Resuming the playback
err := g.SetPaused(true)
Seeking the playback
err := g.Seek(25 * time.Second) // seek to 25 seconds
Updating the volume
err := g.UpdateVolume(25) // 25%

📂 Examples

octave

Octave is a simple music bot written by myself. It uses discordgo as its Discord library.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

Client is used to perform HTTP requests to the server node.

func NewClient

func NewClient(baseURL string, creds Credentials) (*Client, error)

NewClient creates a new client that performs rest actions at the given base url authorized by the given credentials. For instance, a base url can be: "http://localhost:2333".

Example
creds := Credentials{
	Authorization: "youshallnotpass", // passphrase defined in the server's application.yml
}

cl, err := NewClient("http://localhost:2333", creds)
if err != nil {
	log.Fatalln(err)
}

fmt.Printf("Client dispatches actions to %q.", cl.url.String())
Output:

Client dispatches actions to "http://localhost:2333".

func (Client) DecodeTrack

func (c Client) DecodeTrack(trackID string) (res *track.Info, err error)

DecodeTrack decodes the given track ID into track.Info to gain more detailed information about a track.

func (Client) DecodeTracks

func (c Client) DecodeTracks(trackIDs []string) (res []track.Track, err error)

DecodeTracks decodes the given track IDs into an array of track.Info to gain more detailed information about the given preloaded tracks.

func (Client) LoadTracks

func (c Client) LoadTracks(q query.Query) (res *track.LoadResult, err error)

LoadTracks resolves the given query to a track.LoadResult and preloads the resulting tracks.

type Connection

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

Connection is used to receive and dispatch messages from the

func Open

func Open(addr string, creds Credentials, opts ...ConnectionOptions) (*Connection, error)

Open opens a new websocket connection to addr. The given creds are used to authenticate the connection to use the protocol.

Example
creds := Credentials{
	Authorization: "youshallnotpass",  // passphrase defined in the server's application.yml
	UserID:        820112919224124416, // the user ID of the bot user
}

conn, err := Open("ws://localhost:2333", creds)
if err != nil {
	log.Fatalln(err)
}

fmt.Printf("The server is running on version %q.", conn.APIVersion())
Output:

The server is running on version "3".
Example (ListenToEvents)
creds := Credentials{
	Authorization: "youshallnotpass",  // passphrase defined in the server's application.yml
	UserID:        820112919224124416, // the user ID of the bot user
}

events := EventHandlerFunc(func(evt interface{}) {
	switch evt := evt.(type) {
	case event.Stats:
		fmt.Println("Stats received:", evt)
	case event.TrackEnd:
		fmt.Println("Track ended:", evt)
	}
})
opts := ConnectionOptions{EventHandler: events}

conn, err := Open("ws://localhost:2333", creds, opts)
if err != nil {
	log.Fatalln(err)
}

fmt.Printf("The server is running on version %q.", conn.APIVersion())
Output:

The server is running on version "3".
Example (ResumeSession)
creds := Credentials{
	Authorization: "youshallnotpass",  // passphrase defined in the server's application.yml
	UserID:        820112919224124416, // the user ID of the bot user
	ResumeKey:     "myResumeKey",      // the former configured resume key
}

conn, err := Open("ws://localhost:2333", creds)
if err != nil {
	log.Fatalln(err)
}

fmt.Printf("The server is running on version %q.", conn.APIVersion())
Output:

The server is running on version "3".

func (*Connection) APIVersion

func (conn *Connection) APIVersion() string

APIVersion returns the server's API version that was acquired during the handshake.

func (*Connection) Close

func (conn *Connection) Close() error

Close closes the underlying websocket connection.

func (*Connection) Closed

func (conn *Connection) Closed() bool

Closed returns whether the connection has been closed.

func (*Connection) ConfigureResuming

func (conn *Connection) ConfigureResuming(key string, timeout time.Duration) error

ConfigureResuming enable the resumption of the session and defines the number of seconds after which the session will be considered expired server-side. This is useful to avoid stopping the audio players that are related to the session.

Example
var conn Connection // TODO: open connection

err := conn.ConfigureResuming("myResumeKey", 1*time.Minute)
if err != nil {
	log.Fatalln(err)
}
Output:

func (*Connection) DisableResuming

func (conn *Connection) DisableResuming() error

DisableResuming disables the resumption of the session. If disabled, audio players will stop immediately after the connection is closed.

func (*Connection) Guild

func (conn *Connection) Guild(id snowflake.Snowflake) Guild

Guild returns a Guild used to interact with a specific guild. The availability is not checked client-side.

func (*Connection) SessionResumed

func (conn *Connection) SessionResumed() bool

SessionResumed returns true whether a previous session has been resumed.

type ConnectionOptions

type ConnectionOptions struct {
	// EventHandler is the EventHandler to handle incoming events. If nil, the
	// connection will not listen for incoming events.
	EventHandler EventHandler `json:"eventHandler,omitempty"`

	// HandleEventError is the function to be called when an error occurs while
	// listening for incoming events.
	HandleEventError func(err error)
}

ConnectionOptions contains optional values of a Connection.

type Credentials

type Credentials struct {
	// Authorization is the password matching the server configuration. This
	// is required for the initial handshake.
	Authorization string `json:"authorization,omitempty"`

	// UserID is the user ID of the bot to play music with. This is required
	// to play audio.
	UserID snowflake.Snowflake `json:"userId,omitempty"`

	// ResumeKey is the key of the session you want to resume. If it is empty,
	// a new session will be created.
	ResumeKey string `json:"resumeKey,omitempty"`
}

Credentials is a struct that holds the necessary information to communicate with the server.

type EventHandler

type EventHandler interface {
	// HandleEvent handles the incoming event. The following events are available:
	//    - event.PlayerUpdate
	//    - event.Stats
	//    - event.TrackEnd
	//    - event.TrackException
	//    - event.TrackStart
	//    - event.TrackStuck
	//    - event.WebSocketClosed
	HandleEvent(evt interface{})
}

EventHandler is an interface that is responsible for handling incoming events provided by the server.

type EventHandlerFunc

type EventHandlerFunc func(evt interface{})

EventHandlerFunc is a function that implements the EventHandler interface.

func (EventHandlerFunc) HandleEvent

func (fn EventHandlerFunc) HandleEvent(evt interface{})

HandleEvent calls itself using the provided event.

type Guild

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

Guild is a struct that is used to send guild-scoped messages via the Connection.

func (Guild) Destroy

func (g Guild) Destroy() error

Destroy destroys the server-side audio player instance.

func (Guild) Filters added in v2.0.1

func (g Guild) Filters(filters filter.Filters) error

Filters sets the filter of the current playback.

func (Guild) Play

func (g Guild) Play(trackID string, params ...PlayParams) error

Play plays the preloaded audio track whose id is given via the guild's audio player. If no params should be given, the defaultPlayParams are used.

func (Guild) PlayTrack

func (g Guild) PlayTrack(tr track.Track, params ...PlayParams) error

PlayTrack plays the given audio track. If no params should be given, the defaultPlayParams are used.

func (Guild) Seek

func (g Guild) Seek(position time.Duration) error

Seek seeks the current playing audio track to a specific position.

func (Guild) SetPaused

func (g Guild) SetPaused(paused bool) error

SetPaused pauses or resumes the audio playback of the guild's audio player.

func (Guild) Stop

func (g Guild) Stop() error

Stop stops the audio playback of the guild's audio player.

func (Guild) UpdateVoice

func (g Guild) UpdateVoice(session string, token, endpoint string) error

UpdateVoice provides an intercepted voice server update event to the server. This causes the server to connect to a voice channel.

func (Guild) UpdateVolume

func (g Guild) UpdateVolume(volume uint16) error

UpdateVolume updates the volume of the guild's audio player. The value must be between 0 and 1000. Defaults to 100.

type PlayParams

type PlayParams struct {
	// StartTime is the time in milliseconds to start playing the track at.
	StartTime time.Duration `json:"startTime,omitempty"`

	// EndTime is the time in milliseconds to end playing the track at.
	EndTime time.Duration `json:"endTime,omitempty"`

	// Volume is the new volume of the player. The value must be between 0 and
	// 1000. Defaults to 100.
	Volume uint8 `json:"volume,omitempty"`

	// NoReplace is the optional flag to not replace the current track.
	NoReplace bool `json:"noReplace,omitempty"`

	// Pause is the optional flag to pause the playback.
	Pause bool `json:"pause,omitempty"`
}

PlayParams contains optional parameters of the Guild.Play() method.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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