discord

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2018 License: MIT Imports: 35 Imported by: 0

README

GoDoc License MIT Discord Build Status

Discord

An unofficial client for the Discord API written in Go.

Although this package is usable, it still is under active development so please don't use it for anything other than experiments, yet.

Contents :

Installation

Make sure you have a working Go installation, if not see this page first.

Then, install this package with the go get command :

go get -u github.com/skwair/discord

Note that go get -u will always pull the latest version from the master branch before Go 1.11. With newer versions and Go modules enabled, the latest minor or patch release will be downloaded. go get github.com/skwair/discord@major.minor.patch can be used to download a specific version. See Go modules for more information.

Usage

package main

import (
	"fmt"
	"log"

	"github.com/skwair/discord"
)

func main() {
    c, err := discord.NewClient(discord.WithBotToken("your.bot.token"))
    if err != nil {
        log.Fatal(err)
    }

    // Get information about the current user.
    u, err := c.CurrentUser().Get()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(u)
}

For information about how to create bots and more examples on how to use this package, check out the examples directory.

How does it compare to DiscordGo ?

DiscordGo offers some additional features right now, such as a way to create and manage your Discord applications. The majority of features though, such a receiving events, sending messages, receiving and sending voice data, etc. are also implemented in this library.

The main difference resides in the Gateway (websocket) real time API implementation. This library takes a different approach (using more synchronisation mechanisms) to avoid having to rely on hacks like this or this, hopefully providing a more robust implementation as well as a better user experience.

Another difference is in the "event handler" mechanism. Instead of having a single method that takes an interface{} as a parameter and guesses for which event you registered a handler based on its concrete type, this library provides one method per event type, making it clear what signature your handler must have and ensuring it at compile time, not at runtime.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Original logo by Renee French, dressed with the cool t-shirt by @HlneChd.

Documentation

Overview

Package discord provides an interface to the Discord API (https://discordapp.com/developers/docs/intro).

Getting started

The first thing you do is to create a Client. For a normal user, you can get one like this:

c := discord.NewClient(discord.WithToken("userToken"))

If you want to create a client for a bot, use WithBotToken instead of WithToken, without prefixing the token with "Bot :":

c := discord.NewClient(discord.WithBotToken("botToken"))

You can pass more configuration parameters to NewClient. Review the documentation of NewClient for more information.

With this client, you can start interacting with the Discord API, but some methods (such as event handlers) won't be available until you connect to the Gateway:

if err = c.Connect(); err != nil {
	// Handle error
}
defer c.Disconnect() // Gracefully disconnect

Once connected to the Gateway, you have full access to the Discord API.

Using the HTTP API

Discord's HTTP API is organized by resource:

  • Guild
  • Channel
  • CurrentUser
  • Webhook
  • Invite

Each resource has its own method on the Client to interact with. For example, to send a message to a channel:

msg, err := c.Channel("channel-id").SendMessage("content of the message")
if err != nil {
	// Handle error
}
// msg is the message sent

Registering event handlers

To receive messages, use the HandleMessageCreate method and give it your handler. It will be called each time a message is sent to a channel your bot is in with the message as a parameter.

c.HandleMessageCreate(func(msg *discord.Message) {
	fmt.Println(msg.Content)
})

To register handlers for other types of events, see Client.Handle* methods.

Using the state

When connecting to Discord, a session state is created with initial data sent by Discord's Gateway. As events are received by the client, this state is constantly updated so it always have the newest data available.

This session state acts as a cache to avoid making requests over the HTTP API each time. If you need to get information about the current user :

user := c.State.CurrentUser()

Because this state might become memory hungry for bots that are in a very large number of servers, it can be disabled with the WithStateTracking option while creating the Discord client.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrGatewayNotConnected is returned when the client is not connected to the Gateway.
	ErrGatewayNotConnected = errors.New("gateway is not connected")
	// ErrNoFileProvided is returned by SendFiles when no files are provided.
	ErrNoFileProvided = errors.New("no file provided")
)
View Source
var (
	// ErrAlreadyConnected is returned by Connect when a connection to the Gateway already exists.
	ErrAlreadyConnected = errors.New("already connected to the Gateway")
)
View Source
var (
	// ErrNoTokenProvided is returned by NewClient when neither a user token nor a bot token is provided.
	ErrNoTokenProvided = errors.New("no token provided, use WithToken or WithBotToken when creating a new client")
)

Functions

func CreationTimeOf

func CreationTimeOf(id string) (time.Time, error)

CreationTimeOf returns the creation time of the given Discord ID (userID, guildID, channelID). For more information, see : https://discordapp.com/developers/docs/reference#snowflakes.

func DeleteWebhookWithToken

func DeleteWebhookWithToken(id, token string) error

DeleteWebhookWithToken is like DeleteWebhook except it does not require authentication.

Types

type APIError

type APIError struct {
	HTTPCode int    `json:"http_code"`
	Code     int    `json:"code"`
	Message  string `json:"message"`
}

APIError is an error returned by the Discord HTTP API.

func (APIError) Error

func (e APIError) Error() string

type Activity

type Activity struct {
	Name string       `json:"name"`
	Type ActivityType `json:"type"`
	// Stream url, is validated when type is Streaming.
	URL string `json:"url,omitempty"`
	// Unix timestamps for start and/or end of the game.
	Timestamps *ActivityTimestamp `json:"timestamps,omitempty"`
	// Application id for the game.
	ApplicationID string `json:"application_id,omitempty"`
	// What the player is currently doing.
	Details string `json:"details,omitempty"`
	// The user's current party status.
	State string `json:"state,omitempty"`
	// Information for the current party of the player.
	Party *ActivityParty `json:"party,omitempty"`
	// Images for the presence and their hover texts.
	Assets *ActivityAssets `json:"assets,omitempty"`
}

Activity represents a user activity (playing a game, streaming, etc.).

type ActivityAssets

type ActivityAssets struct {
	LargeImage string `json:"large_image,omitempty"`
	LargeText  string `json:"large_text,omitempty"`
	SmallImage string `json:"small_image,omitempty"`
	SmallText  string `json:"small_text,omitempty"`
}

ActivityAssets contains images for the presence and their hover texts.

type ActivityParty

type ActivityParty struct {
	ID   string `json:"id,omitempty"`
	Size []int  `json:"size,omitempty"` // Array of two integers (current_size, max_size).
}

ActivityParty contains information for the current party of the player.

type ActivityTimestamp

type ActivityTimestamp struct {
	Start int `json:"start,omitempty"`
	End   int `json:"end,omitempty"`
}

ActivityTimestamp is the unix time (in milliseconds) of when the activity starts and ends.

type ActivityType

type ActivityType int

ActivityType describes what the user is doing.

const (
	// ActivityPlaying will display "Playing {name}".
	ActivityPlaying ActivityType = iota
	// ActivityStreaming will display "Streaming {name}".
	ActivityStreaming
	// ActivityListening will display "Listening to {name}".
	ActivityListening
)

type Attachment

type Attachment struct {
	ID       string `json:"id"`
	Filename string `json:"filename"`
	Size     int    `json:"size"`
	URL      string `json:"url"`
	ProxyURL string `json:"proxy_url"`
	Height   int    `json:"height"`
	Width    int    `json:"width"`
}

Attachment is file attached to a message.

type AudioPacket

type AudioPacket struct {
	Type      uint8
	Version   uint8
	Sequence  uint16
	Timestamp uint32
	SSRC      uint32
	Opus      []byte
}

AudioPacket is a parsed and decrypted RTP frame containing Opus encoded audio.

type Ban

type Ban struct {
	Reason string
	User   *User
}

Ban represents a Guild ban.

type Channel

type Channel struct {
	ID                   string                 `json:"id,omitempty"`
	Type                 channel.Type           `json:"type,omitempty"`
	GuildID              string                 `json:"guild_id,omitempty"`
	Position             int                    `json:"position,omitempty"` // Sorting position of the channel.
	PermissionOverwrites []permission.Overwrite `json:"permission_overwrites,omitempty"`
	Name                 string                 `json:"name,omitempty"`
	Topic                string                 `json:"topic,omitempty"`
	NSFW                 bool                   `json:"nsfw,omitempty"`
	LastMessageID        string                 `json:"last_message_id,omitempty"`

	// For voice channels.
	Bitrate   int `json:"bitrate,omitempty"`
	UserLimit int `json:"user_limit,omitempty"`

	// For DMs.
	Recipients    []User `json:"recipients,omitempty"`
	Icon          string `json:"icon,omitempty"`
	OwnerID       string `json:"owner_id,omitempty"`
	ApplicationID string `json:"application_id,omitempty"` // Application id of the group DM creator if it is bot-created.

	ParentID         string    `json:"parent_id,omitempty"` // ID of the parent category for a channel.
	LastPinTimestamp time.Time `json:"last_pin_timestamp,omitempty"`
}

Channel represents a guild or DM channel within Discord.

func (*Channel) Clone added in v0.3.0

func (c *Channel) Clone() *Channel

Clone returns a clone of this Channel.

type ChannelPinsUpdate

type ChannelPinsUpdate struct {
	ChannelID        string    `json:"channel_id"`
	LastPinTimestamp time.Time `json:"last_pin_timestamp"`
}

ChannelPinsUpdate is Fired when a message is pinned or unpinned in a text channel.

type ChannelPosition

type ChannelPosition struct {
	ID       string `json:"id"`
	Position int    `json:"position"`
}

ChannelPosition is a pair of channel ID with its position.

type ChannelResource added in v0.2.0

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

ChannelResource is a resource that allows to perform various actions on a Discord channel. Create one with Client.Channel.

func (*ChannelResource) AddReaction added in v0.4.0

func (r *ChannelResource) AddReaction(messageID, emoji string) error

AddReaction adds a reaction to a message in the channel. This endpoint requires the 'READ_MESSAGE_HISTORY' permission to be present on the current user. Additionally, if nobody else has reacted to the message using this emoji, this endpoint requires the'ADD_REACTIONS' permission to be present on the current user.

func (*ChannelResource) AddRecipient added in v0.2.0

func (r *ChannelResource) AddRecipient(channelID, recipientID string) error

AddRecipient adds a recipient to the existing Group DM or to a DM channel, creating a new Group DM channel. Groups have a limit of 10 recipients, including the current user.

func (*ChannelResource) Delete added in v0.2.0

func (r *ChannelResource) Delete() (*Channel, error)

Delete deletes the channel, or closes the private message. Requires the 'MANAGE_CHANNELS' permission for the guild. Deleting a category does not delete its child channels; they will have their parent_id removed and a Channel Update Gateway event will fire for each of them. Returns the deleted channel on success. Fires a Channel Delete Gateway event.

func (*ChannelResource) DeleteMessage added in v0.2.0

func (r *ChannelResource) DeleteMessage(messageID string) error

DeleteMessage deletes a message. If operating on a guild channel and trying to delete a message that was not sent by the current user, this endpoint requires the 'MANAGE_MESSAGES' permission. Fires a Message Delete Gateway event.

func (*ChannelResource) DeleteMessageBulk added in v0.2.0

func (r *ChannelResource) DeleteMessageBulk(messageIDs []string) error

DeleteMessageBulk deletes multiple messages in a single request. This endpoint can only be used on guild channels and requires the 'MANAGE_MESSAGES' permission. Fires multiple Message Delete Gateway events. Any message IDs given that do not exist or are invalid will count towards the minimum and maximum message count (currently 2 and 100 respectively). Additionally, duplicated IDs will only be counted once.

func (*ChannelResource) DeletePermission added in v0.2.0

func (r *ChannelResource) DeletePermission(channelID, targetID string) error

DeletePermission deletes the channel permission overwrite for a user or role in a channel. Only usable for guild channels. Requires the 'MANAGE_ROLES' permission.

func (*ChannelResource) EditEmbed added in v0.2.0

func (r *ChannelResource) EditEmbed(messageID, content string, embed *embed.Embed) (*Message, error)

EditEmbed is like EditMessage but with embedded content support.

func (*ChannelResource) EditMessage added in v0.2.0

func (r *ChannelResource) EditMessage(messageID, content string) (*Message, error)

EditMessage edits a previously sent message. You can only edit messages that have been sent by the current user. Fires a Message Update Gateway event. See EditEmbed if you need to edit some emended content.

func (*ChannelResource) Get added in v0.2.0

func (r *ChannelResource) Get() (*Channel, error)

Get returns the channel.

func (*ChannelResource) GetReactions added in v0.2.0

func (r *ChannelResource) GetReactions(messageID, emoji string, limit int, before, after string) ([]User, error)

GetReactions returns a list of users that reacted to a message with the given emoji. limit is the number of users to return and can be set to any value ranging from 1 to 100. If set to 0, it defaults to 25. If more than 100 users reacted with the given emoji, the before and after parameters can be used to fetch more users.

func (*ChannelResource) Invites added in v0.2.0

func (r *ChannelResource) Invites() ([]Invite, error)

Invites returns a list of invites (with invite metadata) for the channel. Only usable for guild channels. Requires the 'MANAGE_CHANNELS' permission.

func (*ChannelResource) Message added in v0.2.0

func (r *ChannelResource) Message(id string) (*Message, error)

Message returns a specific message in the channel. If operating on a guild channel, this endpoints requires the 'READ_MESSAGE_HISTORY' permission to be present on the current user.

func (*ChannelResource) Messages added in v0.2.0

func (r *ChannelResource) Messages(query string, limit int) ([]Message, error)

Messages returns messages in the channel. If operating on a guild channel, this endpoint requires the 'VIEW_CHANNEL' permission to be present on the current user. If the current user is missing the 'READ_MESSAGE_HISTORY' permission in the channel then this will return no messages (since they cannot read the message history). The query parameter is a message ID prefixed with one of the following character :

  • '>' for fetching messages after
  • '<' for fetching messages before
  • '~' for fetching messages around

For example, to retrieve 50 messages around (25 before, 25 after) a message having the ID 221588207995121520, set query to "~221588207995121520". Limit is a positive integer between 1 and 100 that default to 50 if set to 0.

func (*ChannelResource) Modify added in v0.2.0

func (r *ChannelResource) Modify(settings *channel.Settings) (*Channel, error)

Modify updates the channel's settings. Requires the 'MANAGE_CHANNELS' permission for the guild. Fires a Channel Update Gateway event. If modifying category, individual Channel Update events will fire for each child channel that also changes.

func (*ChannelResource) NewInvite added in v0.2.0

func (r *ChannelResource) NewInvite(maxAge, maxUses int, temporary, unique bool) (*Invite, error)

NewInvite creates a new invite for the channel. Only usable for guild channels. Requires the CREATE_INSTANT_INVITE permission.

func (*ChannelResource) NewWebhook added in v0.2.0

func (r *ChannelResource) NewWebhook(name, avatar string) (*Webhook, error)

NewWebhook creates a new webhook for the channel. Requires the 'MANAGE_WEBHOOKS' permission. name must contain between 2 and 32 characters. avatar is an avatar data string, see https://discordapp.com/developers/docs/resources/user#avatar-data for more info. It can be left empty to have the default avatar.

func (*ChannelResource) PinMessage added in v0.2.0

func (r *ChannelResource) PinMessage(id string) error

PinMessage pins a message in the channel. Requires the 'MANAGE_MESSAGES' permission.

func (*ChannelResource) Pins added in v0.2.0

func (r *ChannelResource) Pins() ([]Message, error)

Pins returns all pinned messages in the channel as an array of messages.

func (*ChannelResource) RemoveAllReactions added in v0.4.0

func (r *ChannelResource) RemoveAllReactions(messageID string) error

RemoveAllReactions removes all reactions on a message. This endpoint requires the 'MANAGE_MESSAGES' permission to be present on the current user.

func (*ChannelResource) RemoveReaction added in v0.4.0

func (r *ChannelResource) RemoveReaction(messageID, emoji string) error

RemoveReaction removes a reaction the current user has made for the message.

func (*ChannelResource) RemoveRecipient added in v0.2.0

func (r *ChannelResource) RemoveRecipient(recipientID string) error

RemoveRecipient removes a recipient from the Group DM.

func (*ChannelResource) RemoveUserReaction added in v0.4.0

func (r *ChannelResource) RemoveUserReaction(messageID, userID, emoji string) error

RemoveUserReaction removes another user's reaction. This endpoint requires the 'MANAGE_MESSAGES' permission to be present on the current user.

func (*ChannelResource) SendEmbed added in v0.2.0

func (r *ChannelResource) SendEmbed(embed *embed.Embed) (*Message, error)

SendEmbed is like SendEmbedWithOptions with no text, an empty nonce and text to speech disabled.

func (*ChannelResource) SendEmbedWithOptions added in v0.2.0

func (r *ChannelResource) SendEmbedWithOptions(embed *embed.Embed, text, nonce string, tts bool) (*Message, error)

SendEmbedWithOptions sends some embedded rich content attached to a message to the channel. See SendMessageWithOptions for required permissions and the embed sub package for more information about embeds.

func (*ChannelResource) SendFiles added in v0.2.0

func (r *ChannelResource) SendFiles(files ...File) (*Message, error)

SendFiles is like SendFilesWithOptions with no text, an empty nonce, no embed and text to speech disabled.

func (*ChannelResource) SendFilesWithOptions added in v0.2.0

func (r *ChannelResource) SendFilesWithOptions(text, nonce string, embed *embed.Embed, tts bool, files ...File) (*Message, error)

SendFilesWithOptions sends some attached files with an optional text and/or embedded rich content to the channel. See SendMessageWithOptions for required permissions and the embed sub package for more information about embeds.

func (*ChannelResource) SendMessage added in v0.2.0

func (r *ChannelResource) SendMessage(text string) (*Message, error)

SendMessage is like SendMessageWithOptions with an empty nonce and text to speech disabled.

func (*ChannelResource) SendMessageWithOptions added in v0.2.0

func (r *ChannelResource) SendMessageWithOptions(text, nonce string, tts bool) (*Message, error)

SendMessageWithOptions posts a message to the channel. If operating on a guild channel, this endpoint requires the 'SEND_MESSAGES' permission to be present on the current user. If the tts field is set to true, the 'SEND_TTS_MESSAGES' permission is required for the message to be spoken. Returns the message sent. Fires a Message Create Gateway event. Before using this endpoint, you must connect to the gateway at least once. The nonce will be returned in the result and also transmitted to other clients. You can set it to empty if you do not need this feature.

func (*ChannelResource) TriggerTyping added in v0.2.0

func (r *ChannelResource) TriggerTyping() error

TriggerTyping triggers a typing indicator for the channel. Generally bots should not implement this route. However, if a bot is responding to a command and expects the computation to take a few seconds, this endpoint may be called to let the user know that the bot is processing their message. Fires a Typing Start Gateway event.

func (*ChannelResource) UnpinMessage added in v0.2.0

func (r *ChannelResource) UnpinMessage(id string) error

UnpinMessage deletes a pinned message in the channel. Requires the 'MANAGE_MESSAGES' permission.

func (*ChannelResource) UpdatePermissions added in v0.2.0

func (r *ChannelResource) UpdatePermissions(targetID string, allow, deny int, typ string) error

UpdatePermissions updates the channel permission overwrites for a user or role in the channel. typ is "member" if targetID is a user or "role" if it is a role. If the channel permission overwrites do not not exist, they are created. Only usable for guild channels. Requires the 'MANAGE_ROLES' permission.

func (*ChannelResource) Webhooks added in v0.2.0

func (r *ChannelResource) Webhooks() ([]Webhook, error)

Webhooks returns webhooks for the channel.

type Client

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

Client is used to communicate with Discord's API. To start receiving events from the Gateway with a Client, you first need to call its Connect method.

func NewClient

func NewClient(opts ...ClientOption) (*Client, error)

NewClient creates a new client to work with Discord's API. It is meant to be long lived and shared across your application.

func (*Client) Channel added in v0.2.0

func (c *Client) Channel(id string) *ChannelResource

Channel returns a new channel resource to manage the channel with the given ID.

func (*Client) Connect

func (c *Client) Connect() error

Connect connects and identifies the client to the Discord gateway.

func (*Client) ConnectToVoice

func (c *Client) ConnectToVoice(guildID, channelID string, opts ...VoiceConnectionOption) (*VoiceConnection, error)

ConnectToVoice will create a new VoiceConnection to the specified guild/channel. This method is safe to call from multiple goroutines, but connections will happen sequentially.

func (*Client) CreateGuild

func (c *Client) CreateGuild(name string) (*Guild, error)

CreateGuild creates a new guild with the given name. Returns the created guild on success. Fires a Guild Create Gateway event.

func (*Client) CurrentUser added in v0.2.0

func (c *Client) CurrentUser() *CurrentUserResource

CurrentUser returns a new resource to manage the current user.

func (*Client) Disconnect

func (c *Client) Disconnect()

Disconnect closes the connection to the Discord Gateway.

func (*Client) Gateway

func (c *Client) Gateway() (string, error)

Gateway returns a valid WSS URL, which the client can use for connecting.

func (*Client) GatewayBot

func (c *Client) GatewayBot() (string, int, error)

GatewayBot returns a valid WSS URL and the recommended number of shards to connect with.

func (*Client) GetUser

func (c *Client) GetUser(id string) (*User, error)

GetUser returns a user given its ID. Use "@me" as the ID to fetch information about the connected user. For every other IDs, this endpoint can only be used by bots.

func (*Client) GetVoiceRegions

func (c *Client) GetVoiceRegions(guildID string) ([]VoiceRegion, error)

GetVoiceRegions returns a list of available voice regions that can be used when creating servers.

func (*Client) Guild added in v0.2.0

func (c *Client) Guild(id string) *GuildResource

Guild returns a new guild resource to manage the guild with the given ID.

func (*Client) HandleChannelCreate

func (c *Client) HandleChannelCreate(f func(c *Channel))

HandleChannelCreate registers the handler function for the "CHANNEL_CREATE" event. This event is fired when a new channel is created, relevant to the current user.

func (*Client) HandleChannelDelete

func (c *Client) HandleChannelDelete(f func(c *Channel))

HandleChannelDelete registers the handler function for the "CHANNEL_DELETE" event. This event is fired when a channel is deleted, relevant to the current user.

func (*Client) HandleChannelPinsUpdate

func (c *Client) HandleChannelPinsUpdate(f func(cpu *ChannelPinsUpdate))

HandleChannelPinsUpdate registers the handler function for the "CHANNEL_PINS_UPDATE" event. This event is fired when a message is pinned or unpinned, but not when a pinned message is deleted.

func (*Client) HandleChannelUpdate

func (c *Client) HandleChannelUpdate(f func(c *Channel))

HandleChannelUpdate registers the handler function for the "CHANNEL_UPDATE" event. This event is fired when a channel is updated, relevant to the current user.

func (*Client) HandleGuildBanAdd

func (c *Client) HandleGuildBanAdd(f func(ban *GuildBan))

HandleGuildBanAdd registers the handler function for the "GUILD_BAN_ADD" event.

func (*Client) HandleGuildBanRemove

func (c *Client) HandleGuildBanRemove(f func(ban *GuildBan))

HandleGuildBanRemove registers the handler function for the "GUILD_BAN_REMOVE" event. This event is fired when a guild is updated.

func (*Client) HandleGuildCreate

func (c *Client) HandleGuildCreate(f func(g *Guild))

HandleGuildCreate registers the handler function for the "GUILD_CREATE" event. This event can be sent in three different scenarios :

  1. When a user is initially connecting, to lazily load and backfill information for all unavailable guilds sent in the Ready event.
  2. When a Guild becomes available again to the client.
  3. When the current user joins a new Guild.

func (*Client) HandleGuildDelete

func (c *Client) HandleGuildDelete(f func(g *UnavailableGuild))

HandleGuildDelete registers the handler function for the "GUILD_DELETE" event. This event is fired when a guild becomes unavailable during a guild outage, or when the user leaves or is removed from a guild. If the unavailable field is not set, the user was removed from the guild.

func (*Client) HandleGuildEmojisUpdate

func (c *Client) HandleGuildEmojisUpdate(f func(emojis *GuildEmojis))

HandleGuildEmojisUpdate registers the handler function for the "GUILD_EMOJIS_UPDATE" event. Fired when a guild's emojis have been updated.

func (*Client) HandleGuildIntegrationsUpdate

func (c *Client) HandleGuildIntegrationsUpdate(f func(guildID string))

HandleGuildIntegrationsUpdate registers the handler function for the "GUILD_INTEGRATIONS_UPDATE" event. Fired when a guild integration is updated.

func (*Client) HandleGuildMemberAdd

func (c *Client) HandleGuildMemberAdd(f func(m *GuildMemberAdd))

HandleGuildMemberAdd registers the handler function for the "GUILD_MEMBER_ADD" event. Fired when a new user joins a guild.

func (*Client) HandleGuildMemberRemove

func (c *Client) HandleGuildMemberRemove(f func(m *GuildMemberRemove))

HandleGuildMemberRemove registers the handler function for the "GUILD_MEMBER_REMOVE" event. Fired when a user is removed from a guild (leave/kick/ban).

func (*Client) HandleGuildMemberUpdate

func (c *Client) HandleGuildMemberUpdate(f func(m *GuildMemberUpdate))

HandleGuildMemberUpdate registers the handler function for the "GUILD_MEMBER_UPDATE" event. Fired when a guild member is updated.

func (*Client) HandleGuildMembersChunk

func (c *Client) HandleGuildMembersChunk(f func(m *GuildMembersChunk))

HandleGuildMembersChunk registers the handler function for the "GUILD_MEMBERS_CHUNK" event. Sent in response to Guild Request Members.

func (*Client) HandleGuildRoleCreate

func (c *Client) HandleGuildRoleCreate(f func(r *GuildRole))

HandleGuildRoleCreate registers the handler function for the "GUILD_ROLE_CREATE" event. Fired when a guild role is created.

func (*Client) HandleGuildRoleDelete

func (c *Client) HandleGuildRoleDelete(f func(r *GuildRoleDelete))

HandleGuildRoleDelete registers the handler function for the "GUILD_ROLE_DELETE" event. Fired when a guild role is deleted.

func (*Client) HandleGuildRoleUpdate

func (c *Client) HandleGuildRoleUpdate(f func(r *GuildRole))

HandleGuildRoleUpdate registers the handler function for the "GUILD_ROLE_UPDATE" event. Fired when a guild role is updated.

func (*Client) HandleGuildUpdate

func (c *Client) HandleGuildUpdate(f func(g *Guild))

HandleGuildUpdate registers the handler function for the "GUILD_UPDATE" event.

func (*Client) HandleMessageAck

func (c *Client) HandleMessageAck(f func(ack *MessageAck))

HandleMessageAck registers the handler function for the "MESSAGE_ACK" event.

func (*Client) HandleMessageCreate

func (c *Client) HandleMessageCreate(f func(m *Message))

HandleMessageCreate registers the handler function for the "MESSAGE_CREATE" event. Fired when a message is created.

func (*Client) HandleMessageDelete

func (c *Client) HandleMessageDelete(f func(m *MessageDelete))

HandleMessageDelete registers the handler function for the "MESSAGE_DELETE" event. Fired when a message is deleted.

func (*Client) HandleMessageDeleteBulk

func (c *Client) HandleMessageDeleteBulk(f func(mdb *MessageDeleteBulk))

HandleMessageDeleteBulk registers the handler function for the "MESSAGE_DELETE_BULK" event. Fired when multiple messages are deleted at once.

func (*Client) HandleMessageReactionAdd

func (c *Client) HandleMessageReactionAdd(f func(r *MessageReaction))

HandleMessageReactionAdd registers the handler function for the "MESSAGE_REACTION_ADD" event. Fired when a user adds a reaction to a message.

func (*Client) HandleMessageReactionRemove

func (c *Client) HandleMessageReactionRemove(f func(r *MessageReaction))

HandleMessageReactionRemove registers the handler function for the "MESSAGE_REACTION_REMOVE" event. Fired when a user removes a reaction from a message.

func (*Client) HandleMessageReactionRemoveAll

func (c *Client) HandleMessageReactionRemoveAll(f func(r *MessageReactionRemoveAll))

HandleMessageReactionRemoveAll registers the handler function for the "MESSAGE_REACTION_REMOVE_ALL" event. Fired when a user explicitly removes all reactions from a message.

func (*Client) HandleMessageUpdate

func (c *Client) HandleMessageUpdate(f func(m *Message))

HandleMessageUpdate registers the handler function for the "MESSAGE_UPDATE" event. Fired when a message is updated. Unlike creates, message updates may contain only a subset of the full message object payload (but will always contain an id and channel_id).

func (*Client) HandlePresenceUpdate

func (c *Client) HandlePresenceUpdate(f func(p *Presence))

HandlePresenceUpdate registers the handler function for the "PRESENCE_UPDATE" event. This event is fired when a user's presence is updated for a guild. The user object within this event can be partial, the only field which must be sent is the id field, everything else is optional. Along with this limitation, no fields are required, and the types of the fields are not validated. Your client should expect any combination of fields and types within this event.

func (*Client) HandleReady

func (c *Client) HandleReady(f func(r *Ready))

HandleReady registers the handler function for the "READY" event.

func (*Client) HandleTypingStart

func (c *Client) HandleTypingStart(f func(ts *TypingStart))

HandleTypingStart registers the handler function for the "TYPING_START" event. Fired when a user starts typing in a channel.

func (*Client) HandleUserUpdate

func (c *Client) HandleUserUpdate(f func(u *User))

HandleUserUpdate registers the handler function for the "USER_UPDATE" event. Fired when properties about the user change.

func (*Client) HandleVoiceServerUpdate

func (c *Client) HandleVoiceServerUpdate(f func(vs *VoiceServerUpdate))

HandleVoiceServerUpdate registers the handler function for the "VOICE_SERVER_UPDATE" event. Fired when a guild's voice server is updated. This is Fired when initially connecting to voice, and when the current voice instance fails over to a new server.

func (*Client) HandleVoiceStateUpdate

func (c *Client) HandleVoiceStateUpdate(f func(vs *VoiceState))

HandleVoiceStateUpdate registers the handler function for the "VOICE_STATE_UPDATE" event. Fired when someone joins/leaves/moves voice channels.

func (*Client) HandleWebhooksUpdate

func (c *Client) HandleWebhooksUpdate(f func(wu *WebhooksUpdate))

HandleWebhooksUpdate registers the handler function for the "WEBHOOKS_UPDATE" event. Fired when a guild channel's webhook is created, updated, or deleted.

func (*Client) Invite added in v0.2.0

func (c *Client) Invite(code string) *InviteResource

Invite returns a new invite resource to manage the invite with the given code.

func (*Client) Webhook added in v0.2.0

func (c *Client) Webhook(id string) *WebhookResource

Webhook returns a new webhook resource to manage the webhook with the given ID.

type ClientOption

type ClientOption func(*Client)

ClientOption is a function that configures a Client. It is used in NewClient.

func WithBackoffStrategy

func WithBackoffStrategy(baseDelay, maxDelay time.Duration, factor, jitter float64) ClientOption

WithBackoffStrategy allows you to customize the backoff strategy used when trying to reconnect to the Discord Gateway after an error occurred (such as a network failure).

func WithBaseURL

func WithBaseURL(url string) ClientOption

WithBaseURL can be used to change de base URL of the API. This is used for testing.

func WithBotToken

func WithBotToken(token string) ClientOption

WithBotToken sets the token for a bot client. Every call to NewClient must include this option or the WithToken option if the client is a regular user instead of a bot.

func WithErrorHandler

func WithErrorHandler(h func(error)) ClientOption

WithErrorHandler allows you to specify a custom error handler function that will be called whenever an error occurs while the connection to the Gateway is up.

func WithHTTPClient

func WithHTTPClient(client *http.Client) ClientOption

WithHTTPClient can be used to specify the http.Client to use when making HTTP requests to the Discord HTTP API.

func WithLargeThreshold

func WithLargeThreshold(t int) ClientOption

WithLargeThreshold allows you to set the large threshold when connecting to the Gateway. This threshold will dictate the number of offline guild members are returned with a guild. See: https://discordapp.com/developers/docs/topics/gateway#request-guild-members for more details.

func WithSharding

func WithSharding(current, total int) ClientOption

WithSharding allows you to specify a sharding configuration when connecting to the Gateway. See https://discordapp.com/developers/docs/topics/gateway#sharding for more details.

func WithStateTracking

func WithStateTracking(y bool) ClientOption

WithStateTracking allows you to specify whether the client is tracking the state of the current connection or not.

func WithToken

func WithToken(token string) ClientOption

WithToken sets the token for a user client. Every call to NewClient must include this option or the WithBotToken option if the client is a bot instead of a regular user.

type Connection

type Connection struct {
	ID           string        `json:"id"`
	Name         string        `json:"name"`
	Type         string        `json:"type"`
	Revoked      bool          `json:"revoked"`
	Integrations []Integration `json:"integrations"` // Partial server integrations.
}

Connection that the user has attached.

type CurrentUserResource added in v0.2.0

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

CurrentUserResource is a resource that allows to perform various actions on the current user. Create one with Client.Channel.

func (*CurrentUserResource) Connections added in v0.2.0

func (r *CurrentUserResource) Connections() ([]Connection, error)

Connections returns a list of connections for the connected user.

func (*CurrentUserResource) DMs added in v0.2.0

func (r *CurrentUserResource) DMs(id string) ([]Channel, error)

DMs returns the list of direct message channels the current user is in. This endpoint does not seem to be available for Bot users, always returning an empty list of channels.

func (*CurrentUserResource) Get added in v0.2.0

func (r *CurrentUserResource) Get() (*User, error)

Get returns the current user.

func (*CurrentUserResource) Guilds added in v0.2.0

func (r *CurrentUserResource) Guilds() ([]PartialGuild, error)

Guilds returns a list of partial guilds the current user is a member of. This endpoint returns at most 100 guilds by default, which is the maximum number of guilds a non-bot user can join. Therefore, pagination is not needed for integrations that need to get a list of users' guilds.

func (*CurrentUserResource) LeaveGuild added in v0.2.0

func (r *CurrentUserResource) LeaveGuild(id string) error

LeaveGuild make the current user leave a guild given its ID.

func (*CurrentUserResource) Modify added in v0.2.0

func (r *CurrentUserResource) Modify(username, avatar string) (*User, error)

Modify modifies the current user account settings. Avatar is a Data URI scheme that supports JPG, GIF, and PNG formats. An example Data URI format is:

data:image/jpeg;base64,BASE64_ENCODED_JPEG_IMAGE_DATA

Ensure you use the proper header type (image/jpeg, image/png, image/gif) that matches the image data being provided.

func (*CurrentUserResource) NewDM added in v0.2.0

func (r *CurrentUserResource) NewDM(recipientID string) (*Channel, error)

NewDM creates a new DM channel with a user. Returns the created channel. If a DM channel already exist with this recipient, it does not create a new one and returns the existing one instead.

func (*CurrentUserResource) SetStatus added in v0.2.0

func (r *CurrentUserResource) SetStatus(status *Status) error

SetStatus sets the current user's status. You need to be connected to the Gateway to call this method, else it will return ErrGatewayNotConnected.

type Emoji

type Emoji struct {
	ID            string `json:"id"`
	Name          string `json:"name"`
	Roles         []Role `json:"roles"`
	User          *User  `json:"user"` // The user that created this emoji.
	RequireColons bool   `json:"require_colons"`
	Managed       bool   `json:"managed"`
	Animated      bool   `json:"animated"`
}

Emoji represents a Discord emoji (both standard and custom).

func (*Emoji) Clone added in v0.3.0

func (e *Emoji) Clone() *Emoji

Clone returns a clone of this Emoji.

type File

type File struct {
	Name   string
	Reader io.Reader
}

File is a file along with its name. It is used to send files to channels with SendFiles.

type Guild

type Guild struct {
	ID                          string   `json:"id"`
	Name                        string   `json:"name,omitempty"`
	Icon                        *string  `json:"icon,omitempty"`
	Splash                      *string  `json:"splash,omitempty"`
	Owner                       bool     `json:"owner,omitempty"`
	OwnerID                     string   `json:"owner_id,omitempty"`
	Permissions                 int      `json:"permissions,omitempty"`
	Region                      string   `json:"region,omitempty"`
	AFKChannelID                *string  `json:"afk_channel_id,omitempty"`
	AFKTimeout                  int      `json:"afk_timeout,omitempty"`
	EmbedEnabled                bool     `json:"embed_enabled,omitempty"`
	EmbedChannelID              string   `json:"embed_channel_id,omitempty"`
	VerificationLevel           int      `json:"verification_level,omitempty"`
	DefaultMessageNotifications int      `json:"default_message_notifications,omitempty"`
	ExplicitContentFilter       int      `json:"explicit_content_filter,omitempty"`
	Roles                       []Role   `json:"roles,omitempty"`
	Emojis                      []Emoji  `json:"emojis,omitempty"`
	Features                    []string `json:"features,omitempty"`
	MFALevel                    int      `json:"mfa_level,omitempty"`
	ApplicationID               *string  `json:"application_id,omitempty"`
	WidgetEnabled               bool     `json:"widget_enabled,omitempty"`
	WidgetChannelID             string   `json:"widget_channel_id,omitempty"`
	SystemChannelID             *string  `json:"system_channel_id,omitempty"`

	// Following fields are only sent within the GUILD_CREATE event.
	JoinedAt    time.Time     `json:"joined_at,omitempty"`
	Large       bool          `json:"large,omitempty"`
	Unavailable bool          `json:"unavailable,omitempty"`
	MemberCount int           `json:"member_count,omitempty"`
	VoiceStates []VoiceState  `json:"voice_states,omitempty"`
	Members     []GuildMember `json:"members,omitempty"`
	Channels    []Channel     `json:"channels,omitempty"`
	Presences   []Presence    `json:"presences,omitempty"`
}

Guild in Discord represents an isolated collection of users and channels, and are often referred to as "servers" in the UI.

func (*Guild) Clone added in v0.3.0

func (g *Guild) Clone() *Guild

Clone returns a clone of this Guild.

type GuildBan

type GuildBan struct {
	*User
	GuildID string `json:"guild_id"`
}

type GuildEmojis

type GuildEmojis struct {
	Emojis  []Emoji `json:"emojis"`
	GuildID string  `json:"guild_id"`
}

type GuildMember

type GuildMember struct {
	User     *User     `json:"user,omitempty"`
	Nick     string    `json:"nick,omitempty"`
	Roles    []string  `json:"roles,omitempty"` // Role IDs.
	JoinedAt time.Time `json:"joined_at,omitempty"`
	Deaf     bool      `json:"deaf,omitempty"`
	Mute     bool      `json:"mute,omitempty"`
}

GuildMember represents a User in a Guild.

func (*GuildMember) Clone added in v0.3.0

func (m *GuildMember) Clone() *GuildMember

Clone returns a clone of this GuildMember.

func (*GuildMember) PermissionsIn added in v0.2.0

func (m *GuildMember) PermissionsIn(g *Guild, ch *Channel) (permissions int)

PermissionsIn returns the permissions of the Guild member in the given Guild and channel.

type GuildMemberAdd

type GuildMemberAdd struct {
	*GuildMember
	GuildID string `json:"guild_id"`
}

type GuildMemberRemove

type GuildMemberRemove struct {
	User    *User  `json:"user"`
	GuildID string `json:"guild_id"`
}

type GuildMemberUpdate

type GuildMemberUpdate struct {
	GuildID string   `json:"guild_id"`
	Roles   []string `json:"roles"`
	User    *User    `json:"user"`
	Nick    string   `json:"nick"`
}

type GuildMembersChunk

type GuildMembersChunk struct {
	GuildID string        `json:"guild_id"`
	Members []GuildMember `json:"members"`
}

type GuildResource added in v0.2.0

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

GuildResource is a resource that allows to perform various actions on a Discord guild. Create one with Client.Guild.

func (*GuildResource) AddIntegration added in v0.2.0

func (r *GuildResource) AddIntegration(id, typ string) error

AddIntegration attaches an integration from the current user to the guild. Requires the 'MANAGE_GUILD' permission. Fires a Guild Integrations Update Gateway event.

func (*GuildResource) AddMember added in v0.2.0

func (r *GuildResource) AddMember(userID, token string, settings *guild.MemberSettings) (*GuildMember, error)

AddMember adds a user to the guild, provided you have a valid oauth2 access token for the user with the guilds.join scope. Fires a Guild Member Add Gateway event. Requires the bot to have the CREATE_INSTANT_INVITE permission.

func (*GuildResource) AddMemberRole added in v0.2.0

func (r *GuildResource) AddMemberRole(userID, roleID string) error

AddMemberRole adds a role to a guild member. Requires the 'MANAGE_ROLES' permission. Fires a Guild Member Update Gateway event.

func (*GuildResource) Ban added in v0.2.0

func (r *GuildResource) Ban(userID string) error

Ban is a shorthand to ban a user with no reason and without deleting his messages. Requires the 'BAN_MEMBERS' permission. For more control, use the BanWithReason method.

func (*GuildResource) BanWithReason added in v0.2.0

func (r *GuildResource) BanWithReason(userID string, delMsgDays int, reason string) error

BanWithReason creates a guild ban, and optionally delete previous messages sent by the banned user. Requires the 'BAN_MEMBERS' permission. Parameter delMsgDays is the number of days to delete messages for (0-7). Fires a Guild Ban Add Gateway event.

func (*GuildResource) Bans added in v0.2.0

func (r *GuildResource) Bans() ([]Ban, error)

Bans returns a list of bans for the users banned from this guild. Requires the 'BAN_MEMBERS' permission.

func (*GuildResource) BeginPrune added in v0.2.0

func (r *GuildResource) BeginPrune(days int) (int, error)

BeginPrune begins a prune operation. Requires the 'KICK_MEMBERS' permission. Returns the number of members that were removed in the prune operation. Fires multiple Guild Member Remove Gateway events.

func (*GuildResource) ChangeNick added in v0.2.0

func (r *GuildResource) ChangeNick(name string) (string, error)

ChangeNick modifies the nickname of the current user in the guild. It returns the nickname on success. Requires the 'CHANGE_NICKNAME' permission. Fires a Guild Member Update Gateway event.

func (*GuildResource) Channels added in v0.2.0

func (r *GuildResource) Channels() ([]Channel, error)

Channels returns the list of channels in the guild.

func (*GuildResource) Delete added in v0.2.0

func (r *GuildResource) Delete() error

Delete deletes the guild permanently. Current user must be owner. Fires a Guild Delete Gateway event.

func (*GuildResource) DeleteEmoji added in v0.2.0

func (r *GuildResource) DeleteEmoji(emojiID string) error

DeleteEmoji deletes the given emoji. Requires the 'MANAGE_EMOJIS' permission. Fires a Guild Emojis Update Gateway event.

func (*GuildResource) DeleteRole added in v0.2.0

func (r *GuildResource) DeleteRole(id string) error

DeleteRole deletes a guild role. Requires the 'MANAGE_ROLES' permission. Fires a Guild Role Delete Gateway event.

func (*GuildResource) Embed added in v0.2.0

func (r *GuildResource) Embed() (*guild.Embed, error)

Embed returns the guild's embed. Requires the 'MANAGE_GUILD' permission.

func (*GuildResource) Emoji added in v0.2.0

func (r *GuildResource) Emoji(emojiID string) (*Emoji, error)

Emoji returns an emoji from the guild.

func (*GuildResource) Emojis added in v0.2.0

func (r *GuildResource) Emojis() ([]Emoji, error)

Emojis returns the list of emojis of the guild. Requires the MANAGE_EMOJIS permission.

func (*GuildResource) Get added in v0.2.0

func (r *GuildResource) Get() (*Guild, error)

Get returns the guild.

func (*GuildResource) Integrations added in v0.2.0

func (r *GuildResource) Integrations() ([]Integration, error)

Integrations returns the list of integrations for the guild. Requires the 'MANAGE_GUILD' permission.

func (*GuildResource) Invites added in v0.2.0

func (r *GuildResource) Invites() ([]Invite, error)

Invites returns the list of invites (with invite metadata) for the guild. Requires the 'MANAGE_GUILD' permission.

func (*GuildResource) Member added in v0.2.0

func (r *GuildResource) Member(userID string) (*GuildMember, error)

Member returns a single guild member given its user ID.

func (*GuildResource) Members added in v0.2.0

func (r *GuildResource) Members(limit int, after string) ([]GuildMember, error)

Members returns a list of at most limit guild members, starting at after. limit must be between 1 and 1000 and will be set to those values if higher/lower. after is the ID of the guild member you want to get the list from, leave it empty to start from the beginning.

func (*GuildResource) Modify added in v0.2.0

func (r *GuildResource) Modify(settings *guild.Settings) (*Guild, error)

Modify modifies the guild's settings. Requires the 'MANAGE_GUILD' permission. Returns the updated guild on success. Fires a Guild Update Gateway event.

func (*GuildResource) ModifyChannelPosition added in v0.2.0

func (r *GuildResource) ModifyChannelPosition(pos []ChannelPosition) error

ModifyChannelPosition modifies the positions of a set of channel for the guild. Requires 'MANAGE_CHANNELS' permission. Fires multiple Channel Update Gateway events.

Only channels to be modified are required, with the minimum being a swap between at least two channels.

func (*GuildResource) ModifyEmbed added in v0.2.0

func (r *GuildResource) ModifyEmbed(embed *guild.Embed) (*guild.Embed, error)

ModifyEmbed modifies the guild embed of the guild. Requires the 'MANAGE_GUILD' permission.

func (*GuildResource) ModifyEmoji added in v0.2.0

func (r *GuildResource) ModifyEmoji(emojiID, name string, roles []string) (*Emoji, error)

ModifyEmoji modifies the given emoji for the guild. Requires the 'MANAGE_EMOJIS' permission. Fires a Guild Emojis Update Gateway event.

func (*GuildResource) ModifyIntegration added in v0.2.0

func (r *GuildResource) ModifyIntegration(id string, settings *integration.Settings) error

ModifyIntegration modifies the behavior and settings of a guild integration. Requires the 'MANAGE_GUILD' permission. Fires a Guild Integrations Update Gateway event.

func (*GuildResource) ModifyMember added in v0.2.0

func (r *GuildResource) ModifyMember(userID string, settings *guild.MemberSettings) error

ModifyMember modifies attributes of a guild member. Fires a Guild Member Update Gateway event.

func (*GuildResource) ModifyRole added in v0.2.0

func (r *GuildResource) ModifyRole(id string, settings *role.Settings) (*Role, error)

ModifyRole modifies a guild role. Requires the 'MANAGE_ROLES' permission. Fires a Guild Role Update Gateway event.

func (*GuildResource) ModifyRolePositions added in v0.2.0

func (r *GuildResource) ModifyRolePositions(pos []RolePosition) ([]Role, error)

ModifyRolePositions modifies the positions of a set of roles for the guild. Requires 'MANAGE_ROLES' permission. Fires multiple Guild Role Update Gateway events.

func (*GuildResource) NewChannel added in v0.2.0

func (r *GuildResource) NewChannel(settings *channel.Settings) (*Channel, error)

NewChannel creates a new channel in the guild.

func (*GuildResource) NewEmoji added in v0.2.0

func (r *GuildResource) NewEmoji(name, image string, roles []string) (*Emoji, error)

NewEmoji creates a new emoji for the guild. image is the base64 encoded data of a 128*128 image. Requires the 'MANAGE_EMOJIS' permission. Fires a Guild Emojis Update Gateway event.

func (*GuildResource) NewRole added in v0.2.0

func (r *GuildResource) NewRole(settings *role.Settings) (*Role, error)

NewRole creates a new role for the guild. Requires the 'MANAGE_ROLES' permission. Fires a Guild Role Create Gateway event.

func (*GuildResource) PruneCount added in v0.2.0

func (r *GuildResource) PruneCount(days int) (int, error)

PruneCount returns the number of members that would be removed in a prune operation. Requires the 'KICK_MEMBERS' permission.

func (*GuildResource) RemoveIntegration added in v0.2.0

func (r *GuildResource) RemoveIntegration(id string) error

RemoveIntegration removes the attached integration for the guild. Requires the 'MANAGE_GUILD' permission. Fires a Guild Integrations Update Gateway event.

func (*GuildResource) RemoveMember added in v0.2.0

func (r *GuildResource) RemoveMember(userID string) error

RemoveMember removes the given user from the guild. Requires 'KICK_MEMBERS' permission. Fires a Guild Member Remove Gateway event.

func (*GuildResource) RemoveMemberRole added in v0.2.0

func (r *GuildResource) RemoveMemberRole(userID, roleID string) error

RemoveMemberRole removes a role from a guild member. Requires the 'MANAGE_ROLES' permission. Fires a Guild Member Update Gateway event.

func (*GuildResource) RequestGuildMembers added in v0.2.0

func (r *GuildResource) RequestGuildMembers(query string, limit int) error

RequestGuildMembers is used to request offline members for the guild. When initially connecting, the gateway will only send offline members if a guild has less than the large_threshold members (value in the Gateway Identify). If a client wishes to receive additional members, they need to explicitly request them via this operation. The server will send Guild Members Chunk events in response with up to 1000 members per chunk until all members that match the request have been sent. query is a string that username starts with, or an empty string to return all members. limit is the maximum number of members to send or 0 to request all members matched. You need to be connected to the Gateway to call this method, else it will return ErrGatewayNotConnected.

func (*GuildResource) Roles added in v0.2.0

func (r *GuildResource) Roles() ([]Role, error)

Roles returns a list of roles for the guild. Requires the 'MANAGE_ROLES' permission.

func (*GuildResource) SyncIntegration added in v0.2.0

func (r *GuildResource) SyncIntegration(id string) error

SyncIntegration syncs a guild integration. Requires the 'MANAGE_GUILD' permission.

func (*GuildResource) Unban added in v0.2.0

func (r *GuildResource) Unban(userID string) error

Unban removes the ban for a user. Requires the 'BAN_MEMBERS' permissions. Fires a Guild Ban Remove Gateway event.

func (*GuildResource) VanityURL added in v0.2.0

func (r *GuildResource) VanityURL() (*Invite, error)

VanityURL returns a partial invite for the guild if that feature is enabled. Requires the 'MANAGE_GUILD' permission.

func (*GuildResource) VoiceRegions added in v0.2.0

func (r *GuildResource) VoiceRegions() ([]VoiceRegion, error)

VoiceRegions returns a list of available voice regions for the guild. Unlike the similar GetVoiceRegions method of the Client, this returns VIP servers when the guild is VIP-enabled.

func (*GuildResource) Webhooks added in v0.2.0

func (r *GuildResource) Webhooks() ([]Webhook, error)

Webhooks returns the list of webhooks in the guild. Requires the 'MANAGE_WEBHOOKS' permission.

type GuildRole

type GuildRole struct {
	GuildID string `json:"guild_id"`
	Role    *Role  `json:"role"`
}

type GuildRoleDelete

type GuildRoleDelete struct {
	GuildID string `json:"guild_id"`
	RoleID  string `json:"role_id"`
}

type Integration

type Integration struct {
	ID                string              `json:"id"`
	Name              string              `json:"name"`
	Type              string              `json:"type"`
	Enabled           bool                `json:"enabled"`
	Syncing           bool                `json:"syncing"`
	RoleID            string              `json:"role_id"`
	ExpireBehavior    int                 `json:"expire_behavior"`
	ExpireGravePeriod int                 `json:"expire_grave_period"`
	User              *User               `json:"user"`
	Account           *IntegrationAccount `json:"account"`
	SyncedAt          time.Time           `json:"synced_at"`
}

type IntegrationAccount

type IntegrationAccount struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

type Invite

type Invite struct {
	Code                     string   `json:"code,omitempty"`
	Guild                    *Guild   `json:"guild,omitempty"` // Nil if this invite is for a group DM channel.
	Channel                  *Channel `json:"channel,omitempty"`
	ApproximatePresenceCount int      `json:"approximate_presence_count,omitempty"`
	ApproximateMemberCount   int      `json:"approximate_member_count,omitempty"`

	InviteMetadata
}

Invite represents a code that when used, adds a user to a guild or group DM channel.

type InviteMetadata

type InviteMetadata struct {
	Inviter   *User     `json:"inviter,omitempty"`
	Uses      int       `json:"uses,omitempty"`
	MaxUses   int       `json:"max_uses,omitempty"`
	MaxAge    int       `json:"max_age,omitempty"`
	Temporary bool      `json:"temporary,omitempty"`
	CreatedAt time.Time `json:"created_at,omitempty"`
	Revoked   bool      `json:"revoked,omitempty"`
}

InviteMetadata contains additional information about an Invite.

type InviteResource added in v0.2.0

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

InviteResource is a resource that allows to perform various actions on a Discord invite. Create one with Client.Invite.

func (*InviteResource) Delete added in v0.2.0

func (r *InviteResource) Delete() (*Invite, error)

Delete deletes the invite. Requires the MANAGE_CHANNELS permission. Returns the deleted invite on success.

func (*InviteResource) Get added in v0.2.0

func (r *InviteResource) Get(withCounts bool) (*Invite, error)

Get returns the invite. If withCounts is set to true, the returned invite will contain the approximate member counts.

type Message

type Message struct {
	ID              string        `json:"id"`
	ChannelID       string        `json:"channel_id"`
	GuildID         string        `json:"guild_id"`
	Author          *User         `json:"author"`
	Content         string        `json:"content"`
	Timestamp       time.Time     `json:"timestamp"`
	EditedTimestamp time.Time     `json:"edited_timestamp"`
	TTS             bool          `json:"tts"`
	MentionEveryone bool          `json:"mention_everyone"`
	Mentions        []User        `json:"mentions"`
	MentionRoles    []string      `json:"mention_roles"` // Role IDs
	Attachments     []Attachment  `json:"attachments"`   // Any attached files.
	Embeds          []embed.Embed `json:"embeds"`        // Any embedded content.
	Reactions       []Reaction    `json:"reactions"`
	Nonce           string        `json:"nonce"` // Used for validating a message was sent.
	Pinned          bool          `json:"pinned"`
	WebhookID       string        `json:"webhook_id"`
	Type            MessageType   `json:"type"`

	// Sent with Rich Presence-related chat embeds.
	Activity    *MessageActivity    `json:"activity"`
	Application *MessageApplication `json:"application"`
}

Message represents a message sent in a channel within Discord. The author object follows the structure of the user object, but is only a valid user in the case where the message is generated by a user or bot user. If the message is generated by a webhook, the author object corresponds to the webhook's id, username, and avatar. You can tell if a message is generated by a webhook by checking for the webhook_id on the message object.

func ExecuteWebhook

func ExecuteWebhook(id, token string, p *WebhookParameters, wait bool) (*Message, error)

ExecuteWebhook executes the webhook with the id id given its token and some execution parameters. wait indicates if we should wait for server confirmation of message send before response. If wait is set to false, the returned Message will be nil even if there is no error.

type MessageAck

type MessageAck struct {
	ChannelID string `json:"channel_id"`
	MessageID string `json:"message_id"`
}

type MessageActivity

type MessageActivity struct {
	Type    MessageActivityType
	PartyID string
}

type MessageActivityType

type MessageActivityType int
const (
	Join MessageActivityType = iota
	Spectate
	Listen
	JoinRequest
)

type MessageApplication

type MessageApplication struct {
	ID          string
	CoverImage  string
	Description string
	Icon        string
	Name        string
}

type MessageDelete

type MessageDelete struct {
	ChannelID string `json:"channel_id"`
	MessageID string `json:"id"`
}

type MessageDeleteBulk

type MessageDeleteBulk struct {
	GuildID   string   `json:"guild_id"`
	ChannelID string   `json:"channel_id"`
	IDs       []string `json:"ids"`
}

type MessageReaction

type MessageReaction struct {
	UserID    string `json:"user_id"`
	GuildID   string `json:"guild_id"`
	ChannelID string `json:"channel_id"`
	MessageID string `json:"message_id"`
	Emoji     *Emoji `json:"emoji"`
}

type MessageReactionRemoveAll

type MessageReactionRemoveAll struct {
	GuildID   string `json:"guild_id"`
	ChannelID string `json:"channel_id"`
	MessageID string `json:"message_id"`
}

type MessageType

type MessageType int

MessageType describes the type of a message. Different fields are set or not depending on the message's type.

const (
	Default MessageType = iota
	RecipientAdd
	RecipientRemove
	Call
	ChannelNameChange
	ChannelIconChange
	ChannelPinnedMessage
	GuildMemberJoin
)

supported message types :

type PartialGuild

type PartialGuild struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Icon        string `json:"icon"`
	Owner       bool   `json:"owner"`
	Permissions int    `json:"permissions"`
}

PartialGuild is a subset of the Guild object, returned by the Discord API when fetching current user's guilds.

type Presence

type Presence struct {
	User    *User     `json:"user,omitempty"`
	Roles   []string  `json:"roles,omitempty"` // Array of IDs.
	Game    *Activity `json:"game,omitempty"`
	GuildID string    `json:"guild_id,omitempty"`
	Status  string    `json:"status,omitempty"` // Either "idle", "dnd", "online", or "offline".
}

Presence is a user's current state on a guild. This event is sent when a user's presence is updated for a guild.

func (*Presence) Clone added in v0.3.0

func (p *Presence) Clone() *Presence

Clone returns a clone of this Presence.

type Reaction

type Reaction struct {
	Count int    `json:"count"`
	Me    bool   `json:"me"`
	Emoji *Emoji `json:"emoji"`
}

Reaction is a reaction on a Discord message.

type Ready

type Ready struct {
	V               int            `json:"v"` // Gateway version.
	User            *User          `json:"user"`
	PrivateChannels []Channel      `json:"private_channels"`
	Guilds          []PartialGuild `json:"guilds"`
	SessionID       string         `json:"session_id"`
	Trace           []string       `json:"_trace"`
}

Ready is the Event fired by the Gateway after the client sent a valid Identify payload.

type Role

type Role struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Color       int    `json:"color"`    // Integer representation of hexadecimal color code.
	Hoist       bool   `json:"hoist"`    // Whether this role is pinned in the user listing.
	Position    int    `json:"position"` // Integer	position of this role.
	Permissions int    `json:"permissions"`
	Managed     bool   `json:"managed"` // Whether this role is managed by an integration.
	Mentionable bool   `json:"mentionable"`
}

Role represents a set of permissions attached to a group of users. Roles have unique names, colors, and can be "pinned" to the side bar, causing their members to be listed separately. Roles are unique per guild, and can have separate permission profiles for the global context (guild) and channel context.

func (*Role) Clone added in v0.3.0

func (r *Role) Clone() *Role

Clone returns a clone of this Role.

type RolePosition

type RolePosition struct {
	ID       string `json:"id"`
	Position int    `json:"position"`
}

RolePosition is a pair of role ID with its position. A higher position means it will appear before in the list.

type State

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

State is a cache of the state of the application that is updated in real-time as events are received from the Gateway. Objects returned by State methods are snapshots of original objects used internally by the State. This means they are safe to be used and modified but they won't be updated as new events are received.

func (*State) Channel

func (s *State) Channel(id string) *Channel

Channel returns a channel given its ID from the state.

func (*State) Channels

func (s *State) Channels() map[string]*Channel

Channels returns a map of channels ID to channels from the state.

func (*State) CurrentUser

func (s *State) CurrentUser() *User

CurrentUser returns the current user from the state.

func (*State) DM

func (s *State) DM(id string) *Channel

DM returns a DM given its ID from the state.

func (*State) DMs

func (s *State) DMs() map[string]*Channel

DMs returns a map of DM ID to DM from the state.

func (*State) GroupDM

func (s *State) GroupDM(id string) *Channel

GroupDM returns a group DM given its ID from the state.

func (*State) GroupDMs

func (s *State) GroupDMs() map[string]*Channel

GroupDMs returns a map of group DM ID to group DM from the state.

func (*State) Guild

func (s *State) Guild(id string) *Guild

Guild returns a guild given its ID from the state.

func (*State) Guilds

func (s *State) Guilds() map[string]*Guild

Guilds returns a map of guild ID to guild from the state.

func (*State) Presence

func (s *State) Presence(userID string) *Presence

Presence returns a presence given a user ID from the state.

func (*State) Presences

func (s *State) Presences() map[string]*Presence

Presences returns a map of user ID to presence from the state.

func (*State) RTT

func (s *State) RTT() time.Duration

RTT returns the Round Trip Time between the client and Discord's Gateway. It is calculated and updated when sending heartbeat payloads (roughly every minute).

func (*State) UnavailableGuild

func (s *State) UnavailableGuild(id string) *UnavailableGuild

UnavailableGuild returns an unavailable guild given its ID from the state.

func (*State) UnavailableGuilds

func (s *State) UnavailableGuilds() map[string]*UnavailableGuild

UnavailableGuilds returns a map of guild ID to unavailable guild from the state.

func (*State) User

func (s *State) User(id string) *User

User returns a user given its ID from the state.

func (*State) Users

func (s *State) Users() map[string]*User

Users returns a map of user ID to user from the state.

type Status

type Status struct {
	Since  int       `json:"since"`
	Game   *Activity `json:"game"`
	Status string    `json:"status"`
	AFK    bool      `json:"afk"`
}

Status is sent by the client to indicate a presence or status update.

type TypingStart

type TypingStart struct {
	ChannelID string `json:"channel_id"`
	GuildID   string `json:"guild_id"`
	UserID    string `json:"user_id"`
	Timestamp int64  `json:"timestamp"`
}

type UnavailableGuild

type UnavailableGuild struct {
	ID          string `json:"id"`
	Unavailable *bool  `json:"unavailable"` // If not set, the connected user was removed from this Guild.
}

UnavailableGuild is a Guild that is not available, either because there is a guild outage or because the connected user was removed from this guild.

func (*UnavailableGuild) Clone added in v0.3.0

func (g *UnavailableGuild) Clone() *UnavailableGuild

Clone returns a clone of this UnavailableGuild.

type User

type User struct {
	ID            string `json:"id,omitempty"`
	Username      string `json:"username,omitempty"`
	Discriminator string `json:"discriminator,omitempty"`
	Avatar        string `json:"avatar,omitempty"`
	Bot           bool   `json:"bot,omitempty"`
	MFAEnabled    bool   `json:"mfa_enabled,omitempty"`
	Verified      bool   `json:"verified,omitempty"`
	Email         string `json:"email,omitempty"`
}

User in Discord is generally considered the base entity. Users can spawn across the entire platform, be members of guilds, participate in text and voice chat, and much more. Users are separated by a distinction of "bot" vs "normal." Although they are similar, bot users are automated users that are "owned" by another user. Unlike normal users, bot users do not have a limitation on the number of Guilds they can be a part of.

func (*User) AvatarURL

func (u *User) AvatarURL() string

AvatarURL returns the user's avatar URL.

func (*User) Clone added in v0.3.0

func (u *User) Clone() *User

Clone returns a clone of this User.

type VoiceConnection

type VoiceConnection struct {

	// Send is used to send Opus encoded audio packets.
	Send chan []byte
	// Recv is used to receive audio packets
	// containing Opus encoded audio data.
	Recv chan *AudioPacket
	// contains filtered or unexported fields
}

VoiceConnection represents a Discord voice connection.

func (*VoiceConnection) Disconnect

func (vc *VoiceConnection) Disconnect()

Disconnect closes the voice connection.

func (*VoiceConnection) Speaking

func (vc *VoiceConnection) Speaking(s bool, delay int) error

Speaking sends an Opcode 5 Speaking payload. This does nothing if the user is already in the given state.

type VoiceConnectionOption

type VoiceConnectionOption func(*VoiceConnection)

VoiceConnectionOption is a function that configures a VoiceConnection. It is used in ConnectToVoice.

func WithDeaf

func WithDeaf(t bool) VoiceConnectionOption

WithDeaf allows you to specify whether this voice connection should be deafened when connecting.

func WithMute

func WithMute(t bool) VoiceConnectionOption

WithMute allows you to specify whether this voice connection should be muted when connecting.

func WithVoiceErrorHandler

func WithVoiceErrorHandler(h func(error)) VoiceConnectionOption

WithVoiceErrorHandler allows you to specify a custom error handler function that will be called whenever an error occurs while the connection to the voice is up.

type VoiceRegion

type VoiceRegion struct {
	ID   string `json:"id,omitempty"`
	Name string `json:"name,omitempty"`
	// Whether this is a vip-only server.
	VIP bool `json:"vip,omitempty"`
	// Whether this is a single server that is closest to the current user's client.
	Optimal bool `json:"optimal,omitempty"`
	// Whether this is a deprecated voice region (avoid switching to these.
	Deprecated bool `json:"deprecated,omitempty"`
	// Whether this is a custom voice region (used for events/etc).
	Custom bool `json:"custom,omitempty"`
}

VoiceRegion represents a voice region a guild is in.

type VoiceServerUpdate

type VoiceServerUpdate struct {
	Token    string `json:"token"`
	GuildID  string `json:"guild_id"`
	Endpoint string `json:"endpoint"`
}

type VoiceState

type VoiceState struct {
	GuildID   string `json:"guild_id"`
	ChannelID string `json:"channel_id"`
	UserID    string `json:"user_id"`
	SessionID string `json:"session_id"`
	Deaf      bool   `json:"deaf"`
	Mute      bool   `json:"mute"`
	SelfDeaf  bool   `json:"self_deaf"`
	SelfMute  bool   `json:"self_mute"`
	Suppress  bool   `json:"suppress"` // Whether this user is muted by the current user.
}

VoiceState represents the voice state of a user.

func (*VoiceState) Clone added in v0.3.0

func (v *VoiceState) Clone() *VoiceState

Clone returns a clone of this VoiceState.

type Webhook

type Webhook struct {
	ID        string `json:"id,omitempty"`
	GuildID   string `json:"guild_id,omitempty"`
	ChannelID string `json:"channel_id,omitempty"`
	User      *User  `json:"user,omitempty"`
	Name      string `json:"name,omitempty"`
	Avatar    string `json:"avatar,omitempty"`
	Token     string `json:"token,omitempty"`
}

Webhook is a low-effort way to post messages to channels in Discord. It do not require a bot user or authentication to use.

func GetWebhookWithToken

func GetWebhookWithToken(id, token string) (*Webhook, error)

GetWebhookWithToken is like GetWebhook except this call does not require authentication and returns no user in the webhook.

func ModifyWebhookWithToken

func ModifyWebhookWithToken(id, token string, s *webhook.Settings) (*Webhook, error)

ModifyWebhookWithToken is like ModifyWebhook except this call does not require authentication, does not allow to change the channel_id parameter in the webhook settings, and does not return a user in the webhook.

type WebhookParameters

type WebhookParameters struct {
	Content   string        `json:"content,omitempty"`
	Username  string        `json:"username,omitempty"`
	AvatarURL string        `json:"avatar_url,omitempty"`
	TTS       bool          `json:"tts,omitempty"`
	Embeds    []embed.Embed `json:"embeds,omitempty"`
	Files     []File        `json:"-"`
}

WebhookParameters are the parameters available when executing a webhook with ExecuteWebhook.

type WebhookResource added in v0.2.0

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

WebhookResource is a resource that allows to perform various actions on a Discord webhook. Create one with Client.Webhook.

func (*WebhookResource) Delete added in v0.2.0

func (r *WebhookResource) Delete() error

Delete deletes the webhook.

func (*WebhookResource) Get added in v0.2.0

func (r *WebhookResource) Get() (*Webhook, error)

Get returns the webhook.

func (*WebhookResource) Modify added in v0.2.0

func (r *WebhookResource) Modify(settings *webhook.Settings) (*Webhook, error)

Modify modifies the webhook. Requires the 'MANAGE_WEBHOOKS' permission.

type WebhooksUpdate

type WebhooksUpdate struct {
	GuildID   string `json:"guild_id"`
	ChannelID string `json:"channel_id"`
}

Directories

Path Synopsis
Package embed contains builders to create Discord rich messages.
Package embed contains builders to create Discord rich messages.
examples
internal
Package optional defines optional versions of primitive types that can be nil.
Package optional defines optional versions of primitive types that can be nil.

Jump to

Keyboard shortcuts

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