cord

package module
v0.0.0-...-99e091e Latest Latest
Warning

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

Go to latest
Published: May 29, 2016 License: MIT Imports: 18 Imported by: 1

README

cord Build Status godoc reference

Experimental websocket client for Discord gateways. It parses events and handles gateway retrieval and reconnections transparently.

Example

package main

import (
    "fmt"
    "os"

    "github.com/WatchBeam/cord"
    "github.com/WatchBeam/cord/events"
    "github.com/WatchBeam/cord/model"
)

func main() {
    c := cord.New(os.Args[1], nil)

    c.On(events.Ready(func(r *model.Ready) {
        fmt.Printf("%+v\n", r)
    }))

    c.On(events.PresenceUpdate(func(r *model.PresenceUpdate) {
        fmt.Printf("%+v\n", r)
    }))

    for err := range c.Errs() {
        fmt.Printf("Got an error: %s", err)

        if _, isFatal := err.(cord.FatalError); isFatal {
            os.Exit(1)
        }
    }
}

Development

JSON and the event handlers are auto-generated by the Makefile. Running make will ensure the generations are up-to-date and run all tests.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Debugger

type Debugger interface {
	// Incoming is called with the raw packet string sent to cord, after
	// inflation for gzipped strings.
	Incoming(b []byte)

	// Outgoing is called with data when a packet is sent on cord.
	Outgoing(b []byte)

	// Called when the websocket tries to connect to a server.
	Connecting(endpoint string)

	// Error is called when an error occurs on the socket. The error
	// is ALSO sent down the Errs() channel for your
	Error(error)
}

A Debugger can be passed into the options to be notified of all socket sends and receives.

type DisruptionError

type DisruptionError struct{ Cause error }

A DisruptionError is sent when an error happens which causes the server to try to reconnect to the websocket.

func (DisruptionError) Error

func (d DisruptionError) Error() string

Error implements error.Error

type FatalError

type FatalError struct{ Cause error }

A FatalError is sent when an error happens that the websocket cannot recover from.

func (FatalError) Error

func (d FatalError) Error() string

Error implements error.Error

type GatewayRetriever

type GatewayRetriever interface {
	// Gateway returns the gateway URL to connect to.
	Gateway() (url string, err error)
}

GatewayRetriever calls the Discord API and returns the socket URL to connect to.

type HTTPGatewayRetriever

type HTTPGatewayRetriever struct {
	Client  *http.Client
	BaseURL string
}

HTTPGatewayRetriever is an implementation of the GatewayRetriever that looks up the gateway from Discord's REST API.

func (HTTPGatewayRetriever) Gateway

func (h HTTPGatewayRetriever) Gateway() (string, error)

Gateway implements GatewayRetriever.Gateway

type Operation

type Operation uint8

An Operation is contained in a Payload and defines what should occur as a result of that payload.

const (
	// Dispatch is an operation used to dispatch  an event
	Dispatch Operation = iota
	// Heartbeat is an operation used for ping checking
	Heartbeat
	// Identify is an operation used for client handshake
	Identify
	// StatusUpdate is an operation used to update the client status
	StatusUpdate
	// VoiceStatusUpdate is an operation used to join/move/leave voice channels
	VoiceStatusUpdate
	// VoiceServerPing is an operation used for voice ping checking
	VoiceServerPing
	// Resume is an operation used to resume a closed connection
	Resume
	// Reconnect is an operation used to redirect clients to a new gateway
	Reconnect
	// RequestMembers is an operation used to request guild members
	RequestMembers
	// InvalidSession is an operation used to notify
	// client they have an invalid session id
	InvalidSession
)

type Payload

type Payload struct {
	Operation Operation       `json:"op"`
	Data      json.RawMessage `json:"d"`
	// Provided only for Dispatch operations:
	Sequence uint64 `json:"s"`
	Event    string `json:"t"`
}

A Payload structure is the basic structure in which information is sent to and from the Discord gateway.

func (Payload) MarshalEasyJSON

func (v Payload) MarshalEasyJSON(w *jwriter.Writer)

func (Payload) MarshalJSON

func (v Payload) MarshalJSON() ([]byte, error)

func (*Payload) UnmarshalEasyJSON

func (v *Payload) UnmarshalEasyJSON(l *jlexer.Lexer)

func (*Payload) UnmarshalJSON

func (v *Payload) UnmarshalJSON(data []byte) error

type Socket

type Socket interface {
	// Send dispatches an event down the Discord socket. It returns an error
	// if there was any issue in sending it.
	Send(op Operation, data json.Marshaler) error

	// On attaches a handler to an event.
	On(h events.Handler)

	// On attaches a handler that's called once when an event happens.
	Once(h events.Handler)

	// Off detaches a previously-attached handler from an event.
	Off(h events.Handler)

	// Errs returns a channel of errors which may occur asynchronously
	// on the websocket.
	Errs() <-chan error

	// Frees resources associated with the socket.
	Close() error
}

The Socket represents a connection to a Discord server. All methods on the socket are safe for concurrent use.

func New

func New(token string, options *WsOptions) Socket

New creates a connection to the Discord servers. Options may be nil if you want to use the defaults.

type Websocket

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

Websocket is an implementation of the Socket interface.

func (*Websocket) Close

func (w *Websocket) Close() error

Close frees resources associated with the websocket.

func (*Websocket) Errs

func (w *Websocket) Errs() <-chan error

Errs implements Socket.Errs

func (*Websocket) Off

func (w *Websocket) Off(h events.Handler)

Off implements Socket.Off

func (*Websocket) On

func (w *Websocket) On(h events.Handler)

On implements Socket.On

func (*Websocket) Once

func (w *Websocket) Once(h events.Handler)

Once implements Socket.Once

func (*Websocket) Send

func (w *Websocket) Send(op Operation, data json.Marshaler) error

Send implements Socket.Send

type WsOptions

type WsOptions struct {
	// Handshake packet to send to the server. Note that `compress` and
	// `properties` will be filled for you.
	Handshake *model.Handshake

	// How long to wait without frames or acknowledgment before we consider
	// the server to be dead. Defaults to ten seconds.
	Timeout time.Duration

	// Backoff determines how long to wait between reconnections to the
	// websocket server. Defaults to an exponential backoff.
	Backoff backoff.BackOff

	// Dialer to use for the websocket. Defaults to a dialer with the
	// `timeout` duration.
	Dialer *websocket.Dialer

	// The retriever to get the gateway to connect to. Defaults to the
	// HTTPGatewayRetriever with the given `timeout`.
	Gateway GatewayRetriever

	// Debugger struct we log incoming/outgoing messages to.
	Debugger Debugger

	// Headers to send in the websocket handshake.
	Header http.Header
}

WsOptions is passed to New() to configure the websocket setup.

Directories

Path Synopsis
cmd
AUTOGENERATED FILE, DO NOT EDIT
AUTOGENERATED FILE, DO NOT EDIT
example

Jump to

Keyboard shortcuts

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