harmony

package module
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2019 License: MIT Imports: 40 Imported by: 3

README

GoDoc License MIT Discord Build Status

Harmony

Harmony is a peaceful Go module for interacting with Discord's API.

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/harmony

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/harmony@major.minor.patch can be used to download a specific version. See Go modules for more information.

Usage

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/skwair/harmony"
)

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

    // Get information about the current user.
    u, err := c.CurrentUser().Get(context.Background())
    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 and the tests.

Testing

For now, only some end to end tests are provided with this module. To run them, you will need a valid bot token and a valid Discord server ID. The bot attached to the token must be in the server with administrator permissions.

  1. Create a Discord test server

From a Discord client and with you main account, simply create a new server. Then, right click on the new server and get it's ID.

Note that for the UI to have the Copy ID option when right clicking on the server, you will need to enable developer mode. You can find this option in User settings > Appearance > Advanced > Developer Mode.

  1. Create a bot and add it to the test Discord server

Create a bot (or use an existing one) and add it to the freshly created server.

See the example directory for information on how to create a bot and add it to a server.

  1. Set required environment variables and run the tests

Set HARMONY_TEST_BOT_TOKEN to the token of your bot and HARMONY_TEST_GUILD_ID to the ID of the server you created and simply run:

⚠️ For the tests to be reproducible, they will start by deleting ALL channels in the provided server. Please make sure to provide a server created ONLY for those tests. ⚠️

go test -v -race ./...

Step 1 and 2 must be done only once for initial setup. Once you have your bot token and the ID of your test server, you can run the tests as many times as you want.

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. Another thing that this library does not support is self bot, as they are a violation of Discord's TOS.

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.

Finally, this library has a full support of the context package, allowing the use of timeouts, deadlines and cancellation when interacting with Discord's API.

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 harmony 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. NewClient returns a new Client configured with sain defaults which should work just fine in most cases. However, should you need a more specific configuration, you can always tweak it with optional `ClientOption`s. See the documentation of NewClient and the ClientOption type for more information on how to do so.

client := harmony.NewClient("your.bot.token")

Once you have a Client, you can start interacting with the Discord API, but some methods (such as event handlers) won't be available until you connect to Discord's Gateway (link). You can do so by simply calling the Connect method of the Client:

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

It is only when successfully connected to the Gateway that your bot will appear as online and your Client will be able to receive events and send messages.

Using the HTTP API

Harmony's HTTP API is organized by resource. A resource maps to a core concept in the Discord world, such as a User or a Channel. Here is the list of resources you can interact with:

  • Guild
  • Channel
  • CurrentUser
  • Webhook
  • Invite

Every interaction you can have with a resource can be accessed via methods attached to it. For example, if you wish to send a message to a channel:

msg, err := client.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 OnMessageCreate 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.

client.OnMessageCreate(func(msg *harmony.Message) {
	fmt.Println(msg.Content)
})

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

Note that your handlers are called in their own goroutine, meaning whatever you do inside of them won't block future events.

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 := client.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 harmony 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")
	// ErrInvalidSend is returned by Send when no files are provided.
	ErrInvalidSend = errors.New("no content, embed nor file provided")
)
View Source
var (
	// DefaultErrorHandler is the default handle that is called when an error occurs when connected to the Gateway.
	DefaultErrorHandler = func(err error) { log.Println("gateway client error:", err) }
)
View Source
var (
	// ErrAlreadyConnected is returned by Connect when a connection to the Gateway already exists.
	ErrAlreadyConnected = errors.New("already connected to the Gateway")
)

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(ctx context.Context, 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"`
	Misc     []string `json:"_misc"`
}

APIError is a generic error returned by the Discord HTTP API.

func (APIError) Error

func (e APIError) Error() string

Error implements the error interface.

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 AuditLogOption added in v0.11.0

type AuditLogOption func(*auditLogQuery)

AuditLogOption allows to customize a query to the audit log.

func WithBefore added in v0.11.0

func WithBefore(before string) AuditLogOption

WithBefore is used to paginate the audit log. The before parameter is the ID of the last audit log entry of our previous query.

func WithEntryType added in v0.11.0

func WithEntryType(typ audit.EntryType) AuditLogOption

WithEntryType sets the entry type the query must return.

func WithLimit added in v0.11.0

func WithLimit(limit int) AuditLogOption

WithLimit sets the limit the audit log query should return. It must be between 1 and 100 and defaults to 50 if not specified.

func WithUserID added in v0.11.0

func WithUserID(id string) AuditLogOption

WithUserID sets the user ID of the audit log query. It make the query only return audit log entries that have been creating for actions performed by this user.

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

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

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

func (r *ChannelResource) AddReaction(ctx context.Context, 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

func (r *ChannelResource) AddRecipient(ctx context.Context, 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

func (r *ChannelResource) Delete(ctx context.Context) (*Channel, error)

Delete is like DeleteWithReason but with no particular reason.

func (*ChannelResource) DeleteMessage

func (r *ChannelResource) DeleteMessage(ctx context.Context, messageID string) error

DeleteMessage is like DeleteMessageWithReason but with no particular reason.

func (*ChannelResource) DeleteMessageBulk

func (r *ChannelResource) DeleteMessageBulk(ctx context.Context, 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) DeleteMessageWithReason added in v0.11.0

func (r *ChannelResource) DeleteMessageWithReason(ctx context.Context, messageID, reason string) error

DeleteMessageWithReason 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. The given reason will be set in the audit log entry for this action.

func (*ChannelResource) DeletePermission

func (r *ChannelResource) DeletePermission(ctx context.Context, channelID, targetID string) error

DeletePermission is like DeletePermissionWithReason but with no particular reason.

func (*ChannelResource) DeletePermissionWithReason added in v0.11.0

func (r *ChannelResource) DeletePermissionWithReason(ctx context.Context, channelID, targetID, reason string) error

DeletePermissionWithReason deletes the channel permission overwrite for a user or role in a channel. Only usable for guild channels. Requires the 'MANAGE_ROLES' permission. The given reason will be set in the audit log entry for this action.

func (*ChannelResource) DeleteWithReason added in v0.11.0

func (r *ChannelResource) DeleteWithReason(ctx context.Context, reason string) (*Channel, error)

DeleteWithReason 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. The given reason will be set in the audit log entry for this action.

func (*ChannelResource) EditEmbed

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

EditEmbed is like EditMessage but with embedded content support.

func (*ChannelResource) EditMessage

func (r *ChannelResource) EditMessage(ctx context.Context, 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

func (r *ChannelResource) Get(ctx context.Context) (*Channel, error)

Get returns the channel.

func (*ChannelResource) GetReactions

func (r *ChannelResource) GetReactions(ctx context.Context, 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

func (r *ChannelResource) Invites(ctx context.Context) ([]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

func (r *ChannelResource) Message(ctx context.Context, 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

func (r *ChannelResource) Messages(ctx context.Context, 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

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

Modify is like ModifyWithReason but with no particular reason.

func (*ChannelResource) ModifyWithReason added in v0.11.0

func (r *ChannelResource) ModifyWithReason(ctx context.Context, settings *channel.Settings, reason string) (*Channel, error)

ModifyWithReason 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. The given reason will be set in the audit log entry for this action.

func (*ChannelResource) NewInvite

func (r *ChannelResource) NewInvite(ctx context.Context, settings *invite.Settings) (*Invite, error)

NewInvite is like NewInviteWithReason but with no particular reason.

func (*ChannelResource) NewInviteWithReason added in v0.11.0

func (r *ChannelResource) NewInviteWithReason(ctx context.Context, settings *invite.Settings, reason string) (*Invite, error)

NewInviteWithReason creates a new invite for the channel. Only usable for guild channels. Requires the CREATE_INSTANT_INVITE permission. The given reason will be set in the audit log entry for this action.

func (*ChannelResource) NewWebhook

func (r *ChannelResource) NewWebhook(ctx context.Context, name, avatar string) (*Webhook, error)

NewWebhook is like NewWebhookWithReason but with no particular reason.

func (*ChannelResource) NewWebhookWithReason added in v0.11.0

func (r *ChannelResource) NewWebhookWithReason(ctx context.Context, name, avatar, reason string) (*Webhook, error)

NewWebhookWithReason 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. The given reason will be set in the audit log entry for this action.

func (*ChannelResource) PinMessage

func (r *ChannelResource) PinMessage(ctx context.Context, id string) error

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

func (*ChannelResource) Pins

func (r *ChannelResource) Pins(ctx context.Context) ([]Message, error)

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

func (*ChannelResource) RemoveAllReactions

func (r *ChannelResource) RemoveAllReactions(ctx context.Context, 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

func (r *ChannelResource) RemoveReaction(ctx context.Context, messageID, emoji string) error

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

func (*ChannelResource) RemoveRecipient

func (r *ChannelResource) RemoveRecipient(ctx context.Context, recipientID string) error

RemoveRecipient removes a recipient from the Group DM.

func (*ChannelResource) RemoveUserReaction

func (r *ChannelResource) RemoveUserReaction(ctx context.Context, 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) Send added in v0.9.0

func (r *ChannelResource) Send(ctx context.Context, opts ...MessageOption) (*Message, error)

Send sends 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 option WithTTS is set, 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.

func (*ChannelResource) SendMessage

func (r *ChannelResource) SendMessage(ctx context.Context, text string) (*Message, error)

SendMessage is a shorthand for Send(ctx, WithContent(text)).

func (*ChannelResource) TriggerTyping

func (r *ChannelResource) TriggerTyping(ctx context.Context) 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

func (r *ChannelResource) UnpinMessage(ctx context.Context, id string) error

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

func (*ChannelResource) UpdatePermissions

func (r *ChannelResource) UpdatePermissions(ctx context.Context, targetID string, allow, deny int, typ string) error

UpdatePermissions is like UpdatePermissionsWithReason but with no particular reason.

func (*ChannelResource) UpdatePermissionsWithReason added in v0.11.0

func (r *ChannelResource) UpdatePermissionsWithReason(ctx context.Context, targetID string, allow, deny int, typ, reason string) error

UpdatePermissionsWithReason 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. The given reason will be set in the audit log entry for this action.

func (*ChannelResource) Webhooks

func (r *ChannelResource) Webhooks(ctx context.Context) ([]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(token string, 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. The token is automatically prefixed with "Bot ", which is a requirement by Discord for bot users. Automated normal user accounts (generally called "self-bots"), are not supported.

func (*Client) AuditLog added in v0.11.0

func (c *Client) AuditLog(ctx context.Context, guildID string, opts ...AuditLogOption) (*audit.Log, error)

AuditLog returns the audit log of the given Guild. Requires the 'VIEW_AUDIT_LOG' permission.

func (*Client) Channel

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(ctx context.Context) 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(ctx context.Context, 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

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(ctx context.Context) (string, error)

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

func (*Client) GatewayBot

func (c *Client) GatewayBot(ctx context.Context) (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(ctx context.Context, 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(ctx context.Context, guildID string) ([]VoiceRegion, error)

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

func (*Client) Guild

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

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

func (*Client) Invite

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

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

func (*Client) OnChannelCreate added in v0.6.0

func (c *Client) OnChannelCreate(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) OnChannelDelete added in v0.6.0

func (c *Client) OnChannelDelete(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) OnChannelPinsUpdate added in v0.6.0

func (c *Client) OnChannelPinsUpdate(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) OnChannelUpdate added in v0.6.0

func (c *Client) OnChannelUpdate(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) OnGuildBanAdd added in v0.6.0

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

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

func (*Client) OnGuildBanRemove added in v0.6.0

func (c *Client) OnGuildBanRemove(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) OnGuildCreate added in v0.6.0

func (c *Client) OnGuildCreate(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) OnGuildDelete added in v0.6.0

func (c *Client) OnGuildDelete(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) OnGuildEmojisUpdate added in v0.6.0

func (c *Client) OnGuildEmojisUpdate(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) OnGuildIntegrationsUpdate added in v0.6.0

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

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

func (*Client) OnGuildMemberAdd added in v0.6.0

func (c *Client) OnGuildMemberAdd(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) OnGuildMemberRemove added in v0.6.0

func (c *Client) OnGuildMemberRemove(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) OnGuildMemberUpdate added in v0.6.0

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

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

func (*Client) OnGuildMembersChunk added in v0.6.0

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

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

func (*Client) OnGuildRoleCreate added in v0.6.0

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

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

func (*Client) OnGuildRoleDelete added in v0.6.0

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

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

func (*Client) OnGuildRoleUpdate added in v0.6.0

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

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

func (*Client) OnGuildUpdate added in v0.6.0

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

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

func (*Client) OnMessageAck added in v0.6.0

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

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

func (*Client) OnMessageCreate added in v0.6.0

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

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

func (*Client) OnMessageDelete added in v0.6.0

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

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

func (*Client) OnMessageDeleteBulk added in v0.6.0

func (c *Client) OnMessageDeleteBulk(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) OnMessageReactionAdd added in v0.6.0

func (c *Client) OnMessageReactionAdd(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) OnMessageReactionRemove added in v0.6.0

func (c *Client) OnMessageReactionRemove(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) OnMessageReactionRemoveAll added in v0.6.0

func (c *Client) OnMessageReactionRemoveAll(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) OnMessageUpdate added in v0.6.0

func (c *Client) OnMessageUpdate(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) OnPresenceUpdate added in v0.6.0

func (c *Client) OnPresenceUpdate(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) OnReady added in v0.6.0

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

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

func (*Client) OnTypingStart added in v0.6.0

func (c *Client) OnTypingStart(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) OnUserUpdate added in v0.6.0

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

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

func (*Client) OnVoiceServerUpdate added in v0.6.0

func (c *Client) OnVoiceServerUpdate(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) OnVoiceStateUpdate added in v0.6.0

func (c *Client) OnVoiceStateUpdate(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) OnWebhooksUpdate added in v0.6.0

func (c *Client) OnWebhooksUpdate(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) Webhook

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). Defaults to 1s (baseDelay), 120s (maxDelay), 1.6 (factor), 0.2 (jitter).

func WithBaseURL

func WithBaseURL(url string) ClientOption

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

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. Defaults to DefaultErrorHandler.

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. Defaults to http.DefaultClient.

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. Defaults to 250.

func WithName added in v0.10.0

func WithName(n string) ClientOption

WithName sets the name of the client. It will be used to set the User-Agent of HTTP requests sent by the Client. Defaults to "Harmony".

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. Default to nothing, sharding is not enabled.

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. Defaults to true.

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

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

func (r *CurrentUserResource) Connections(ctx context.Context) ([]Connection, error)

Connections returns a list of connections for the connected user.

func (*CurrentUserResource) DMs

func (r *CurrentUserResource) DMs(ctx context.Context) ([]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

func (r *CurrentUserResource) Get(ctx context.Context) (*User, error)

Get returns the current user.

func (*CurrentUserResource) Guilds

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

func (r *CurrentUserResource) LeaveGuild(ctx context.Context, id string) error

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

func (*CurrentUserResource) Modify

func (r *CurrentUserResource) Modify(ctx context.Context, 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

func (r *CurrentUserResource) NewDM(ctx context.Context, 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

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

func (e *Emoji) Clone() *Emoji

Clone returns a clone of this Emoji.

type File

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

File represents a file that can be sent with Send and the WithFiles option.

func FileFromDisk added in v0.10.0

func FileFromDisk(filepath, name string) (*File, error)

FileFromDisk returns a File from a local, on disk file. If name is left empty, it will default to the name of the file on disk. Note that since Send is responsible for closing files opened by FileFromDisk, calling this function and *not* calling Send after can lead to resource leaks.

func FileFromReadCloser added in v0.10.0

func FileFromReadCloser(r io.ReadCloser, name string) *File

FileFromReadCloser returns a File given a ReadCloser and a name. If the name ends with a valid extension recognized by Discord's client applications, the file will be displayed inline in the channel instead of asking users to manually download it.

func FileFromURL added in v0.10.0

func FileFromURL(url, name string) (*File, error)

FileFromURL returns a File from a remote HTTP resource. If the name is left empty, it will default to the name of the file specified in the URL. Note that since Send is responsible for closing files opened by FileFromURL, calling this function and *not* calling Send after can lead to resource leaks.

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           guild.VerificationLevel        `json:"verification_level,omitempty"`
	DefaultMessageNotifications guild.DefaultNotificationLevel `json:"default_message_notifications,omitempty"`
	ExplicitContentFilter       guild.ExplicitContentFilter    `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

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

func (m *GuildMember) Clone() *GuildMember

Clone returns a clone of this GuildMember.

func (*GuildMember) HasRole

func (m *GuildMember) HasRole(id string) bool

HasRole returns whether this member has the given role. Note that this method does not try to fetch this member latest roles, it instead looks in the roles it already had when this member object was created.

func (*GuildMember) PermissionsIn

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

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

func (r *GuildResource) AddIntegration(ctx context.Context, 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

func (r *GuildResource) AddMember(ctx context.Context, 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

func (r *GuildResource) AddMemberRole(ctx context.Context, userID, roleID string) error

AddMemberRole is like AddMemberRoleWithReason but with no particular reason.

func (*GuildResource) AddMemberRoleWithReason added in v0.11.0

func (r *GuildResource) AddMemberRoleWithReason(ctx context.Context, userID, roleID, reason string) error

AddMemberRole adds a role to a guild member. Requires the 'MANAGE_ROLES' permission. Fires a Guild Member Update Gateway event. The given reason will be set in the audit log entry for this action.

func (*GuildResource) Ban

func (r *GuildResource) Ban(ctx context.Context, 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

func (r *GuildResource) BanWithReason(ctx context.Context, 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

func (r *GuildResource) Bans(ctx context.Context) ([]Ban, error)

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

func (*GuildResource) BeginPrune

func (r *GuildResource) BeginPrune(ctx context.Context, days int, computePruneCount bool) (pruneCount int, err error)

BeginPrune is like BeginPruneWithReason but with no particular reason.

func (*GuildResource) BeginPruneWithReason added in v0.11.0

func (r *GuildResource) BeginPruneWithReason(ctx context.Context, days int, computePruneCount bool, reason string) (pruneCount int, err error)

BeginPruneWithReason begins a prune operation. Requires the 'KICK_MEMBERS' permission. Returns the number of members that were removed in the prune operation if computePruneCount is set to true (not recommended for large guilds). Fires multiple Guild Member Remove Gateway events. The given reason will be set in the audit log entry for this action.

func (*GuildResource) ChangeNick

func (r *GuildResource) ChangeNick(ctx context.Context, name string) (string, error)

ChangeNick modifies the nickname of the current user (i.e.: the bot) for this guild. It returns the nickname on success. Requires the 'CHANGE_NICKNAME' permission. Fires a Guild Member Update Gateway event.

func (*GuildResource) Channels

func (r *GuildResource) Channels(ctx context.Context) ([]Channel, error)

Channels returns the list of channels in the guild.

func (*GuildResource) Delete

func (r *GuildResource) Delete(ctx context.Context) error

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

func (*GuildResource) DeleteEmoji

func (r *GuildResource) DeleteEmoji(ctx context.Context, emojiID string) error

DeleteEmoji is like DeleteEmojiWithReason but with no particular reason.

func (*GuildResource) DeleteEmojiWithReason added in v0.11.0

func (r *GuildResource) DeleteEmojiWithReason(ctx context.Context, emojiID, reason string) error

DeleteEmojiWithReason deletes the given emoji. Requires the 'MANAGE_EMOJIS' permission. Fires a Guild Emojis Update Gateway event. The given reason will be set in the audit log entry for this action.

func (*GuildResource) DeleteRole

func (r *GuildResource) DeleteRole(ctx context.Context, id string) error

DeleteRole is like DeleteRoleWithReason but with no particular reason.

func (*GuildResource) DeleteRoleWithReason added in v0.11.0

func (r *GuildResource) DeleteRoleWithReason(ctx context.Context, id, reason string) error

DeleteRole deletes a guild role. Requires the 'MANAGE_ROLES' permission. Fires a Guild Role Delete Gateway event. The given reason will be set in the audit log entry for this action.

func (*GuildResource) Embed

func (r *GuildResource) Embed(ctx context.Context) (*guild.Embed, error)

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

func (*GuildResource) Emoji

func (r *GuildResource) Emoji(ctx context.Context, emojiID string) (*Emoji, error)

Emoji returns an emoji from the guild.

func (*GuildResource) Emojis

func (r *GuildResource) Emojis(ctx context.Context) ([]Emoji, error)

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

func (*GuildResource) Get

func (r *GuildResource) Get(ctx context.Context) (*Guild, error)

Get returns the guild.

func (*GuildResource) Integrations

func (r *GuildResource) Integrations(ctx context.Context) ([]Integration, error)

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

func (*GuildResource) Invites

func (r *GuildResource) Invites(ctx context.Context) ([]Invite, error)

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

func (*GuildResource) Member

func (r *GuildResource) Member(ctx context.Context, userID string) (*GuildMember, error)

Member returns a single guild member given its user ID.

func (*GuildResource) Members

func (r *GuildResource) Members(ctx context.Context, 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

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

Modify is like ModifyWithReason but with no particular reason.

func (*GuildResource) ModifyChannelPosition

func (r *GuildResource) ModifyChannelPosition(ctx context.Context, 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

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

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

func (*GuildResource) ModifyEmoji

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

ModifyEmoji is like ModifyEmojiWithReason but with no particular reason.

func (*GuildResource) ModifyEmojiWithReason added in v0.11.0

func (r *GuildResource) ModifyEmojiWithReason(ctx context.Context, emojiID, name string, roles []string, reason string) (*Emoji, error)

ModifyEmojiWithReason modifies the given emoji for the guild. Requires the 'MANAGE_EMOJIS' permission. Fires a Guild Emojis Update Gateway event. The given reason will be set in the audit log entry for this action.

func (*GuildResource) ModifyIntegration

func (r *GuildResource) ModifyIntegration(ctx context.Context, 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

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

ModifyMember is like ModifyMemberWithReason but with no particular reason.

func (*GuildResource) ModifyMemberWithReason added in v0.11.0

func (r *GuildResource) ModifyMemberWithReason(ctx context.Context, userID string, settings *guild.MemberSettings, reason string) error

ModifyMember modifies attributes of a guild member. Fires a Guild Member Update Gateway event. The given reason will be set in the audit log entry for this action.

func (*GuildResource) ModifyRole

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

ModifyRole is like ModifyRoleWithReason but with no particular reason.

func (*GuildResource) ModifyRolePositions

func (r *GuildResource) ModifyRolePositions(ctx context.Context, 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) ModifyRoleWithReason added in v0.11.0

func (r *GuildResource) ModifyRoleWithReason(ctx context.Context, id string, settings *role.Settings, reason string) (*Role, error)

ModifyRole modifies a guild role. Requires the 'MANAGE_ROLES' permission. Fires a Guild Role Update Gateway event. The given reason will be set in the audit log entry for this action.

func (*GuildResource) ModifyWithReason added in v0.11.0

func (r *GuildResource) ModifyWithReason(ctx context.Context, settings *guild.Settings, reason string) (*Guild, error)

ModifyWithReason modifies the guild's settings. Requires the 'MANAGE_GUILD' permission. Returns the updated guild on success. Fires a Guild Update Gateway event. The given reason will be set in the audit log entry for this action.

func (*GuildResource) NewChannel

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

NewChannel is like NewChannelWithReason but with no particular reason.

func (*GuildResource) NewChannelWithReason added in v0.11.0

func (r *GuildResource) NewChannelWithReason(ctx context.Context, settings *channel.Settings, reason string) (*Channel, error)

NewChannelWithReason creates a new channel in the guild. Requires the MANAGE_CHANNELS permission. Fires a Channel Create Gateway event. The given reason will be set in the audit log entry for this action.

func (*GuildResource) NewEmoji

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

NewEmoji is like NewEmojiWithReason but with no particular reason.

func (*GuildResource) NewEmojiWithReason added in v0.11.0

func (r *GuildResource) NewEmojiWithReason(ctx context.Context, name, image string, roles []string, reason string) (*Emoji, error)

NewEmojiWithReason 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. The given reason will be set in the audit log entry for this action.

func (*GuildResource) NewRole

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

NewRole is like NewRoleWithReason but with no particular reason.

func (*GuildResource) NewRoleWithReason added in v0.11.0

func (r *GuildResource) NewRoleWithReason(ctx context.Context, settings *role.Settings, reason string) (*Role, error)

NewRole creates a new role for the guild. Requires the 'MANAGE_ROLES' permission. Fires a Guild Role Create Gateway event. The given reason will be set in the audit log entry for this action.

func (*GuildResource) PruneCount

func (r *GuildResource) PruneCount(ctx context.Context, 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

func (r *GuildResource) RemoveIntegration(ctx context.Context, 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

func (r *GuildResource) RemoveMember(ctx context.Context, userID string) error

RemoveMember is like RemoveMemberWithReason but with no particular reason.

func (*GuildResource) RemoveMemberRole

func (r *GuildResource) RemoveMemberRole(ctx context.Context, 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) RemoveMemberWithReason added in v0.11.0

func (r *GuildResource) RemoveMemberWithReason(ctx context.Context, userID, reason string) error

RemoveMember removes the given user from the guild. Requires 'KICK_MEMBERS' permission. Fires a Guild Member Remove Gateway event. The given reason will be set in the audit log entry for this action.

func (*GuildResource) RequestGuildMembers

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

func (r *GuildResource) Roles(ctx context.Context) ([]Role, error)

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

func (*GuildResource) SyncIntegration

func (r *GuildResource) SyncIntegration(ctx context.Context, id string) error

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

func (*GuildResource) Unban

func (r *GuildResource) Unban(ctx context.Context, userID string) error

Unban is like UnbanWithReason but with no particular reason.

func (*GuildResource) UnbanWithReason added in v0.11.0

func (r *GuildResource) UnbanWithReason(ctx context.Context, userID, reason string) error

Unban removes the ban for a user. Requires the 'BAN_MEMBERS' permissions. Fires a Guild Ban Remove Gateway event. The given reason will be set in the audit log entry for this action.

func (*GuildResource) VanityURL

func (r *GuildResource) VanityURL(ctx context.Context) (*Invite, error)

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

func (*GuildResource) VoiceRegions

func (r *GuildResource) VoiceRegions(ctx context.Context) ([]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

func (r *GuildResource) Webhooks(ctx context.Context) ([]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

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

func (r *InviteResource) Delete(ctx context.Context, reason string) (*Invite, error)

Delete is like DeleteWithReason but with no particular reason.

func (*InviteResource) DeleteWithReason added in v0.11.0

func (r *InviteResource) DeleteWithReason(ctx context.Context, reason string) (*Invite, error)

DeleteWithReason deletes the invite. Requires the MANAGE_CHANNELS permission. Returns the deleted invite on success. The given reason will be set in the audit log entry for this action.

func (*InviteResource) Get

func (r *InviteResource) Get(ctx context.Context, 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 is set to true if '@everyone' or '@here'
	// is set in the message's content.
	MentionEveryone bool `json:"mention_everyone"`
	// Mentions contains an array of users that where mentioned
	// in the message's content.
	Mentions []User `json:"mentions"`
	// MentionRoles contains an array of IDs of te roles that
	// were mentioned in the message's content.
	MentionRoles []string      `json:"mention_roles"`
	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(ctx context.Context, 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 MessageOption added in v0.9.0

type MessageOption func(*createMessage)

MessageOption allows to customize the content of a message.

func WithContent added in v0.9.0

func WithContent(text string) MessageOption

WithContent sets the content of a message, up to 2000 characters

func WithEmbed added in v0.9.0

func WithEmbed(e *embed.Embed) MessageOption

WithEmbed sets the embed of a message. See embed sub package for more information about embeds.

func WithFiles added in v0.9.0

func WithFiles(files ...*File) MessageOption

WithFiles attach files to a message.

func WithNonce added in v0.9.0

func WithNonce(n string) MessageOption

WithNonce sets the nonce of a message. The nonce will be returned in the result and also transmitted to other clients.

func WithTTS added in v0.9.0

func WithTTS() MessageOption

WithTTS enables text to speech for a message.

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

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

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

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

func (u *User) Clone() *User

Clone returns a clone of this User.

type ValidationError added in v0.7.0

type ValidationError struct {
	HTTPCode int
	Errors   map[string][]string
}

ValidationError is a validation error returned by the Discord HTTP API when it receives invalid parameters.

func (ValidationError) Error added in v0.7.0

func (e ValidationError) Error() string

Error implements the error interface.

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

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(ctx context.Context, 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(ctx context.Context, 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

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

func (r *WebhookResource) Delete(ctx context.Context) error

Delete is like DeleteWithReason but with no particular reason.

func (*WebhookResource) DeleteWithReason added in v0.11.0

func (r *WebhookResource) DeleteWithReason(ctx context.Context, reason string) error

DeleteWithReason deletes the webhook. The given reason will be set in the audit log entry for this action.

func (*WebhookResource) Get

func (r *WebhookResource) Get(ctx context.Context) (*Webhook, error)

Get returns the webhook.

func (*WebhookResource) Modify

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

Modify is like ModifyWithReason but with no particular reason.

func (*WebhookResource) ModifyWithReason added in v0.11.0

func (r *WebhookResource) ModifyWithReason(ctx context.Context, settings *webhook.Settings, reason string) (*Webhook, error)

ModifyWithReason modifies the webhook. Requires the 'MANAGE_WEBHOOKS' permission. The given reason will be set in the audit log entry for this action.

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