disgord

package module
v0.20.6 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2020 License: BSD-3-Clause Imports: 33 Imported by: 90

README

About

Go module with context support that handles some of the difficulties from interacting with Discord's bot interface for you; websocket sharding, auto-scaling of websocket connections, advanced caching, helper functions, middlewares and lifetime controllers for event handlers, etc.

Warning

Remember to read the docs/code for whatever version of disgord you are using. This README file tries reflects the latest state in the develop branch.

By default DM capabilities are disabled. If you want to activate these, or some, specify their related intent.

client := disgord.New(disgord.Config{
    Intents: disgord.IntentDirectMessages | disgord.IntentDirectMessageReactions | disgord.IntentDirectMessageTyping,
})

Data types & tips

  • Use disgord.Snowflake, not snowflake.Snowflake.
  • Use disgord.Time, not time.Time when dealing with Discord timestamps.

Starter guide

This project uses Go Modules for dealing with dependencies, remember to activate module support in your IDE

Examples can be found in docs/examples and some open source projects Disgord projects in the wiki

I highly suggest reading the Discord API documentation and the Disgord go doc.

Simply use this github template to create your first new bot!

Architecture & Behavior

Discord provide communication in different forms. Disgord tackles the main ones, events (ws), voice (udp + ws), and REST calls.

You can think of Disgord as layered, in which case it will look something like: Simple way to think about Disgord architecture from a layered perspective

Events

For Events, Disgord uses the reactor pattern. Every incoming event from Discord is processed and checked if any handler is registered for it, otherwise it's discarded to save time and resource use. Once a desired event is received, Disgord starts up a Go routine and runs all the related handlers in sequence; avoiding locking the need to use mutexes the handlers.

In addition to traditional handlers, Disgord allows you to use Go channels. Note that if you use more than one channel per event, one of the channels will randomly receive the event data; this is how go channels work. It will act as a randomized load balancer.

But before either channels or handlers are triggered, the cache is updated.

REST

The "REST manager", or the httd.Client, handles rate limiting for outgoing requests, and updated the internal logic on responses. All the REST methods are defined on the disgord.Client and checks for issues before the request is sent out.

If the request is a standard GET request, the cache is always checked first to reduce delay, network traffic and load on the Discord servers. And on responses, regardless of the http method, the data is copied into the cache.

Some of the REST methods (updating existing data structures) will use the builder+command pattern. While the remaining will take a simple config struct.

Note: Methods that update a single field, like SetCurrentUserNick, does not use the builder pattern.

// bypasses local cache
client.CurrentUser().Get(disgord.IgnoreCache)
client.Guild(guildID).GetMembers(disgord.IgnoreCache)

// always checks the local cache first
client.CurrentUser().Get()
client.Guild(guildID).GetMembers()

// with cancellation
deadline, _ := context.WithDeadline(context.Background(), time.Now().Add(2*time.Second))
client.CurrentUser().WithContext(deadline).Get()
Voice

Whenever you want the bot to join a voice channel, a websocket and UDP connection is established. So if your bot is currently in 5 voice channels, then you have 5 websocket connections and 5 udp connections open to handle the voice traffic.

Cache

The cache tries to represent the Discord state as accurate as it can. Because of this, the cache is immutable by default. Meaning the does not allow you to reference any cached objects directly, and every incoming and outgoing data of the cache is deep copied.

Contributing

Please see the CONTRIBUTING.md file (Note that it can be useful to read this regardless if you have the time)

You can contribute with pull requests, issues, wiki updates and helping out in the discord servers mentioned above.

To notify about bugs or suggesting enhancements, simply create a issue. The more the better. But be detailed enough that it can be reproduced and please provide logs.

To contribute with code, always create an issue before you open a pull request. This allows automating change logs and releases.

Q&A

NOTE: To see more examples go to the docs/examples folder. See the GoDoc for a in-depth introduction on the various topics.

1. How do I find my bot token and/or add my bot to a server?

Tutorial here: https://github.com/andersfylling/disgord/wiki/Get-bot-token-and-add-it-to-a-server
2. Is there an alternative Go package?

Yes, it's called DiscordGo (https://github.com/bwmarrin/discordgo). Its purpose is to provide a 
minimalistic API wrapper for Discord, it does not handle multiple websocket sharding, scaling, etc. 
behind the scenes such as Disgord does. Currently I do not have a comparison chart of Disgord and 
DiscordGo. But I do want to create one in the future, for now the biggest difference is that 
Disgord does not support self bots.
3. Why make another Discord lib in Go?

I'm trying to take over the world and then become a intergalactic war lord. Have to start somewhere.
4. Does this project re-use any code from DiscordGo?

Yes. See guild.go. The permission consts are pretty much a copy from DiscordGo.
5. Will Disgord support self bots?

No. Self bots are againts ToS and could result in account termination (see
https://support.discord.com/hc/en-us/articles/115002192352-Automated-user-accounts-self-bots-). 
In addition, self bots aren't a part of the official Discord API, meaning support could change at
any time and Disgord could break unexpectedly if this feature were to be added.

Documentation

Overview

Package disgord provides Go bindings for the documented Discord API, and allows for a stateful Client using the Session interface, with the option of a configurable caching system or bypass the built-in caching logic all together.

Getting started

Create a Disgord session to get access to the REST API and socket functionality. In the following example, we listen for new messages and write a "hello" message when our handler function gets fired.

Session interface: https://pkg.go.dev/github.com/andersfylling/disgord?tab=doc#Session

discord := disgord.New(&disgord.Config{
  BotToken: "my-secret-bot-token",
})
defer discord.StayConnectedUntilInterrupted()

// listen for incoming messages and reply with a "hello"
discord.On(event.MessageCreate, func(s disgord.Session, evt *disgord.MessageCreate) {
    msg := evt.Message
    msg.Reply(s, "hello")
})

// If you want some logic to fire when the bot is ready
// (all shards has received their ready event), please use the Ready method.
discord.Ready(func() {
	fmt.Println("READY NOW!")
})

Listen for events using Channels

Disgord also provides the option to listen for events using a channel. The setup is exactly the same as registering a function. Simply define your channel, add buffering if you need it, and register it as a handler in the `.On` method.

msgCreateChan := make(chan *disgord.MessageCreate, 10)
session.On(disgord.EvtMessageCreate, msgCreateChan)

Never close a channel without removing the handler from Disgord. You can't directly call Remove, instead you inject a controller to dictate the handler's lifetime. Since you are the owner of the channel, disgord will never close it for you.

ctrl := &disgord.Ctrl{Channel: msgCreateChan}
session.On(disgord.EvtMessageCreate, msgCreateChan, ctrl)
go func() {
  // close the channel after 20 seconds and safely remove it from Disgord
  // without Disgord trying to send data through it after it has closed
  <- time.After(20 * time.Second)
  ctrl.CloseChannel()
}

Here is what it would look like to use the channel for handling events. Please run this in a go routine unless you know what you are doing.

for {
    var message *disgord.Message
    var status string
    select {
    case evt, alive := <- msgCreateChan
        if !alive {
            return
        }
        msg = evt.Message
        status = "created"
    }

    fmt.Printf("A message from %s was %s\n", msg.Author.Mention(), status)
    // output: "A message from @Anders was created"
}

WebSockets and Sharding

Disgord handles sharding for you automatically; when starting the bot, when discord demands you to scale up your shards (during runtime), etc. It also gives you control over the shard setup in case you want to run multiple instances of Disgord (in these cases you must handle scaling yourself as Disgord can not).

Sharding is done behind the scenes, so you do not need to worry about any settings. Disgord will simply ask Discord for the recommended amount of shards for your bot on startup. However, to set specific amount of shards you can use the `disgord.ShardConfig` to specify a range of valid shard IDs (starts from 0).

starting a bot with exactly 5 shards

client := disgord.New(&disgord.Config{
  ShardConfig: disgord.ShardConfig{
    // this is a copy so u can't manipulate the config later on
    ShardIDs: []uint{0,1,2,3,4},
  },
})

Running multiple instances each with 1 shard (note each instance must use unique shard ids)

client := disgord.New(&disgord.Config{
  ShardConfig: disgord.ShardConfig{
    // this is a copy so u can't manipulate the config later on
    ShardIDs: []uint{0}, // this number must change for each instance. Try to automate this.
    ShardCount: 5, // total of 5 shards, but this disgord instance only has one. AutoScaling is disabled - use OnScalingRequired.
  },
})

Handle scaling options yourself

client := disgord.New(&disgord.Config{
  ShardConfig: disgord.ShardConfig{
    // this is a copy so u can't manipulate it later on
    DisableAutoScaling: true,
    OnScalingRequired: func(shardIDs []uint) (TotalNrOfShards uint, AdditionalShardIDs []uint) {
      // instead of asking discord for exact number of shards recommended
      // this is increased by 50% every time discord complains you don't have enough shards
      // to reduce the number of times you have to scale
      TotalNrOfShards := uint(len(shardIDs) * 1.5)
      for i := len(shardIDs) - 1; i < TotalNrOfShards; i++ {
        AdditionalShardIDs = append(AdditionalShardIDs, i)
      }
      return
    }, // end OnScalingRequired
  }, // end ShardConfig
})

Caching

> Note: if you create a CacheConfig you don't have to set every field.

> Note: Only LFU is supported.

> Note: Lifetime options does not currently work/do anything (yet).

A part of Disgord is the control you have; while this can be a good detail for advanced Users, we recommend beginners to utilise the default configurations (by simply not editing the configuration). Example of configuring the cache:

 discord, err := disgord.NewClient(&disgord.Config{
   BotToken: "my-secret-bot-token",
   CacheDefault: &disgord.CacheConfig{
             Mutable: false, // everything going in and out of the cache is deep copied
				// setting Mutable to true, might break your program as this is experimental and not supported.

             DisableUserCaching: false, // activates caching for Users
             UserCacheLifetime: time.Duration(4) * time.Hour, // removed from cache after 9 hours, unless updated

             DisableVoiceStateCaching: true, // don't cache voice states

             DisableChannelCaching: false,
             ChannelCacheLifetime: 0, // lives forever unless cache replacement strategy kicks in
          },
 })

If you just want to change a specific field, you can do so. The fields are always default values.

> Note: Disabling caching for some types while activating it for others (eg. disabling Channels, but activating guild caching), can cause items extracted from the cache to not reflect the true discord state.

Example, activated guild but disabled channel caching: The guild is stored to the cache, but it's Channels are discarded. Guild Channels are dismantled from the guild object and otherwise stored in the channel cache to improve performance and reduce memory use. So when you extract the cached guild object, all of the channel will only hold their channel ID, and nothing more.

Immutable cache

To keep it safe and reliable, you can not directly affect the contents of the cache. Unlike discordgo where everything is mutable, the caching in disgord is immutable. This does reduce performance as a copy must be made (only on new cache entries), but as a performance freak, I can tell you right now that a simple struct copy is not that expensive. This also means that, as long as discord sends their events properly, the caching will always reflect the true state of discord.

If there is a bug in the cache and you keep getting the incorrect data, please file an issue at github.com/andersfylling/disgord so it can quickly be resolved(!)

Bypass the built-in REST cache

Whenever you call a REST method from the Session interface; the cache is always checked first. Upon a cache hit, no REST request is executed and you get the data from the cache in return. However, if this is problematic for you or there exist a bug which gives you bad/outdated data, you can bypass it by using Disgord flags.

// get a user using the Session implementation (checks cache, and updates the cache on cache miss)
user, err := session.GetUser(userID)

// bypass the cache checking. Same as before, but we insert a disgord.Flag type.
user, err := session.GetUser(userID, disgord.IgnoreCache)

Disgord Flags

In addition to disgord.IgnoreCache, as shown above, you can pass in other flags such as: disgord.SortByID, disgord.OrderAscending, etc. You can find these flags in the flag.go file.

Build tags

`disgord_diagnosews` will store all the incoming and outgoing JSON data as files in the directory "diagnose-report/packets". The file format is as follows: unix_clientType_direction_shardID_operationCode_sequenceNumber[_eventName].json

`json_std` switches out jsoniter with the json package from the std libs.

`disgord_removeDiscordMutex` replaces mutexes in discord structures with a empty mutex; removes locking behaviour and any mutex code when compiled.

`disgord_parallelism` activates built-in locking in discord structure methods. Eg. Guild.AddChannel(*Channel) does not do locking by default. But if you find yourself using these discord data structures in parallel environment, you can activate the internal locking to reduce race conditions. Note that activating `disgord_parallelism` and `disgord_removeDiscordMutex` at the same time, will cause you to have no locking as `disgord_removeDiscordMutex` affects the same mutexes.

`disgord_legacy` adds wrapper methods with the original discord naming. eg. For REST requests you will notice Disgord uses a consistency between update/create/get/delete/set while discord uses edit/update/modify/close/delete/remove/etc. So if you struggle find a REST method, you can enable this build tag to gain access to mentioned wrappers.

`disgordperf` does some low level tweaking that can help boost json unmarshalling and drops json validation from Discord responses/events. Other optimizations might take place as well.

`disgord_websocket_gorilla` replaces nhooyr/websocket dependency with gorilla/websocket for gateway communication.

Deleting Discord data

In addition to the typical REST endpoints for deleting data, you can also use Client/Session.DeleteFromDiscord(...) for basic deletions. If you need to delete a specific range of messages, or anything complex as that; you can't use .DeleteFromDiscord(...). Not every struct has implemented the interface that allows you to call DeleteFromDiscord. Do not fret, if you try to pass a type that doesn't qualify, you get a compile error.

Index

Constants

View Source
const (
	ChannelTypeGuildText uint = iota
	ChannelTypeDM
	ChannelTypeGuildVoice
	ChannelTypeGroupDM
	ChannelTypeGuildCategory
	ChannelTypeGuildNews
	ChannelTypeGuildStore
)

Channel types https://discord.com/developers/docs/resources/channel#channel-object-channel-types

View Source
const (
	PermissionOverwriteTypeRole uint8 = iota
	PermissionOverwriteTypeMember
)
View Source
const (
	// GatewayCmdRequestGuildMembers Used to request offline members for a guild or
	// a list of Guilds. 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.
	RequestGuildMembers gatewayCmdName = cmd.RequestGuildMembers

	// UpdateVoiceState Sent when a Client wants to join, move, or
	// disconnect from a voice channel.
	UpdateVoiceState gatewayCmdName = cmd.UpdateVoiceState

	// UpdateStatus Sent by the Client to indicate a presence or status
	// update.
	UpdateStatus gatewayCmdName = cmd.UpdateStatus
)
View Source
const (
	StatusOnline  = string(gateway.StatusOnline)
	StatusOffline = string(gateway.StatusOffline)
	StatusDnd     = string(gateway.StatusDND)
	StatusIdle    = string(gateway.StatusIdle)
)

Constants for the different bit offsets of general permissions

View Source
const (
	IntentDirectMessageReactions = gateway.IntentDirectMessageReactions
	IntentDirectMessageTyping    = gateway.IntentDirectMessageTyping
	IntentDirectMessages         = gateway.IntentDirectMessages
	IntentGuildBans              = gateway.IntentGuildBans
	IntentGuildEmojis            = gateway.IntentGuildEmojis
	IntentGuildIntegrations      = gateway.IntentGuildIntegrations
	IntentGuildInvites           = gateway.IntentGuildInvites
	IntentGuildMembers           = gateway.IntentGuildMembers
	IntentGuildMessageReactions  = gateway.IntentGuildMessageReactions
	IntentGuildMessageTyping     = gateway.IntentGuildMessageTyping
	IntentGuildMessages          = gateway.IntentGuildMessages
	IntentGuildPresences         = gateway.IntentGuildPresences
	IntentGuildVoiceStates       = gateway.IntentGuildVoiceStates
	IntentGuildWebhooks          = gateway.IntentGuildWebhooks
	IntentGuilds                 = gateway.IntentGuilds
)
View Source
const (
	MessageActivityTypeJoin
	MessageActivityTypeSpectate
	MessageActivityTypeListen
	MessageActivityTypeJoinRequest
)

different message acticity types

View Source
const (
	ActivityTypeGame acitivityType = iota
	ActivityTypeStreaming
	ActivityTypeListening

	ActivityTypeCustom
)
View Source
const (
	ActivityFlagInstance activityFlag = 1 << iota
	ActivityFlagJoin
	ActivityFlagSpectate
	ActivityFlagJoinRequest
	ActivityFlagSync
	ActivityFlagPlay
)

flags for the Activity object to signify the type of action taken place

View Source
const (
	AttachmentSpoilerPrefix = "SPOILER_"
)
View Source
const EvtChannelCreate = event.ChannelCreate

EvtChannelCreate Sent when a new channel is created, relevant to the current user. The inner payload is a DM channel or guild channel object.

View Source
const EvtChannelDelete = event.ChannelDelete

EvtChannelDelete Sent when a channel relevant to the current user is deleted. The inner payload is a DM or Guild channel object.

View Source
const EvtChannelPinsUpdate = event.ChannelPinsUpdate

EvtChannelPinsUpdate Sent when a message is pinned or unpinned in a text channel. This is not sent when a pinned message is deleted.

Fields:
- ChannelID int64 or Snowflake
- LastPinTimestamp time.Now().UTC().Format(time.RFC3339)

TODO fix.

View Source
const EvtChannelUpdate = event.ChannelUpdate

EvtChannelUpdate Sent when a channel is updated. The inner payload is a guild channel object.

View Source
const EvtGuildBanAdd = event.GuildBanAdd

EvtGuildBanAdd Sent when a user is banned from a guild. The inner payload is a user object, with an extra guild_id key.

View Source
const EvtGuildBanRemove = event.GuildBanRemove

EvtGuildBanRemove Sent when a user is unbanned from a guild. The inner payload is a user object, with an extra guild_id key.

View Source
const EvtGuildCreate = event.GuildCreate

EvtGuildCreate 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.
View Source
const EvtGuildDelete = event.GuildDelete

EvtGuildDelete Sent when a guild becomes unavailable during a guild outage, or when the user leaves or is removed from a guild. The inner payload is an unavailable guild object. If the unavailable field is not set, the user was removed from the guild.

View Source
const EvtGuildEmojisUpdate = event.GuildEmojisUpdate

EvtGuildEmojisUpdate Sent when a guild's emojis have been updated.

Fields:
- GuildID Snowflake
- Emojis []*Emoji
View Source
const EvtGuildIntegrationsUpdate = event.GuildIntegrationsUpdate

EvtGuildIntegrationsUpdate Sent when a guild integration is updated.

Fields:
- GuildID Snowflake
View Source
const EvtGuildMemberAdd = event.GuildMemberAdd

EvtGuildMemberAdd Sent when a new user joins a guild. The inner payload is a guild member object with these extra fields:

  • GuildID Snowflake

    Fields:

  • Member *Member

View Source
const EvtGuildMemberRemove = event.GuildMemberRemove

EvtGuildMemberRemove Sent when a user is removed from a guild (leave/kick/ban).

Fields:
- GuildID   Snowflake
- User      *User
View Source
const EvtGuildMemberUpdate = event.GuildMemberUpdate

EvtGuildMemberUpdate Sent when a guild member is updated.

Fields:
- GuildID   Snowflake
- Roles     []Snowflake
- User      *User
- Nick      string
View Source
const EvtGuildMembersChunk = event.GuildMembersChunk

EvtGuildMembersChunk Sent in response to Gateway Request Guild Members.

Fields:
- GuildID Snowflake
- Members []*Member
View Source
const EvtGuildRoleCreate = event.GuildRoleCreate

EvtGuildRoleCreate Sent when a guild role is created.

Fields:
- GuildID   Snowflake
- Role      *Role
View Source
const EvtGuildRoleDelete = event.GuildRoleDelete

EvtGuildRoleDelete Sent when a guild role is created.

Fields:
- GuildID Snowflake
- RoleID  Snowflake
View Source
const EvtGuildRoleUpdate = event.GuildRoleUpdate

EvtGuildRoleUpdate Sent when a guild role is created.

Fields:
- GuildID Snowflake
- Role    *Role
View Source
const EvtGuildUpdate = event.GuildUpdate

EvtGuildUpdate Sent when a guild is updated. The inner payload is a guild object.

View Source
const EvtInviteCreate = event.InviteCreate

EvtInviteCreate Sent when a guild's invite is created.

Fields:
- Code String
- GuildID   Snowflake
- ChannelID Snowflake
- Inviter *User
- Inviter *User
- Target *User
- TargetType int
- CreatedAt Time
- MaxAge int
- MaxUses int
- Temporary bool
- Uses int
- Revoked bool
- Unique bool
- ApproximatePresenceCount int
- ApproximateMemberCount int
View Source
const EvtInviteDelete = event.InviteDelete

EvtInviteDelete Sent when an invite is deleted.

View Source
const EvtMessageCreate = event.MessageCreate

EvtMessageCreate Sent when a message is created. The inner payload is a message object.

View Source
const EvtMessageDelete = event.MessageDelete

EvtMessageDelete Sent when a message is deleted.

Fields:
- ID        Snowflake
- ChannelID Snowflake
View Source
const EvtMessageDeleteBulk = event.MessageDeleteBulk

EvtMessageDeleteBulk Sent when multiple messages are deleted at once.

Fields:
- IDs       []Snowflake
- ChannelID Snowflake
View Source
const EvtMessageReactionAdd = event.MessageReactionAdd

EvtMessageReactionAdd Sent when a user adds a reaction to a message.

Fields:
- UserID     Snowflake
- ChannelID  Snowflake
- MessageID  Snowflake
- Emoji      *Emoji
View Source
const EvtMessageReactionRemove = event.MessageReactionRemove

EvtMessageReactionRemove Sent when a user removes a reaction from a message.

Fields:
- UserID     Snowflake
- ChannelID  Snowflake
- MessageID  Snowflake
- Emoji      *Emoji
View Source
const EvtMessageReactionRemoveAll = event.MessageReactionRemoveAll

EvtMessageReactionRemoveAll Sent when a user explicitly removes all reactions from a message.

Fields:
- ChannelID Snowflake
- MessageID Snowflake
View Source
const EvtMessageReactionRemoveEmoji = event.MessageReactionRemoveEmoji

EvtMessageReactionRemoveEmoji Sent when a bot removes all instances of a given emoji from the reactions of a message.

View Source
const EvtMessageUpdate = event.MessageUpdate

EvtMessageUpdate Sent when a message is updated. The inner payload is a message object.

NOTE! Has _at_least_ the GuildID and ChannelID fields.

View Source
const EvtPresenceUpdate = event.PresenceUpdate

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

Fields:
- User    *User
- Roles   []Snowflake
- Game    *Activity
- GuildID Snowflake
- Status  string
View Source
const EvtReady = event.Ready

EvtReady The ready event is dispatched when a client has completed the initial handshake with the gateway (for new sessions). // The ready event can be the largest and most complex event the gateway will send, as it contains all the state // required for a client to begin interacting with the rest of the platform. // Fields: // - V int // - User *User // - PrivateChannels []*Channel // - Guilds []*GuildUnavailable // - SessionID string // - Trace []string

View Source
const EvtResumed = event.Resumed

EvtResumed The resumed event is dispatched when a client has sent a resume payload to the gateway (for resuming existing sessions).

Fields:
- Trace []string
View Source
const EvtTypingStart = event.TypingStart

EvtTypingStart Sent when a user starts typing in a channel.

Fields:
- ChannelID     Snowflake
- UserID        Snowflake
- TimestampUnix int
View Source
const EvtUserUpdate = event.UserUpdate

EvtUserUpdate Sent when properties about the user change. Inner payload is a user object.

View Source
const EvtVoiceServerUpdate = event.VoiceServerUpdate

EvtVoiceServerUpdate Sent when a guild's voice server is updated. This is sent when initially connecting to voice, and when the current voice instance fails over to a new server.

Fields:
- Token     string
- ChannelID Snowflake
- Endpoint  string
View Source
const EvtVoiceStateUpdate = event.VoiceStateUpdate

EvtVoiceStateUpdate Sent when someone joins/leaves/moves voice channels. Inner payload is a voice state object.

View Source
const EvtWebhooksUpdate = event.WebhooksUpdate

EvtWebhooksUpdate Sent when a guild channel's WebHook is created, updated, or deleted.

Fields:
- GuildID   Snowflake
- ChannelID Snowflake
View Source
const Name = constant.Name
View Source
const Version = constant.Version

Variables

This section is empty.

Functions

func AllEvents added in v0.14.2

func AllEvents(except ...string) []string

func AllIntents added in v0.17.0

func AllIntents(except ...gateway.Intent) gateway.Intent

func CreateTermSigListener added in v0.16.3

func CreateTermSigListener() <-chan os.Signal

CreateTermSigListener create a channel to listen for termination signals (graceful shutdown)

func LibraryInfo added in v0.4.0

func LibraryInfo() string

LibraryInfo returns name + version

func ShardID added in v0.12.0

func ShardID(guildID Snowflake, nrOfShards uint) uint

ShardID calculate the shard id for a given guild. https://discord.com/developers/docs/topics/gateway#sharding-sharding-formula

func Sort added in v0.10.0

func Sort(v interface{}, fs ...Flag)

func ValidateHandlerInputs added in v0.10.0

func ValidateHandlerInputs(inputs ...interface{}) (err error)

func ValidateUsername added in v0.8.0

func ValidateUsername(name string) (err error)

ValidateUsername uses Discords rule-set to verify user-names and nicknames https://discord.com/developers/docs/resources/user#usernames-and-nicknames

Note that not all the rules are listed in the docs:

There are other rules and restrictions not shared here for the sake of spam and abuse mitigation, but the
majority of Users won't encounter them. It's important to properly handle all error messages returned by
Discord when editing or updating names.

Types

type Activity added in v0.8.0

type Activity struct {
	Name          string             `json:"name"`                     // the activity's name
	Type          acitivityType      `json:"type"`                     // activity type
	URL           string             `json:"url,omitempty"`            //stream url, is validated when type is 1
	Timestamps    *ActivityTimestamp `json:"timestamps,omitempty"`     // timestamps object	unix timestamps for start and/or end of the game
	ApplicationID Snowflake          `json:"application_id,omitempty"` //?	snowflake	application id for the game
	Details       string             `json:"details,omitempty"`        //?	?string	what the player is currently doing
	State         string             `json:"state,omitempty"`          //state?	?string	the user's current party status
	Emoji         *ActivityEmoji     `json:"emoji"`
	Party         *ActivityParty     `json:"party,omitempty"`    //party?	party object	information for the current party of the player
	Assets        *ActivityAssets    `json:"assets,omitempty"`   // assets?	assets object	images for the presence and their hover texts
	Secrets       *ActivitySecrets   `json:"secrets,omitempty"`  // secrets?	secrets object	secrets for Rich Presence joining and spectating
	Instance      bool               `json:"instance,omitempty"` // instance?	boolean	whether or not the activity is an instanced game session
	Flags         activityFlag       `json:"flags,omitempty"`    // flags?	int	activity flags ORd together, describes what the payload includes
}

Activity https://discord.com/developers/docs/topics/gateway#activity-object-activity-structure

func (*Activity) CopyOverTo added in v0.8.0

func (a *Activity) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*Activity) DeepCopy added in v0.8.0

func (a *Activity) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

func (*Activity) Reset added in v0.10.0

func (a *Activity) Reset()

type ActivityAssets added in v0.7.0

type ActivityAssets struct {
	LargeImage string `json:"large_image,omitempty"` // the id for a large asset of the activity, usually a snowflake
	LargeText  string `json:"large_text,omitempty"`  //text displayed when hovering over the large image of the activity
	SmallImage string `json:"small_image,omitempty"` // the id for a small asset of the activity, usually a snowflake
	SmallText  string `json:"small_text,omitempty"`  //	text displayed when hovering over the small image of the activity
}

ActivityAssets ...

func (*ActivityAssets) CopyOverTo added in v0.7.0

func (a *ActivityAssets) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*ActivityAssets) DeepCopy added in v0.7.0

func (a *ActivityAssets) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type ActivityEmoji added in v0.14.1

type ActivityEmoji struct {
	Name     string    `json:"name"`
	ID       Snowflake `json:"id,omitempty"`
	Animated bool      `json:"animated,omitempty"`
}

ActivityEmoji ...

type ActivityParty added in v0.7.0

type ActivityParty struct {
	ID   string `json:"id,omitempty"`   // the id of the party
	Size []int  `json:"size,omitempty"` // used to show the party's current and maximum size
}

ActivityParty ...

func (*ActivityParty) CopyOverTo added in v0.7.0

func (ap *ActivityParty) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*ActivityParty) DeepCopy added in v0.7.0

func (ap *ActivityParty) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

func (*ActivityParty) Limit added in v0.7.0

func (ap *ActivityParty) Limit() int

Limit shows the maximum number of guests/people allowed

func (*ActivityParty) NumberOfPeople added in v0.7.0

func (ap *ActivityParty) NumberOfPeople() int

NumberOfPeople shows the current number of people attending the Party

type ActivitySecrets added in v0.7.0

type ActivitySecrets struct {
	Join     string `json:"join,omitempty"`     // the secret for joining a party
	Spectate string `json:"spectate,omitempty"` // the secret for spectating a game
	Match    string `json:"match,omitempty"`    // the secret for a specific instanced match
}

ActivitySecrets ...

func (*ActivitySecrets) CopyOverTo added in v0.7.0

func (a *ActivitySecrets) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*ActivitySecrets) DeepCopy added in v0.7.0

func (a *ActivitySecrets) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type ActivityTimestamp added in v0.7.0

type ActivityTimestamp struct {
	Start int `json:"start,omitempty"` // unix time (in milliseconds) of when the activity started
	End   int `json:"end,omitempty"`   // unix time (in milliseconds) of when the activity ends
}

ActivityTimestamp ...

func (*ActivityTimestamp) CopyOverTo added in v0.7.0

func (a *ActivityTimestamp) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*ActivityTimestamp) DeepCopy added in v0.7.0

func (a *ActivityTimestamp) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type AddGuildMemberParams added in v0.6.0

type AddGuildMemberParams struct {
	AccessToken string      `json:"access_token"` // required
	Nick        string      `json:"nick,omitempty"`
	Roles       []Snowflake `json:"roles,omitempty"`
	Mute        bool        `json:"mute,omitempty"`
	Deaf        bool        `json:"deaf,omitempty"`
}

AddGuildMemberParams ... https://discord.com/developers/docs/resources/guild#add-guild-member-json-params

type AllowedMentions added in v0.19.0

type AllowedMentions struct {
	Parse []string `json:"parse"` // this is purposefully not marked as omitempty as to allow `parse: []` which blocks all mentions.

	Roles []Snowflake `json:"roles,omitempty"`
	Users []Snowflake `json:"users,omitempty"`
}

AllowedMentions allows finer control over mentions in a message, see https://discord.com/developers/docs/resources/channel#allowed-mentions-object for more info. Any strings in the Parse value must be any from ["everyone", "users", "roles"].

type Attachment added in v0.6.0

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

	SpoilerTag bool `json:"-"`
}

Attachment https://discord.com/developers/docs/resources/channel#attachment-object

func (*Attachment) DeepCopy added in v0.8.0

func (a *Attachment) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type AuditLog added in v0.6.0

type AuditLog struct {
	Webhooks        []*Webhook       `json:"webhooks"`
	Users           []*User          `json:"users"`
	AuditLogEntries []*AuditLogEntry `json:"audit_log_entries"`
}

AuditLog ...

func (*AuditLog) Bans added in v0.10.0

func (l *AuditLog) Bans() (bans []*PartialBan)

func (*AuditLog) CopyOverTo added in v0.7.0

func (l *AuditLog) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*AuditLog) DeepCopy added in v0.7.0

func (l *AuditLog) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type AuditLogChange added in v0.6.0

type AuditLogChange string
const (
	// key name,								          identifier                       changed, type,   description
	AuditLogChangeName                        AuditLogChange = "name"                          // guild	string	name changed
	AuditLogChangeIconHash                    AuditLogChange = "icon_hash"                     // guild	string	icon changed
	AuditLogChangeSplashHash                  AuditLogChange = "splash_hash"                   // guild	string	invite splash page artwork changed
	AuditLogChangeOwnerID                     AuditLogChange = "owner_id"                      // guild	snowflake	owner changed
	AuditLogChangeRegion                      AuditLogChange = "region"                        // guild	string	region changed
	AuditLogChangeAFKChannelID                AuditLogChange = "afk_channel_id"                // guild	snowflake	afk channel changed
	AuditLogChangeAFKTimeout                  AuditLogChange = "afk_timeout"                   // guild	integer	afk timeout duration changed
	AuditLogChangeMFALevel                    AuditLogChange = "mfa_level"                     // guild	integer	two-factor auth requirement changed
	AuditLogChangeVerificationLevel           AuditLogChange = "verification_level"            // guild	integer	required verification level changed
	AuditLogChangeExplicitContentFilter       AuditLogChange = "explicit_content_filter"       // guild	integer	change in whose messages are scanned and deleted for explicit content in the server
	AuditLogChangeDefaultMessageNotifications AuditLogChange = "default_message_notifications" // guild	integer	default message notification level changed
	AuditLogChangeVanityURLCode               AuditLogChange = "vanity_url_code"               // guild	string	guild invite vanity url changed
	AuditLogChangeAdd                         AuditLogChange = "$add"                          // add	guild	array of role objects	new role added
	AuditLogChangeRemove                      AuditLogChange = "$remove"                       // remove	guild	array of role objects	role removed
	AuditLogChangePruneDeleteDays             AuditLogChange = "prune_delete_days"             // guild	integer	change in number of days after which inactive and role-unassigned members are kicked
	AuditLogChangeWidgetEnabled               AuditLogChange = "widget_enabled"                // guild	bool	server widget enabled/disable
	AuditLogChangeWidgetChannelID             AuditLogChange = "widget_channel_id"             // guild	snowflake	channel id of the server widget changed
	AuditLogChangePosition                    AuditLogChange = "position"                      // channel	integer	text or voice channel position changed
	AuditLogChangeTopic                       AuditLogChange = "topic"                         // channel	string	text channel topic changed
	AuditLogChangeBitrate                     AuditLogChange = "bitrate"                       // channel	integer	voice channel bitrate changed
	AuditLogChangePermissionOverwrites        AuditLogChange = "permission_overwrites"         // channel	array of channel overwrite objects	permissions on a channel changed
	AuditLogChangeNSFW                        AuditLogChange = "nsfw"                          // channel	bool	channel nsfw restriction changed
	AuditLogChangeApplicationID               AuditLogChange = "application_id"                // channel	snowflake	application id of the added or removed webhook or bot
	AuditLogChangePermissions                 AuditLogChange = "permissions"                   // role	integer	permissions for a role changed
	AuditLogChangeColor                       AuditLogChange = "color"                         // role	integer	role color changed
	AuditLogChangeHoist                       AuditLogChange = "hoist"                         // role	bool	role is now displayed/no longer displayed separate from online users
	AuditLogChangeMentionable                 AuditLogChange = "mentionable"                   // role	bool	role is now mentionable/unmentionable
	AuditLogChangeAllow                       AuditLogChange = "allow"                         // role	integer	a permission on a text or voice channel was allowed for a role
	AuditLogChangeDeny                        AuditLogChange = "deny"                          // role	integer	a permission on a text or voice channel was denied for a role
	AuditLogChangeCode                        AuditLogChange = "code"                          // invite	string	invite code changed
	AuditLogChangeChannelID                   AuditLogChange = "channel_id"                    // invite	snowflake	channel for invite code changed
	AuditLogChangeInviterID                   AuditLogChange = "inviter_id"                    // invite	snowflake	person who created invite code changed
	AuditLogChangeMaxUses                     AuditLogChange = "max_uses"                      // invite	integer	change to max number of times invite code can be used
	AuditLogChangeUses                        AuditLogChange = "uses"                          // invite	integer	number of times invite code used changed
	AuditLogChangeMaxAge                      AuditLogChange = "max_age"                       // invite	integer	how long invite code lasts changed
	AuditLogChangeTemporary                   AuditLogChange = "temporary"                     // invite	bool	invite code is temporary/never expires
	AuditLogChangeDeaf                        AuditLogChange = "deaf"                          // user	bool	user server deafened/undeafened
	AuditLogChangeMute                        AuditLogChange = "mute"                          // user	bool	user server muted/unmuteds
	AuditLogChangeNick                        AuditLogChange = "nick"                          // user	string	user nickname changed
	AuditLogChangeAvatarHash                  AuditLogChange = "avatar_hash"                   // user	string	user avatar changed
	AuditLogChangeID                          AuditLogChange = "id"                            // any	snowflake	the id of the changed entity - sometimes used in conjunction with other keys
	AuditLogChangeType                        AuditLogChange = "type"                          // any	integer (channel type) or string	type of entity created
)

all the different keys for an audit log change

type AuditLogChanges added in v0.10.0

type AuditLogChanges struct {
	NewValue interface{} `json:"new_value,omitempty"`
	OldValue interface{} `json:"old_value,omitempty"`
	Key      string      `json:"key"`
}

AuditLogChanges ...

func (*AuditLogChanges) CopyOverTo added in v0.10.0

func (l *AuditLogChanges) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*AuditLogChanges) DeepCopy added in v0.10.0

func (l *AuditLogChanges) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type AuditLogEntry added in v0.6.0

type AuditLogEntry struct {
	TargetID Snowflake          `json:"target_id"`
	Changes  []*AuditLogChanges `json:"changes,omitempty"`
	UserID   Snowflake          `json:"user_id"`
	ID       Snowflake          `json:"id"`
	Event    AuditLogEvt        `json:"action_type"`
	Options  *AuditLogOption    `json:"options,omitempty"`
	Reason   string             `json:"reason,omitempty"`
}

AuditLogEntry ...

func (*AuditLogEntry) CopyOverTo added in v0.7.0

func (l *AuditLogEntry) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*AuditLogEntry) DeepCopy added in v0.7.0

func (l *AuditLogEntry) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type AuditLogEvt added in v0.10.0

type AuditLogEvt uint
const (
	AuditLogEvtChannelCreate AuditLogEvt = 10 + iota
	AuditLogEvtChannelUpdate
	AuditLogEvtChannelDelete
	AuditLogEvtOverwriteCreate
	AuditLogEvtOverwriteUpdate
	AuditLogEvtOverwriteDelete
)
const (
	AuditLogEvtMemberKick AuditLogEvt = 20 + iota
	AuditLogEvtMemberPrune
	AuditLogEvtMemberBanAdd
	AuditLogEvtMemberBanRemove
	AuditLogEvtMemberUpdate
	AuditLogEvtMemberRoleUpdate
	AuditLogEvtMemberMove
	AuditLogEvtMemberDisconnect
	AuditLogEvtBotAdd
)
const (
	AuditLogEvtRoleCreate AuditLogEvt = 30 + iota
	AuditLogEvtRoleUpdate
	AuditLogEvtRoleDelete
)
const (
	AuditLogEvtInviteCreate AuditLogEvt = 40
	AuditLogEvtInviteUpdate
	AuditLogEvtInviteDelete
)
const (
	AuditLogEvtWebhookCreate AuditLogEvt = 50 + iota
	AuditLogEvtWebhookUpdate
	AuditLogEvtWebhookDelete
)
const (
	AuditLogEvtEmojiCreate AuditLogEvt = 60 + iota
	AuditLogEvtEmojiUpdate
	AuditLogEvtEmojiDelete
)
const (
	AuditLogEvtGuildUpdate AuditLogEvt = 1
)

Audit-log event types

const (
	AuditLogEvtMessageDelete AuditLogEvt = 72
)

type AuditLogOption added in v0.6.0

type AuditLogOption struct {
	DeleteMemberDays string    `json:"delete_member_days"`
	MembersRemoved   string    `json:"members_removed"`
	ChannelID        Snowflake `json:"channel_id"`
	Count            string    `json:"count"`
	ID               Snowflake `json:"id"`
	Type             string    `json:"type"` // type of overwritten entity ("member" or "role")
	RoleName         string    `json:"role_name"`
}

AuditLogOption ...

func (*AuditLogOption) CopyOverTo added in v0.7.0

func (l *AuditLogOption) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*AuditLogOption) DeepCopy added in v0.7.0

func (l *AuditLogOption) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type AvatarParamHolder added in v0.8.0

type AvatarParamHolder interface {
	json.Marshaler
	Empty() bool
	SetAvatar(avatar string)
	UseDefaultAvatar()
}

AvatarParamHolder is used when handling avatar related REST structs. since a Avatar can be reset by using nil, it causes some extra issues as omit empty cannot be used to get around this, the struct requires an internal state and must also handle custom marshalling

type Ban added in v0.6.0

type Ban struct {
	Reason string `json:"reason"`
	User   *User  `json:"user"`
}

Ban https://discord.com/developers/docs/resources/guild#ban-object

func (*Ban) CopyOverTo added in v0.7.0

func (b *Ban) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*Ban) DeepCopy added in v0.7.0

func (b *Ban) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type BanMemberParams added in v0.10.0

type BanMemberParams struct {
	DeleteMessageDays int    `urlparam:"delete_message_days,omitempty"` // number of days to delete messages for (0-7)
	Reason            string `urlparam:"reason,omitempty"`              // reason for being banned
}

BanMemberParams ... https://discord.com/developers/docs/resources/guild#create-guild-ban-query-string-params

func (*BanMemberParams) FindErrors added in v0.10.0

func (b *BanMemberParams) FindErrors() error

func (*BanMemberParams) URLQueryString added in v0.10.0

func (b *BanMemberParams) URLQueryString() string

type BasicBuilder added in v0.19.0

type BasicBuilder interface {
	Execute() (err error)
	IgnoreCache() BasicBuilder
	CancelOnRatelimit() BasicBuilder
	URLParam(name string, v interface{}) BasicBuilder
	Set(name string, v interface{}) BasicBuilder
}

BasicBuilder is the interface for the builder.

type Cache added in v0.6.0

type Cache interface {
	CacheUpdater
	CacheGetter
}

Cache interface for event handling and REST methods commented out fields are simply not supported yet. PR's are welcome

Note that on events you are expected to return a unmarshalled object. For delete methods you should return nil, and a nil error if the objected to be deleted was not found (nop!). Note that the error might change to a "CacheMiss" or something similar such that we can

get more metrics!

func NewCacheLFUImmutable added in v0.19.0

func NewCacheLFUImmutable(limitUsers, limitVoiceStates, limitChannels, limitGuilds uint) Cache

type CacheGetter added in v0.19.0

type CacheGetter interface {

	// GetGuildAuditLogs(guildID Snowflake) *guildAuditLogsBuilder // TODO
	GetMessages(channelID Snowflake, params *GetMessagesParams) ([]*Message, error)
	GetMessage(channelID, messageID Snowflake) (ret *Message, err error)
	//GetUsersWhoReacted(channelID, messageID Snowflake, emoji interface{}, params URLQueryStringer) (reactors []*User, err error)
	//GetPinnedMessages(channelID Snowflake) (ret []*Message, err error)
	GetChannel(id Snowflake) (ret *Channel, err error)
	//GetChannelInvites(id Snowflake) (ret []*Invite, err error)
	GetGuildEmoji(guildID, emojiID Snowflake) (*Emoji, error)
	GetGuildEmojis(id Snowflake) ([]*Emoji, error)
	GetGuild(id Snowflake) (*Guild, error)
	GetGuildChannels(id Snowflake) ([]*Channel, error)
	GetMember(guildID, userID Snowflake) (*Member, error)
	GetMembers(guildID Snowflake, params *GetMembersParams) ([]*Member, error)
	//GetGuildBans(id Snowflake) ([]*Ban, error)
	//GetGuildBan(guildID, userID Snowflake) (*Ban, error)
	GetGuildRoles(guildID Snowflake) ([]*Role, error)
	//GetMemberPermissions(guildID, userID Snowflake) (permissions PermissionBit, err error)
	//GetGuildVoiceRegions(id Snowflake) ([]*VoiceRegion, error)
	//GetGuildInvites(id Snowflake) ([]*Invite, error)
	//GetGuildIntegrations(id Snowflake) ([]*Integration, error)
	//GetGuildEmbed(guildID Snowflake) (*GuildEmbed, error)
	//GetGuildVanityURL(guildID Snowflake) (*PartialInvite, error)
	//GetInvite(inviteCode string, params URLQueryStringer) (*Invite, error)
	GetCurrentUser() (*User, error)
	GetUser(id Snowflake) (*User, error)
	GetCurrentUserGuilds(params *GetCurrentUserGuildsParams) (ret []*Guild, err error)
}

type CacheLFUImmutable added in v0.19.0

type CacheLFUImmutable struct {
	CacheNop

	CurrentUserMu sync.Mutex
	CurrentUser   *User

	Users       crs.LFU
	VoiceStates crs.LFU
	Channels    crs.LFU
	Guilds      crs.LFU
	// contains filtered or unexported fields
}

CacheLFUImmutable cache with CRS support for Users and voice states use NewCacheLFUImmutable to instantiate it!

func (*CacheLFUImmutable) ChannelCreate added in v0.19.0

func (c *CacheLFUImmutable) ChannelCreate(data []byte) (*ChannelCreate, error)

func (*CacheLFUImmutable) ChannelDelete added in v0.19.0

func (c *CacheLFUImmutable) ChannelDelete(data []byte) (*ChannelDelete, error)

func (*CacheLFUImmutable) ChannelPinsUpdate added in v0.19.0

func (c *CacheLFUImmutable) ChannelPinsUpdate(data []byte) (*ChannelPinsUpdate, error)

func (*CacheLFUImmutable) ChannelUpdate added in v0.19.0

func (c *CacheLFUImmutable) ChannelUpdate(data []byte) (*ChannelUpdate, error)

func (*CacheLFUImmutable) GetChannel added in v0.19.0

func (c *CacheLFUImmutable) GetChannel(id Snowflake) (*Channel, error)

REST lookup

func (c *CacheLFUImmutable) GetMessage(channelID, messageID Snowflake) (*Message, error) {
	return nil, nil
}
func (c *CacheLFUImmutable) GetCurrentUserGuilds(p *GetCurrentUserGuildsParams) ([]*PartialGuild, error) {
	return nil, nil
}
func (c *CacheLFUImmutable) GetMessages(channel Snowflake, p *GetMessagesParams) ([]*Message, error) {
	return nil, nil
}
func (c *CacheLFUImmutable) GetMembers(guildID Snowflake, p *GetMembersParams) ([]*Member, error) {
	return nil, nil
}

func (*CacheLFUImmutable) GetCurrentUser added in v0.19.0

func (c *CacheLFUImmutable) GetCurrentUser() (*User, error)

func (*CacheLFUImmutable) GetGuild added in v0.19.0

func (c *CacheLFUImmutable) GetGuild(id Snowflake) (*Guild, error)

func (*CacheLFUImmutable) GetGuildChannels added in v0.19.0

func (c *CacheLFUImmutable) GetGuildChannels(id Snowflake) ([]*Channel, error)

func (*CacheLFUImmutable) GetGuildEmoji added in v0.19.0

func (c *CacheLFUImmutable) GetGuildEmoji(guildID, emojiID Snowflake) (*Emoji, error)

func (*CacheLFUImmutable) GetGuildEmojis added in v0.19.0

func (c *CacheLFUImmutable) GetGuildEmojis(id Snowflake) ([]*Emoji, error)

func (*CacheLFUImmutable) GetGuildRoles added in v0.19.0

func (c *CacheLFUImmutable) GetGuildRoles(guildID Snowflake) ([]*Role, error)

func (*CacheLFUImmutable) GetMember added in v0.19.0

func (c *CacheLFUImmutable) GetMember(guildID, userID Snowflake) (*Member, error)

func (*CacheLFUImmutable) GetUser added in v0.19.0

func (c *CacheLFUImmutable) GetUser(id Snowflake) (*User, error)

func (*CacheLFUImmutable) GuildCreate added in v0.19.0

func (c *CacheLFUImmutable) GuildCreate(data []byte) (*GuildCreate, error)

func (*CacheLFUImmutable) GuildDelete added in v0.19.0

func (c *CacheLFUImmutable) GuildDelete(data []byte) (*GuildDelete, error)

func (*CacheLFUImmutable) GuildMemberAdd added in v0.19.0

func (c *CacheLFUImmutable) GuildMemberAdd(data []byte) (*GuildMemberAdd, error)

func (*CacheLFUImmutable) GuildMemberRemove added in v0.19.0

func (c *CacheLFUImmutable) GuildMemberRemove(data []byte) (*GuildMemberRemove, error)

func (*CacheLFUImmutable) GuildUpdate added in v0.19.0

func (c *CacheLFUImmutable) GuildUpdate(data []byte) (*GuildUpdate, error)

func (*CacheLFUImmutable) MessageCreate added in v0.20.0

func (c *CacheLFUImmutable) MessageCreate(data []byte) (*MessageCreate, error)

func (*CacheLFUImmutable) Mutex added in v0.19.0

func (c *CacheLFUImmutable) Mutex(repo *crs.LFU, id Snowflake) *sync.Mutex

func (*CacheLFUImmutable) Ready added in v0.19.0

func (c *CacheLFUImmutable) Ready(data []byte) (*Ready, error)

func (*CacheLFUImmutable) UserUpdate added in v0.19.0

func (c *CacheLFUImmutable) UserUpdate(data []byte) (*UserUpdate, error)

func (*CacheLFUImmutable) VoiceServerUpdate added in v0.19.0

func (c *CacheLFUImmutable) VoiceServerUpdate(data []byte) (*VoiceServerUpdate, error)

type CacheNop added in v0.19.0

type CacheNop struct{}

nop cache

func (*CacheNop) ChannelCreate added in v0.19.0

func (c *CacheNop) ChannelCreate(data []byte) (evt *ChannelCreate, err error)

func (*CacheNop) ChannelDelete added in v0.19.0

func (c *CacheNop) ChannelDelete(data []byte) (evt *ChannelDelete, err error)

func (*CacheNop) ChannelPinsUpdate added in v0.19.0

func (c *CacheNop) ChannelPinsUpdate(data []byte) (evt *ChannelPinsUpdate, err error)

func (*CacheNop) ChannelUpdate added in v0.19.0

func (c *CacheNop) ChannelUpdate(data []byte) (evt *ChannelUpdate, err error)

func (*CacheNop) GetChannel added in v0.19.0

func (c *CacheNop) GetChannel(id Snowflake) (*Channel, error)

func (*CacheNop) GetCurrentUser added in v0.19.0

func (c *CacheNop) GetCurrentUser() (*User, error)

func (*CacheNop) GetCurrentUserGuilds added in v0.19.0

func (c *CacheNop) GetCurrentUserGuilds(p *GetCurrentUserGuildsParams) ([]*Guild, error)

func (*CacheNop) GetGuild added in v0.19.0

func (c *CacheNop) GetGuild(id Snowflake) (*Guild, error)

func (*CacheNop) GetGuildChannels added in v0.19.0

func (c *CacheNop) GetGuildChannels(id Snowflake) ([]*Channel, error)

func (*CacheNop) GetGuildEmoji added in v0.19.0

func (c *CacheNop) GetGuildEmoji(guildID, emojiID Snowflake) (*Emoji, error)

func (*CacheNop) GetGuildEmojis added in v0.19.0

func (c *CacheNop) GetGuildEmojis(id Snowflake) ([]*Emoji, error)

func (*CacheNop) GetGuildRoles added in v0.19.0

func (c *CacheNop) GetGuildRoles(guildID Snowflake) ([]*Role, error)

func (*CacheNop) GetMember added in v0.19.0

func (c *CacheNop) GetMember(guildID, userID Snowflake) (*Member, error)

func (*CacheNop) GetMembers added in v0.19.0

func (c *CacheNop) GetMembers(guildID Snowflake, p *GetMembersParams) ([]*Member, error)

func (*CacheNop) GetMessage added in v0.19.0

func (c *CacheNop) GetMessage(channelID, messageID Snowflake) (*Message, error)

REST lookup

func (*CacheNop) GetMessages added in v0.19.0

func (c *CacheNop) GetMessages(channel Snowflake, p *GetMessagesParams) ([]*Message, error)

func (*CacheNop) GetUser added in v0.19.0

func (c *CacheNop) GetUser(id Snowflake) (*User, error)

func (*CacheNop) GuildBanAdd added in v0.19.0

func (c *CacheNop) GuildBanAdd(data []byte) (evt *GuildBanAdd, err error)

func (*CacheNop) GuildBanRemove added in v0.19.0

func (c *CacheNop) GuildBanRemove(data []byte) (evt *GuildBanRemove, err error)

func (*CacheNop) GuildCreate added in v0.19.0

func (c *CacheNop) GuildCreate(data []byte) (evt *GuildCreate, err error)

func (*CacheNop) GuildDelete added in v0.19.0

func (c *CacheNop) GuildDelete(data []byte) (evt *GuildDelete, err error)

func (*CacheNop) GuildEmojisUpdate added in v0.19.0

func (c *CacheNop) GuildEmojisUpdate(data []byte) (evt *GuildEmojisUpdate, err error)

func (*CacheNop) GuildIntegrationsUpdate added in v0.19.0

func (c *CacheNop) GuildIntegrationsUpdate(data []byte) (evt *GuildIntegrationsUpdate, err error)

func (*CacheNop) GuildMemberAdd added in v0.19.0

func (c *CacheNop) GuildMemberAdd(data []byte) (evt *GuildMemberAdd, err error)

func (*CacheNop) GuildMemberRemove added in v0.19.0

func (c *CacheNop) GuildMemberRemove(data []byte) (evt *GuildMemberRemove, err error)

func (*CacheNop) GuildMemberUpdate added in v0.19.0

func (c *CacheNop) GuildMemberUpdate(data []byte) (evt *GuildMemberUpdate, err error)

func (*CacheNop) GuildMembersChunk added in v0.19.0

func (c *CacheNop) GuildMembersChunk(data []byte) (evt *GuildMembersChunk, err error)

func (*CacheNop) GuildRoleCreate added in v0.19.0

func (c *CacheNop) GuildRoleCreate(data []byte) (evt *GuildRoleCreate, err error)

func (*CacheNop) GuildRoleDelete added in v0.19.0

func (c *CacheNop) GuildRoleDelete(data []byte) (evt *GuildRoleDelete, err error)

func (*CacheNop) GuildRoleUpdate added in v0.19.0

func (c *CacheNop) GuildRoleUpdate(data []byte) (evt *GuildRoleUpdate, err error)

func (*CacheNop) GuildUpdate added in v0.19.0

func (c *CacheNop) GuildUpdate(data []byte) (evt *GuildUpdate, err error)

func (*CacheNop) InviteCreate added in v0.19.0

func (c *CacheNop) InviteCreate(data []byte) (evt *InviteCreate, err error)

func (*CacheNop) InviteDelete added in v0.19.0

func (c *CacheNop) InviteDelete(data []byte) (evt *InviteDelete, err error)

func (*CacheNop) MessageCreate added in v0.19.0

func (c *CacheNop) MessageCreate(data []byte) (evt *MessageCreate, err error)

func (*CacheNop) MessageDelete added in v0.19.0

func (c *CacheNop) MessageDelete(data []byte) (evt *MessageDelete, err error)

func (*CacheNop) MessageDeleteBulk added in v0.19.0

func (c *CacheNop) MessageDeleteBulk(data []byte) (evt *MessageDeleteBulk, err error)

func (*CacheNop) MessageReactionAdd added in v0.19.0

func (c *CacheNop) MessageReactionAdd(data []byte) (evt *MessageReactionAdd, err error)

func (*CacheNop) MessageReactionRemove added in v0.19.0

func (c *CacheNop) MessageReactionRemove(data []byte) (evt *MessageReactionRemove, err error)

func (*CacheNop) MessageReactionRemoveAll added in v0.19.0

func (c *CacheNop) MessageReactionRemoveAll(data []byte) (evt *MessageReactionRemoveAll, err error)

func (*CacheNop) MessageReactionRemoveEmoji added in v0.20.0

func (c *CacheNop) MessageReactionRemoveEmoji(data []byte) (evt *MessageReactionRemoveEmoji, err error)

func (*CacheNop) MessageUpdate added in v0.19.0

func (c *CacheNop) MessageUpdate(data []byte) (evt *MessageUpdate, err error)

func (*CacheNop) Patch added in v0.19.0

func (c *CacheNop) Patch(v interface{})

func (*CacheNop) PresenceUpdate added in v0.19.0

func (c *CacheNop) PresenceUpdate(data []byte) (evt *PresenceUpdate, err error)

func (*CacheNop) Ready added in v0.19.0

func (c *CacheNop) Ready(data []byte) (evt *Ready, err error)

func (*CacheNop) Resumed added in v0.19.0

func (c *CacheNop) Resumed(data []byte) (evt *Resumed, err error)

func (*CacheNop) TypingStart added in v0.19.0

func (c *CacheNop) TypingStart(data []byte) (evt *TypingStart, err error)

func (*CacheNop) UserUpdate added in v0.19.0

func (c *CacheNop) UserUpdate(data []byte) (evt *UserUpdate, err error)

func (*CacheNop) VoiceServerUpdate added in v0.19.0

func (c *CacheNop) VoiceServerUpdate(data []byte) (evt *VoiceServerUpdate, err error)

func (*CacheNop) VoiceStateUpdate added in v0.19.0

func (c *CacheNop) VoiceStateUpdate(data []byte) (evt *VoiceStateUpdate, err error)

func (*CacheNop) WebhooksUpdate added in v0.19.0

func (c *CacheNop) WebhooksUpdate(data []byte) (evt *WebhooksUpdate, err error)

type CacheUpdater added in v0.19.0

type CacheUpdater interface {
	// Gateway events
	ChannelCreate(data []byte) (*ChannelCreate, error)
	ChannelDelete(data []byte) (*ChannelDelete, error)
	ChannelPinsUpdate(data []byte) (*ChannelPinsUpdate, error)
	ChannelUpdate(data []byte) (*ChannelUpdate, error)
	GuildBanAdd(data []byte) (*GuildBanAdd, error)
	GuildBanRemove(data []byte) (*GuildBanRemove, error)
	GuildCreate(data []byte) (*GuildCreate, error)
	GuildDelete(data []byte) (*GuildDelete, error)
	GuildEmojisUpdate(data []byte) (*GuildEmojisUpdate, error)
	GuildIntegrationsUpdate(data []byte) (*GuildIntegrationsUpdate, error)
	GuildMemberAdd(data []byte) (*GuildMemberAdd, error)
	GuildMemberRemove(data []byte) (*GuildMemberRemove, error)
	GuildMemberUpdate(data []byte) (*GuildMemberUpdate, error)
	GuildMembersChunk(data []byte) (*GuildMembersChunk, error)
	GuildRoleCreate(data []byte) (*GuildRoleCreate, error)
	GuildRoleDelete(data []byte) (*GuildRoleDelete, error)
	GuildRoleUpdate(data []byte) (*GuildRoleUpdate, error)
	GuildUpdate(data []byte) (*GuildUpdate, error)
	InviteCreate(data []byte) (*InviteCreate, error)
	InviteDelete(data []byte) (*InviteDelete, error)
	MessageCreate(data []byte) (*MessageCreate, error)
	MessageDelete(data []byte) (*MessageDelete, error)
	MessageDeleteBulk(data []byte) (*MessageDeleteBulk, error)
	MessageReactionAdd(data []byte) (*MessageReactionAdd, error)
	MessageReactionRemove(data []byte) (*MessageReactionRemove, error)
	MessageReactionRemoveAll(data []byte) (*MessageReactionRemoveAll, error)
	MessageReactionRemoveEmoji(data []byte) (*MessageReactionRemoveEmoji, error)
	MessageUpdate(data []byte) (*MessageUpdate, error)
	PresenceUpdate(data []byte) (*PresenceUpdate, error)
	Ready(data []byte) (*Ready, error)
	Resumed(data []byte) (*Resumed, error)
	TypingStart(data []byte) (*TypingStart, error)
	UserUpdate(data []byte) (*UserUpdate, error)
	VoiceServerUpdate(data []byte) (*VoiceServerUpdate, error)
	VoiceStateUpdate(data []byte) (*VoiceStateUpdate, error)
	WebhooksUpdate(data []byte) (*WebhooksUpdate, error)
}

type Channel added in v0.6.0

type Channel struct {
	ID                   Snowflake             `json:"id"`
	Type                 uint                  `json:"type"`
	GuildID              Snowflake             `json:"guild_id,omitempty"`              // ?|
	Position             int                   `json:"position,omitempty"`              // ?| can be less than 0
	PermissionOverwrites []PermissionOverwrite `json:"permission_overwrites,omitempty"` // ?|
	Name                 string                `json:"name,omitempty"`                  // ?|
	Topic                string                `json:"topic,omitempty"`                 // ?|?
	NSFW                 bool                  `json:"nsfw,omitempty"`                  // ?|
	LastMessageID        Snowflake             `json:"last_message_id,omitempty"`       // ?|?
	Bitrate              uint                  `json:"bitrate,omitempty"`               // ?|
	UserLimit            uint                  `json:"user_limit,omitempty"`            // ?|
	RateLimitPerUser     uint                  `json:"rate_limit_per_user,omitempty"`   // ?|
	Recipients           []*User               `json:"recipient,omitempty"`             // ?| , empty if not DM/GroupDM
	Icon                 string                `json:"icon,omitempty"`                  // ?|?
	OwnerID              Snowflake             `json:"owner_id,omitempty"`              // ?|
	ApplicationID        Snowflake             `json:"application_id,omitempty"`        // ?|
	ParentID             Snowflake             `json:"parent_id,omitempty"`             // ?|?
	LastPinTimestamp     Time                  `json:"last_pin_timestamp,omitempty"`    // ?|
	// contains filtered or unexported fields
}

Channel ...

func (*Channel) Compare added in v0.6.0

func (c *Channel) Compare(other *Channel) bool

Compare checks if channel A is the same as channel B

func (*Channel) CopyOverTo added in v0.7.0

func (c *Channel) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*Channel) DeepCopy added in v0.6.0

func (c *Channel) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

func (*Channel) GetPermissions added in v0.18.0

func (c *Channel) GetPermissions(ctx context.Context, s GuildQueryBuilderCaller, member *Member, flags ...Flag) (permissions PermissionBit, err error)

GetPermissions is used to get a members permissions in a channel.

func (*Channel) Mention added in v0.6.0

func (c *Channel) Mention() string

Mention creates a channel mention string. Mention format is according the Discord protocol.

func (*Channel) Reset added in v0.10.0

func (c *Channel) Reset()

func (*Channel) SendMsg added in v0.6.0

func (c *Channel) SendMsg(ctx context.Context, s Session, message *Message) (msg *Message, err error)

SendMsg sends a message to a channel

func (*Channel) SendMsgString added in v0.6.0

func (c *Channel) SendMsgString(ctx context.Context, s Session, content string) (msg *Message, err error)

SendMsgString same as SendMsg, however this only takes the message content (string) as a argument for the message

func (*Channel) String added in v0.10.0

func (c *Channel) String() string

type ChannelCreate added in v0.6.0

type ChannelCreate struct {
	Channel *Channel `json:"channel"`
	ShardID uint     `json:"-"`
}

ChannelCreate new channel created

func (*ChannelCreate) UnmarshalJSON added in v0.8.0

func (obj *ChannelCreate) UnmarshalJSON(data []byte) error

UnmarshalJSON ...

type ChannelCreateHandler added in v0.9.0

type ChannelCreateHandler = func(s Session, h *ChannelCreate)

ChannelCreateHandler is triggered in ChannelCreate events

type ChannelDelete added in v0.6.0

type ChannelDelete struct {
	Channel *Channel `json:"channel"`
	ShardID uint     `json:"-"`
}

ChannelDelete channel was deleted

func (*ChannelDelete) UnmarshalJSON added in v0.8.0

func (obj *ChannelDelete) UnmarshalJSON(data []byte) error

UnmarshalJSON ...

type ChannelDeleteHandler added in v0.9.0

type ChannelDeleteHandler = func(s Session, h *ChannelDelete)

ChannelDeleteHandler is triggered in ChannelDelete events

type ChannelPinsUpdate added in v0.6.0

type ChannelPinsUpdate struct {
	// ChannelID snowflake	the id of the channel
	ChannelID Snowflake `json:"channel_id"`

	GuildID Snowflake `json:"guild_id,omitempty"`

	// LastPinTimestamp	ISO8601 timestamp	the time at which the most recent pinned message was pinned
	LastPinTimestamp Time `json:"last_pin_timestamp,omitempty"`
	ShardID          uint `json:"-"`
}

ChannelPinsUpdate message was pinned or unpinned

type ChannelPinsUpdateHandler added in v0.9.0

type ChannelPinsUpdateHandler = func(s Session, h *ChannelPinsUpdate)

ChannelPinsUpdateHandler is triggered in ChannelPinsUpdate events

type ChannelQueryBuilder added in v0.19.0

type ChannelQueryBuilder interface {
	WithContext(ctx context.Context) ChannelQueryBuilder

	// TriggerTypingIndicator Post a typing indicator for the specified 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. Returns a 204 empty response
	// on success. Fires a Typing Start Gateway event.
	TriggerTypingIndicator(flags ...Flag) error

	// GetChannel Get a channel by Snowflake. Returns a channel object.
	Get(flags ...Flag) (*Channel, error)

	// UpdateChannel Update a Channels settings. Requires the 'MANAGE_CHANNELS' permission for the guild. Returns
	// a channel on success, and a 400 BAD REQUEST on invalid parameters. Fires a Channel Update Gateway event. If
	// modifying a category, individual Channel Update events will fire for each child channel that also changes.
	// For the PATCH method, all the JSON Params are optional.
	Update(flags ...Flag) *updateChannelBuilder

	// DeleteChannel Delete a channel, or close a 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 a channel object on success.
	// Fires a Channel Delete Gateway event.
	Delete(flags ...Flag) (*Channel, error)

	// EditChannelPermissions Edit the channel permission overwrites for a user or role in a channel. Only usable
	// for guild Channels. Requires the 'MANAGE_ROLES' permission. Returns a 204 empty response on success.
	// For more information about permissions, see permissions.
	UpdatePermissions(overwriteID Snowflake, params *UpdateChannelPermissionsParams, flags ...Flag) error

	// GetChannelInvites Returns a list of invite objects (with invite metadata) for the channel. Only usable for
	// guild Channels. Requires the 'MANAGE_CHANNELS' permission.
	GetInvites(flags ...Flag) ([]*Invite, error)

	// CreateChannelInvite Create a new invite object for the channel. Only usable for guild Channels. Requires
	// the CREATE_INSTANT_INVITE permission. All JSON parameters for this route are optional, however the request
	// body is not. If you are not sending any fields, you still have to send an empty JSON object ({}).
	// Returns an invite object.
	CreateInvite(flags ...Flag) *createChannelInviteBuilder

	// DeleteChannelPermission Delete a channel permission overwrite for a user or role in a channel. Only usable
	// for guild Channels. Requires the 'MANAGE_ROLES' permission. Returns a 204 empty response on success. For more
	// information about permissions,
	// see permissions: https://discord.com/developers/docs/topics/permissions#permissions
	DeletePermission(overwriteID Snowflake, flags ...Flag) error

	// AddDMParticipant Adds a recipient to a Group DM using their access token. Returns a 204 empty response
	// on success.
	AddDMParticipant(participant *GroupDMParticipant, flags ...Flag) error

	// KickParticipant Removes a recipient from a Group DM. Returns a 204 empty response on success.
	KickParticipant(userID Snowflake, flags ...Flag) error

	// GetPinnedMessages Returns all pinned messages in the channel as an array of message objects.
	GetPinnedMessages(flags ...Flag) ([]*Message, error)

	// DeleteMessages Delete multiple messages in a single request. This endpoint can only be used on guild
	// Channels and requires the 'MANAGE_MESSAGES' permission. Returns a 204 empty response on success. 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.
	DeleteMessages(params *DeleteMessagesParams, flags ...Flag) error

	// GetMessages Returns the messages for a 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). Returns an array of message objects on success.
	GetMessages(params *GetMessagesParams, flags ...Flag) ([]*Message, error)

	// CreateMessage Post a message to a guild text or DM 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 a message object. Fires a
	// Message Create Gateway event. See message formatting for more information on how to properly format messages.
	// The maximum request size when sending a message is 8MB.
	CreateMessage(params *CreateMessageParams, flags ...Flag) (*Message, error)

	// CreateWebhook Create a new webhook. Requires the 'MANAGE_WEBHOOKS' permission.
	// Returns a webhook object on success.
	CreateWebhook(params *CreateWebhookParams, flags ...Flag) (ret *Webhook, err error)

	// GetChannelWebhooks Returns a list of channel webhook objects. Requires the 'MANAGE_WEBHOOKS' permission.
	GetWebhooks(flags ...Flag) (ret []*Webhook, err error)

	Message(id Snowflake) MessageQueryBuilder
}

ChannelQueryBuilder REST interface for all Channel endpoints

type ChannelUpdate added in v0.6.0

type ChannelUpdate struct {
	Channel *Channel `json:"channel"`
	ShardID uint     `json:"-"`
}

ChannelUpdate channel was updated

func (*ChannelUpdate) UnmarshalJSON added in v0.8.0

func (obj *ChannelUpdate) UnmarshalJSON(data []byte) error

UnmarshalJSON ...

type ChannelUpdateHandler added in v0.9.0

type ChannelUpdateHandler = func(s Session, h *ChannelUpdate)

ChannelUpdateHandler is triggered in ChannelUpdate events

type Client

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

Client is the main disgord Client to hold your state and data. You must always initiate it using the constructor methods (eg. New(..) or NewClient(..)).

Note that this Client holds all the REST methods, and is split across files, into whatever category the REST methods regards.

func New added in v0.9.0

func New(conf Config) *Client

New create a Client. But panics on configuration/setup errors.

func NewClient

func NewClient(conf Config) (*Client, error)

NewClient creates a new Disgord Client and returns an error on configuration issues

func (*Client) AddPermission added in v0.10.0

func (c *Client) AddPermission(permission PermissionBit) (updatedPermissions PermissionBit)

AddPermission adds a minimum required permission to the bot. If the permission is negative, it is overwritten to 0. This is useful for creating the bot URL.

At the moment, this holds no other effect than aesthetics.

func (*Client) AvgHeartbeatLatency added in v0.12.0

func (c *Client) AvgHeartbeatLatency() (duration time.Duration, err error)

AvgHeartbeatLatency checks the duration of waiting before receiving a response from Discord when a heartbeat packet was sent. Note that heartbeats are usually sent around once a minute and is not a accurate way to measure delay between the Client and Discord server

func (Client) BotAuthorizeURL added in v0.19.0

func (c Client) BotAuthorizeURL() (*url.URL, error)

BotAuthorizeURL creates a URL that can be used to invite this bot to a guild/server. Note that it depends on the bot ID to be after the Discord update where the Client ID is the same as the Bot ID.

By default the permissions will be 0, as in none. If you want to add/set the minimum required permissions for your bot to run successfully, you should utilise

Client.

func (*Client) Cache added in v0.8.0

func (c *Client) Cache() Cache

Cache returns the cacheLink manager for the session

func (Client) Channel added in v0.19.0

func (c Client) Channel(id Snowflake) ChannelQueryBuilder

func (*Client) Connect

func (c *Client) Connect(ctx context.Context) (err error)

Connect establishes a websocket connection to the discord API

func (Client) CreateGuild

func (c Client) CreateGuild(guildName string, params *CreateGuildParams, flags ...Flag) (ret *Guild, err error)

CreateGuild [REST] Create a new guild. Returns a guild object on success. Fires a Guild Create Gateway event.

 Method                  POST
 Endpoint                /guilds
 Discord documentation   https://discord.com/developers/docs/resources/guild#create-guild
 Reviewed                2018-08-16
 Comment                 This endpoint. can be used only by bots in less than 10 Guilds. Creating channel
                         categories from this endpoint. is not supported.
							The params argument is optional.

func (Client) CurrentUser added in v0.19.0

func (c Client) CurrentUser() CurrentUserQueryBuilder

Guild is used to create a guild query builder.

func (*Client) Disconnect

func (c *Client) Disconnect() (err error)

Disconnect closes the discord websocket connection

func (*Client) DisconnectOnInterrupt added in v0.6.2

func (c *Client) DisconnectOnInterrupt() (err error)

DisconnectOnInterrupt wait until a termination signal is detected

func (*Client) Emit added in v0.8.0

func (c *Client) Emit(name gatewayCmdName, payload gatewayCmdPayload) (unchandledGuildIDs []Snowflake, err error)

Emit sends a socket command directly to Discord.

func (*Client) Event added in v0.19.0

func (c *Client) Event() SocketHandlerRegistrator

func (*Client) GetConnectedGuilds added in v0.10.0

func (c *Client) GetConnectedGuilds() []Snowflake

GetConnectedGuilds get a list over guild IDs that this Client is "connected to"; or have joined through the ws connection. This will always hold the different Guild IDs, while the GetGuilds or GetCurrentUserGuilds might be affected by cache configuration.

func (Client) GetGateway added in v0.12.0

func (c Client) GetGateway() (gateway *gateway.Gateway, err error)

GetGateway [REST] Returns an object with a single valid WSS URL, which the Client can use for Connecting. Clients should cacheLink this value and only call this endpoint to retrieve a new URL if they are unable to properly establish a connection using the cached version of the URL.

Method                  GET
Endpoint                /gateway
Discord documentation   https://discord.com/developers/docs/topics/gateway#get-gateway
Reviewed                2018-10-12
Comment                 This endpoint does not require authentication.

func (Client) GetGatewayBot added in v0.12.0

func (c Client) GetGatewayBot() (gateway *gateway.GatewayBot, err error)

GetGatewayBot [REST] Returns an object based on the information in Get Gateway, plus additional metadata that can help during the operation of large or sharded bots. Unlike the Get Gateway, this route should not be cached for extended periods of time as the value is not guaranteed to be the same per-call, and changes as the bot joins/leaves Guilds.

Method                  GET
Endpoint                /gateway/bot
Discord documentation   https://discord.com/developers/docs/topics/gateway#get-gateway-bot
Reviewed                2018-10-12
Comment                 This endpoint requires authentication using a valid bot token.

func (*Client) GetPermissions added in v0.10.0

func (c *Client) GetPermissions() (permissions PermissionBit)

GetPermissions returns the minimum bot requirements.

func (Client) GetVoiceRegions

func (c Client) GetVoiceRegions(flags ...Flag) (regions []*VoiceRegion, err error)

GetVoiceRegionsBuilder [REST] Returns an array of voice region objects that can be used when creating servers.

Method                  GET
Endpoint                /voice/regions
Discord documentation   https://discord.com/developers/docs/resources/voice#list-voice-regions
Reviewed                2018-08-21
Comment                 -

func (Client) Guild added in v0.19.0

func (c Client) Guild(id Snowflake) GuildQueryBuilder

Guild is used to create a guild query builder.

func (*Client) GuildsReady added in v0.12.0

func (c *Client) GuildsReady(cb func())

GuildsReady is triggered once all unavailable Guilds given in the READY event has loaded from their respective GUILD_CREATE events.

func (*Client) HeartbeatLatencies added in v0.12.0

func (c *Client) HeartbeatLatencies() (latencies map[uint]time.Duration, err error)

HeartbeatLatencies returns latencies mapped to each shard, by their respective ID. shardID => latency.

func (Client) Invite added in v0.19.0

func (c Client) Invite(code string) InviteQueryBuilder

func (*Client) Logger added in v0.10.0

func (c *Client) Logger() logger.Logger

Logger returns the log instance of Disgord. Note that this instance is never nil. When the conf.Logger is not assigned an empty struct is used instead. Such that all calls are simply discarded at compile time removing the need for nil checks.

func (*Client) On added in v0.8.0

func (c *Client) On(event string, inputs ...interface{})

On creates a specification to be executed on the given event. The specification consists of, in order, 0 or more middlewares, 1 or more handlers, 0 or 1 controller. On incorrect ordering, or types, the method will panic. See reactor.go for types.

Each of the three sub-types of a specification is run in sequence, as well as the specifications registered for a event. However, the slice of specifications are executed in a goroutine to avoid blocking future events. The middlewares allows manipulating the event data before it reaches the handlers. The handlers executes short-running logic based on the event data (use go routine if you need a long running task). The controller dictates lifetime of the specification.

// a handler that is executed on every Ready event
Client.On(EvtReady, onReady)

// a handler that runs only the first three times a READY event is fired
Client.On(EvtReady, onReady, &Ctrl{Runs: 3})

// a handler that only runs for events within the first 10 minutes
Client.On(EvtReady, onReady, &Ctrl{Duration: 10*time.Minute})

Another example is to create a voting system where you specify a deadline instead of a Runs counter:

On("MESSAGE_CREATE", mdlwHasMentions, handleMsgsWithMentions, saveVoteToDB, &Ctrl{Until:time.Now().Add(time.Hour)})

You can use your own Ctrl struct, as long as it implements disgord.HandlerCtrl. Do not execute long running tasks in the methods. Use a go routine instead.

If the HandlerCtrl.OnInsert returns an error, the related handlers are still added to the dispatcher. But the error is logged to the injected logger instance (log.Error).

This ctrl feature was inspired by https://github.com/discordjs/discord.js

func (*Client) Pool added in v0.10.0

func (c *Client) Pool() *pools

////////////////////////////////////////////////////

METHODS

////////////////////////////////////////////////////

func (*Client) RESTRatelimitBuckets added in v0.16.5

func (c *Client) RESTRatelimitBuckets() (group map[string][]string)

RESTBucketGrouping shows which hashed endpoints belong to which bucket hash for the REST API. Note that these bucket hashes are eventual consistent.

func (*Client) Ready added in v0.10.0

func (c *Client) Ready(cb func())

Ready triggers a given callback when all shards has gotten their first Ready event Warning: Do not call Client.Connect before this.

func (Client) SendMsg added in v0.4.0

func (c Client) SendMsg(channelID Snowflake, data ...interface{}) (msg *Message, err error)

SendMsg should convert all inputs into a single message. If you supply a object with an ID such as a channel, message, role, etc. It will become a reference. If say the Message provided does not have an ID, the Message will populate a CreateMessage with it's fields.

If you want to affect the actual message data besides .Content; provide a MessageCreateParams. The reply message will be updated by the last one provided.

func (*Client) StayConnectedUntilInterrupted added in v0.10.0

func (c *Client) StayConnectedUntilInterrupted(ctx context.Context) (err error)

StayConnectedUntilInterrupted is a simple wrapper for connect, and disconnect that listens for system interrupts. When a error happens you can terminate the application without worries.

func (*Client) String

func (c *Client) String() string

func (*Client) Suspend added in v0.10.0

func (c *Client) Suspend() (err error)

Suspend in case you want to temporary disconnect from the Gateway. But plan on connecting again without restarting your software/application, this should be used.

func (*Client) UpdateStatus added in v0.8.4

func (c *Client) UpdateStatus(s *UpdateStatusPayload) error

UpdateStatus updates the Client's game status note: for simple games, check out UpdateStatusString

func (*Client) UpdateStatusString added in v0.8.4

func (c *Client) UpdateStatusString(s string) error

UpdateStatusString sets the Client's game activity to the provided string, status to online and type to Playing

func (Client) User added in v0.19.0

func (c Client) User(id Snowflake) UserQueryBuilder

Guild is used to create a guild query builder.

func (Client) VoiceConnectOptions added in v0.12.0

func (r Client) VoiceConnectOptions(guildID, channelID Snowflake, selfDeaf, selfMute bool) (ret VoiceConnection, err error)

func (Client) Webhook added in v0.19.0

func (c Client) Webhook(id Snowflake) WebhookQueryBuilder

func (Client) WithContext added in v0.19.0

func (c Client) WithContext(ctx context.Context) ClientQueryBuilderExecutables

type ClientQueryBuilder added in v0.19.0

type ClientQueryBuilderExecutables added in v0.19.0

type ClientQueryBuilderExecutables interface {
	// CreateGuild Create a new guild. Returns a guild object on success. Fires a Guild Create Gateway event.
	CreateGuild(guildName string, params *CreateGuildParams, flags ...Flag) (*Guild, error)

	// GetVoiceRegionsBuilder Returns an array of voice region objects that can be used when creating servers.
	GetVoiceRegions(flags ...Flag) ([]*VoiceRegion, error)

	BotAuthorizeURL() (*url.URL, error)
	SendMsg(channelID Snowflake, data ...interface{}) (*Message, error)

	GetGateway() (gateway *gateway.Gateway, err error)
	GetGatewayBot() (gateway *gateway.GatewayBot, err error)
}

type CloseConnectionErr added in v0.16.4

type CloseConnectionErr = disgorderr.ClosedConnectionErr

type Config

type Config struct {
	// ################################################
	// ##
	// ## Basic bot configuration.
	// ## This section is for everyone. And beginners
	// ## should stick to this section unless they know
	// ## what they are doing.
	// ##
	// ################################################
	BotToken   string
	HTTPClient *http.Client
	Proxy      proxy.Dialer

	// For direct communication with you bot you must specify intents (eg.
	Intents Intent

	// your project name, name of bot, or application
	ProjectName string

	CancelRequestWhenRateLimited bool

	// LoadMembersQuietly will start fetching members for all Guilds in the background.
	// There is currently no proper way to detect when the loading is done nor if it
	// finished successfully.
	LoadMembersQuietly bool

	// Presence will automatically be emitted to discord on start up
	Presence *UpdateStatusPayload

	// Logger is a dependency that must be injected to support logging.
	// disgord.DefaultLogger() can be used
	Logger Logger

	// ################################################
	// ##
	// ## WARNING! For advanced Users only.
	// ## This section of options might break the bot,
	// ## make it incoherent to the Discord API requirements,
	// ## potentially causing your bot to be banned.
	// ## You use these features on your own risk.
	// ##
	// ################################################
	RESTBucketManager httd.RESTBucketManager

	DisableCache bool
	Cache        Cache
	ShardConfig  ShardConfig

	// IgnoreEvents will skip events that matches the given event names.
	// WARNING! This can break your caching, so be careful about what you want to ignore.
	//
	// Note this also triggers discord optimizations behind the scenes, such that disgord_diagnosews might
	// seem to be missing some events. But actually the lack of certain events will mean Discord aren't sending
	// them at all due to how the identify command was defined. eg. guildS_subscriptions
	IgnoreEvents []string
	// contains filtered or unexported fields
}

Config Configuration for the Disgord Client

type Copier added in v0.7.0

type Copier interface {
	CopyOverTo(other interface{}) error
}

Copier holds the CopyOverTo method which copies all it's content from one struct to another. Note that this requires a deep copy. useful when overwriting already existing content in the cacheLink to reduce GC.

type CreateChannelInviteBuilder added in v0.19.0

type CreateChannelInviteBuilder interface {
	Execute() (invite *Invite, err error)
	IgnoreCache() CreateChannelInviteBuilder
	CancelOnRatelimit() CreateChannelInviteBuilder
	URLParam(name string, v interface{}) CreateChannelInviteBuilder
	Set(name string, v interface{}) CreateChannelInviteBuilder
	SetMaxAge(maxAge int) CreateChannelInviteBuilder
	SetMaxUses(maxUses int) CreateChannelInviteBuilder
	SetTemporary(temporary bool) CreateChannelInviteBuilder
	SetUnique(unique bool) CreateChannelInviteBuilder
}

CreateChannelInviteBuilder is the interface for the builder.

type CreateDMBuilder added in v0.19.0

type CreateDMBuilder interface {
	Execute() (channel *Channel, err error)
	IgnoreCache() CreateDMBuilder
	CancelOnRatelimit() CreateDMBuilder
	URLParam(name string, v interface{}) CreateDMBuilder
	Set(name string, v interface{}) CreateDMBuilder
}

CreateDMBuilder is the interface for the builder.

type CreateGroupDMBuilder added in v0.19.0

type CreateGroupDMBuilder interface {
	Execute() (channel *Channel, err error)
	IgnoreCache() CreateGroupDMBuilder
	CancelOnRatelimit() CreateGroupDMBuilder
	URLParam(name string, v interface{}) CreateGroupDMBuilder
	Set(name string, v interface{}) CreateGroupDMBuilder
}

CreateGroupDMBuilder is the interface for the builder.

type CreateGroupDMParams added in v0.6.0

type CreateGroupDMParams struct {
	// AccessTokens access tokens of Users that have granted your app the gdm.join scope
	AccessTokens []string `json:"access_tokens"`

	// map[UserID] = nickname
	Nicks map[Snowflake]string `json:"nicks"`
}

CreateGroupDMParams required JSON params for func CreateGroupDM https://discord.com/developers/docs/resources/user#create-group-dm

type CreateGuildChannelParams added in v0.6.0

type CreateGuildChannelParams struct {
	Name                 string                `json:"name"` // required
	Type                 uint                  `json:"type,omitempty"`
	Topic                string                `json:"topic,omitempty"`
	Bitrate              uint                  `json:"bitrate,omitempty"`
	UserLimit            uint                  `json:"user_limit,omitempty"`
	RateLimitPerUser     uint                  `json:"rate_limit_per_user,omitempty"`
	PermissionOverwrites []PermissionOverwrite `json:"permission_overwrites,omitempty"`
	ParentID             Snowflake             `json:"parent_id,omitempty"`
	NSFW                 bool                  `json:"nsfw,omitempty"`
	Position             int                   `json:"position"` // can not omitempty in case position is 0

	// Reason is a X-Audit-Log-Reason header field that will show up on the audit log for this action.
	Reason string `json:"-"`
}

CreateGuildChannelParams https://discord.com/developers/docs/resources/guild#create-guild-channel-json-params

type CreateGuildEmojiBuilder added in v0.19.0

type CreateGuildEmojiBuilder interface {
	Execute() (emoji *Emoji, err error)
	IgnoreCache() CreateGuildEmojiBuilder
	CancelOnRatelimit() CreateGuildEmojiBuilder
	URLParam(name string, v interface{}) CreateGuildEmojiBuilder
	Set(name string, v interface{}) CreateGuildEmojiBuilder
	SetRoles(roles []Snowflake) CreateGuildEmojiBuilder
}

CreateGuildEmojiBuilder is the interface for the builder.

type CreateGuildEmojiParams added in v0.6.0

type CreateGuildEmojiParams struct {
	Name  string      `json:"name"`  // required
	Image string      `json:"image"` // required
	Roles []Snowflake `json:"roles"` // optional

	// Reason is a X-Audit-Log-Reason header field that will show up on the audit log for this action.
	Reason string `json:"-"`
}

CreateGuildEmojiParams JSON params for func CreateGuildEmoji

type CreateGuildIntegrationParams added in v0.6.0

type CreateGuildIntegrationParams struct {
	Type string    `json:"type"`
	ID   Snowflake `json:"id"`
}

CreateGuildIntegrationParams ... https://discord.com/developers/docs/resources/guild#create-guild-integration-json-params

type CreateGuildParams added in v0.6.0

type CreateGuildParams struct {
	Name                    string                        `json:"name"` // required
	Region                  string                        `json:"region"`
	Icon                    string                        `json:"icon"`
	VerificationLvl         int                           `json:"verification_level"`
	DefaultMsgNotifications DefaultMessageNotificationLvl `json:"default_message_notifications"`
	ExplicitContentFilter   ExplicitContentFilterLvl      `json:"explicit_content_filter"`
	Roles                   []*Role                       `json:"roles"`
	Channels                []*PartialChannel             `json:"channels"`
}

CreateGuildParams ... https://discord.com/developers/docs/resources/guild#create-guild-json-params example partial channel object:

{
   "name": "naming-things-is-hard",
   "type": 0
}

type CreateGuildRoleParams added in v0.6.0

type CreateGuildRoleParams struct {
	Name        string `json:"name,omitempty"`
	Permissions uint64 `json:"permissions,omitempty"`
	Color       uint   `json:"color,omitempty"`
	Hoist       bool   `json:"hoist,omitempty"`
	Mentionable bool   `json:"mentionable,omitempty"`

	// Reason is a X-Audit-Log-Reason header field that will show up on the audit log for this action.
	Reason string `json:"-"`
}

CreateGuildRoleParams ... https://discord.com/developers/docs/resources/guild#create-guild-role-json-params

type CreateMessageFileParams added in v0.9.3

type CreateMessageFileParams struct {
	Reader   io.Reader `json:"-"` // always omit as we don't want this as part of the JSON payload
	FileName string    `json:"-"`

	// SpoilerTag lets discord know that this image should be blurred out.
	// Current Discord behaviour is that whenever a message with one or more images is marked as
	// spoiler tag, all the images in that message are blurred out. (independent of msg.Content)
	SpoilerTag bool `json:"-"`
}

CreateMessageFileParams contains the information needed to upload a file to Discord, it is part of the CreateMessageParams struct.

type CreateMessageParams added in v0.9.3

type CreateMessageParams struct {
	Content string `json:"content"`
	Nonce   string `json:"nonce,omitempty"` // THIS IS A STRING. NOT A SNOWFLAKE! DONT TOUCH!
	Tts     bool   `json:"tts,omitempty"`
	Embed   *Embed `json:"embed,omitempty"` // embedded rich content

	Files []CreateMessageFileParams `json:"-"` // Always omit as this is included in multipart, not JSON payload

	SpoilerTagContent        bool `json:"-"`
	SpoilerTagAllAttachments bool `json:"-"`

	AllowedMentions *AllowedMentions `json:"allowed_mentions,omitempty"` // The allowed mentions object for the message.
}

CreateMessageParams JSON params for CreateChannelMessage

type CreateWebhookParams added in v0.6.0

type CreateWebhookParams struct {
	Name   string `json:"name"`   // name of the webhook (2-32 characters)
	Avatar string `json:"avatar"` // avatar data uri scheme, image for the default webhook avatar

	// Reason is a X-Audit-Log-Reason header field that will show up on the audit log for this action.
	Reason string `json:"-"`
}

CreateWebhookParams json params for the create webhook rest request avatar string https://discord.com/developers/docs/resources/user#avatar-data

func (*CreateWebhookParams) FindErrors added in v0.10.0

func (c *CreateWebhookParams) FindErrors() error

type Ctrl added in v0.10.0

type Ctrl struct {
	Runs     int
	Until    time.Time
	Duration time.Duration
	Channel  interface{}
}

Ctrl is a handler controller that supports lifetime and max number of execution for one or several handlers.

// register only the first 6 votes
Client.On("MESSAGE_CREATE", filter.NonVotes, registerVoteHandler, &disgord.Ctrl{Runs: 6})

// Allow voting for only 10 minutes
Client.On("MESSAGE_CREATE", filter.NonVotes, registerVoteHandler, &disgord.Ctrl{Duration: 10*time.Second})

// Allow voting until the month is over
Client.On("MESSAGE_CREATE", filter.NonVotes, registerVoteHandler, &disgord.Ctrl{Until: time.Now().AddDate(0, 1, 0)})

func (*Ctrl) CloseChannel added in v0.12.0

func (c *Ctrl) CloseChannel()

CloseChannel must be called instead of closing an event channel directly. This is to make sure Disgord does not go into a deadlock

func (*Ctrl) IsDead added in v0.10.0

func (c *Ctrl) IsDead() bool

func (*Ctrl) OnInsert added in v0.10.0

func (c *Ctrl) OnInsert(Session) error

func (*Ctrl) OnRemove added in v0.10.0

func (c *Ctrl) OnRemove(Session) error

func (*Ctrl) Update added in v0.10.0

func (c *Ctrl) Update()

type CurrentUserQueryBuilder added in v0.19.0

type CurrentUserQueryBuilder interface {
	WithContext(ctx context.Context) CurrentUserQueryBuilder

	// GetCurrentUser Returns the user object of the requester's account. For OAuth2, this requires the identify
	// scope, which will return the object without an email, and optionally the email scope, which returns the object
	// with an email.
	Get(flags ...Flag) (*User, error)

	// UpdateCurrentUser Modify the requester's user account settings. Returns a user object on success.
	Update(flags ...Flag) UpdateCurrentUserBuilder

	// GetCurrentUserGuilds Returns a list of partial guild objects the current user is a member of.
	// Requires the Guilds OAuth2 scope.
	GetGuilds(params *GetCurrentUserGuildsParams, flags ...Flag) (ret []*Guild, err error)

	// LeaveGuild Leave a guild. Returns a 204 empty response on success.
	LeaveGuild(id Snowflake, flags ...Flag) (err error)

	// CreateGroupDM Create a new group DM channel with multiple Users. Returns a DM channel object.
	// This endpoint was intended to be used with the now-deprecated GameBridge SDK. DMs created with this
	// endpoint will not be shown in the Discord Client
	CreateGroupDM(params *CreateGroupDMParams, flags ...Flag) (ret *Channel, err error)

	// GetUserConnections Returns a list of connection objects. Requires the connections OAuth2 scope.
	GetUserConnections(flags ...Flag) (ret []*UserConnection, err error)
}

type DeepCopier added in v0.7.0

type DeepCopier interface {
	DeepCopy() interface{}
}

DeepCopier holds the DeepCopy method which creates and returns a deep copy of any struct.

type DefaultMessageNotificationLvl added in v0.6.0

type DefaultMessageNotificationLvl uint

DefaultMessageNotificationLvl ... https://discord.com/developers/docs/resources/guild#guild-object-default-message-notification-level

const (
	DefaultMessageNotificationLvlAllMessages DefaultMessageNotificationLvl = iota
	DefaultMessageNotificationLvlOnlyMentions
)

different notification levels on new messages

func (*DefaultMessageNotificationLvl) AllMessages added in v0.6.0

func (dmnl *DefaultMessageNotificationLvl) AllMessages() bool

AllMessages ...

func (*DefaultMessageNotificationLvl) OnlyMentions added in v0.6.0

func (dmnl *DefaultMessageNotificationLvl) OnlyMentions() bool

OnlyMentions ...

type DeleteMessagesParams added in v0.10.0

type DeleteMessagesParams struct {
	Messages []Snowflake `json:"messages"`
	// contains filtered or unexported fields
}

DeleteMessagesParams https://discord.com/developers/docs/resources/channel#bulk-delete-messages-json-params

func (*DeleteMessagesParams) AddMessage added in v0.10.0

func (p *DeleteMessagesParams) AddMessage(msg *Message) (err error)

AddMessage Adds a message to be deleted

func (*DeleteMessagesParams) Valid added in v0.10.0

func (p *DeleteMessagesParams) Valid() (err error)

Valid validates the DeleteMessagesParams data

type Discriminator added in v0.8.0

type Discriminator uint16

Discriminator value

func NewDiscriminator added in v0.8.0

func NewDiscriminator(d string) (discriminator Discriminator, err error)

NewDiscriminator Discord user discriminator hashtag

func (Discriminator) MarshalJSON added in v0.8.0

func (d Discriminator) MarshalJSON() (data []byte, err error)

MarshalJSON see interface json.Marshaler

func (Discriminator) NotSet added in v0.8.0

func (d Discriminator) NotSet() bool

NotSet checks if the discriminator is not set

func (Discriminator) String added in v0.8.0

func (d Discriminator) String() (str string)

func (*Discriminator) UnmarshalJSON added in v0.8.0

func (d *Discriminator) UnmarshalJSON(data []byte) error

UnmarshalJSON see interface json.Unmarshaler

type Embed added in v0.10.0

type Embed struct {
	Title       string          `json:"title,omitempty"`       // title of embed
	Type        string          `json:"type,omitempty"`        // type of embed (always "rich" for webhook embeds)
	Description string          `json:"description,omitempty"` // description of embed
	URL         string          `json:"url,omitempty"`         // url of embed
	Timestamp   Time            `json:"timestamp,omitempty"`   // timestamp	timestamp of embed content
	Color       int             `json:"color,omitempty"`       // color code of the embed
	Footer      *EmbedFooter    `json:"footer,omitempty"`      // embed footer object	footer information
	Image       *EmbedImage     `json:"image,omitempty"`       // embed image object	image information
	Thumbnail   *EmbedThumbnail `json:"thumbnail,omitempty"`   // embed thumbnail object	thumbnail information
	Video       *EmbedVideo     `json:"video,omitempty"`       // embed video object	video information
	Provider    *EmbedProvider  `json:"provider,omitempty"`    // embed provider object	provider information
	Author      *EmbedAuthor    `json:"author,omitempty"`      // embed author object	author information
	Fields      []*EmbedField   `json:"fields,omitempty"`      //	array of embed field objects	fields information
}

Embed https://discord.com/developers/docs/resources/channel#embed-object

func (*Embed) CopyOverTo added in v0.10.0

func (c *Embed) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*Embed) DeepCopy added in v0.10.0

func (c *Embed) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type EmbedAuthor added in v0.10.0

type EmbedAuthor struct {
	Name         string `json:"name,omitempty"`           // ?| , name of author
	URL          string `json:"url,omitempty"`            // ?| , url of author
	IconURL      string `json:"icon_url,omitempty"`       // ?| , url of author icon (only supports http(s) and attachments)
	ProxyIconURL string `json:"proxy_icon_url,omitempty"` // ?| , a proxied url of author icon
}

EmbedAuthor https://discord.com/developers/docs/resources/channel#embed-object-embed-author-structure

func (*EmbedAuthor) CopyOverTo added in v0.10.0

func (c *EmbedAuthor) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*EmbedAuthor) DeepCopy added in v0.10.0

func (c *EmbedAuthor) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type EmbedField added in v0.10.0

type EmbedField struct {
	Name   string `json:"name"`             //  | , name of the field
	Value  string `json:"value"`            //  | , value of the field
	Inline bool   `json:"inline,omitempty"` // ?| , whether or not this field should display inline
}

EmbedField https://discord.com/developers/docs/resources/channel#embed-object-embed-field-structure

func (*EmbedField) CopyOverTo added in v0.10.0

func (c *EmbedField) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*EmbedField) DeepCopy added in v0.10.0

func (c *EmbedField) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type EmbedFooter added in v0.10.0

type EmbedFooter struct {
	Text         string `json:"text"`                     //  | , url of author
	IconURL      string `json:"icon_url,omitempty"`       // ?| , url of footer icon (only supports http(s) and attachments)
	ProxyIconURL string `json:"proxy_icon_url,omitempty"` // ?| , a proxied url of footer icon
}

EmbedFooter https://discord.com/developers/docs/resources/channel#embed-object-embed-footer-structure

func (*EmbedFooter) CopyOverTo added in v0.10.0

func (c *EmbedFooter) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*EmbedFooter) DeepCopy added in v0.10.0

func (c *EmbedFooter) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type EmbedImage added in v0.10.0

type EmbedImage struct {
	URL      string `json:"url,omitempty"`       // ?| , source url of image (only supports http(s) and attachments)
	ProxyURL string `json:"proxy_url,omitempty"` // ?| , a proxied url of the image
	Height   int    `json:"height,omitempty"`    // ?| , height of image
	Width    int    `json:"width,omitempty"`     // ?| , width of image
}

EmbedImage https://discord.com/developers/docs/resources/channel#embed-object-embed-image-structure

func (*EmbedImage) CopyOverTo added in v0.10.0

func (c *EmbedImage) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*EmbedImage) DeepCopy added in v0.10.0

func (c *EmbedImage) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type EmbedProvider added in v0.10.0

type EmbedProvider struct {
	Name string `json:"name,omitempty"` // ?| , name of provider
	URL  string `json:"url,omitempty"`  // ?| , url of provider
}

EmbedProvider https://discord.com/developers/docs/resources/channel#embed-object-embed-provider-structure

func (*EmbedProvider) CopyOverTo added in v0.10.0

func (c *EmbedProvider) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*EmbedProvider) DeepCopy added in v0.10.0

func (c *EmbedProvider) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type EmbedThumbnail added in v0.10.0

type EmbedThumbnail struct {
	URL      string `json:"url,omitempty"`       // ?| , source url of image (only supports http(s) and attachments)
	ProxyURL string `json:"proxy_url,omitempty"` // ?| , a proxied url of the image
	Height   int    `json:"height,omitempty"`    // ?| , height of image
	Width    int    `json:"width,omitempty"`     // ?| , width of image
}

EmbedThumbnail https://discord.com/developers/docs/resources/channel#embed-object-embed-thumbnail-structure

func (*EmbedThumbnail) CopyOverTo added in v0.10.0

func (c *EmbedThumbnail) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*EmbedThumbnail) DeepCopy added in v0.10.0

func (c *EmbedThumbnail) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type EmbedVideo added in v0.10.0

type EmbedVideo struct {
	URL    string `json:"url,omitempty"`    // ?| , source url of video
	Height int    `json:"height,omitempty"` // ?| , height of video
	Width  int    `json:"width,omitempty"`  // ?| , width of video
}

EmbedVideo https://discord.com/developers/docs/resources/channel#embed-object-embed-video-structure

func (*EmbedVideo) CopyOverTo added in v0.10.0

func (c *EmbedVideo) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*EmbedVideo) DeepCopy added in v0.10.0

func (c *EmbedVideo) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type Emitter added in v0.9.0

type Emitter interface {
	Emit(name gatewayCmdName, data gatewayCmdPayload) (unhandledGuildIDs []Snowflake, err error)
}

Emitter for emitting data from A to B. Used in websocket connection

type Emoji added in v0.6.0

type Emoji struct {
	ID            Snowflake   `json:"id"`
	Name          string      `json:"name"`
	Roles         []Snowflake `json:"roles,omitempty"`
	User          *User       `json:"user,omitempty"` // the user who created the emoji
	RequireColons bool        `json:"require_colons,omitempty"`
	Managed       bool        `json:"managed,omitempty"`
	Animated      bool        `json:"animated,omitempty"`
}

Emoji ...

func (*Emoji) CopyOverTo added in v0.7.0

func (e *Emoji) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*Emoji) DeepCopy added in v0.7.0

func (e *Emoji) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

func (*Emoji) Mention added in v0.6.0

func (e *Emoji) Mention() string

Mention mentions an emoji. Adds the animation prefix, if animated

func (*Emoji) Reset added in v0.10.0

func (e *Emoji) Reset()

func (*Emoji) String added in v0.10.0

func (e *Emoji) String() string

type Err added in v0.12.2

type Err = disgorderr.Err

TODO: go generate from internal/errors/*

type ErrRest added in v0.8.0

type ErrRest = httd.ErrREST

type ErrorEmptyValue added in v0.7.0

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

ErrorEmptyValue when a required value was set as empty

func (*ErrorEmptyValue) Error added in v0.7.0

func (e *ErrorEmptyValue) Error() string

type ErrorMissingSnowflake added in v0.7.0

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

ErrorMissingSnowflake used by methods about to communicate with the Discord API. If a snowflake value is required this is used to identify that you must set the value before being able to interact with the Discord API

func (*ErrorMissingSnowflake) Error added in v0.7.0

func (e *ErrorMissingSnowflake) Error() string

type ErrorUnsupportedType added in v0.7.0

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

ErrorUnsupportedType used when the given param type is not supported

func (*ErrorUnsupportedType) Error added in v0.7.0

func (e *ErrorUnsupportedType) Error() string

type EventType added in v0.19.0

type EventType interface {
	// contains filtered or unexported methods
}

type ExecuteWebhookParams added in v0.6.0

type ExecuteWebhookParams struct {
	Content   string      `json:"content"`
	Username  string      `json:"username"`
	AvatarURL string      `json:"avatar_url"`
	TTS       bool        `json:"tts"`
	File      interface{} `json:"file"`
	Embeds    []*Embed    `json:"embeds"`
}

ExecuteWebhookParams JSON params for func ExecuteWebhook

type ExplicitContentFilterLvl added in v0.6.0

type ExplicitContentFilterLvl uint

ExplicitContentFilterLvl ... https://discord.com/developers/docs/resources/guild#guild-object-explicit-content-filter-level

const (
	ExplicitContentFilterLvlDisabled ExplicitContentFilterLvl = iota
	ExplicitContentFilterLvlMembersWithoutRoles
	ExplicitContentFilterLvlAllMembers
)

Explicit content filter levels

func (*ExplicitContentFilterLvl) AllMembers added in v0.6.0

func (ecfl *ExplicitContentFilterLvl) AllMembers() bool

AllMembers if the filter applies for all members regardles of them having a role or not

func (*ExplicitContentFilterLvl) Disabled added in v0.6.0

func (ecfl *ExplicitContentFilterLvl) Disabled() bool

Disabled if the content filter is disabled

func (*ExplicitContentFilterLvl) MembersWithoutRoles added in v0.6.0

func (ecfl *ExplicitContentFilterLvl) MembersWithoutRoles() bool

MembersWithoutRoles if the filter only applies for members without a role

type Flag added in v0.10.0

type Flag uint32
const (
	IgnoreCache Flag = 1 << iota
	IgnoreEmptyParams

	// sort options
	SortByID
	SortByName
	SortByHoist
	SortByGuildID
	SortByChannelID

	// ordering
	OrderAscending // default when sorting
	OrderDescending
)

func (Flag) IgnoreEmptyParams added in v0.10.0

func (f Flag) IgnoreEmptyParams() bool

func (Flag) Ignorecache added in v0.10.0

func (f Flag) Ignorecache() bool

func (Flag) Sort added in v0.10.0

func (f Flag) Sort() bool

func (Flag) String added in v0.10.0

func (i Flag) String() string

type GetCurrentUserGuildsBuilder added in v0.19.0

type GetCurrentUserGuildsBuilder interface {
	Execute() (guilds []*Guild, err error)
	IgnoreCache() GetCurrentUserGuildsBuilder
	CancelOnRatelimit() GetCurrentUserGuildsBuilder
	URLParam(name string, v interface{}) GetCurrentUserGuildsBuilder
	Set(name string, v interface{}) GetCurrentUserGuildsBuilder
	SetBefore(before Snowflake) GetCurrentUserGuildsBuilder
	SetAfter(after Snowflake) GetCurrentUserGuildsBuilder
	SetLimit(limit int) GetCurrentUserGuildsBuilder
}

GetCurrentUserGuildsBuilder is the interface for the builder.

type GetCurrentUserGuildsParams added in v0.6.0

type GetCurrentUserGuildsParams struct {
	Before Snowflake `urlparam:"before,omitempty"`
	After  Snowflake `urlparam:"after,omitempty"`
	Limit  int       `urlparam:"limit,omitempty"`
}

GetCurrentUserGuildsParams JSON params for func GetCurrentUserGuilds

func (*GetCurrentUserGuildsParams) URLQueryString added in v0.10.0

func (g *GetCurrentUserGuildsParams) URLQueryString() string

type GetMembersParams added in v0.10.0

type GetMembersParams struct {
	After Snowflake `urlparam:"after,omitempty"`
	Limit uint32    `urlparam:"limit,omitempty"` // 0 will fetch everyone
}

GetMembersParams if Limit is 0, every member is fetched. This does not follow the Discord API where a 0 is converted into a 1. 0 = every member. The rest is exactly the same, you should be able to do everything the Discord docs says with the addition that you can bypass a limit of 1,000.

If you specify a limit of +1,000 Disgord will run N requests until that amount is met, or until you run out of members to fetch.

type GetMessagesParams added in v0.9.3

type GetMessagesParams struct {
	Around Snowflake `urlparam:"around,omitempty"`
	Before Snowflake `urlparam:"before,omitempty"`
	After  Snowflake `urlparam:"after,omitempty"`
	Limit  uint      `urlparam:"limit,omitempty"`
}

GetChannelMessagesParams https://discord.com/developers/docs/resources/channel#get-channel-messages-query-string-params TODO: ensure limits

func (*GetMessagesParams) URLQueryString added in v0.10.0

func (g *GetMessagesParams) URLQueryString() string

func (*GetMessagesParams) Validate added in v0.12.0

func (g *GetMessagesParams) Validate() error

type GetReactionURLParams added in v0.6.0

type GetReactionURLParams struct {
	Before Snowflake `urlparam:"before,omitempty"` // get Users before this user Snowflake
	After  Snowflake `urlparam:"after,omitempty"`  // get Users after this user Snowflake
	Limit  int       `urlparam:"limit,omitempty"`  // max number of Users to return (1-100)
}

GetReactionURLParams https://discord.com/developers/docs/resources/channel#get-reactions-query-string-params

func (*GetReactionURLParams) URLQueryString added in v0.10.0

func (g *GetReactionURLParams) URLQueryString() string

type GetUserBuilder added in v0.19.0

type GetUserBuilder interface {
	IgnoreCache() GetUserBuilder
	CancelOnRatelimit() GetUserBuilder
	URLParam(name string, v interface{}) GetUserBuilder
	Set(name string, v interface{}) GetUserBuilder
}

GetUserBuilder is the interface for the builder.

type GetUserConnectionsBuilder added in v0.19.0

type GetUserConnectionsBuilder interface {
	Execute() (cons []*UserConnection, err error)
	IgnoreCache() GetUserConnectionsBuilder
	CancelOnRatelimit() GetUserConnectionsBuilder
	URLParam(name string, v interface{}) GetUserConnectionsBuilder
	Set(name string, v interface{}) GetUserConnectionsBuilder
}

GetUserConnectionsBuilder is the interface for the builder.

type GetUserDMsBuilder added in v0.19.0

type GetUserDMsBuilder interface {
	Execute() (channels []*Channel, err error)
	IgnoreCache() GetUserDMsBuilder
	CancelOnRatelimit() GetUserDMsBuilder
	URLParam(name string, v interface{}) GetUserDMsBuilder
	Set(name string, v interface{}) GetUserDMsBuilder
}

GetUserDMsBuilder is the interface for the builder.

type GroupDMParticipant added in v0.10.0

type GroupDMParticipant struct {
	AccessToken string    `json:"access_token"`   // access token of a user that has granted your app the gdm.join scope
	Nickname    string    `json:"nick,omitempty"` // nickname of the user being added
	UserID      Snowflake `json:"-"`
}

GroupDMParticipant Information needed to add a recipient to a group chat

func (*GroupDMParticipant) FindErrors added in v0.10.0

func (g *GroupDMParticipant) FindErrors() error

type Guild added in v0.6.0

type Guild struct {
	ID                          Snowflake                     `json:"id"`
	ApplicationID               Snowflake                     `json:"application_id"` //   |?
	Name                        string                        `json:"name"`
	Icon                        string                        `json:"icon"`            //  |?, icon hash
	Splash                      string                        `json:"splash"`          //  |?, image hash
	Owner                       bool                          `json:"owner,omitempty"` // ?|
	OwnerID                     Snowflake                     `json:"owner_id"`
	Permissions                 PermissionBit                 `json:"permissions,omitempty"` // ?|, permission flags for connected user `/users/@me/guilds`
	Region                      string                        `json:"region"`
	AfkChannelID                Snowflake                     `json:"afk_channel_id"` // |?
	AfkTimeout                  uint                          `json:"afk_timeout"`
	VerificationLevel           VerificationLvl               `json:"verification_level"`
	DefaultMessageNotifications DefaultMessageNotificationLvl `json:"default_message_notifications"`
	ExplicitContentFilter       ExplicitContentFilterLvl      `json:"explicit_content_filter"`
	Roles                       []*Role                       `json:"roles"`
	Emojis                      []*Emoji                      `json:"emojis"`
	Features                    []string                      `json:"features"`
	MFALevel                    MFALvl                        `json:"mfa_level"`
	WidgetEnabled               bool                          `json:"widget_enabled,omit_empty"`    //   |
	WidgetChannelID             Snowflake                     `json:"widget_channel_id,omit_empty"` //   |?
	SystemChannelID             Snowflake                     `json:"system_channel_id,omitempty"`  //   |?

	// JoinedAt must be a pointer, as we can't hide non-nil structs
	JoinedAt    *Time           `json:"joined_at,omitempty"`    // ?*|
	Large       bool            `json:"large,omitempty"`        // ?*|
	Unavailable bool            `json:"unavailable"`            // ?*| omitempty?
	MemberCount uint            `json:"member_count,omitempty"` // ?*|
	VoiceStates []*VoiceState   `json:"voice_states,omitempty"` // ?*|
	Members     []*Member       `json:"members,omitempty"`      // ?*|
	Channels    []*Channel      `json:"channels,omitempty"`     // ?*|
	Presences   []*UserPresence `json:"presences,omitempty"`    // ?*|
}

Guild Guilds in Discord represent an isolated collection of Users and Channels,

and are often referred to as "servers" in the UI.

https://discord.com/developers/docs/resources/guild#guild-object Fields with `*` are only sent within the GUILD_CREATE event reviewed: 2018-08-25

func (*Guild) AddChannel added in v0.6.0

func (g *Guild) AddChannel(c *Channel) error

AddChannel adds a channel to the Guild object. Note that this method does not interact with Discord.

func (*Guild) AddMember added in v0.6.0

func (g *Guild) AddMember(member *Member) error

AddMember adds a member to the Guild object. Note that this method does not interact with Discord.

func (*Guild) AddMembers added in v0.7.0

func (g *Guild) AddMembers(members []*Member)

AddMembers adds multiple members to the Guild object. Note that this method does not interact with Discord.

func (*Guild) AddRole added in v0.6.0

func (g *Guild) AddRole(role *Role) error

AddRole adds a role to the Guild object. Note that this does not interact with Discord.

func (*Guild) Channel added in v0.6.0

func (g *Guild) Channel(id Snowflake) (*Channel, error)

Channel get a guild channel given it's ID

func (*Guild) CopyOverTo added in v0.7.0

func (g *Guild) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*Guild) DeepCopy added in v0.6.0

func (g *Guild) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

func (*Guild) DeleteChannel added in v0.6.0

func (g *Guild) DeleteChannel(c *Channel) error

DeleteChannel removes a channel from the Guild object. Note that this method does not interact with Discord.

func (*Guild) DeleteChannelByID added in v0.6.0

func (g *Guild) DeleteChannelByID(ID Snowflake) error

DeleteChannelByID removes a channel from the Guild object. Note that this method does not interact with Discord.

func (*Guild) DeleteRoleByID added in v0.6.0

func (g *Guild) DeleteRoleByID(ID Snowflake)

DeleteRoleByID remove a role from the guild struct

func (*Guild) Emoji added in v0.8.0

func (g *Guild) Emoji(id Snowflake) (emoji *Emoji, err error)

Emoji get a guild emoji by it's ID

func (*Guild) GetMemberWithHighestSnowflake added in v0.7.0

func (g *Guild) GetMemberWithHighestSnowflake() *Member

GetMemberWithHighestSnowflake finds the member with the highest snowflake value.

func (*Guild) GetMembersCountEstimate added in v0.12.0

func (g *Guild) GetMembersCountEstimate(ctx context.Context, s Session) (estimate int, err error)

GetMembersCountEstimate estimates the number of members in a guild without fetching everyone. There is no proper way to get this number, so a invite is created and the estimate is read from there. The invite is then deleted again.

func (*Guild) Member added in v0.6.0

func (g *Guild) Member(id Snowflake) (*Member, error)

Member return a member by his/her userid

func (*Guild) MembersByName added in v0.7.0

func (g *Guild) MembersByName(name string) (members []*Member)

MembersByName retrieve a slice of members with same username or nickname

func (*Guild) Reset added in v0.10.0

func (g *Guild) Reset()

func (*Guild) Role added in v0.6.0

func (g *Guild) Role(id Snowflake) (role *Role, err error)

Role retrieve a role based on role id

func (*Guild) RoleByName added in v0.6.0

func (g *Guild) RoleByName(name string) ([]*Role, error)

RoleByName retrieves a slice of roles with same name

func (*Guild) String added in v0.10.0

func (g *Guild) String() string

type GuildAuditLogsBuilder added in v0.19.0

type GuildAuditLogsBuilder interface {
	Execute() (log *AuditLog, err error)
	IgnoreCache() GuildAuditLogsBuilder
	CancelOnRatelimit() GuildAuditLogsBuilder
	URLParam(name string, v interface{}) GuildAuditLogsBuilder
	Set(name string, v interface{}) GuildAuditLogsBuilder
	SetUserID(userID Snowflake) GuildAuditLogsBuilder
	SetActionType(actionType uint) GuildAuditLogsBuilder
	SetBefore(before Snowflake) GuildAuditLogsBuilder
	SetLimit(limit int) GuildAuditLogsBuilder
}

GuildAuditLogsBuilder is the interface for the builder.

type GuildBanAdd added in v0.6.0

type GuildBanAdd struct {
	GuildID Snowflake `json:"guild_id"`
	User    *User     `json:"user"`
	ShardID uint      `json:"-"`
}

GuildBanAdd user was banned from a guild

type GuildBanAddHandler added in v0.9.0

type GuildBanAddHandler = func(s Session, h *GuildBanAdd)

GuildBanAddHandler is triggered in GuildBanAdd events

type GuildBanRemove added in v0.6.0

type GuildBanRemove struct {
	GuildID Snowflake `json:"guild_id"`
	User    *User     `json:"user"`
	ShardID uint      `json:"-"`
}

GuildBanRemove user was unbanned from a guild

type GuildBanRemoveHandler added in v0.9.0

type GuildBanRemoveHandler = func(s Session, h *GuildBanRemove)

GuildBanRemoveHandler is triggered in GuildBanRemove events

type GuildCreate added in v0.6.0

type GuildCreate struct {
	Guild   *Guild `json:"guild"`
	ShardID uint   `json:"-"`
}

GuildCreate 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 (*GuildCreate) UnmarshalJSON added in v0.8.0

func (obj *GuildCreate) UnmarshalJSON(data []byte) error

UnmarshalJSON ...

type GuildCreateHandler added in v0.9.0

type GuildCreateHandler = func(s Session, h *GuildCreate)

GuildCreateHandler is triggered in GuildCreate events

type GuildDelete added in v0.6.0

type GuildDelete struct {
	UnavailableGuild *GuildUnavailable `json:"guild_unavailable"`
	ShardID          uint              `json:"-"`
}

GuildDelete guild became unavailable, or user left/was removed from a guild

func (*GuildDelete) UnmarshalJSON added in v0.8.0

func (obj *GuildDelete) UnmarshalJSON(data []byte) error

UnmarshalJSON ...

func (*GuildDelete) UserWasRemoved added in v0.8.0

func (obj *GuildDelete) UserWasRemoved() bool

UserWasRemoved ... TODO

type GuildDeleteHandler added in v0.9.0

type GuildDeleteHandler = func(s Session, h *GuildDelete)

GuildDeleteHandler is triggered in GuildDelete events

type GuildEmbed added in v0.6.0

type GuildEmbed struct {
	Enabled   bool      `json:"enabled"`
	ChannelID Snowflake `json:"channel_id"`
}

GuildEmbed https://discord.com/developers/docs/resources/guild#guild-embed-object

func (*GuildEmbed) CopyOverTo added in v0.7.0

func (e *GuildEmbed) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*GuildEmbed) DeepCopy added in v0.7.0

func (e *GuildEmbed) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type GuildEmojiQueryBuilder added in v0.19.0

type GuildEmojiQueryBuilder interface {
	WithContext(ctx context.Context) GuildEmojiQueryBuilder

	Get(flags ...Flag) (*Emoji, error)
	Update(flags ...Flag) UpdateGuildEmojiBuilder
	Delete(flags ...Flag) error
}

type GuildEmojisUpdate added in v0.6.0

type GuildEmojisUpdate struct {
	GuildID Snowflake `json:"guild_id"`
	Emojis  []*Emoji  `json:"emojis"`
	ShardID uint      `json:"-"`
}

GuildEmojisUpdate guild emojis were updated

type GuildEmojisUpdateHandler added in v0.9.0

type GuildEmojisUpdateHandler = func(s Session, h *GuildEmojisUpdate)

GuildEmojisUpdateHandler is triggered in GuildEmojisUpdate events

type GuildIntegrationsUpdate added in v0.6.0

type GuildIntegrationsUpdate struct {
	GuildID Snowflake `json:"guild_id"`
	ShardID uint      `json:"-"`
}

GuildIntegrationsUpdate guild integration was updated

type GuildIntegrationsUpdateHandler added in v0.9.0

type GuildIntegrationsUpdateHandler = func(s Session, h *GuildIntegrationsUpdate)

GuildIntegrationsUpdateHandler is triggered in GuildIntegrationsUpdate events

type GuildMemberAdd added in v0.6.0

type GuildMemberAdd struct {
	Member  *Member `json:"member"`
	ShardID uint    `json:"-"`
}

GuildMemberAdd new user joined a guild

func (*GuildMemberAdd) UnmarshalJSON added in v0.9.0

func (obj *GuildMemberAdd) UnmarshalJSON(data []byte) error

UnmarshalJSON ...

type GuildMemberAddHandler added in v0.9.0

type GuildMemberAddHandler = func(s Session, h *GuildMemberAdd)

GuildMemberAddHandler is triggered in GuildMemberAdd events

type GuildMemberQueryBuilder added in v0.19.0

type GuildMemberQueryBuilder interface {
	WithContext(ctx context.Context) GuildMemberQueryBuilder

	Get(flags ...Flag) (*Member, error)
	Update(flags ...Flag) UpdateGuildMemberBuilder
	AddRole(roleID Snowflake, flags ...Flag) error
	RemoveRole(roleID Snowflake, flags ...Flag) error
	Kick(reason string, flags ...Flag) error
	Ban(params *BanMemberParams, flags ...Flag) error
}

type GuildMemberRemove added in v0.6.0

type GuildMemberRemove struct {
	GuildID Snowflake `json:"guild_id"`
	User    *User     `json:"user"`
	ShardID uint      `json:"-"`
}

GuildMemberRemove user was removed from a guild

type GuildMemberRemoveHandler added in v0.9.0

type GuildMemberRemoveHandler = func(s Session, h *GuildMemberRemove)

GuildMemberRemoveHandler is triggered in GuildMemberRemove events

type GuildMemberUpdate added in v0.6.0

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

GuildMemberUpdate guild member was updated

type GuildMemberUpdateHandler added in v0.9.0

type GuildMemberUpdateHandler = func(s Session, h *GuildMemberUpdate)

GuildMemberUpdateHandler is triggered in GuildMemberUpdate events

type GuildMembersChunk added in v0.6.0

type GuildMembersChunk struct {
	GuildID Snowflake `json:"guild_id"`
	Members []*Member `json:"members"`
	ShardID uint      `json:"-"`
}

GuildMembersChunk response to Request Guild Members

type GuildMembersChunkHandler added in v0.9.0

type GuildMembersChunkHandler = func(s Session, h *GuildMembersChunk)

GuildMembersChunkHandler is triggered in GuildMembersChunk events

type GuildQueryBuilder added in v0.19.0

type GuildQueryBuilder interface {
	WithContext(ctx context.Context) GuildQueryBuilder

	// TODO: Add more guild attribute things. Waiting for caching changes before then.
	Get(flags ...Flag) (guild *Guild, err error)
	// TODO: For GetChannels, it might sense to have the option for a function to filter before each channel ends up deep copied.
	// TODO-2: This could be much more performant in guilds with a large number of channels.
	GetChannels(flags ...Flag) ([]*Channel, error)
	// TODO: For GetMembers, it might sense to have the option for a function to filter before each member ends up deep copied.
	// TODO-2: This could be much more performant in larger guilds where this is needed.
	GetMembers(params *GetMembersParams, flags ...Flag) ([]*Member, error)
	Update(flags ...Flag) UpdateGuildBuilder
	Delete(flags ...Flag) error

	CreateChannel(name string, params *CreateGuildChannelParams, flags ...Flag) (*Channel, error)
	UpdateChannelPositions(params []UpdateGuildChannelPositionsParams, flags ...Flag) error
	CreateMember(userID Snowflake, accessToken string, params *AddGuildMemberParams, flags ...Flag) (*Member, error)
	Member(userID Snowflake) GuildMemberQueryBuilder

	KickVoiceParticipant(userID Snowflake) error
	SetCurrentUserNick(nick string, flags ...Flag) (newNick string, err error)
	GetBans(flags ...Flag) ([]*Ban, error)
	GetBan(userID Snowflake, flags ...Flag) (*Ban, error)
	UnbanUser(userID Snowflake, reason string, flags ...Flag) error
	// TODO: For GetRoles, it might sense to have the option for a function to filter before each role ends up deep copied.
	// TODO-2: This could be much more performant in larger guilds where this is needed.
	// TODO-3: Add GetRole.
	GetRoles(flags ...Flag) ([]*Role, error)
	GetMemberPermissions(userID Snowflake, flags ...Flag) (permissions PermissionBit, err error)
	UpdateRolePositions(params []UpdateGuildRolePositionsParams, flags ...Flag) ([]*Role, error)
	CreateRole(params *CreateGuildRoleParams, flags ...Flag) (*Role, error)
	Role(roleID Snowflake) GuildRoleQueryBuilder

	EstimatePruneMembersCount(days int, flags ...Flag) (estimate int, err error)
	PruneMembers(days int, reason string, flags ...Flag) error
	GetVoiceRegions(flags ...Flag) ([]*VoiceRegion, error)
	GetInvites(flags ...Flag) ([]*Invite, error)

	GetIntegrations(flags ...Flag) ([]*Integration, error)
	CreateIntegration(params *CreateGuildIntegrationParams, flags ...Flag) error
	UpdateIntegration(integrationID Snowflake, params *UpdateGuildIntegrationParams, flags ...Flag) error
	DeleteIntegration(integrationID Snowflake, flags ...Flag) error
	SyncIntegration(integrationID Snowflake, flags ...Flag) error

	GetEmbed(flags ...Flag) (*GuildEmbed, error)
	UpdateEmbed(flags ...Flag) UpdateGuildEmbedBuilder
	GetVanityURL(flags ...Flag) (*PartialInvite, error)
	GetAuditLogs(flags ...Flag) GuildAuditLogsBuilder
	VoiceConnect(channelID Snowflake) (ret VoiceConnection, err error)

	// TODO: For GetEmojis, it might sense to have the option for a function to filter before each emoji ends up deep copied.
	// TODO-2: This could be much more performant in guilds with a large number of channels.
	GetEmojis(flags ...Flag) ([]*Emoji, error)
	CreateEmoji(params *CreateGuildEmojiParams, flags ...Flag) (*Emoji, error)
	Emoji(emojiID Snowflake) GuildEmojiQueryBuilder

	GetWebhooks(flags ...Flag) (ret []*Webhook, err error)
}

GuildQueryBuilder defines the exposed functions from the guild query builder.

type GuildQueryBuilderCaller added in v0.19.0

type GuildQueryBuilderCaller interface {
	Guild(id Snowflake) GuildQueryBuilder
}

type GuildRoleCreate added in v0.6.0

type GuildRoleCreate struct {
	GuildID Snowflake `json:"guild_id"`
	Role    *Role     `json:"role"`
	ShardID uint      `json:"-"`
}

GuildRoleCreate guild role was created

type GuildRoleCreateHandler added in v0.9.0

type GuildRoleCreateHandler = func(s Session, h *GuildRoleCreate)

GuildRoleCreateHandler is triggered in GuildRoleCreate events

type GuildRoleDelete added in v0.6.0

type GuildRoleDelete struct {
	GuildID Snowflake `json:"guild_id"`
	RoleID  Snowflake `json:"role_id"`
	ShardID uint      `json:"-"`
}

GuildRoleDelete a guild role was deleted

type GuildRoleDeleteHandler added in v0.9.0

type GuildRoleDeleteHandler = func(s Session, h *GuildRoleDelete)

GuildRoleDeleteHandler is triggered in GuildRoleDelete events

type GuildRoleQueryBuilder added in v0.19.0

type GuildRoleQueryBuilder interface {
	WithContext(ctx context.Context) GuildRoleQueryBuilder

	Update(flags ...Flag) (builder UpdateGuildRoleBuilder)
	Delete(flags ...Flag) error
}

type GuildRoleUpdate added in v0.6.0

type GuildRoleUpdate struct {
	GuildID Snowflake `json:"guild_id"`
	Role    *Role     `json:"role"`
	ShardID uint      `json:"-"`
}

GuildRoleUpdate guild role was updated

type GuildRoleUpdateHandler added in v0.9.0

type GuildRoleUpdateHandler = func(s Session, h *GuildRoleUpdate)

GuildRoleUpdateHandler is triggered in GuildRoleUpdate events

type GuildUnavailable added in v0.6.0

type GuildUnavailable struct {
	ID          Snowflake `json:"id"`
	Unavailable bool      `json:"unavailable"` // ?*|
}

GuildUnavailable is a partial Guild object.

type GuildUpdate added in v0.6.0

type GuildUpdate struct {
	Guild   *Guild `json:"guild"`
	ShardID uint   `json:"-"`
}

GuildUpdate guild was updated

func (*GuildUpdate) UnmarshalJSON added in v0.8.0

func (obj *GuildUpdate) UnmarshalJSON(data []byte) error

UnmarshalJSON ...

type GuildUpdateHandler added in v0.9.0

type GuildUpdateHandler = func(s Session, h *GuildUpdate)

GuildUpdateHandler is triggered in GuildUpdate events

type Handler added in v0.9.2

type Handler = interface{}

Handler needs to match one of the *Handler signatures

type HandlerChannelCreate added in v0.17.0

type HandlerChannelCreate = func(Session, *ChannelCreate)

type HandlerChannelDelete added in v0.17.0

type HandlerChannelDelete = func(Session, *ChannelDelete)

type HandlerChannelPinsUpdate added in v0.17.0

type HandlerChannelPinsUpdate = func(Session, *ChannelPinsUpdate)

type HandlerChannelUpdate added in v0.17.0

type HandlerChannelUpdate = func(Session, *ChannelUpdate)

type HandlerCtrl added in v0.9.2

type HandlerCtrl interface {
	OnInsert(Session) error
	OnRemove(Session) error

	// IsDead does not need to be locked as the demultiplexer access it synchronously.
	IsDead() bool

	// Update For every time Update is called, it's internal trackers must be updated.
	// you should assume that .Update() means the handler was used.
	Update()
}

HandlerCtrl used when inserting a handler to dictate whether or not the handler(s) should still be kept in the handlers list..

type HandlerGuildBanAdd added in v0.17.0

type HandlerGuildBanAdd = func(Session, *GuildBanAdd)

type HandlerGuildBanRemove added in v0.17.0

type HandlerGuildBanRemove = func(Session, *GuildBanRemove)

type HandlerGuildCreate added in v0.17.0

type HandlerGuildCreate = func(Session, *GuildCreate)

type HandlerGuildDelete added in v0.17.0

type HandlerGuildDelete = func(Session, *GuildDelete)

type HandlerGuildEmojisUpdate added in v0.17.0

type HandlerGuildEmojisUpdate = func(Session, *GuildEmojisUpdate)

type HandlerGuildIntegrationsUpdate added in v0.17.0

type HandlerGuildIntegrationsUpdate = func(Session, *GuildIntegrationsUpdate)

type HandlerGuildMemberAdd added in v0.17.0

type HandlerGuildMemberAdd = func(Session, *GuildMemberAdd)

type HandlerGuildMemberRemove added in v0.17.0

type HandlerGuildMemberRemove = func(Session, *GuildMemberRemove)

type HandlerGuildMemberUpdate added in v0.17.0

type HandlerGuildMemberUpdate = func(Session, *GuildMemberUpdate)

type HandlerGuildMembersChunk added in v0.17.0

type HandlerGuildMembersChunk = func(Session, *GuildMembersChunk)

type HandlerGuildRoleCreate added in v0.17.0

type HandlerGuildRoleCreate = func(Session, *GuildRoleCreate)

type HandlerGuildRoleDelete added in v0.17.0

type HandlerGuildRoleDelete = func(Session, *GuildRoleDelete)

type HandlerGuildRoleUpdate added in v0.17.0

type HandlerGuildRoleUpdate = func(Session, *GuildRoleUpdate)

type HandlerGuildUpdate added in v0.17.0

type HandlerGuildUpdate = func(Session, *GuildUpdate)

type HandlerInviteCreate added in v0.17.0

type HandlerInviteCreate = func(Session, *InviteCreate)

type HandlerInviteDelete added in v0.17.0

type HandlerInviteDelete = func(Session, *InviteDelete)

type HandlerMessageCreate added in v0.17.0

type HandlerMessageCreate = func(Session, *MessageCreate)

type HandlerMessageDelete added in v0.17.0

type HandlerMessageDelete = func(Session, *MessageDelete)

type HandlerMessageDeleteBulk added in v0.17.0

type HandlerMessageDeleteBulk = func(Session, *MessageDeleteBulk)

type HandlerMessageReactionAdd added in v0.17.0

type HandlerMessageReactionAdd = func(Session, *MessageReactionAdd)

type HandlerMessageReactionRemove added in v0.17.0

type HandlerMessageReactionRemove = func(Session, *MessageReactionRemove)

type HandlerMessageReactionRemoveAll added in v0.17.0

type HandlerMessageReactionRemoveAll = func(Session, *MessageReactionRemoveAll)

type HandlerMessageReactionRemoveEmoji added in v0.20.0

type HandlerMessageReactionRemoveEmoji = func(Session, *MessageReactionRemoveEmoji)

type HandlerMessageUpdate added in v0.17.0

type HandlerMessageUpdate = func(Session, *MessageUpdate)

type HandlerPresenceUpdate added in v0.17.0

type HandlerPresenceUpdate = func(Session, *PresenceUpdate)

type HandlerReady added in v0.17.0

type HandlerReady = func(Session, *Ready)

type HandlerResumed added in v0.17.0

type HandlerResumed = func(Session, *Resumed)

type HandlerSpecErr added in v0.16.5

type HandlerSpecErr = disgorderr.HandlerSpecErr

type HandlerTypingStart added in v0.17.0

type HandlerTypingStart = func(Session, *TypingStart)

type HandlerUserUpdate added in v0.17.0

type HandlerUserUpdate = func(Session, *UserUpdate)

type HandlerVoiceServerUpdate added in v0.17.0

type HandlerVoiceServerUpdate = func(Session, *VoiceServerUpdate)

type HandlerVoiceStateUpdate added in v0.17.0

type HandlerVoiceStateUpdate = func(Session, *VoiceStateUpdate)

type HandlerWebhooksUpdate added in v0.17.0

type HandlerWebhooksUpdate = func(Session, *WebhooksUpdate)

type Integration added in v0.6.0

type Integration struct {
	ID                Snowflake           `json:"id"`
	Name              string              `json:"name"`
	Type              string              `json:"type"`
	Enabled           bool                `json:"enabled"`
	Syncing           bool                `json:"syncing"`
	RoleID            Snowflake           `json:"role_id"`
	ExpireBehavior    int                 `json:"expire_behavior"`
	ExpireGracePeriod int                 `json:"expire_grace_period"`
	User              *User               `json:"user"`
	Account           *IntegrationAccount `json:"account"`
}

Integration https://discord.com/developers/docs/resources/guild#integration-object

func (*Integration) CopyOverTo added in v0.7.0

func (i *Integration) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*Integration) DeepCopy added in v0.7.0

func (i *Integration) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type IntegrationAccount added in v0.6.0

type IntegrationAccount struct {
	ID   string `json:"id"`   // id of the account
	Name string `json:"name"` // name of the account
}

IntegrationAccount https://discord.com/developers/docs/resources/guild#integration-account-object

func (*IntegrationAccount) CopyOverTo added in v0.7.0

func (i *IntegrationAccount) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*IntegrationAccount) DeepCopy added in v0.7.0

func (i *IntegrationAccount) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type Intent added in v0.20.0

type Intent = gateway.Intent

type Invite added in v0.6.0

type Invite struct {
	// Code the invite code (unique Snowflake)
	Code string `json:"code"`

	// Guild the guild this invite is for
	Guild *Guild `json:"guild"`

	// Channel the channel this invite is for
	Channel *PartialChannel `json:"channel"`

	// Inviter the user that created the invite
	Inviter *User `json:"inviter"`

	// CreatedAt the time at which the invite was created
	CreatedAt Time `json:"created_at"`

	// MaxAge how long the invite is valid for (in seconds)
	MaxAge int `json:"max_age"`

	// MaxUses the maximum number of times the invite can be used
	MaxUses int `json:"max_uses"`

	// Temporary whether or not the invite is temporary (invited Users will be kicked on disconnect unless they're assigned a role)
	Temporary bool `json:"temporary"`

	// Uses how many times the invite has been used (always will be 0)
	Uses int `json:"uses"`

	Revoked bool `json:"revoked"`
	Unique  bool `json:"unique"`

	// ApproximatePresenceCount approximate count of online members
	ApproximatePresenceCount int `json:"approximate_presence_count,omitempty"`

	// ApproximatePresenceCount approximate count of total members
	ApproximateMemberCount int `json:"approximate_member_count,omitempty"`
}

Invite Represents a code that when used, adds a user to a guild. https://discord.com/developers/docs/resources/invite#invite-object Reviewed: 2018-06-10

func (*Invite) CopyOverTo added in v0.7.0

func (i *Invite) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*Invite) DeepCopy added in v0.7.0

func (i *Invite) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type InviteCreate added in v0.17.0

type InviteCreate struct {
	// Code the invite code (unique Snowflake)
	Code string `json:"code"`

	// GuildID the guild this invite is for
	GuildID Snowflake `json:"guild_id,omitempty"`

	// ChannelID the channel this invite is for
	ChannelID Snowflake `json:"channel_id"`

	// Inviter the user that created the invite
	Inviter *User `json:"inviter"`

	// Target the target user for this invite
	Target *User `json:"target_user,omitempty"`

	// TargetType the type of user target for this invite
	// 1 STREAM (currently the STREAM only)
	TargetType int `json:"target_user_type"`

	// CreatedAt the time at which the invite was created
	CreatedAt Time `json:"created_at"`

	// MaxAge how long the invite is valid for (in seconds)
	MaxAge int `json:"max_age"`

	// MaxUses the maximum number of times the invite can be used
	MaxUses int `json:"max_uses"`

	// Temporary whether or not the invite is temporary (invited Users will be kicked on disconnect unless they're assigned a role)
	Temporary bool `json:"temporary"`

	// Uses how many times the invite has been used (always will be 0)
	Uses int `json:"uses"`

	Revoked bool `json:"revoked"`
	Unique  bool `json:"unique"`

	// ApproximatePresenceCount approximate count of online members
	ApproximatePresenceCount int `json:"approximate_presence_count,omitempty"`

	// ApproximatePresenceCount approximate count of total members
	ApproximateMemberCount int `json:"approximate_member_count,omitempty"`

	ShardID uint `json:"-"`
}

InviteCreate guild invite was created

type InviteCreateHandler added in v0.17.0

type InviteCreateHandler = func(s Session, h *InviteCreate)

InviteCreateHandler is triggered in InviteCreate events

type InviteDelete added in v0.17.0

type InviteDelete struct {
	ChannelID Snowflake `json:"channel_id"`
	GuildID   Snowflake `json:"guild_id"`
	Code      string    `json:"code"`
	ShardID   uint      `json:"-"`
}

InviteDelete Sent when an invite is deleted.

type InviteDeleteHandler added in v0.17.0

type InviteDeleteHandler = func(s Session, h *InviteDelete)

InviteDeleteHandler is triggered in InviteDelete events

type InviteMetadata added in v0.6.0

type InviteMetadata struct {
	// Inviter user who created the invite
	Inviter *User `json:"inviter"`

	// Uses number of times this invite has been used
	Uses int `json:"uses"`

	// MaxUses max number of times this invite can be used
	MaxUses int `json:"max_uses"`

	// MaxAge duration (in seconds) after which the invite expires
	MaxAge int `json:"max_age"`

	// Temporary whether this invite only grants temporary membership
	Temporary bool `json:"temporary"`

	// CreatedAt when this invite was created
	CreatedAt Time `json:"created_at"`

	// Revoked whether this invite is revoked
	Revoked bool `json:"revoked"`
}

InviteMetadata Object https://discord.com/developers/docs/resources/invite#invite-metadata-object Reviewed: 2018-06-10

func (*InviteMetadata) CopyOverTo added in v0.7.0

func (i *InviteMetadata) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*InviteMetadata) DeepCopy added in v0.7.0

func (i *InviteMetadata) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type InviteQueryBuilder added in v0.19.0

type InviteQueryBuilder interface {
	WithContext(ctx context.Context) InviteQueryBuilder

	// Get Returns an invite object for the given code.
	Get(withMemberCount bool, flags ...Flag) (*Invite, error)

	// Delete an invite. Requires the MANAGE_CHANNELS permission. Returns an invite object on success.
	Delete(flags ...Flag) (deleted *Invite, err error)
}
type Link interface {
	// Connect establishes a websocket connection to the discord API
	Connect(ctx context.Context) error

	// Disconnect closes the discord websocket connection
	Disconnect() error
}

Link allows basic Discord connection control. Affects all shards

type Logger added in v0.9.0

type Logger = logger.Logger

Logger super basic logging interface

type MFALvl added in v0.6.0

type MFALvl uint

MFALvl ... https://discord.com/developers/docs/resources/guild#guild-object-mfa-level

const (
	MFALvlNone MFALvl = iota
	MFALvlElevated
)

Different MFA levels

func (*MFALvl) Elevated added in v0.6.0

func (mfal *MFALvl) Elevated() bool

Elevated ...

func (*MFALvl) None added in v0.6.0

func (mfal *MFALvl) None() bool

None ...

type Member added in v0.6.0

type Member struct {
	GuildID      Snowflake   `json:"guild_id,omitempty"`
	User         *User       `json:"user"`
	Nick         string      `json:"nick,omitempty"`
	Roles        []Snowflake `json:"roles"`
	JoinedAt     Time        `json:"joined_at,omitempty"`
	PremiumSince Time        `json:"premium_since,omitempty"`
	Deaf         bool        `json:"deaf"`
	Mute         bool        `json:"mute"`

	// custom
	UserID Snowflake `json:"-"`
}

Member https://discord.com/developers/docs/resources/guild#guild-member-object

func (*Member) CopyOverTo added in v0.7.0

func (m *Member) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*Member) DeepCopy added in v0.7.0

func (m *Member) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

func (*Member) GetPermissions added in v0.10.1

func (m *Member) GetPermissions(ctx context.Context, s GuildQueryBuilderCaller, flags ...Flag) (permissions PermissionBit, err error)

GetPermissions populates a uint64 with all the permission flags

func (*Member) GetUser added in v0.9.0

func (m *Member) GetUser(ctx context.Context, session Session) (usr *User, err error)

GetUser tries to ensure that you get a user object and not a nil. The user can be nil if the guild was fetched from the cache.

func (*Member) Mention added in v0.7.0

func (m *Member) Mention() string

Mention creates a string which is parsed into a member mention on Discord GUI's

func (*Member) Reset added in v0.10.0

func (m *Member) Reset()

func (*Member) String added in v0.7.0

func (m *Member) String() string

func (*Member) UpdateNick added in v0.12.0

func (m *Member) UpdateNick(ctx context.Context, client GuildQueryBuilderCaller, nickname string, flags ...Flag) error

type MentionChannel added in v0.12.0

type MentionChannel struct {
	ID      Snowflake `json:"id"`
	GuildID Snowflake `json:"guild_id"`
	Type    int       `json:"type"`
	Name    string    `json:"name"`
}

type Mentioner added in v0.16.0

type Mentioner interface {
	Mention() string
}

Mentioner can be implemented by any type that is mentionable. https://discord.com/developers/docs/reference#message-formatting-formats

type Message added in v0.6.0

type Message struct {
	ID               Snowflake          `json:"id"`
	ChannelID        Snowflake          `json:"channel_id"`
	Author           *User              `json:"author"`
	Member           *Member            `json:"member"`
	Content          string             `json:"content"`
	Timestamp        Time               `json:"timestamp"`
	EditedTimestamp  Time               `json:"edited_timestamp"` // ?
	Tts              bool               `json:"tts"`
	MentionEveryone  bool               `json:"mention_everyone"`
	Mentions         []*User            `json:"mentions"`
	MentionRoles     []Snowflake        `json:"mention_roles"`
	MentionChannels  []*MentionChannel  `json:"mention_channels"`
	Attachments      []*Attachment      `json:"attachments"`
	Embeds           []*Embed           `json:"embeds"`
	Reactions        []*Reaction        `json:"reactions"` // ?
	Nonce            interface{}        `json:"nonce"`     // NOT A SNOWFLAKE! DONT TOUCH!
	Pinned           bool               `json:"pinned"`
	WebhookID        Snowflake          `json:"webhook_id"` // ?
	Type             MessageType        `json:"type"`
	Activity         MessageActivity    `json:"activity"`
	Application      MessageApplication `json:"application"`
	MessageReference *MessageReference  `json:"message_reference"`
	Flags            MessageFlag        `json:"flags"`

	// GuildID is not set when using a REST request. Only socket events.
	GuildID Snowflake `json:"guild_id"`

	// SpoilerTagContent is only true if the entire message text is tagged as a spoiler (aka completely wrapped in ||)
	SpoilerTagContent        bool `json:"-"`
	SpoilerTagAllAttachments bool `json:"-"`
	HasSpoilerImage          bool `json:"-"`
}

Message https://discord.com/developers/docs/resources/channel#message-object-message-structure

func (*Message) CopyOverTo added in v0.8.0

func (m *Message) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*Message) DeepCopy added in v0.8.0

func (m *Message) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

func (*Message) DiscordURL added in v0.16.0

func (m *Message) DiscordURL() (string, error)

DiscordURL returns the Discord link to the message. This can be used to jump directly to a message from within the client.

Example: https://discord.com/channels/319567980491046913/644376487331495967/646925626523254795

func (*Message) IsDirectMessage added in v0.16.0

func (m *Message) IsDirectMessage() bool

IsDirectMessage checks if the message is from a direct message channel.

WARNING! Note that, when fetching messages using the REST API the guildID might be empty -> giving a false positive.

func (*Message) React added in v0.12.0

func (m *Message) React(ctx context.Context, s Session, emoji interface{}, flags ...Flag) error

func (*Message) Reply added in v0.10.0

func (m *Message) Reply(ctx context.Context, s Session, data ...interface{}) (*Message, error)

Reply input any type as an reply. int, string, an object, etc.

func (*Message) Reset added in v0.10.0

func (m *Message) Reset()

func (*Message) Send added in v0.6.0

func (m *Message) Send(ctx context.Context, s Session, flags ...Flag) (msg *Message, err error)

Send sends this message to discord.

func (*Message) String added in v0.10.0

func (m *Message) String() string

func (*Message) Unreact added in v0.12.0

func (m *Message) Unreact(ctx context.Context, s Session, emoji interface{}, flags ...Flag) error

type MessageActivity added in v0.6.0

type MessageActivity struct {
	Type    int    `json:"type"`
	PartyID string `json:"party_id"`
}

MessageActivity https://discord.com/developers/docs/resources/channel#message-object-message-activity-structure

type MessageApplication added in v0.6.0

type MessageApplication struct {
	ID          Snowflake `json:"id"`
	CoverImage  string    `json:"cover_image"`
	Description string    `json:"description"`
	Icon        string    `json:"icon"`
	Name        string    `json:"name"`
}

MessageApplication https://discord.com/developers/docs/resources/channel#message-object-message-application-structure

type MessageCreate added in v0.6.0

type MessageCreate struct {
	Message *Message
	ShardID uint `json:"-"`
}

MessageCreate message was created

func (*MessageCreate) Reset added in v0.10.0

func (m *MessageCreate) Reset()

func (*MessageCreate) UnmarshalJSON added in v0.8.0

func (obj *MessageCreate) UnmarshalJSON(data []byte) error

UnmarshalJSON ...

type MessageCreateHandler added in v0.9.0

type MessageCreateHandler = func(s Session, h *MessageCreate)

MessageCreateHandler is triggered in MessageCreate events

type MessageDelete added in v0.6.0

type MessageDelete struct {
	MessageID Snowflake `json:"id"`
	ChannelID Snowflake `json:"channel_id"`
	GuildID   Snowflake `json:"guild_id,omitempty"`
	ShardID   uint      `json:"-"`
}

MessageDelete message was deleted

type MessageDeleteBulk added in v0.6.0

type MessageDeleteBulk struct {
	MessageIDs []Snowflake `json:"ids"`
	ChannelID  Snowflake   `json:"channel_id"`
	ShardID    uint        `json:"-"`
}

MessageDeleteBulk multiple messages were deleted at once

type MessageDeleteBulkHandler added in v0.9.0

type MessageDeleteBulkHandler = func(s Session, h *MessageDeleteBulk)

MessageDeleteBulkHandler is triggered in MessageDeleteBulk events

type MessageDeleteHandler added in v0.9.0

type MessageDeleteHandler = func(s Session, h *MessageDelete)

MessageDeleteHandler is triggered in MessageDelete events

type MessageFlag added in v0.12.0

type MessageFlag uint
const (
	// MessageFlagCrossposted this message has been published to subscribed Channels (via Channel Following)
	MessageFlagCrossposted MessageFlag = 1 << iota

	// MessageFlagIsCrosspost this message originated from a message in another channel (via Channel Following)
	MessageFlagIsCrosspost

	// MessageFlagSupressEmbeds do not include any embeds when serializing this message
	MessageFlagSupressEmbeds
)

type MessageQueryBuilder added in v0.19.0

type MessageQueryBuilder interface {
	WithContext(ctx context.Context) MessageQueryBuilder

	// PinMessageID Pin a message by its ID and channel ID. Requires the 'MANAGE_MESSAGES' permission.
	// Returns a 204 empty response on success.
	Pin(flags ...Flag) error

	// UnpinMessageID Delete a pinned message in a channel. Requires the 'MANAGE_MESSAGES' permission.
	// Returns a 204 empty response on success. Returns a 204 empty response on success.
	Unpin(flags ...Flag) error

	// GetMessage 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.
	// Returns a message object on success.
	Get(flags ...Flag) (*Message, error)

	// UpdateMessage Edit a previously sent message. You can only edit messages that have been sent by the
	// current user. Returns a message object. Fires a Message Update Gateway event.
	Update(flags ...Flag) *updateMessageBuilder
	SetContent(content string) (*Message, error)
	SetEmbed(embed *Embed) (*Message, error)

	// DeleteMessage Delete 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. Returns a 204 empty response
	// on success. Fires a Message Delete Gateway event.
	Delete(flags ...Flag) error

	// DeleteAllReactions Deletes all reactions on a message. This endpoint requires the 'MANAGE_MESSAGES'
	// permission to be present on the current user.
	DeleteAllReactions(flags ...Flag) error

	Reaction(emoji interface{}) ReactionQueryBuilder
}

type MessageReactionAdd added in v0.6.0

type MessageReactionAdd struct {
	UserID    Snowflake `json:"user_id"`
	ChannelID Snowflake `json:"channel_id"`
	MessageID Snowflake `json:"message_id"`
	// PartialEmoji id and name. id might be nil
	PartialEmoji *Emoji `json:"emoji"`
	ShardID      uint   `json:"-"`
}

MessageReactionAdd user reacted to a message Note! do not cache emoji, unless it's updated with guildID TODO: find guildID when given UserID, ChannelID and MessageID

type MessageReactionAddHandler added in v0.9.0

type MessageReactionAddHandler = func(s Session, h *MessageReactionAdd)

MessageReactionAddHandler is triggered in MessageReactionAdd events

type MessageReactionRemove added in v0.6.0

type MessageReactionRemove struct {
	UserID    Snowflake `json:"user_id"`
	ChannelID Snowflake `json:"channel_id"`
	MessageID Snowflake `json:"message_id"`
	// PartialEmoji id and name. id might be nil
	PartialEmoji *Emoji `json:"emoji"`
	ShardID      uint   `json:"-"`
}

MessageReactionRemove user removed a reaction from a message Note! do not cache emoji, unless it's updated with guildID TODO: find guildID when given UserID, ChannelID and MessageID

type MessageReactionRemoveAll added in v0.6.0

type MessageReactionRemoveAll struct {
	ChannelID Snowflake `json:"channel_id"`
	MessageID Snowflake `json:"message_id"`
	ShardID   uint      `json:"-"`
}

MessageReactionRemoveAll all reactions were explicitly removed from a message

type MessageReactionRemoveAllHandler added in v0.9.0

type MessageReactionRemoveAllHandler = func(s Session, h *MessageReactionRemoveAll)

MessageReactionRemoveAllHandler is triggered in MessageReactionRemoveAll events

type MessageReactionRemoveEmoji added in v0.20.0

type MessageReactionRemoveEmoji struct {
	ChannelID Snowflake `json:"channel_id"`
	GuildID   Snowflake `json:"guild_id"`
	MessageID Snowflake `json:"message_id"`
	Emoji     *Emoji    `json:"emoji"`
	ShardID   uint      `json:"-"`
}

MessageReactionRemoveEmoji Sent when a bot removes all instances of a given emoji from the reactions of a message

type MessageReactionRemoveEmojiHandler added in v0.20.0

type MessageReactionRemoveEmojiHandler = func(s Session, h *MessageReactionRemoveEmoji)

MessageReactionRemoveEmojiHandler is triggered in MessageReactionRemoveEmoji events

type MessageReactionRemoveHandler added in v0.9.0

type MessageReactionRemoveHandler = func(s Session, h *MessageReactionRemove)

MessageReactionRemoveHandler is triggered in MessageReactionRemove events

type MessageReference added in v0.12.0

type MessageReference struct {
	MessageID Snowflake `json:"message_id"`
	ChannelID Snowflake `json:"channel_id"`
	GuildID   Snowflake `json:"guild_id"`
}

type MessageType added in v0.12.0

type MessageType uint // TODO: once auto generated, un-export this.

The different message types usually generated by Discord. eg. "a new user joined"

const (
	MessageTypeDefault MessageType = iota
	MessageTypeRecipientAdd
	MessageTypeRecipientRemove
	MessageTypeCall
	MessageTypeChannelNameChange
	MessageTypeChannelIconChange
	MessageTypeChannelPinnedMessage
	MessageTypeGuildMemberJoin
	MessageTypeUserPremiumGuildSubscription
	MessageTypeUserPremiumGuildSubscriptionTier1
	MessageTypeUserPremiumGuildSubscriptionTier2
	MessageTypeUserPremiumGuildSubscriptionTier3
	MessageTypeChannelFollowAdd
)

type MessageUpdate added in v0.6.0

type MessageUpdate struct {
	Message *Message
	ShardID uint `json:"-"`
}

MessageUpdate message was edited

func (*MessageUpdate) UnmarshalJSON added in v0.8.0

func (obj *MessageUpdate) UnmarshalJSON(data []byte) error

UnmarshalJSON ...

type MessageUpdateHandler added in v0.9.0

type MessageUpdateHandler = func(s Session, h *MessageUpdate)

MessageUpdateHandler is triggered in MessageUpdate events

type Middleware added in v0.9.2

type Middleware = func(interface{}) interface{}

Middleware allows you to manipulate data during the "stream"

type OnSocketEventer added in v0.19.0

type OnSocketEventer interface {
	// On creates a specification to be executed on the given event. The specification
	// consists of, in order, 0 or more middlewares, 1 or more handlers, 0 or 1 controller.
	// On incorrect ordering, or types, the method will panic. See reactor.go for types.
	//
	// Each of the three sub-types of a specification is run in sequence, as well as the specifications
	// registered for a event. However, the slice of specifications are executed in a goroutine to avoid
	// blocking future events. The middlewares allows manipulating the event data before it reaches the
	// handlers. The handlers executes short-running logic based on the event data (use go routine if
	// you need a long running task). The controller dictates lifetime of the specification.
	//
	//  // a handler that is executed on every Ready event
	//  Client.On(EvtReady, onReady)
	//
	//  // a handler that runs only the first three times a READY event is fired
	//  Client.On(EvtReady, onReady, &Ctrl{Runs: 3})
	//
	//  // a handler that only runs for events within the first 10 minutes
	//  Client.On(EvtReady, onReady, &Ctrl{Duration: 10*time.Minute})
	On(event string, inputs ...interface{})
}

type PartialBan added in v0.10.0

type PartialBan struct {
	Reason                 string
	BannedUserID           Snowflake
	ModeratorResponsibleID Snowflake
}

PartialBan is used by audit logs

func (*PartialBan) String added in v0.10.0

func (p *PartialBan) String() string

type PartialChannel added in v0.6.0

type PartialChannel struct {
	ID   Snowflake `json:"id"`
	Name string    `json:"name"`
	Type uint      `json:"type"`
}

PartialChannel ... example of partial channel // "channel": { // "id": "165176875973476352", // "name": "illuminati", // "type": 0 // }

type PartialEmoji added in v0.6.0

type PartialEmoji = Emoji

PartialEmoji see Emoji

type PartialInvite added in v0.6.0

type PartialInvite = Invite

PartialInvite ...

{
   "code": "abc"
}

type PermissionBit added in v0.10.3

type PermissionBit uint64

PermissionBit is used to define the permission bit(s) which are set.

const (
	PermissionReadMessages PermissionBit = 1 << (iota + 10)
	PermissionSendMessages
	PermissionSendTTSMessages
	PermissionManageMessages
	PermissionEmbedLinks
	PermissionAttachFiles
	PermissionReadMessageHistory
	PermissionMentionEveryone
	PermissionUseExternalEmojis
	PermissionViewGuildInsights
)

Constants for the different bit offsets of text channel permissions

const (
	PermissionVoiceConnect PermissionBit = 1 << (iota + 20)
	PermissionVoiceSpeak
	PermissionVoiceMuteMembers
	PermissionVoiceDeafenMembers
	PermissionVoiceMoveMembers
	PermissionVoiceUseVAD
	PermissionVoicePrioritySpeaker PermissionBit = 1 << (iota + 2)
	PermissionStream
)

Constants for the different bit offsets of voice permissions

const (
	PermissionChangeNickname PermissionBit = 1 << (iota + 26)
	PermissionManageNicknames
	PermissionManageRoles
	PermissionManageWebhooks
	PermissionManageEmojis
)

Constants for general management.

func (PermissionBit) Contains added in v0.19.0

func (b PermissionBit) Contains(Bits PermissionBit) bool

Contains is used to check if the permission bits contains the bits specified.

func (*PermissionBit) MarshalJSON added in v0.20.0

func (b *PermissionBit) MarshalJSON() ([]byte, error)

func (*PermissionBit) UnmarshalJSON added in v0.20.0

func (b *PermissionBit) UnmarshalJSON(bytes []byte) error

type PermissionOverwrite added in v0.6.0

type PermissionOverwrite struct {
	ID    Snowflake     `json:"id"`    // role or user id
	Type  uint8         `json:"type"`  // either 0 for `role` or 1 for `member`
	Allow PermissionBit `json:"allow"` // permission bit set
	Deny  PermissionBit `json:"deny"`  // permission bit set
}

PermissionOverwrite https://discord.com/developers/docs/resources/channel#overwrite-object

WARNING! Discord is bugged, and the Type field needs to be a string to read Permission Overwrites from audit log

type Pool added in v0.10.0

type Pool interface {
	Put(x Reseter)
	Get() (x Reseter)
}

type PremiumType added in v0.9.3

type PremiumType int
const (
	// PremiumTypeNitroClassic includes app perks like animated emojis and avatars, but not games
	PremiumTypeNitroClassic PremiumType = 1

	// PremiumTypeNitro includes app perks as well as the games subscription service
	PremiumTypeNitro PremiumType = 2
)

func (PremiumType) String added in v0.9.3

func (p PremiumType) String() (t string)

type PresenceUpdate added in v0.6.0

type PresenceUpdate struct {
	User       *User       `json:"user"`
	RoleIDs    []Snowflake `json:"roles"`
	GuildID    Snowflake   `json:"guild_id"`
	Activities []*Activity `json:"activities"`

	// Status either "idle", "dnd", "online", or "offline"
	// TODO: constants somewhere..
	Status  string `json:"status"`
	ShardID uint   `json:"-"`
}

PresenceUpdate user's presence was updated in a guild

func (*PresenceUpdate) Game added in v0.6.0

func (h *PresenceUpdate) Game() (*Activity, error)

type PresenceUpdateHandler added in v0.9.0

type PresenceUpdateHandler = func(s Session, h *PresenceUpdate)

PresenceUpdateHandler is triggered in PresenceUpdate events

type RESTBuilder added in v0.9.3

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

func (*RESTBuilder) CancelOnRatelimit added in v0.9.3

func (b *RESTBuilder) CancelOnRatelimit() *RESTBuilder

func (*RESTBuilder) IgnoreCache added in v0.9.3

func (b *RESTBuilder) IgnoreCache() *RESTBuilder

type Reaction added in v0.6.0

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

Reaction ... https://discord.com/developers/docs/resources/channel#reaction-object

func (*Reaction) CopyOverTo added in v0.7.0

func (r *Reaction) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*Reaction) DeepCopy added in v0.7.0

func (r *Reaction) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

func (*Reaction) Reset added in v0.10.0

func (r *Reaction) Reset()

type ReactionQueryBuilder added in v0.19.0

type ReactionQueryBuilder interface {
	WithContext(ctx context.Context) ReactionQueryBuilder

	// CreateReaction Create a reaction for the message. 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. Returns a 204
	// empty response on success. The maximum request size when sending a message is 8MB.
	Create(flags ...Flag) (err error)

	// GetReaction Get a list of Users that reacted with this emoji. Returns an array of user objects on success.
	Get(params URLQueryStringer, flags ...Flag) (reactors []*User, err error)

	// DeleteOwnReaction Delete a reaction the current user has made for the message.
	// Returns a 204 empty response on success.
	DeleteOwn(flags ...Flag) (err error)

	// DeleteUserReaction Deletes another user's reaction. This endpoint requires the 'MANAGE_MESSAGES' permission
	// to be present on the current user. Returns a 204 empty response on success.
	DeleteUser(userID Snowflake, flags ...Flag) (err error)
}

type Ready added in v0.6.0

type Ready struct {
	APIVersion int                 `json:"v"`
	User       *User               `json:"user"`
	Guilds     []*GuildUnavailable `json:"guilds"`

	// not really needed, as it is handled on the socket layer.
	SessionID string `json:"session_id"`

	ShardID uint `json:"-"`
}

Ready contains the initial state information

type ReadyHandler added in v0.9.0

type ReadyHandler = func(s Session, h *Ready)

ReadyHandler is triggered in Ready events

type RequestGuildMembersPayload added in v0.12.0

type RequestGuildMembersPayload struct {
	// GuildID	id of the guild(s) to get the members for
	GuildIDs []Snowflake

	// Query string that username starts with, or an empty string to return all members
	Query string

	// Limit maximum number of members to send or 0 to request all members matched
	Limit uint

	// UserIDs used to specify which Users you wish to fetch
	UserIDs []Snowflake
}

################################################################# RequestGuildMembersPayload payload for socket command REQUEST_GUILD_MEMBERS. See RequestGuildMembers

WARNING: If this request is in queue while a auto-scaling is forced, it will be removed from the queue and not re-inserted like the other commands. This is due to the guild id slice, which is a bit trickier to handle.

Wrapper for websocket.RequestGuildMembersPayload

type Reseter added in v0.10.0

type Reseter interface {
	Reset()
}

Reseter Reset() zero initialises or empties a struct instance

type Resumed added in v0.6.0

type Resumed struct {
	ShardID uint `json:"-"`
}

Resumed response to Resume

type ResumedHandler added in v0.9.0

type ResumedHandler = func(s Session, h *Resumed)

ResumedHandler is triggered in Resumed events

type Role added in v0.6.0

type Role struct {
	ID          Snowflake     `json:"id"`
	Name        string        `json:"name"`
	Color       uint          `json:"color"`
	Hoist       bool          `json:"hoist"`
	Position    int           `json:"position"` // can be -1
	Permissions PermissionBit `json:"permissions"`
	Managed     bool          `json:"managed"`
	Mentionable bool          `json:"mentionable"`
	// contains filtered or unexported fields
}

Role https://discord.com/developers/docs/topics/permissions#role-object

func (*Role) CopyOverTo added in v0.7.0

func (r *Role) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*Role) DeepCopy added in v0.7.0

func (r *Role) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

func (*Role) Mention added in v0.6.0

func (r *Role) Mention() string

Mention gives a formatted version of the role such that it can be parsed by Discord clients

func (*Role) Reset added in v0.10.0

func (r *Role) Reset()

func (*Role) SetGuildID added in v0.7.0

func (r *Role) SetGuildID(id Snowflake)

SetGuildID link role to a guild before running session.SaveToDiscord(*Role)

func (*Role) String added in v0.10.0

func (r *Role) String() string

type Session

type Session interface {
	// Logger returns the injected logger instance. If nothing was injected, a empty wrapper is returned
	// to avoid nil panics.
	Logger() logger.Logger

	// Discord Gateway, web socket
	SocketHandler

	// HeartbeatLatency returns the avg. ish time used to send and receive a heartbeat signal.
	// The latency is calculated as such:
	// 0. start timer (start)
	// 1. send heartbeat signal
	// 2. wait until a heartbeat ack is sent by Discord
	// 3. latency = time.Now().Sub(start)
	// 4. avg = (avg + latency) / 2
	//
	// This feature was requested. But should never be used as a proof for delay between client and Discord.
	AvgHeartbeatLatency() (duration time.Duration, err error)
	// returns the latency for each given shard id. shardID => latency
	HeartbeatLatencies() (latencies map[uint]time.Duration, err error)

	RESTRatelimitBuckets() (group map[string][]string)

	// AddPermission is to store the permissions required by the bot to function as intended.
	AddPermission(permission PermissionBit) (updatedPermissions PermissionBit)
	GetPermissions() (permissions PermissionBit)

	Pool() *pools

	ClientQueryBuilder

	// Status update functions
	UpdateStatus(s *UpdateStatusPayload) error
	UpdateStatusString(s string) error

	GetConnectedGuilds() []Snowflake
}

Session Is the runtime interface for Disgord. It allows you to interact with a live session (using sockets or not). Note that this interface is used after you've configured Disgord, and therefore won't allow you to configure it further.

type ShardConfig added in v0.12.0

type ShardConfig = gateway.ShardConfig

type SimpleHandler added in v0.9.0

type SimpleHandler = func(Session)

type SimplestHandler added in v0.9.0

type SimplestHandler = func()

these "simple" handler can be used, if you don't care about the actual event data

type Snowflake added in v0.6.0

type Snowflake = util.Snowflake

Snowflake twitter snowflake identification for Discord

func GetSnowflake added in v0.6.0

func GetSnowflake(v interface{}) (Snowflake, error)

GetSnowflake see snowflake.GetSnowflake

func ParseSnowflakeString added in v0.6.0

func ParseSnowflakeString(v string) Snowflake

ParseSnowflakeString see snowflake.ParseSnowflakeString

type SocketHandler added in v0.8.0

type SocketHandler interface {

	// Disconnect closes the discord websocket connection
	Disconnect() error

	// Suspend temporary closes the socket connection, allowing resources to be
	// reused on reconnect
	Suspend() error

	OnSocketEventer

	// Event gives access to type safe event handler registration using the builder pattern
	Event() SocketHandlerRegistrator

	Emitter
}

SocketHandler all socket related logic

type SocketHandlerRegistrator added in v0.19.0

type SocketHandlerRegistrator interface {
	ChannelCreate(...HandlerChannelCreate)
	ChannelDelete(...HandlerChannelDelete)
	ChannelPinsUpdate(...HandlerChannelPinsUpdate)
	ChannelUpdate(...HandlerChannelUpdate)
	GuildBanAdd(...HandlerGuildBanAdd)
	GuildBanRemove(...HandlerGuildBanRemove)
	GuildCreate(...HandlerGuildCreate)
	GuildDelete(...HandlerGuildDelete)
	GuildEmojisUpdate(...HandlerGuildEmojisUpdate)
	GuildIntegrationsUpdate(...HandlerGuildIntegrationsUpdate)
	GuildMemberAdd(...HandlerGuildMemberAdd)
	GuildMemberRemove(...HandlerGuildMemberRemove)
	GuildMemberUpdate(...HandlerGuildMemberUpdate)
	GuildMembersChunk(...HandlerGuildMembersChunk)
	GuildRoleCreate(...HandlerGuildRoleCreate)
	GuildRoleDelete(...HandlerGuildRoleDelete)
	GuildRoleUpdate(...HandlerGuildRoleUpdate)
	GuildUpdate(...HandlerGuildUpdate)
	InviteCreate(...HandlerInviteCreate)
	InviteDelete(...HandlerInviteDelete)
	MessageCreate(...HandlerMessageCreate)
	MessageDelete(...HandlerMessageDelete)
	MessageDeleteBulk(...HandlerMessageDeleteBulk)
	MessageReactionAdd(...HandlerMessageReactionAdd)
	MessageReactionRemove(...HandlerMessageReactionRemove)
	MessageReactionRemoveAll(...HandlerMessageReactionRemoveAll)
	MessageReactionRemoveEmoji(...HandlerMessageReactionRemoveEmoji)
	MessageUpdate(...HandlerMessageUpdate)
	PresenceUpdate(...HandlerPresenceUpdate)
	Ready(...HandlerReady)
	Resumed(...HandlerResumed)
	TypingStart(...HandlerTypingStart)
	UserUpdate(...HandlerUserUpdate)
	VoiceServerUpdate(...HandlerVoiceServerUpdate)
	VoiceStateUpdate(...HandlerVoiceStateUpdate)
	WebhooksUpdate(...HandlerWebhooksUpdate)
	WithCtrl(HandlerCtrl) SocketHandlerRegistrator
	WithMdlw(...Middleware) SocketHandlerRegistrator
}

type Time added in v0.10.0

type Time struct {
	time.Time
}

Time handles Discord timestamps

func (Time) MarshalJSON added in v0.10.0

func (t Time) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler. error: https://stackoverflow.com/questions/28464711/go-strange-json-hyphen-unmarshall-error

func (Time) String added in v0.10.0

func (t Time) String() string

String returns the timestamp as a Discord formatted timestamp. Formatting with time.RFC3331 does not suffice.

func (*Time) UnmarshalJSON added in v0.10.0

func (t *Time) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type TypingStart added in v0.6.0

type TypingStart struct {
	ChannelID     Snowflake `json:"channel_id"`
	UserID        Snowflake `json:"user_id"`
	TimestampUnix int       `json:"timestamp"`
	ShardID       uint      `json:"-"`
}

TypingStart user started typing in a channel

type TypingStartHandler added in v0.9.0

type TypingStartHandler = func(s Session, h *TypingStart)

TypingStartHandler is triggered in TypingStart events

type URLQueryStringer added in v0.10.0

type URLQueryStringer interface {
	URLQueryString() string
}

URLQueryStringer converts a struct of values to a valid URL query string

type UpdateChannelBuilder added in v0.19.0

type UpdateChannelBuilder interface {
	Execute() (channel *Channel, err error)
	IgnoreCache() UpdateChannelBuilder
	CancelOnRatelimit() UpdateChannelBuilder
	URLParam(name string, v interface{}) UpdateChannelBuilder
	Set(name string, v interface{}) UpdateChannelBuilder
	SetParentID(parentID Snowflake) UpdateChannelBuilder
	SetPermissionOverwrites(permissionOverwrites []PermissionOverwrite) UpdateChannelBuilder
	SetUserLimit(userLimit uint) UpdateChannelBuilder
	SetBitrate(bitrate uint) UpdateChannelBuilder
	SetRateLimitPerUser(rateLimitPerUser uint) UpdateChannelBuilder
	SetNsfw(nsfw bool) UpdateChannelBuilder
	SetTopic(topic string) UpdateChannelBuilder
	SetPosition(position int) UpdateChannelBuilder
	SetName(name string) UpdateChannelBuilder
}

UpdateChannelBuilder is the interface for the builder.

type UpdateChannelPermissionsParams added in v0.10.0

type UpdateChannelPermissionsParams struct {
	Allow PermissionBit `json:"allow"` // the bitwise value of all allowed permissions
	Deny  PermissionBit `json:"deny"`  // the bitwise value of all disallowed permissions
	Type  uint          `json:"type"`  // 0=role, 1=member
}

UpdateChannelPermissionsParams https://discord.com/developers/docs/resources/channel#edit-channel-permissions-json-params

type UpdateCurrentUserBuilder added in v0.19.0

type UpdateCurrentUserBuilder interface {
	Execute() (user *User, err error)
	IgnoreCache() UpdateCurrentUserBuilder
	CancelOnRatelimit() UpdateCurrentUserBuilder
	URLParam(name string, v interface{}) UpdateCurrentUserBuilder
	Set(name string, v interface{}) UpdateCurrentUserBuilder
	SetUsername(username string) UpdateCurrentUserBuilder
	SetAvatar(avatar string) UpdateCurrentUserBuilder
}

UpdateCurrentUserBuilder is the interface for the builder.

type UpdateGuildBuilder added in v0.19.0

type UpdateGuildBuilder interface {
	Execute() (guild *Guild, err error)
	IgnoreCache() UpdateGuildBuilder
	CancelOnRatelimit() UpdateGuildBuilder
	URLParam(name string, v interface{}) UpdateGuildBuilder
	Set(name string, v interface{}) UpdateGuildBuilder
	SetName(name string) UpdateGuildBuilder
	SetRegion(region string) UpdateGuildBuilder
	SetVerificationLevel(verificationLevel int) UpdateGuildBuilder
	SetDefaultMessageNotifications(defaultMessageNotifications DefaultMessageNotificationLvl) UpdateGuildBuilder
	SetExplicitContentFilter(explicitContentFilter ExplicitContentFilterLvl) UpdateGuildBuilder
	SetAfkChannelID(afkChannelID Snowflake) UpdateGuildBuilder
	SetAfkTimeout(afkTimeout int) UpdateGuildBuilder
	SetIcon(icon string) UpdateGuildBuilder
	SetOwnerID(ownerID Snowflake) UpdateGuildBuilder
	SetSplash(splash string) UpdateGuildBuilder
	SetSystemChannelID(systemChannelID Snowflake) UpdateGuildBuilder
}

UpdateGuildBuilder is the interface for the builder.

type UpdateGuildChannelPositionsParams added in v0.10.0

type UpdateGuildChannelPositionsParams struct {
	ID       Snowflake `json:"id"`
	Position int       `json:"position"`

	// Reason is a X-Audit-Log-Reason header field that will show up on the audit log for this action.
	// just reuse the string. Go will optimize it to point to the same memory anyways
	// TODO: improve this?
	Reason string `json:"-"`
}

UpdateGuildChannelPositionsParams ... https://discord.com/developers/docs/resources/guild#modify-guild-channel-positions-json-params

type UpdateGuildEmbedBuilder added in v0.19.0

type UpdateGuildEmbedBuilder interface {
	Execute() (embed *GuildEmbed, err error)
	IgnoreCache() UpdateGuildEmbedBuilder
	CancelOnRatelimit() UpdateGuildEmbedBuilder
	URLParam(name string, v interface{}) UpdateGuildEmbedBuilder
	Set(name string, v interface{}) UpdateGuildEmbedBuilder
	SetEnabled(enabled bool) UpdateGuildEmbedBuilder
	SetChannelID(channelID Snowflake) UpdateGuildEmbedBuilder
}

UpdateGuildEmbedBuilder is the interface for the builder.

type UpdateGuildEmojiBuilder added in v0.19.0

type UpdateGuildEmojiBuilder interface {
	Execute() (emoji *Emoji, err error)
	IgnoreCache() UpdateGuildEmojiBuilder
	CancelOnRatelimit() UpdateGuildEmojiBuilder
	URLParam(name string, v interface{}) UpdateGuildEmojiBuilder
	Set(name string, v interface{}) UpdateGuildEmojiBuilder
	SetName(name string) UpdateGuildEmojiBuilder
	SetRoles(roles []Snowflake) UpdateGuildEmojiBuilder
}

UpdateGuildEmojiBuilder is the interface for the builder.

type UpdateGuildIntegrationParams added in v0.10.0

type UpdateGuildIntegrationParams struct {
	ExpireBehavior    int  `json:"expire_behavior"`
	ExpireGracePeriod int  `json:"expire_grace_period"`
	EnableEmoticons   bool `json:"enable_emoticons"`
}

UpdateGuildIntegrationParams ... https://discord.com/developers/docs/resources/guild#modify-guild-integration-json-params TODO: currently unsure which are required/optional params

type UpdateGuildMemberBuilder added in v0.19.0

type UpdateGuildMemberBuilder interface {
	Execute() (err error)
	IgnoreCache() UpdateGuildMemberBuilder
	CancelOnRatelimit() UpdateGuildMemberBuilder
	URLParam(name string, v interface{}) UpdateGuildMemberBuilder
	Set(name string, v interface{}) UpdateGuildMemberBuilder
	SetNick(nick string) UpdateGuildMemberBuilder
	SetRoles(roles []Snowflake) UpdateGuildMemberBuilder
	SetMute(mute bool) UpdateGuildMemberBuilder
	SetDeaf(deaf bool) UpdateGuildMemberBuilder
	SetChannelID(channelID Snowflake) UpdateGuildMemberBuilder

	KickFromVoice() UpdateGuildMemberBuilder
	DeleteNick() UpdateGuildMemberBuilder
}

UpdateGuildMemberBuilder is the interface for the builder.

type UpdateGuildRoleBuilder added in v0.19.0

type UpdateGuildRoleBuilder interface {
	Execute() (role *Role, err error)
	IgnoreCache() UpdateGuildRoleBuilder
	CancelOnRatelimit() UpdateGuildRoleBuilder
	URLParam(name string, v interface{}) UpdateGuildRoleBuilder
	Set(name string, v interface{}) UpdateGuildRoleBuilder
	SetName(name string) UpdateGuildRoleBuilder
	SetPermissions(permissions PermissionBit) UpdateGuildRoleBuilder
	SetColor(color uint) UpdateGuildRoleBuilder
	SetHoist(hoist bool) UpdateGuildRoleBuilder
	SetMentionable(mentionable bool) UpdateGuildRoleBuilder
}

UpdateGuildRoleBuilder is the interface for the builder.

type UpdateGuildRolePositionsParams added in v0.10.0

type UpdateGuildRolePositionsParams struct {
	ID       Snowflake `json:"id"`
	Position int       `json:"position"`

	// Reason is a X-Audit-Log-Reason header field that will show up on the audit log for this action.
	Reason string `json:"-"`
}

UpdateGuildRolePositionsParams ... https://discord.com/developers/docs/resources/guild#modify-guild-role-positions-json-params

func NewUpdateGuildRolePositionsParams added in v0.10.0

func NewUpdateGuildRolePositionsParams(rs []*Role) (p []UpdateGuildRolePositionsParams)

type UpdateMessageBuilder added in v0.19.0

type UpdateMessageBuilder interface {
	Execute() (message *Message, err error)
	IgnoreCache() UpdateMessageBuilder
	CancelOnRatelimit() UpdateMessageBuilder
	URLParam(name string, v interface{}) UpdateMessageBuilder
	Set(name string, v interface{}) UpdateMessageBuilder
	SetContent(content string) UpdateMessageBuilder
	SetEmbed(embed *Embed) UpdateMessageBuilder
}

UpdateMessageBuilder is the interface for the builder.

type UpdateStatusPayload added in v0.12.0

type UpdateStatusPayload struct {

	// Since unix time (in milliseconds) of when the Client went idle, or null if the Client is not idle
	Since *uint

	// Game null, or the user's new activity
	Game *Activity

	// Status the user's new status
	Status string

	// AFK whether or not the Client is afk
	AFK bool
	// contains filtered or unexported fields
}

UpdateStatusPayload payload for socket command UPDATE_STATUS. see UpdateStatus

Wrapper for websocket.UpdateStatusPayload

type UpdateVoiceStatePayload added in v0.12.0

type UpdateVoiceStatePayload struct {
	// GuildID id of the guild
	GuildID Snowflake

	// ChannelID id of the voice channel Client wants to join
	// (0 if disconnecting)
	ChannelID Snowflake

	// SelfMute is the Client mute
	SelfMute bool

	// SelfDeaf is the Client deafened
	// Currently, it's n ot documented how to receive sound from discord
	// therefore it's not supported and the bot is always going to be deaf.
	//
	// deprecated, this is always true
	SelfDeaf bool
}

UpdateVoiceStatePayload payload for socket command UPDATE_VOICE_STATE. see UpdateVoiceState

Wrapper for websocket.UpdateVoiceStatePayload

type UpdateWebhookBuilder added in v0.19.0

type UpdateWebhookBuilder interface {
	Execute() (webhook *Webhook, err error)
	IgnoreCache() UpdateWebhookBuilder
	CancelOnRatelimit() UpdateWebhookBuilder
	URLParam(name string, v interface{}) UpdateWebhookBuilder
	Set(name string, v interface{}) UpdateWebhookBuilder
	SetName(name string) UpdateWebhookBuilder
	SetAvatar(avatar string) UpdateWebhookBuilder
	SetChannelID(channelID Snowflake) UpdateWebhookBuilder
}

UpdateWebhookBuilder is the interface for the builder.

type User added in v0.6.0

type User struct {
	ID            Snowflake     `json:"id,omitempty"`
	Username      string        `json:"username,omitempty"`
	Discriminator Discriminator `json:"discriminator,omitempty"`
	Email         string        `json:"email,omitempty"`
	Avatar        string        `json:"avatar"` // data:image/jpeg;base64,BASE64_ENCODED_JPEG_IMAGE_DATA //TODO: pointer?
	Token         string        `json:"token,omitempty"`
	Verified      bool          `json:"verified,omitempty"`
	MFAEnabled    bool          `json:"mfa_enabled,omitempty"`
	Bot           bool          `json:"bot,omitempty"`
	PremiumType   PremiumType   `json:"premium_type,omitempty"`
	Locale        string        `json:"locale,omitempty"`
	Flags         UserFlag      `json:"flag,omitempty"`
	PublicFlags   UserFlag      `json:"public_flag,omitempty"`
}

User the Discord user object which is reused in most other data structures.

func (*User) AvatarURL added in v0.12.0

func (u *User) AvatarURL(size int, preferGIF bool) (url string, err error)

AvatarURL returns a link to the Users avatar with the given size.

func (*User) CopyOverTo added in v0.7.0

func (u *User) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*User) DeepCopy added in v0.6.0

func (u *User) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier CopyOverTo see interface at struct.go#Copier

func (*User) Mention added in v0.6.0

func (u *User) Mention() string

Mention returns the a string that Discord clients can format into a valid Discord mention

func (*User) Reset added in v0.10.0

func (u *User) Reset()

func (*User) SendMsg added in v0.6.0

func (u *User) SendMsg(ctx context.Context, session Session, message *Message) (channel *Channel, msg *Message, err error)

SendMsg send a message to a user where you utilize a Message object instead of a string

func (*User) SendMsgString added in v0.6.0

func (u *User) SendMsgString(ctx context.Context, session Session, content string) (channel *Channel, msg *Message, err error)

SendMsgString send a message to given user where the message is in the form of a string.

func (*User) String added in v0.6.0

func (u *User) String() string

String formats the user to Anders#1234{1234567890}

func (*User) Tag added in v0.12.0

func (u *User) Tag() string

Tag formats the user to Anders#1234

func (*User) Valid added in v0.6.0

func (u *User) Valid() bool

Valid ensure the user object has enough required information to be used in Discord interactions

type UserConnection added in v0.6.0

type UserConnection struct {
	ID           string                `json:"id"`           // id of the connection account
	Name         string                `json:"name"`         // the username of the connection account
	Type         string                `json:"type"`         // the service of the connection (twitch, youtube)
	Revoked      bool                  `json:"revoked"`      // whether the connection is revoked
	Integrations []*IntegrationAccount `json:"integrations"` // an array of partial server integrations
}

UserConnection ...

func (*UserConnection) CopyOverTo added in v0.7.0

func (c *UserConnection) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*UserConnection) DeepCopy added in v0.7.0

func (c *UserConnection) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type UserFlag added in v0.17.3

type UserFlag uint64
const (
	UserFlagNone            UserFlag = 0
	UserFlagDiscordEmployee UserFlag = 0b1 << iota
	UserFlagDiscordPartner
	UserFlagHypeSquadEvents
	UserFlagBugHunterLevel1

	UserFlagHouseBravery
	UserFlagHouseBrilliance
	UserFlagHouseBalance
	UserFlagEarlySupporter
	UserFlagTeamUser

	UserFlagSystem

	UserFlagBugHunterLevel2

	UserFlagVerifiedBot
	UserFlagVerifiedBotDeveloper
)

type UserPresence added in v0.6.0

type UserPresence struct {
	User    *User       `json:"user"`
	Roles   []Snowflake `json:"roles"`
	Game    *Activity   `json:"activity"`
	GuildID Snowflake   `json:"guild_id"`
	Nick    string      `json:"nick"`
	Status  string      `json:"status"`
}

UserPresence presence info for a guild member or friend/user in a DM

func (*UserPresence) CopyOverTo added in v0.7.0

func (p *UserPresence) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*UserPresence) DeepCopy added in v0.7.0

func (p *UserPresence) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

func (*UserPresence) String added in v0.6.0

func (p *UserPresence) String() string

type UserQueryBuilder added in v0.19.0

type UserQueryBuilder interface {
	WithContext(ctx context.Context) UserQueryBuilder

	// GetUser Returns a user object for a given user Snowflake.
	Get(flags ...Flag) (*User, error)

	// CreateDM Create a new DM channel with a user. Returns a DM channel object.
	CreateDM(flags ...Flag) (ret *Channel, err error)
}

RESTUser REST interface for all user endpoints

type UserUpdate added in v0.6.0

type UserUpdate struct {
	*User
	ShardID uint `json:"-"`
}

UserUpdate properties about a user changed

func (*UserUpdate) UnmarshalJSON added in v0.17.3

func (obj *UserUpdate) UnmarshalJSON(data []byte) error

UnmarshalJSON ...

type UserUpdateHandler added in v0.9.0

type UserUpdateHandler = func(s Session, h *UserUpdate)

UserUpdateHandler is triggered in UserUpdate events

type VerificationLvl added in v0.6.0

type VerificationLvl uint

VerificationLvl ... https://discord.com/developers/docs/resources/guild#guild-object-verification-level

const (
	VerificationLvlNone VerificationLvl = iota
	VerificationLvlLow
	VerificationLvlMedium
	VerificationLvlHigh
	VerificationLvlVeryHigh
)

the different verification levels

func (*VerificationLvl) High added in v0.6.0

func (vl *VerificationLvl) High() bool

High (╯°□°)╯︵ ┻━┻ - must be a member of the server for longer than 10 minutes

func (*VerificationLvl) Low added in v0.6.0

func (vl *VerificationLvl) Low() bool

Low must have verified email on account

func (*VerificationLvl) Medium added in v0.6.0

func (vl *VerificationLvl) Medium() bool

Medium must be registered on Discord for longer than 5 minutes

func (*VerificationLvl) None added in v0.6.0

func (vl *VerificationLvl) None() bool

None unrestricted

func (*VerificationLvl) VeryHigh added in v0.6.0

func (vl *VerificationLvl) VeryHigh() bool

VeryHigh ┻━┻ミヽ(ಠ益ಠ)ノ彡┻━┻ - must have a verified phone number

type VoiceConnection added in v0.9.0

type VoiceConnection interface {
	// StartSpeaking should be sent before sending voice data.
	StartSpeaking() error
	// StopSpeaking should be sent after sending voice data. If there's a break in the sent data, you should not simply
	// stop sending data. Instead you have to send five frames of silence ([]byte{0xF8, 0xFF, 0xFE}) before stopping
	// to avoid unintended Opus interpolation with subsequent transmissions.
	StopSpeaking() error

	// SendOpusFrame sends a single frame of opus data to the UDP server. Frames are sent every 20ms with 960 samples (48kHz).
	//
	// if the bot has been disconnected or the channel removed, an error will be returned. The voice object must then be properly dealt with to avoid further issues.
	SendOpusFrame(data []byte) error
	// SendDCA reads from a Reader expecting a DCA encoded stream/file and sends them as frames.
	SendDCA(r io.Reader) error

	// MoveTo moves from the current voice channel to the given.
	MoveTo(channelID Snowflake) error

	// Close closes the websocket and UDP connection. This VoiceConnection interface will no
	// longer be usable.
	// It is the callers responsibility to ensure there are no concurrent calls to any other
	// methods of this interface after calling Close.
	Close() error
}

VoiceConnection is the interface used to interact with active voice connections.

type VoiceRegion added in v0.6.0

type VoiceRegion struct {
	// Snowflake unique Snowflake for the region
	ID string `json:"id"`

	// Name name of the region
	Name string `json:"name"`

	// SampleHostname an example hostname for the region
	SampleHostname string `json:"sample_hostname"`

	// SamplePort an example port for the region
	SamplePort uint `json:"sample_port"`

	// VIP true if this is a vip-only server
	VIP bool `json:"vip"`

	// Optimal true for a single server that is closest to the current user's Client
	Optimal bool `json:"optimal"`

	// Deprecated 	whether this is a deprecated voice region (avoid switching to these)
	Deprecated bool `json:"deprecated"`

	// Custom whether this is a custom voice region (used for events/etc)
	Custom bool `json:"custom"`
}

VoiceRegion voice region structure https://discord.com/developers/docs/resources/voice#voice-region

func (*VoiceRegion) CopyOverTo added in v0.7.0

func (v *VoiceRegion) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*VoiceRegion) DeepCopy added in v0.7.0

func (v *VoiceRegion) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

func (*VoiceRegion) Reset added in v0.10.0

func (v *VoiceRegion) Reset()

type VoiceServerUpdate added in v0.6.0

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

VoiceServerUpdate guild's voice server was updated. Sent when a guild's voice server is updated. This is sent when initially connecting to voice, and when the current voice instance fails over to a new server.

type VoiceServerUpdateHandler added in v0.9.0

type VoiceServerUpdateHandler = func(s Session, h *VoiceServerUpdate)

VoiceServerUpdateHandler is triggered in VoiceServerUpdate events

type VoiceState added in v0.6.0

type VoiceState struct {
	// GuildID the guild id this voice state is for
	GuildID Snowflake `json:"guild_id,omitempty"` // ? |

	// ChannelID the channel id this user is connected to
	ChannelID Snowflake `json:"channel_id"` // | ?

	// UserID the user id this voice state is for
	UserID Snowflake `json:"user_id"` // |

	// the guild member this voice state is for
	Member *Member `json:"member,omitempty"`

	// SessionID the session id for this voice state
	SessionID string `json:"session_id"` // |

	// Deaf whether this user is deafened by the server
	Deaf bool `json:"deaf"` // |

	// Mute whether this user is muted by the server
	Mute bool `json:"mute"` // |

	// SelfDeaf whether this user is locally deafened
	SelfDeaf bool `json:"self_deaf"` // |

	// SelfMute whether this user is locally muted
	SelfMute bool `json:"self_mute"` // |

	// Suppress whether this user is muted by the current user
	Suppress bool `json:"suppress"` // |
}

VoiceState Voice State structure https://discord.com/developers/docs/resources/voice#voice-state-object reviewed 2018-09-29

func (*VoiceState) CopyOverTo added in v0.7.0

func (v *VoiceState) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*VoiceState) DeepCopy added in v0.7.0

func (v *VoiceState) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

func (*VoiceState) Reset added in v0.10.0

func (v *VoiceState) Reset()

func (*VoiceState) UnmarshalJSON added in v0.19.0

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

UnmarshalJSON is used to unmarshal Discord's JSON.

type VoiceStateUpdate added in v0.6.0

type VoiceStateUpdate struct {
	*VoiceState
	ShardID uint `json:"-"`
}

VoiceStateUpdate someone joined, left, or moved a voice channel

func (*VoiceStateUpdate) UnmarshalJSON added in v0.19.0

func (h *VoiceStateUpdate) UnmarshalJSON(data []byte) error

UnmarshalJSON ...

type VoiceStateUpdateHandler added in v0.9.0

type VoiceStateUpdateHandler = func(s Session, h *VoiceStateUpdate)

VoiceStateUpdateHandler is triggered in VoiceStateUpdate events

type Webhook added in v0.6.0

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

Webhook Used to represent a webhook https://discord.com/developers/docs/resources/webhook#webhook-object

func (*Webhook) CopyOverTo added in v0.7.0

func (w *Webhook) CopyOverTo(other interface{}) (err error)

CopyOverTo see interface at struct.go#Copier

func (*Webhook) DeepCopy added in v0.7.0

func (w *Webhook) DeepCopy() (copy interface{})

DeepCopy see interface at struct.go#DeepCopier

type WebhookQueryBuilder added in v0.19.0

type WebhookQueryBuilder interface {
	WithContext(ctx context.Context) WebhookQueryBuilder

	// GetWebhook Returns the new webhook object for the given id.
	Get(flags ...Flag) (*Webhook, error)

	// UpdateWebhook Modify a webhook. Requires the 'MANAGE_WEBHOOKS' permission.
	// Returns the updated webhook object on success.
	Update(flags ...Flag) *updateWebhookBuilder

	// DeleteWebhook Delete a webhook permanently. User must be owner. Returns a 204 NO CONTENT response on success.
	Delete(flags ...Flag) error

	// ExecuteWebhook Trigger a webhook in Discord.
	Execute(params *ExecuteWebhookParams, wait bool, URLSuffix string, flags ...Flag) (*Message, error)

	// ExecuteSlackWebhook Trigger a webhook in Discord from the Slack app.
	ExecuteSlackWebhook(params *ExecuteWebhookParams, wait bool, flags ...Flag) (*Message, error)

	// ExecuteGitHubWebhook Trigger a webhook in Discord from the GitHub app.
	ExecuteGitHubWebhook(params *ExecuteWebhookParams, wait bool, flags ...Flag) (*Message, error)

	WithToken(token string) WebhookWithTokenQueryBuilder
}

type WebhookWithTokenQueryBuilder added in v0.19.0

type WebhookWithTokenQueryBuilder interface {
	WithContext(ctx context.Context) WebhookWithTokenQueryBuilder

	// GetWebhookWithToken Same as GetWebhook, except this call does not require authentication and
	// returns no user in the webhook object.
	Get(flags ...Flag) (*Webhook, error)

	// UpdateWebhookWithToken Same as UpdateWebhook, except this call does not require authentication,
	// does _not_ accept a channel_id parameter in the body, and does not return a user in the webhook object.
	Update(flags ...Flag) *updateWebhookBuilder

	// DeleteWebhookWithToken Same as DeleteWebhook, except this call does not require authentication.
	Delete(flags ...Flag) error

	Execute(params *ExecuteWebhookParams, wait bool, URLSuffix string, flags ...Flag) (*Message, error)
}

type WebhooksUpdate added in v0.6.0

type WebhooksUpdate struct {
	GuildID   Snowflake `json:"guild_id"`
	ChannelID Snowflake `json:"channel_id"`
	ShardID   uint      `json:"-"`
}

WebhooksUpdate guild channel webhook was created, update, or deleted

type WebhooksUpdateHandler added in v0.9.0

type WebhooksUpdateHandler = func(s Session, h *WebhooksUpdate)

WebhooksUpdateHandler is triggered in WebhooksUpdate events

Directories

Path Synopsis
cmd
generate
discorddocs Module
internal
crs
endpoint
Package endpoint holds all discord urls for the REST endpoints
Package endpoint holds all discord urls for the REST endpoints
event
Package event is a universal discord package that holds all the event types one can receive (currently only bot events).
Package event is a universal discord package that holds all the event types one can receive (currently only bot events).

Jump to

Keyboard shortcuts

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