fluxer

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: MIT Imports: 30 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

fluxer-go

Go library for the Fluxer API: REST client, gateway, typed events, a state cache and voice over LiveKit.

go get github.com/invaliduser231/fluxer-go

The voice support lives in its own module so the WebRTC dependencies stay out of bots that do not need them:

go get github.com/invaliduser231/fluxer-go/voice

Requires Go 1.26 or newer. The API is not stable before 1.0.

Guides are at invaliduser231.github.io/fluxer-go, the API reference is on pkg.go.dev.

Questions, help and release announcements are in the fluxer-go community on Fluxer.

Packages

Package Contents
fluxer REST client, gateway session, sharding, events, router, permissions, OAuth2
fluxer/state Cache fed by gateway events, with policies, old values, a message cache, member chunking and REST fallback
fluxer/state/redis Redis storage for the cache
fluxer/fluxertest Fake Fluxer server with REST routes and a gateway for tests
fluxer/voice Joining voice channels, playing Ogg Opus, publishing and receiving tracks

A small bot

client := fluxer.NewClient(os.Getenv("FLUXER_TOKEN"))
router := fluxer.NewRouter()

fluxer.On(router, func(m *fluxer.MessageCreate) {
	if m.Content == "!ping" {
		go client.Reply(ctx, &m.Message, fluxer.MessageSend{Content: "pong"})
	}
})

session := &fluxer.Session{Token: client.Token, Handler: router.Handle}
log.Fatal(session.Run(ctx))

Session.Run keeps the connection alive until the context ends. It resumes after drops, identifies again when a session cannot be resumed and returns only for errors that a reconnect cannot fix, such as fluxer.ErrInvalidToken, a *fluxer.BanError or the close codes 4002 and 4010 to 4012.

Handlers run on the gateway goroutine. Start a goroutine for anything that waits on the network.

A complete example is in examples/ping.

REST

Every call takes a context and returns typed results.

msg, err := client.SendMessage(ctx, channelID, fluxer.MessageSend{
	Content: "Release notes",
	Embeds:  []fluxer.Embed{{Title: "v1.4.2", Description: "Fixes the login loop."}},
})

files := []fluxer.File{{Name: "report.csv", Data: data}}
_, err = client.SendMessageFiles(ctx, channelID, fluxer.MessageSend{Content: "Weekly report"}, files)

for m, err := range client.MessagesBefore(ctx, channelID, "") {
	if err != nil {
		return err
	}
	fmt.Println(m.Author.Tag(), m.Content)
}

Files above a few megabytes go through presigned uploads, which send the bytes straight to storage and split large files into parts:

_, err = client.SendMessageUploads(ctx, channelID, fluxer.MessageSend{Content: "Recording"}, []fluxer.File{{Name: "call.mp4", Data: video}})

Edits use pointer fields, so only the fields you set are sent:

topic := "Read the rules first"
_, err := client.ModifyChannel(ctx, channelID, fluxer.ChannelEdit{Topic: &topic})

Moderation calls accept an audit log reason through the context:

ctx = fluxer.WithReason(ctx, "spam")
err := client.Ban(ctx, guildID, userID, fluxer.BanOptions{DeleteMessageSeconds: 3600})

The client follows the rate limit headers per bucket, waits on 429 responses and retries GET, PUT, PATCH and DELETE requests as well as message sends that carry a nonce. SendMessage sets a nonce when you do not. Errors from the API are *fluxer.APIError values:

if fluxer.ErrorCode(err) == "MISSING_PERMISSIONS" {
	...
}

A 401 marks the token as rejected and later calls fail without a request. errors.Is(err, fluxer.ErrTokenRejected) reports it.

Events

fluxer.On registers a handler for one event type and returns a function that removes it. The router decodes each event once, no matter how many handlers it has.

fluxer.On(router, func(e *fluxer.GuildMemberAdd) {
	log.Printf("%s joined %s", e.User.Tag(), e.GuildID)
})
router.OnAny(func(event string, data json.RawMessage) {
	log.Println(event)
})
router.OnError = func(event string, err error) {
	log.Printf("%s: %v", event, err)
}

fluxer.Decode(event, data) turns a raw dispatch into its typed event if you prefer your own dispatching.

State

cache := state.New()
session.Handler = func(event string, data json.RawMessage) {
	cache.Handle(event, data)
	router.Handle(event, data)
}

g, ok := cache.Guild(guildID)
perms, ok := cache.Permissions(guildID, channelID, userID)
if perms.Has(fluxer.PermSendMessages | fluxer.PermEmbedLinks) {
	...
}

The cache keeps guilds, channels, threads, roles, members, users, presences, voice states, emojis, stickers and the last messages of each channel. Every entity can be switched off, and members, channels and messages can be filtered with policies:

cache := state.New(
	state.WithoutFlags(state.FlagPresences),
	state.WithMemberPolicy(state.MembersInVoice().Or(state.MemberOwner())),
	state.WithChannelPolicy(state.ChannelTypes(fluxer.ChannelText, fluxer.ChannelVoice)),
	state.WithMessages(200, time.Hour),
	state.WithMessagePolicy(state.MessagesFromHumans()),
)

The bot's own member is always kept. A member that stops matching its policy, for example by leaving voice, is dropped. SweepMembers and SweepMessages apply the policies and the message TTL to everything already stored.

Members from the guild burst after READY carry only a user ID. The cache fills them from the users it has seen, and MemberPartial reports the ones it could not complete.

Handlers that need the state before an update register with state.OnChange:

state.OnChange(cache, func(old *fluxer.Message, e *fluxer.MessageUpdate) {
	if old != nil && old.Content != e.Content {
		log.Printf("edited: %q -> %q", old.Content, e.Content)
	}
})
state.OnChange(cache, func(old *fluxer.Member, e *fluxer.GuildMemberRemove) {
	if old != nil {
		log.Printf("%s left", old.DisplayName())
	}
})

Chunker requests members and waits until every chunk has arrived. With a filter it loads the members of each guild as it becomes available. WaitGuilds blocks until all guilds from READY have arrived.

chunker := state.NewChunker(session)
chunker.Filter = state.ChunkGuilds(mainGuildID)
session.Handler = func(event string, data json.RawMessage) {
	cache.Handle(event, data)
	chunker.Handle(event, data)
	router.Handle(event, data)
}
members, err := chunker.Request(ctx, fluxer.RequestMembers{GuildID: guildID, Query: "ann", Limit: 10})

Resolver reads from the cache and falls back to REST. Parallel lookups of the same entity share one request, and the result is written back.

resolver := state.NewResolver(cache, client)
member, err := resolver.Member(ctx, guildID, userID)
perms, err := resolver.Permissions(ctx, guildID, channelID, userID)

There are also helpers for the role hierarchy (HighestRole, CanManageMember, CanManageRole), name lookups (FindMember, RoleByName, ChannelByName, EmojiByName), voice (VoiceMembers, VoiceChannel), message history (Messages with before and after), iterators (EachGuild, EachMember, EachMessage) and Stats.

fluxer.ChannelPermissions computes permissions from a guild, roles and a channel without the cache.

Redis

The storage behind the cache is an interface. state/redis keeps it in Redis, so several processes or shards can share one cache:

go get github.com/invaliduser231/fluxer-go/state/redis
client := goredis.NewClient(&goredis.Options{Addr: "localhost:6379"})
store := redis.New(client, "mybot")
store.OnError = func(err error) { log.Print(err) }
cache := state.New(state.WithStore(store))

Gateway options

session := &fluxer.Session{
	Token:         token,
	Handler:       router.Handle,
	Compress:      true,
	IgnoredEvents: []string{"TYPING_START", "PRESENCE_UPDATE"},
	Presence:      &fluxer.StatusUpdate{Status: fluxer.StatusIdle},
	Logger:        slog.Default(),
}

Compress negotiates zstd-stream compression. IgnoredEvents asks Fluxer not to send those dispatches at all. Commands such as UpdateStatus, RequestGuildMembers, RequestGuildCounts and UpdateVoiceState are methods on the session.

Session.User returns the bot user from the last READY. Checkpoint and Restore carry a session ID and sequence across a process restart, so a new process can resume within the 60 seconds Fluxer keeps a session.

Sharding

A bot in more than 2,500 guilds needs several shards. fluxer.Shards runs one session per shard and paces the identifies.

shards := &fluxer.Shards{
	Token:  token,
	Client: client,
	Handler: func(shard int, event string, data json.RawMessage) {
		router.Handle(event, data)
	},
}
log.Fatal(shards.Run(ctx))

Without Count the recommendation from GET /gateway/bot is used. shards.ForGuild(guildID) returns the session that owns a guild.

Voice

Fluxer runs voice through LiveKit. The voice package sends the voice state update, waits for the grant and connects to the LiveKit room.

manager := voice.NewManager(session, router)
conn, err := manager.Join(ctx, guildID, channelID, voice.Options{SelfDeaf: true})
if err != nil {
	return err
}
defer conn.Leave(ctx)

err = conn.PlayFile(ctx, "song.ogg")

Play takes any Ogg Opus stream. Other formats can be converted on the fly:

cmd := exec.CommandContext(ctx, "ffmpeg", "-i", input, "-c:a", "libopus", "-b:a", "96k", "-f", "ogg", "-")
out, _ := cmd.StdoutPipe()
if err := cmd.Start(); err != nil {
	return err
}
err = conn.Play(ctx, out)

conn.OpusTrack publishes a track that takes Opus frames directly, voice.Options.OnTrack receives the tracks of other participants and voice.Options.OnDisconnect reports a dropped media connection. Move, SetMute and SetDeaf change the connection without leaving. A refused join returns a *fluxer.GatewayError, for example with the code fluxer.VoiceChannelFull.

See voice/examples/play.

Webhooks

hook, err := fluxer.ParseWebhookURL(webhookURL)
client := fluxer.NewClient("")
_, err = client.ExecuteWebhook(ctx, hook, "", fluxer.WebhookMessage{
	MessageSend: fluxer.MessageSend{Content: "Build passed"},
	Username:    "CI",
}, nil)

OAuth2

o := &fluxer.OAuth{
	ClientID:     clientID,
	ClientSecret: secret,
	RedirectURI:  "https://example.com/callback",
	Scopes:       []string{fluxer.ScopeIdentify, fluxer.ScopeGuilds},
}
verifier := fluxer.NewVerifier()
http.Redirect(w, r, o.AuthorizeURL(state, verifier), http.StatusFound)

token, err := o.Exchange(ctx, r.URL.Query().Get("code"), verifier)
user, err := o.User(ctx, token.AccessToken)

fluxer.BotInviteURL builds the link that adds a bot to a guild with a set of permissions.

GitHub, Slack, Instatus and Libredesk payloads can be forwarded to a webhook with ExecuteGitHubWebhook, ExecuteSlackWebhook, ExecuteInstatusWebhook and ExecuteLibredeskWebhook.

Instances

Fluxer can be self-hosted. fluxer.Discover reads the discovery document of an instance and returns its endpoints.

inst, err := fluxer.Discover(ctx, "https://chat.example.org")
client := inst.NewClient(token)
session := inst.NewSession(token)

A bot that runs on several instances at once keeps a fluxer.Instances registry. It caches the discovery documents, keeps serving the last good document when an instance is briefly unreachable and paces identifies per instance. IDs are only unique within one instance, so state.Instances keeps one cache per origin. Its Options function gives each instance its own settings, for example a Redis prefix.

instances := fluxer.NewInstances()
caches := state.NewInstances()

for origin, token := range tokens {
	client, err := instances.Client(ctx, origin, token)
	session, err := instances.Session(ctx, origin, token)
	cache := caches.For(origin)
	session.Handler = func(event string, data json.RawMessage) {
		cache.Handle(event, data)
		handle(origin, client, event, data)
	}
	go session.Run(ctx)
}

See examples/multi.

Testing

fluxertest starts a fake server with REST routes, a gateway that supports resume, compression and voice grants, and helpers to inspect what your code sent.

srv := fluxertest.NewServer("1000.secret")
defer srv.Close()
srv.AddGuild(fluxer.Guild{ID: "3", Name: "Test"})

client := srv.Client()
session := &fluxer.Session{URL: srv.GatewayURL(), Token: srv.Token, Handler: router.Handle}

srv.Dispatch("MESSAGE_CREATE", fluxer.Message{ID: "1", ChannelID: "2", Content: "!ping"})
reqs := srv.Requests()

FailOnce, RateLimitOnce, Drop, RequestReconnect and InvalidateSessions simulate failures. Handle adds routes the fake does not know.

License

MIT

Documentation

Overview

Package fluxer is a client for the Fluxer API at fluxer.app and on self-hosted instances.

A Client sends REST requests and handles rate limits and retries. A Session keeps a gateway connection open, resumes it after drops and hands every event to its Handler. A Router decodes those events into types such as MessageCreate and calls the functions registered with On.

client := fluxer.NewClient(os.Getenv("FLUXER_TOKEN"))
router := fluxer.NewRouter()
fluxer.On(router, func(m *fluxer.MessageCreate) {
	if m.Content == "!ping" {
		go client.Reply(ctx, &m.Message, fluxer.MessageSend{Content: "pong"})
	}
})
session := &fluxer.Session{Token: client.Token, Handler: router.Handle}
log.Fatal(session.Run(ctx))

The state package caches what the gateway reports, the voice module joins voice channels and fluxertest provides a fake server for tests. Guides are at https://invaliduser231.github.io/fluxer-go/.

Index

Examples

Constants

View Source
const (
	AuditGuildUpdate            = 1
	AuditChannelCreate          = 10
	AuditChannelUpdate          = 11
	AuditChannelDelete          = 12
	AuditChannelOverwriteCreate = 13
	AuditChannelOverwriteUpdate = 14
	AuditChannelOverwriteDelete = 15
	AuditMemberKick             = 20
	AuditMemberPrune            = 21
	AuditMemberBanAdd           = 22
	AuditMemberBanRemove        = 23
	AuditMemberUpdate           = 24
	AuditMemberRoleUpdate       = 25
	AuditMemberMove             = 26
	AuditMemberDisconnect       = 27
	AuditBotAdd                 = 28
	AuditRoleCreate             = 30
	AuditRoleUpdate             = 31
	AuditRoleDelete             = 32
	AuditInviteCreate           = 40
	AuditInviteUpdate           = 41
	AuditInviteDelete           = 42
	AuditWebhookCreate          = 50
	AuditWebhookUpdate          = 51
	AuditWebhookDelete          = 52
	AuditEmojiCreate            = 60
	AuditEmojiUpdate            = 61
	AuditEmojiDelete            = 62
	AuditMessageDelete          = 72
	AuditMessageBulkDelete      = 73
	AuditMessagePin             = 74
	AuditMessageUnpin           = 75
	AuditStickerCreate          = 90
	AuditStickerUpdate          = 91
	AuditStickerDelete          = 92
	AuditThreadCreate           = 110
	AuditThreadUpdate           = 111
	AuditThreadDelete           = 112
)

Audit log action types for AuditLogEntry.ActionType and AuditLogQuery.ActionType.

View Source
const (
	TemporaryBanRetry = time.Hour
	PermanentBanRetry = 24 * time.Hour
)

TemporaryBanRetry is the wait used for a temporary IP ban that comes without an expiry time. PermanentBanRetry is the minimum wait used for a permanent IP ban.

View Source
const (
	ChannelText                  = 0
	ChannelDM                    = 1
	ChannelVoice                 = 2
	ChannelGroupDM               = 3
	ChannelCategory              = 4
	ChannelAnnouncement          = 5
	ThreadAnnouncement           = 10
	ThreadPublic                 = 11
	ThreadPrivate                = 12
	ChannelForum                 = 15
	ChannelMedia                 = 16
	ChannelLink                  = 998
	ChannelPersonalNotes         = 999
	ChannelFlagPinned            = 1 << 1
	ChannelFlagRequireTag        = 1 << 4
	ChannelFlagHideMediaDownload = 1 << 15
)

Channel types and channel flags. The Channel* and Thread* type values are used in Channel.Type; the ChannelFlag* values are bits in Channel.Flags.

View Source
const (
	ForumLayoutDefault      = 0
	ForumLayoutList         = 1
	ForumLayoutGrid         = 2
	ForumSortLatestActivity = 0
	ForumSortCreationTime   = 1
	TagsMatchSome           = "match_some"
	TagsMatchAll            = "match_all"
)

Forum settings for Channel.DefaultForumLayout, Channel.DefaultSortOrder and Channel.DefaultTagSetting.

View Source
const (
	ArchiveAfterHour      = 60
	ArchiveAfterDay       = 1440
	ArchiveAfterThreeDays = 4320
	ArchiveAfterWeek      = 10080
)

Auto archive durations in minutes for threads and Channel.DefaultAutoArchiveDuration.

View Source
const (
	ContentWarningInherit = 0
	ContentWarningShow    = 1
)

Content warning levels for Channel.ContentWarningLevel and Guild.ContentWarningLevel. ContentWarningInherit takes the setting of the category or guild.

View Source
const (
	OverwriteRole   = 0
	OverwriteMember = 1
)

Overwrite types for Overwrite.Type.

View Source
const (
	DefaultAPI     = "https://api.fluxer.app/v1"
	DefaultGateway = "wss://gateway.fluxer.app"
	DefaultMedia   = "https://fluxerusercontent.com"
)

DefaultAPI, DefaultGateway and DefaultMedia are the endpoints of the public fluxer.app instance. Use Discover to find the endpoints of a self-hosted instance.

View Source
const (
	FlagDebounceMessageReactions = 1 << 1
	FlagChannelThreads           = 1 << 2
	FlagGuildVisits              = 1 << 3
)

Flags for Session.Flags, sent with IDENTIFY. FlagGuildVisits makes the session receive the guilds the account is visiting without being a member.

View Source
const (
	StatusOnline    = "online"
	StatusIdle      = "idle"
	StatusDND       = "dnd"
	StatusInvisible = "invisible"
	StatusOffline   = "offline"
)

Presence status values for StatusUpdate and Presence.

View Source
const (
	VerificationNone   = 0
	VerificationLow    = 1
	VerificationMedium = 2
	VerificationHigh   = 3
)

Verification levels for Guild.VerificationLevel.

View Source
const (
	MFANone     = 0
	MFAElevated = 1
)

MFA levels for Guild.MFALevel. MFAElevated requires moderators to have two-factor authentication enabled.

View Source
const (
	ContentFilterDisabled            = 0
	ContentFilterMembersWithoutRoles = 1
	ContentFilterAllMembers          = 2
)

Explicit content filter settings for Guild.ExplicitContentFilter.

View Source
const (
	NotifyAllMessages  = 0
	NotifyOnlyMentions = 1
)

Default notification settings for Guild.DefaultMessageNotifications.

View Source
const (
	NSFWLevelSafe          = 0
	NSFWLevelAgeRestricted = 3
)

NSFW levels for the legacy Guild.NSFWLevel. Guild.NSFW is the current setting.

View Source
const (
	SplashCenter = 0
	SplashLeft   = 1
	SplashRight  = 2
)

Splash card alignments for Guild.SplashCardAlignment.

View Source
const (
	OperationPushNotifications = 1 << 0
	OperationEveryoneMentions  = 1 << 1
	OperationTypingEvents      = 1 << 2
	OperationInstantInvites    = 1 << 3
	OperationSendMessage       = 1 << 4
	OperationReactions         = 1 << 5
	OperationMemberListUpdates = 1 << 6
)

Operation bits for Guild.DisabledOperations. A set bit turns that operation off for the whole guild.

View Source
const (
	FeatureAnimatedIcon                   = "ANIMATED_ICON"
	FeatureAnimatedBanner                 = "ANIMATED_BANNER"
	FeatureAudioBitrate128                = "AUDIO_BITRATE_128_KBPS"
	FeatureAudioBitrate256                = "AUDIO_BITRATE_256_KBPS"
	FeatureAudioBitrate384                = "AUDIO_BITRATE_384_KBPS"
	FeatureBanner                         = "BANNER"
	FeatureCloneEmojiDisabled             = "CLONE_EMOJI_DISABLED"
	FeatureCloneEmojiEnabled              = "CLONE_EMOJI_ENABLED"
	FeatureCloneStickerDisabled           = "CLONE_STICKER_DISABLED"
	FeatureCloneStickerEnabled            = "CLONE_STICKER_ENABLED"
	FeatureDetachedBanner                 = "DETACHED_BANNER"
	FeatureInviteSplash                   = "INVITE_SPLASH"
	FeatureInvitesDisabled                = "INVITES_DISABLED"
	FeatureRaidDetected                   = "RAID_DETECTED"
	FeatureTextChannelFlexibleNames       = "TEXT_CHANNEL_FLEXIBLE_NAMES"
	FeatureHideOwnerCrown                 = "HIDE_OWNER_CROWN"
	FeatureMoreEmoji                      = "MORE_EMOJI"
	FeatureMoreStickers                   = "MORE_STICKERS"
	FeatureUnlimitedEmoji                 = "UNLIMITED_EMOJI"
	FeatureUnlimitedStickers              = "UNLIMITED_STICKERS"
	FeatureExpressionPurgeAllowed         = "EXPRESSION_PURGE_ALLOWED"
	FeatureVanityURL                      = "VANITY_URL"
	FeatureDiscoverable                   = "DISCOVERABLE"
	FeaturePartnered                      = "PARTNERED"
	FeatureVerified                       = "VERIFIED"
	FeatureVIPVoice                       = "VIP_VOICE"
	FeatureVoiceE2EE                      = "VOICE_E2EE"
	FeatureUnavailableForEveryone         = "UNAVAILABLE_FOR_EVERYONE"
	FeatureUnavailableForEveryoneButStaff = "UNAVAILABLE_FOR_EVERYONE_BUT_STAFF"
	FeatureUnavailableHidden              = "UNAVAILABLE_HIDDEN"
	FeatureVisionary                      = "VISIONARY"
	FeatureLargeGuildOverride             = "LARGE_GUILD_OVERRIDE"
	FeatureVeryLargeGuild                 = "VERY_LARGE_GUILD"
	FeatureAnnouncementChannelsDisabled   = "ANNOUNCEMENT_CHANNELS_DISABLED"
	FeatureVisitsEnabled                  = "VISITS_ENABLED"
)

Guild feature flags as found in Guild.Features.

View Source
const (
	InviteGuild   = 0
	InviteGroupDM = 1
)

Invite types for Invite.Type.

View Source
const (
	MentionNoPreference = 0
	MentionPreferred    = 1
	MentionNotPreferred = 2
)

Reply mention preferences for Member.MentionFlags and User.MentionFlags: whether the user wants to be pinged when someone replies to them.

View Source
const (
	MemberAvatarUnset = 1 << 0
	MemberBannerUnset = 1 << 1
)

Profile flags for Member.ProfileFlags, set when the guild avatar or banner of the member is unset.

View Source
const (
	JoinCreator    = 0
	JoinInvite     = 1
	JoinVanityURL  = 2
	JoinBotInvite  = 3
	JoinForceAdded = 4
	JoinDiscovery  = 6
)

Join sources for MemberSearch.JoinSourceTypes and MemberSearchExtra.JoinSourceType.

View Source
const (
	MessageDefault              = 0
	MessageRecipientAdd         = 1
	MessageRecipientRemove      = 2
	MessageCall                 = 3
	MessageChannelNameChange    = 4
	MessageChannelIconChange    = 5
	MessageChannelPinnedMessage = 6
	MessageUserJoin             = 7
	MessageChannelFollowAdd     = 12
	MessageThreadCreated        = 18
	MessageReply                = 19
	MessageThreadStarter        = 21
)

Message types for Message.Type.

View Source
const (
	FlagCrossposted                  = 1 << 0
	FlagIsCrosspost                  = 1 << 1
	FlagSuppressEmbeds               = 1 << 2
	FlagSourceMessageDeleted         = 1 << 3
	FlagHasThread                    = 1 << 5
	FlagFailedToMentionRolesInThread = 1 << 8
	FlagSuppressNotifications        = 1 << 12
	FlagVoiceMessage                 = 1 << 13
)

Message flags, used as bits in Message.Flags and MessageSend.Flags. FlagFailedToMentionRolesInThread marks a thread message whose role mentions did not reach every member of the roles.

View Source
const (
	AttachmentSpoiler       = 1 << 3
	AttachmentExplicitMedia = 1 << 4
	AttachmentAnimated      = 1 << 5
)

Attachment flags for Attachment.Flags and File.Flags.

View Source
const (
	ReferenceDefault = 0
	ReferenceForward = 1
)

Reference types for MessageReference.Type. ReferenceDefault is a reply, ReferenceForward a forwarded message.

View Source
const (
	ScopeIdentify    = "identify"
	ScopeEmail       = "email"
	ScopeGuilds      = "guilds"
	ScopeConnections = "connections"
	ScopeBot         = "bot"
)

OAuth2 scopes for OAuth.Scopes. ScopeBot is used by BotInviteURL.

View Source
const (
	ThreadSortLastMessage = "last_message_time"
	ThreadSortArchived    = "archive_time"
	ThreadSortRelevance   = "relevance"
	ThreadSortCreated     = "creation_time"
)

Sort keys for ThreadSearch.SortBy.

View Source
const (
	UserStaff                     = 1 << 0
	UserPartner                   = 1 << 2
	UserBugHunter                 = 1 << 3
	UserFriendlyBot               = 1 << 4
	UserFriendlyBotManualApproval = 1 << 5
	UserSpammer                   = 1 << 6
)

Public user flags for User.Flags.

View Source
const (
	VoiceP2PConsentRequired = "VOICE_P2P_CONSENT_REQUIRED"
	VoiceP2PUnavailable     = "VOICE_P2P_UNAVAILABLE"
	VoiceChannelFull        = "VOICE_CHANNEL_FULL"
)

Voice related codes Fluxer reports in GatewayError.Code.

View Source
const (
	WebhookIncoming        = 1
	WebhookChannelFollower = 2
)

WebhookIncoming and WebhookChannelFollower are the values of Webhook.Type.

View Source
const (
	DefaultInstance = "https://fluxer.app"
)

DefaultInstance is the origin of the public Fluxer instance.

View Source
const SnowflakeEpoch = 1420070400000

SnowflakeEpoch is the Unix time in milliseconds that snowflake timestamps count from, the start of 2015 in UTC.

View Source
const SystemSuppressJoinNotifications = 1 << 0

SystemSuppressJoinNotifications is the bit in Guild.SystemChannelFlags that stops join messages in the system channel.

View Source
const Version = "0.2.0"

Version is the version of this library. It is part of the default User-Agent.

Variables

View Source
var (
	// ErrInvalidToken is returned by Session.Run when the gateway closes a new session with code
	// 4004. A 4004 during a resume drops the saved session and Run identifies again instead.
	ErrInvalidToken = errors.New("fluxer: invalid token")
	// ErrNotConnected is returned by Session.Send and the command methods while the session has no
	// connection that received READY or RESUMED.
	ErrNotConnected = errors.New("fluxer: gateway is not connected")
)
View Source
var ErrTokenRejected = errors.New("fluxer: token rejected")

ErrTokenRejected matches, through errors.Is, every *APIError with status 401. Once a Client has seen a 401 it returns such an error for all later calls.

Functions

func AvatarURL

func AvatarURL(media, userID, hash string) string

AvatarURL builds the WebP avatar URL for userID and hash on the media host, such as DefaultMedia. It returns an empty string when hash or media is empty.

func BotInviteURL

func BotInviteURL(api, clientID string, perms Permissions, guildID string) string

BotInviteURL returns the URL that adds the bot of application clientID to a guild. api is the API base URL and defaults to DefaultAPI. perms is left out when zero, and a non-empty guildID preselects the guild.

func Challenge

func Challenge(verifier string) string

Challenge returns the S256 PKCE code challenge for verifier.

func CompareSnowflakes

func CompareSnowflakes(a, b string) int

CompareSnowflakes compares two snowflake IDs numerically and returns -1, 0 or +1. An ID that does not parse counts as 0.

func ErrorCode

func ErrorCode(err error) string

ErrorCode returns the Code of the first *APIError in err's chain, or an empty string if there is none.

func IconURL

func IconURL(media, guildID, hash string) string

IconURL builds the WebP guild icon URL for guildID and hash on the media host. It returns an empty string when hash or media is empty.

func ImageData

func ImageData(contentType string, data []byte) string

ImageData encodes data as a base64 data URI, the format the API expects for icons, banners, avatars, emoji and sticker uploads.

func MemberAvatarURL

func MemberAvatarURL(media, guildID, userID, hash string) string

MemberAvatarURL builds the WebP URL of a guild-specific member avatar on the media host. It returns an empty string when hash or media is empty.

func MetricRoute

func MetricRoute(route string) string

MetricRoute reduces a route such as "GET /channels/123/messages" to a label with few distinct values, here "GET /channels/:id/messages", for use in metrics. Segments in ID positions become :id unless they are @me, bot or bulk-delete, unexpected resource names become :?, and paths with more than eight segments are cut off with "…". Client.Observe receives routes in this form.

func NewVerifier

func NewVerifier() string

NewVerifier returns a random PKCE code verifier. Keep it until the code is exchanged and pass it to both AuthorizeURL and Exchange.

func NormalizeOrigin

func NormalizeOrigin(raw string) (string, error)

NormalizeOrigin turns user input such as "Chat.Example.com" into a lowercase origin like "https://chat.example.com". It adds https:// when no scheme is given and rejects schemes other than http and https as well as addresses with a path, query, fragment or user info.

func On

func On[T any, P interface {
	*T
	Event
}](r *Router, fn func(P)) func()

On registers fn for the event type P and returns a function that removes it. The data of each dispatch is decoded once and every handler of that type receives the same value. Empty or null data yields a zero value.

Example
package main

import (
	"context"
	"log"
	"os"

	"github.com/invaliduser231/fluxer-go"
)

func main() {
	client := fluxer.NewClient(os.Getenv("FLUXER_TOKEN"))
	router := fluxer.NewRouter()
	fluxer.On(router, func(m *fluxer.MessageCreate) {
		if m.Content == "!ping" {
			go client.Reply(context.Background(), &m.Message, fluxer.MessageSend{Content: "pong"})
		}
	})
	session := &fluxer.Session{Token: client.Token, Handler: router.Handle}
	log.Fatal(session.Run(context.Background()))
}

func ParseSnowflake

func ParseSnowflake(id string) (uint64, error)

ParseSnowflake parses a snowflake ID from its decimal string form.

func ShardFor

func ShardFor(guildID string, count int) int

ShardFor returns the shard, out of count shards, that receives the events of guildID. It returns 0 when count is 1 or less.

func SnowflakeAt

func SnowflakeAt(t time.Time) string

SnowflakeAt returns the smallest snowflake for time t, which works as a Before or After bound when paging by time. Times before SnowflakeEpoch give "0".

func SnowflakeTime

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

SnowflakeTime returns the creation time encoded in a snowflake ID, in UTC.

func WithReason

func WithReason(ctx context.Context, reason string) context.Context

WithReason returns a context whose requests carry reason as the audit log reason, sent in the X-Audit-Log-Reason header. Control characters are replaced by spaces and the reason is cut to 512 characters. A blank reason returns ctx unchanged.

Types

type APIError

type APIError struct {
	Status        int
	Code          string       `json:"code"`
	Message       string       `json:"message"`
	Errors        []FieldError `json:"errors"`
	RequiredScope string       `json:"required_scope"`
	RequestID     string
	RetryAfter    time.Duration
}

APIError is an error response from the Fluxer API. Code is the error code from the response body; when the body has none, Code is derived from the HTTP status and Message holds the raw body. RequiredScope names the OAuth2 scope the token lacks, if the API reports one. RequestID comes from the X-Request-ID header and RetryAfter is set for 429 responses.

func (*APIError) Error

func (e *APIError) Error() string

Error formats the status, code and message, followed by the first field error if there is one.

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is reports whether target is ErrTokenRejected and the error has status 401.

type AllowedMentions

type AllowedMentions struct {
	Parse       []string `json:"parse"`
	Users       []string `json:"users,omitempty"`
	Roles       []string `json:"roles,omitempty"`
	RepliedUser bool     `json:"replied_user"`
}

AllowedMentions limits which mentions in a message notify anyone. Parse and RepliedUser are always sent, even when nil or false.

type Application

type Application struct {
	ID                  string   `json:"id"`
	Name                string   `json:"name"`
	Icon                string   `json:"icon,omitempty"`
	Description         string   `json:"description,omitempty"`
	BotPublic           bool     `json:"bot_public"`
	BotRequireCodeGrant bool     `json:"bot_require_code_grant"`
	VerifyKey           string   `json:"verify_key,omitempty"`
	Owner               *User    `json:"owner"`
	Bot                 *User    `json:"bot,omitempty"`
	RedirectURIs        []string `json:"redirect_uris,omitempty"`
}

Application is an OAuth2 application, as returned for the bot's own application. Bot is the application's bot user when it has one.

type Attachment

type Attachment struct {
	ID          string     `json:"id"`
	Filename    string     `json:"filename"`
	Title       string     `json:"title,omitempty"`
	Description string     `json:"description,omitempty"`
	ContentType string     `json:"content_type,omitempty"`
	ContentHash string     `json:"content_hash,omitempty"`
	Size        int64      `json:"size"`
	URL         string     `json:"url,omitempty"`
	ProxyURL    string     `json:"proxy_url,omitempty"`
	Width       int        `json:"width,omitempty"`
	Height      int        `json:"height,omitempty"`
	Placeholder string     `json:"placeholder,omitempty"`
	Flags       int        `json:"flags,omitempty"`
	NSFW        bool       `json:"nsfw,omitempty"`
	Duration    int        `json:"duration,omitempty"`
	Waveform    string     `json:"waveform,omitempty"`
	ExpiresAt   *time.Time `json:"expires_at,omitempty"`
	Expired     bool       `json:"expired,omitempty"`
}

Attachment is a file attached to a message. Size is in bytes and Duration in seconds. URL stops working at ExpiresAt; Client.RefreshAttachmentURLs gets a fresh one. Placeholder is a small base64 preview image and Waveform the base64 waveform of a voice message.

type AttachmentEdit added in v0.2.0

type AttachmentEdit struct {
	ID          string  `json:"id"`
	Title       *string `json:"title,omitempty"`
	Description *string `json:"description,omitempty"`
	Flags       *int    `json:"flags,omitempty"`
}

AttachmentEdit keeps an existing attachment of an edited message. Title, Description and Flags change it when non-nil.

type AuditLog

type AuditLog struct {
	Entries  []AuditLogEntry `json:"audit_log_entries"`
	Users    []User          `json:"users"`
	Webhooks []Webhook       `json:"webhooks"`
	Threads  []Channel       `json:"threads,omitempty"`
}

AuditLog is a page of audit log entries plus the users, webhooks and threads they reference. The webhooks carry no token or user.

func (*AuditLog) UnmarshalJSON added in v0.1.1

func (l *AuditLog) UnmarshalJSON(data []byte) error

UnmarshalJSON reads an audit log, taking the webhook avatars from the avatar_hash field the audit log uses in place of avatar.

type AuditLogChange

type AuditLogChange struct {
	Key      string          `json:"key"`
	OldValue json.RawMessage `json:"old_value,omitempty"`
	NewValue json.RawMessage `json:"new_value,omitempty"`
}

AuditLogChange is one changed field in an audit log entry. The old and new values are kept as raw JSON because their type depends on Key.

type AuditLogEntry

type AuditLogEntry struct {
	ID         string           `json:"id"`
	ActionType int              `json:"action_type"`
	UserID     string           `json:"user_id,omitempty"`
	TargetID   string           `json:"target_id,omitempty"`
	Reason     string           `json:"reason,omitempty"`
	Options    map[string]any   `json:"options,omitempty"`
	Changes    []AuditLogChange `json:"changes,omitempty"`
}

AuditLogEntry is a single audit log record. UserID is the user who performed the action and TargetID the affected object, if any.

type AuditLogQuery

type AuditLogQuery struct {
	Before     string
	After      string
	UserID     string
	ActionType int
	Limit      int
}

AuditLogQuery filters AuditLog. Before and After are entry IDs and UserID limits the results to one actor. Zero values are not sent.

type BanError

type BanError struct {
	Until     time.Time
	Permanent bool
}

BanError reports that the server refused the connection because the client's IP address is banned. Until is the earliest time a new attempt makes sense. A Session returns it when the gateway handshake is answered with 403 and a ban code.

func Ban

func Ban(code string, expires time.Time) *BanError

Ban builds a BanError from a Fluxer error code and expiry time. It returns nil unless code is GLOBAL_IP_TEMPORARILY_BANNED or GLOBAL_IP_BANNED. A temporary ban without expiry lasts TemporaryBanRetry from now; a permanent ban lasts until expires or PermanentBanRetry from now, whichever is later.

func (*BanError) Error

func (e *BanError) Error() string

Error describes the ban and, for a temporary ban, when it ends.

type BanOptions

type BanOptions struct {
	DeleteMessageSeconds int    `json:"delete_message_seconds"`
	BanDurationSeconds   int    `json:"ban_duration_seconds,omitempty"`
	Reason               string `json:"reason,omitempty"`
}

BanOptions configures Ban. DeleteMessageSeconds is always sent and removes the user's messages from that many seconds before the ban; zero keeps them. A zero BanDurationSeconds bans permanently.

type BulkFailure

type BulkFailure struct {
	Name  string `json:"name"`
	Error string `json:"error"`
}

BulkFailure reports why one item of a bulk upload, identified by its name, was rejected.

type Call

type Call struct {
	ChannelID   string       `json:"channel_id"`
	MessageID   string       `json:"message_id"`
	Region      *string      `json:"region"`
	Ringing     []string     `json:"ringing"`
	VoiceStates []VoiceState `json:"voice_states"`
}

Call is the state of a call in a private channel, shared by CALL_CREATE and CALL_UPDATE.

type CallCreate

type CallCreate struct {
	Call
	Recipients []string `json:"recipients,omitempty"`
}

CallCreate is the CALL_CREATE dispatch.

func (CallCreate) EventName

func (CallCreate) EventName() string

type CallDelete

type CallDelete struct {
	ChannelID   string `json:"channel_id"`
	Unavailable bool   `json:"unavailable,omitempty"`
}

CallDelete is the CALL_DELETE dispatch.

func (CallDelete) EventName

func (CallDelete) EventName() string

type CallInfo added in v0.2.0

type CallInfo struct {
	Participants   []string   `json:"participants"`
	EndedTimestamp *time.Time `json:"ended_timestamp,omitempty"`
}

CallInfo describes the call of a call message.

type CallUpdate

type CallUpdate struct{ Call }

CallUpdate is the CALL_UPDATE dispatch.

func (CallUpdate) EventName

func (CallUpdate) EventName() string

type Channel

type Channel struct {
	ID                   string            `json:"id"`
	GuildID              string            `json:"guild_id,omitempty"`
	Type                 int               `json:"type"`
	Name                 string            `json:"name,omitempty"`
	Topic                string            `json:"topic,omitempty"`
	URL                  string            `json:"url,omitempty"`
	Icon                 string            `json:"icon,omitempty"`
	OwnerID              string            `json:"owner_id,omitempty"`
	Position             int               `json:"position,omitempty"`
	ParentID             string            `json:"parent_id,omitempty"`
	Bitrate              int               `json:"bitrate,omitempty"`
	UserLimit            int               `json:"user_limit,omitempty"`
	VoiceConnectionLimit int               `json:"voice_connection_limit,omitempty"`
	RTCRegion            string            `json:"rtc_region,omitempty"`
	RTCP2P               bool              `json:"rtc_p2p,omitempty"`
	LastMessageID        string            `json:"last_message_id,omitempty"`
	LastPinTimestamp     *time.Time        `json:"last_pin_timestamp,omitempty"`
	PermissionOverwrites []Overwrite       `json:"permission_overwrites,omitempty"`
	Recipients           []User            `json:"recipients,omitempty"`
	Nicks                map[string]string `json:"nicks,omitempty"`
	NSFW                 bool              `json:"nsfw,omitempty"`
	NSFWOverride         *bool             `json:"nsfw_override,omitempty"`
	ContentWarningLevel  int               `json:"content_warning_level,omitempty"`
	ContentWarningText   string            `json:"content_warning_text,omitempty"`
	RateLimitPerUser     int               `json:"rate_limit_per_user,omitempty"`
	Flags                int               `json:"flags,omitempty"`

	ThreadMetadata                *ThreadMetadata  `json:"thread_metadata,omitempty"`
	AppliedTags                   []string         `json:"applied_tags,omitempty"`
	MessageCount                  int              `json:"message_count,omitempty"`
	TotalMessageSent              int              `json:"total_message_sent,omitempty"`
	MemberCount                   int              `json:"member_count,omitempty"`
	MemberIDsPreview              []string         `json:"member_ids_preview,omitempty"`
	Member                        *ThreadMember    `json:"member,omitempty"`
	DefaultAutoArchiveDuration    int              `json:"default_auto_archive_duration,omitempty"`
	DefaultThreadRateLimitPerUser int              `json:"default_thread_rate_limit_per_user,omitempty"`
	AvailableTags                 []ForumTag       `json:"available_tags,omitempty"`
	DefaultReactionEmoji          *DefaultReaction `json:"default_reaction_emoji,omitempty"`
	DefaultSortOrder              *int             `json:"default_sort_order,omitempty"`
	DefaultForumLayout            int              `json:"default_forum_layout,omitempty"`
	DefaultTagSetting             string           `json:"default_tag_setting,omitempty"`
}

Channel is a guild channel, thread, DM or group DM. The thread fields at the end are only set for threads and forum channels. NSFW is the effective value, NSFWOverride the channel's own setting, nil when it inherits. VoiceConnectionLimit caps the voice connections per user and RTCP2P makes calls connect participants directly. Nicks holds the nicknames in a group DM. TotalMessageSent counts every message ever sent in a thread, while MessageCount drops deleted ones. MemberIDsPreview lists the latest members of a forum post.

func (Channel) IsPrivate

func (c Channel) IsPrivate() bool

IsPrivate reports whether the channel is a DM, a group DM or the personal notes channel.

func (Channel) IsThread

func (c Channel) IsThread() bool

IsThread reports whether the channel is an announcement, public or private thread.

func (Channel) Mention

func (c Channel) Mention() string

Mention returns the <#id> mention string for the channel.

type ChannelCreate

type ChannelCreate struct{ Channel }

ChannelCreate is the CHANNEL_CREATE dispatch.

func (ChannelCreate) EventName

func (ChannelCreate) EventName() string

type ChannelDelete

type ChannelDelete struct{ Channel }

ChannelDelete is the CHANNEL_DELETE dispatch.

func (ChannelDelete) EventName

func (ChannelDelete) EventName() string

type ChannelEdit

type ChannelEdit struct {
	Name                          *string            `json:"name,omitempty"`
	Type                          *int               `json:"type,omitempty"`
	Topic                         *string            `json:"topic,omitempty"`
	URL                           *string            `json:"url,omitempty"`
	ParentID                      *string            `json:"parent_id,omitempty"`
	Bitrate                       *int               `json:"bitrate,omitempty"`
	UserLimit                     *int               `json:"user_limit,omitempty"`
	VoiceConnectionLimit          *int               `json:"voice_connection_limit,omitempty"`
	RTCRegion                     *string            `json:"rtc_region,omitempty"`
	RTCP2P                        *bool              `json:"rtc_p2p,omitempty"`
	RateLimitPerUser              *int               `json:"rate_limit_per_user,omitempty"`
	NSFW                          *bool              `json:"nsfw,omitempty"`
	NSFWOverride                  *bool              `json:"nsfw_override,omitempty"`
	ContentWarningLevel           *int               `json:"content_warning_level,omitempty"`
	ContentWarningText            *string            `json:"content_warning_text,omitempty"`
	PermissionOverwrites          *[]Overwrite       `json:"permission_overwrites,omitempty"`
	Flags                         *int               `json:"flags,omitempty"`
	Icon                          *string            `json:"icon,omitempty"`
	OwnerID                       *string            `json:"owner_id,omitempty"`
	Nicks                         *map[string]string `json:"nicks,omitempty"`
	DefaultAutoArchiveDuration    *int               `json:"default_auto_archive_duration,omitempty"`
	DefaultThreadRateLimitPerUser *int               `json:"default_thread_rate_limit_per_user,omitempty"`
	AvailableTags                 *[]ForumTag        `json:"available_tags,omitempty"`
	DefaultReactionEmoji          *DefaultReaction   `json:"default_reaction_emoji,omitempty"`
	DefaultSortOrder              *int               `json:"default_sort_order,omitempty"`
	DefaultForumLayout            *int               `json:"default_forum_layout,omitempty"`
	DefaultTagSetting             *string            `json:"default_tag_setting,omitempty"`
	Archived                      *bool              `json:"archived,omitempty"`
	Locked                        *bool              `json:"locked,omitempty"`
	Invitable                     *bool              `json:"invitable,omitempty"`
	AutoArchiveDuration           *int               `json:"auto_archive_duration,omitempty"`
	AppliedTags                   *[]string          `json:"applied_tags,omitempty"`
}

ChannelEdit holds the fields to change on a channel or thread. Only non-nil fields are sent, so a field cannot be reset to null through this struct. Archived, Locked, Invitable, AutoArchiveDuration and AppliedTags apply to threads, Icon, OwnerID and Nicks to group DMs. Icon is a data URI.

type ChannelMemberCount

type ChannelMemberCount struct {
	GuildID     string `json:"guild_id"`
	ChannelID   string `json:"channel_id"`
	MemberCount int    `json:"member_count"`
	OnlineCount int    `json:"online_count"`
}

ChannelMemberCount holds the member and online count of one channel.

type ChannelMemberCountsUpdate

type ChannelMemberCountsUpdate struct {
	Counts []ChannelMemberCount `json:"counts"`
	Nonce  string               `json:"nonce,omitempty"`
}

ChannelMemberCountsUpdate is the CHANNEL_MEMBER_COUNTS_UPDATE dispatch, the answer to Session.RequestChannelMemberCounts.

func (ChannelMemberCountsUpdate) EventName

func (ChannelMemberCountsUpdate) EventName() string

type ChannelMention

type ChannelMention struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	Type int    `json:"type"`
}

ChannelMention is a channel referenced in a message's content.

type ChannelPins

type ChannelPins struct {
	Items   []PinnedMessage `json:"items"`
	HasMore bool            `json:"has_more"`
}

ChannelPins is one page of pinned messages. While HasMore is true, pass the PinnedAt of the last item to Pins to get the next page.

type ChannelPinsUpdate

type ChannelPinsUpdate struct {
	ChannelID        string     `json:"channel_id"`
	GuildID          string     `json:"guild_id,omitempty"`
	LastPinTimestamp *time.Time `json:"last_pin_timestamp"`
}

ChannelPinsUpdate is the CHANNEL_PINS_UPDATE dispatch.

func (ChannelPinsUpdate) EventName

func (ChannelPinsUpdate) EventName() string

type ChannelPosition

type ChannelPosition struct {
	ID                 string  `json:"id"`
	Position           *int    `json:"position,omitempty"`
	ParentID           *string `json:"parent_id,omitempty"`
	PrecedingSiblingID *string `json:"preceding_sibling_id,omitempty"`
	LockPermissions    bool    `json:"lock_permissions,omitempty"`
}

ChannelPosition moves one channel in ModifyChannelPositions. PrecedingSiblingID places it directly after that channel, as an alternative to Position. Nil pointer fields are not sent.

type ChannelRecipientAdd

type ChannelRecipientAdd struct {
	ChannelID string `json:"channel_id"`
	User      User   `json:"user"`
}

ChannelRecipientAdd is the CHANNEL_RECIPIENT_ADD dispatch.

func (ChannelRecipientAdd) EventName

func (ChannelRecipientAdd) EventName() string

type ChannelRecipientRemove

type ChannelRecipientRemove struct {
	ChannelID string `json:"channel_id"`
	User      User   `json:"user"`
}

ChannelRecipientRemove is the CHANNEL_RECIPIENT_REMOVE dispatch.

func (ChannelRecipientRemove) EventName

func (ChannelRecipientRemove) EventName() string

type ChannelUpdate

type ChannelUpdate struct{ Channel }

ChannelUpdate is the CHANNEL_UPDATE dispatch.

func (ChannelUpdate) EventName

func (ChannelUpdate) EventName() string

type ChannelUpdateBulk

type ChannelUpdateBulk struct {
	GuildID  string    `json:"guild_id"`
	Channels []Channel `json:"channels"`
}

ChannelUpdateBulk is the CHANNEL_UPDATE_BULK dispatch.

func (ChannelUpdateBulk) EventName

func (ChannelUpdateBulk) EventName() string

type Checkpoint

type Checkpoint struct {
	SessionID string
	Seq       int64
}

Checkpoint holds the session ID and last sequence number needed to resume a gateway session. Passing one to Session.Restore lets a new process resume a session Fluxer still keeps.

type Client

type Client struct {
	BaseURL    string
	Token      string
	UserAgent  string
	HTTP       *http.Client
	MaxRetries int
	BodyLimit  int64
	Observe    func(route string, status int, took time.Duration)
	// contains filtered or unexported fields
}

Client is a REST client for the Fluxer API. It learns rate limit buckets from response headers and waits before sending a request into a bucket that is exhausted or while a global rate limit is active. A Client is safe for concurrent use once its fields are set.

After the API answers a request with 401, the Client considers its token rejected and fails every later call with an *APIError matching ErrTokenRejected without contacting the API.

MaxRetries limits retries of transient failures, see Do. BodyLimit caps how many bytes of a response body are read and defaults to 8 MiB. Observe, when set, is called after every HTTP round trip with the route in MetricRoute form, the status code (0 on a transport error) and the duration.

func NewClient

func NewClient(token string) *Client

NewClient returns a Client for the public fluxer.app API that authenticates as the bot with the given token. Surrounding whitespace and a leading "Bot " prefix are removed from token. The client uses a 15 second HTTP timeout and retries up to 3 times.

func (*Client) AckPins

func (c *Client) AckPins(ctx context.Context, channelID string) error

AckPins marks the pins of a channel as seen by the current user.

func (*Client) ActiveThreads

func (c *Client) ActiveThreads(ctx context.Context, guildID string) (*ThreadList, error)

ActiveThreads lists all active threads in a guild that the current user can see.

func (*Client) AddMemberRole

func (c *Client) AddMemberRole(ctx context.Context, guildID, userID, roleID string) error

AddMemberRole grants a role to a guild member.

func (*Client) AddReaction

func (c *Client) AddReaction(ctx context.Context, channelID, messageID, emoji string) error

AddReaction reacts to a message as the current user. The emoji is a Unicode emoji or name:id for a custom emoji, as returned by ReactionEmoji.APIName. It is path-escaped before use.

func (*Client) AddRecipient

func (c *Client) AddRecipient(ctx context.Context, channelID, userID string) error

AddRecipient adds a user to a group DM.

func (*Client) AddThreadMember

func (c *Client) AddThreadMember(ctx context.Context, threadID, userID string) error

AddThreadMember adds a user to a thread.

func (*Client) AllMembers

func (c *Client) AllMembers(ctx context.Context, guildID string) iter.Seq2[Member, error]

AllMembers iterates over every member of a guild, fetching 1000 at a time. Iteration ends after a short page or after yielding the first error.

func (*Client) Application

func (c *Client) Application(ctx context.Context) (*Application, error)

Application returns the application the bot belongs to. It calls GET /applications/@me.

func (*Client) ApplyForDiscovery

func (c *Client) ApplyForDiscovery(ctx context.Context, guildID string, a DiscoveryApplication) (*DiscoveryApplication, error)

ApplyForDiscovery submits a guild for discovery listing.

func (*Client) ArchiveThread

func (c *Client) ArchiveThread(ctx context.Context, threadID string, archived bool) (*Channel, error)

ArchiveThread archives or unarchives a thread.

func (*Client) ArchivedThreads

func (c *Client) ArchivedThreads(ctx context.Context, channelID string, private bool, before time.Time, limit int) (*ThreadList, error)

ArchivedThreads lists public or private archived threads in a channel, archived before the given time. A zero before starts with the most recent, and a limit of zero or less uses the server default.

func (*Client) AuditLog

func (c *Client) AuditLog(ctx context.Context, guildID string, q AuditLogQuery) (*AuditLog, error)

AuditLog fetches the audit log of a guild.

func (*Client) Ban

func (c *Client) Ban(ctx context.Context, guildID, userID string, b BanOptions) error

Ban bans a user from a guild.

func (*Client) Bans

func (c *Client) Bans(ctx context.Context, guildID string) ([]GuildBan, error)

Bans lists the bans of a guild.

func (*Client) BulkDelete

func (c *Client) BulkDelete(ctx context.Context, channelID string, ids []string) error

BulkDelete deletes several messages in a channel with one request.

func (*Client) Channel

func (c *Client) Channel(ctx context.Context, channelID string) (*Channel, error)

Channel fetches a channel by ID.

func (*Client) ChannelInvites

func (c *Client) ChannelInvites(ctx context.Context, channelID string) ([]Invite, error)

ChannelInvites lists the invites of a channel.

func (*Client) ChannelWebhooks

func (c *Client) ChannelWebhooks(ctx context.Context, channelID string) ([]Webhook, error)

ChannelWebhooks lists the webhooks of a channel. It calls GET /channels/{id}/webhooks.

func (*Client) ClearReadState

func (c *Client) ClearReadState(ctx context.Context, channelID string) error

ClearReadState removes the current user's read state for a channel (DELETE /channels/{id}/messages/ack).

func (*Client) CloneEmoji

func (c *Client) CloneEmoji(ctx context.Context, guildID, sourceEmojiID string) (*Emoji, error)

CloneEmoji copies an existing emoji from another guild into guildID by its ID.

func (*Client) CloneSticker

func (c *Client) CloneSticker(ctx context.Context, guildID, sourceStickerID string) (*Sticker, error)

CloneSticker copies an existing sticker from another guild into guildID by its ID.

func (*Client) CreateChannel

func (c *Client) CreateChannel(ctx context.Context, guildID string, ch NewChannel) (*Channel, error)

CreateChannel creates a channel in a guild.

func (*Client) CreateDM

func (c *Client) CreateDM(ctx context.Context, userID string) (*Channel, error)

CreateDM opens a DM channel with a user (POST /users/@me/channels).

func (*Client) CreateEmoji

func (c *Client) CreateEmoji(ctx context.Context, guildID string, e NewEmoji) (*Emoji, error)

CreateEmoji uploads a custom emoji to a guild.

func (*Client) CreateEmojis

func (c *Client) CreateEmojis(ctx context.Context, guildID string, emojis []NewEmoji) (*EmojiBulkResult, error)

CreateEmojis uploads several emoji in one request. Individual failures are listed in the result instead of failing the whole call.

func (*Client) CreateForumTag

func (c *Client) CreateForumTag(ctx context.Context, channelID string, tag ForumTag) (*Channel, error)

CreateForumTag adds a tag to a forum channel and returns the updated channel.

func (*Client) CreateGroupDM

func (c *Client) CreateGroupDM(ctx context.Context, recipientIDs []string) (*Channel, error)

CreateGroupDM creates a group DM with the given users.

func (*Client) CreateInvite

func (c *Client) CreateInvite(ctx context.Context, channelID string, i NewInvite) (*Invite, error)

CreateInvite creates an invite for a channel.

func (*Client) CreatePost

func (c *Client) CreatePost(ctx context.Context, forumID string, p NewPost) (*Post, error)

CreatePost creates a post in a forum channel.

func (*Client) CreatePostFiles

func (c *Client) CreatePostFiles(ctx context.Context, forumID string, p NewPost, files []File) (*Post, error)

CreatePostFiles creates a forum post with file uploads attached to its first message. Unlike SendMessageFiles it sets no nonce, so a failed POST is not retried.

func (*Client) CreateRole

func (c *Client) CreateRole(ctx context.Context, guildID string, r NewRole) (*Role, error)

CreateRole creates a role in a guild.

func (*Client) CreateSticker

func (c *Client) CreateSticker(ctx context.Context, guildID string, s NewSticker) (*Sticker, error)

CreateSticker uploads a custom sticker to a guild.

func (*Client) CreateStickers

func (c *Client) CreateStickers(ctx context.Context, guildID string, stickers []NewSticker) (*StickerBulkResult, error)

CreateStickers uploads several stickers in one request. Individual failures are listed in the result instead of failing the whole call.

func (*Client) CreateWebhook

func (c *Client) CreateWebhook(ctx context.Context, channelID, name, avatar string) (*Webhook, error)

CreateWebhook creates a webhook in channelID. An empty avatar is left out of the request.

func (*Client) Crosspost

func (c *Client) Crosspost(ctx context.Context, channelID, messageID string) (*Message, error)

Crosspost publishes a message in an announcement channel to all following channels.

func (*Client) CrosspostSource

func (c *Client) CrosspostSource(ctx context.Context, channelID, messageID string) (*CrosspostSource, error)

CrosspostSource fetches the origin of a crossposted message.

func (*Client) CurrentMember

func (c *Client) CurrentMember(ctx context.Context, guildID string) (*Member, error)

CurrentMember fetches the client's own member object in a guild.

func (*Client) CurrentUser

func (c *Client) CurrentUser(ctx context.Context) (*User, error)

CurrentUser fetches the user the client is authenticated as (GET /users/@me).

func (*Client) DeleteAttachment

func (c *Client) DeleteAttachment(ctx context.Context, channelID, messageID, attachmentID string) error

DeleteAttachment removes one attachment from a message.

func (*Client) DeleteChannel

func (c *Client) DeleteChannel(ctx context.Context, channelID string) error

DeleteChannel deletes a guild channel or closes a DM.

func (*Client) DeleteEmoji

func (c *Client) DeleteEmoji(ctx context.Context, guildID, emojiID string) error

DeleteEmoji removes a custom emoji from a guild.

func (*Client) DeleteForumTag

func (c *Client) DeleteForumTag(ctx context.Context, channelID, tagID string) (*Channel, error)

DeleteForumTag removes a tag from a forum channel and returns the updated channel.

func (*Client) DeleteGuild

func (c *Client) DeleteGuild(ctx context.Context, guildID string) error

DeleteGuild permanently deletes a guild (POST /guilds/{id}/delete). Only the owner can do this.

func (*Client) DeleteInvite

func (c *Client) DeleteInvite(ctx context.Context, code string) error

DeleteInvite revokes an invite.

func (*Client) DeleteMessage

func (c *Client) DeleteMessage(ctx context.Context, channelID, messageID string) error

DeleteMessage deletes a message.

func (*Client) DeleteOwnGuildMessages

func (c *Client) DeleteOwnGuildMessages(ctx context.Context, guildID string) error

DeleteOwnGuildMessages asks the server to delete all messages the current user sent anywhere in a guild.

func (*Client) DeleteOwnMessages

func (c *Client) DeleteOwnMessages(ctx context.Context, channelID string) error

DeleteOwnMessages asks the server to delete all messages the current user sent in a channel (POST /channels/{id}/messages/bulk-delete-mine).

func (*Client) DeletePermission

func (c *Client) DeletePermission(ctx context.Context, channelID, overwriteID string) error

DeletePermission removes the overwrite for a role or user from a channel.

func (*Client) DeleteRole

func (c *Client) DeleteRole(ctx context.Context, guildID, roleID string) error

DeleteRole deletes a role.

func (*Client) DeleteSticker

func (c *Client) DeleteSticker(ctx context.Context, guildID, stickerID string) error

DeleteSticker removes a custom sticker from a guild.

func (*Client) DeleteWebhook

func (c *Client) DeleteWebhook(ctx context.Context, webhookID string) error

DeleteWebhook deletes a webhook by ID.

func (*Client) DeleteWebhookMessage

func (c *Client) DeleteWebhookMessage(ctx context.Context, w Webhook, threadID, messageID string) error

DeleteWebhookMessage deletes a message that w has sent. Pass threadID when the message is in a thread.

func (*Client) DeleteWebhookWithToken

func (c *Client) DeleteWebhookWithToken(ctx context.Context, w Webhook) error

DeleteWebhookWithToken deletes w through its token route.

func (*Client) DisconnectMember

func (c *Client) DisconnectMember(ctx context.Context, guildID, userID string) (*Member, error)

DisconnectMember removes a member from voice by setting their voice channel to null.

func (*Client) DiscoveryCategories

func (c *Client) DiscoveryCategories(ctx context.Context) ([]DiscoveryCategory, error)

DiscoveryCategories lists the available discovery categories.

func (*Client) DiscoveryStatus

func (c *Client) DiscoveryStatus(ctx context.Context, guildID string) (*DiscoveryStatus, error)

DiscoveryStatus fetches the discovery state of a guild.

func (*Client) Do

func (c *Client) Do(ctx context.Context, method, path string, body, out any) error

Do sends a request to path, relative to BaseURL, with body encoded as JSON, and decodes the response into out when out is non-nil. A nil body sends no request body. Responses with a status of 300 or higher are returned as *APIError.

Do waits for known rate limits before sending. It retries 429 responses after the advertised delay, and 423, 502, 503 and 504 responses after Retry-After or one second, up to MaxRetries times. A POST is only retried on 429, unless body carries a nonce, as a MessageSend with Nonce set does. Transport errors are not retried. A reason set with WithReason is sent as X-Audit-Log-Reason.

func (*Client) DoFiles

func (c *Client) DoFiles(ctx context.Context, method, path string, body any, files []File, out any) error

DoFiles sends a multipart/form-data request with body encoded as the payload_json field and files as files[0], files[1] and so on, and decodes the response into out. When any file has a title, description, flags, duration or waveform, an attachments array with ids, filenames and those fields is added to the payload; this only works when body encodes as a JSON object, otherwise they are dropped. Without files DoFiles behaves like Do. Retries follow the same rules as Do.

func (*Client) EditDiscoveryApplication

func (c *Client) EditDiscoveryApplication(ctx context.Context, guildID string, e DiscoveryEdit) (*DiscoveryApplication, error)

EditDiscoveryApplication applies e to a guild's discovery application.

func (*Client) EditMessage

func (c *Client) EditMessage(ctx context.Context, channelID, messageID string, m MessageEdit) (*Message, error)

EditMessage applies m to a message and returns the updated message.

func (*Client) EditMessageUploads added in v0.2.0

func (c *Client) EditMessageUploads(ctx context.Context, channelID, messageID string, m MessageEdit, files []File) (*Message, error)

EditMessageUploads uploads files with Upload and edits a message with m, adding the uploaded files to m.Uploads. See MessageEdit for how the attachment list is replaced.

func (*Client) EditWebhookMessage

func (c *Client) EditWebhookMessage(ctx context.Context, w Webhook, threadID, messageID string, m MessageEdit) (*Message, error)

EditWebhookMessage edits a message that w has sent. Pass threadID when the message is in a thread.

func (*Client) EmojiMetadata

func (c *Client) EmojiMetadata(ctx context.Context, emojiID string) (*ExpressionMetadata, error)

EmojiMetadata fetches metadata for any emoji by ID (GET /emojis/{id}/metadata).

func (*Client) EmojiSource

func (c *Client) EmojiSource(ctx context.Context, emojiID string) (*ExpressionSource, error)

EmojiSource fetches the guild an emoji belongs to (GET /emojis/{id}/source).

func (*Client) Emojis

func (c *Client) Emojis(ctx context.Context, guildID string) ([]Emoji, error)

Emojis lists the custom emoji of a guild.

func (*Client) ExecuteGitHubWebhook

func (c *Client) ExecuteGitHubWebhook(ctx context.Context, w Webhook, threadID, event, delivery string, payload json.RawMessage) error

ExecuteGitHubWebhook forwards a GitHub webhook delivery to the /github endpoint of w. event and delivery are sent as the X-GitHub-Event and X-GitHub-Delivery headers, and payload is the body GitHub sent. The request is only retried on 429.

func (*Client) ExecuteInstatusWebhook

func (c *Client) ExecuteInstatusWebhook(ctx context.Context, w Webhook, payload json.RawMessage) error

ExecuteInstatusWebhook forwards an Instatus notification to the /instatus endpoint of w. That endpoint takes no thread.

func (*Client) ExecuteLibredeskWebhook

func (c *Client) ExecuteLibredeskWebhook(ctx context.Context, w Webhook, threadID string, payload json.RawMessage) error

ExecuteLibredeskWebhook forwards a Libredesk webhook payload to the /libredesk endpoint of w.

func (*Client) ExecuteSlackWebhook

func (c *Client) ExecuteSlackWebhook(ctx context.Context, w Webhook, threadID string, m SlackMessage) error

ExecuteSlackWebhook posts m to the Slack-compatible /slack endpoint of w.

func (*Client) ExecuteWebhook

func (c *Client) ExecuteWebhook(ctx context.Context, w Webhook, threadID string, m WebhookMessage, files []File) (*Message, error)

ExecuteWebhook posts m through w and returns the created message. When threadID is non-empty the message goes to that thread. files are sent as multipart attachments, see DoFiles. A nonce is generated when m.Nonce is empty, which makes the request safe to retry.

func (*Client) ExecuteWebhookNoWait added in v0.2.0

func (c *Client) ExecuteWebhookNoWait(ctx context.Context, w Webhook, threadID string, m WebhookMessage, files []File) error

ExecuteWebhookNoWait posts m through w like ExecuteWebhook but does not ask Fluxer to return the message, which makes the call a little faster.

func (*Client) FollowChannel

func (c *Client) FollowChannel(ctx context.Context, channelID, targetChannelID string) (*FollowedChannel, error)

FollowChannel follows the announcement channel channelID, so its crossposted messages are delivered to targetChannelID through a webhook.

func (*Client) FollowerStats

func (c *Client) FollowerStats(ctx context.Context, channelID string) (*FollowerStats, error)

FollowerStats fetches follower counts for an announcement channel.

func (*Client) Forward added in v0.2.0

func (c *Client) Forward(ctx context.Context, m *Message, channelID string) (*Message, error)

Forward forwards m to channelID. A forward carries no content of its own; Fluxer copies the original into the new message's MessageSnapshots.

func (*Client) GatewayBot

func (c *Client) GatewayBot(ctx context.Context) (*GatewayBot, error)

GatewayBot returns the gateway URL and sharding information for the bot. It calls GET /gateway/bot.

func (*Client) Guild

func (c *Client) Guild(ctx context.Context, guildID string) (*Guild, error)

Guild fetches a guild by ID.

func (*Client) GuildChannels

func (c *Client) GuildChannels(ctx context.Context, guildID string) ([]Channel, error)

GuildChannels lists the channels of a guild.

func (*Client) GuildInvites

func (c *Client) GuildInvites(ctx context.Context, guildID string) ([]Invite, error)

GuildInvites lists all invites of a guild.

func (*Client) GuildWebhooks

func (c *Client) GuildWebhooks(ctx context.Context, guildID string) ([]Webhook, error)

GuildWebhooks lists the webhooks of a guild. It calls GET /guilds/{id}/webhooks.

func (*Client) Guilds

func (c *Client) Guilds(ctx context.Context, q GuildQuery) ([]Guild, error)

Guilds lists the guilds the current user is in (GET /users/@me/guilds).

func (*Client) Invite

func (c *Client) Invite(ctx context.Context, code string) (*Invite, error)

Invite resolves an invite code. The code is path-escaped.

func (*Client) JoinThread

func (c *Client) JoinThread(ctx context.Context, threadID string) error

JoinThread adds the current user to a thread.

func (*Client) JoinedArchivedThreads

func (c *Client) JoinedArchivedThreads(ctx context.Context, channelID string, before time.Time, limit int) (*ThreadList, error)

JoinedArchivedThreads lists archived private threads in a channel that the current user has joined. before and limit work as in ArchivedThreads.

func (*Client) LatestMessages

func (c *Client) LatestMessages(ctx context.Context, channelIDs []string) (map[string]*Message, error)

LatestMessages fetches the most recent message of each given channel in one request (POST /users/@me/preload-messages). The map is keyed by channel ID; a channel without messages may map to nil.

func (*Client) LeaveGuild

func (c *Client) LeaveGuild(ctx context.Context, guildID string) error

LeaveGuild makes the current user leave a guild.

func (*Client) LeaveThread

func (c *Client) LeaveThread(ctx context.Context, threadID string) error

LeaveThread removes the current user from a thread.

func (*Client) LockThread

func (c *Client) LockThread(ctx context.Context, threadID string, locked bool) (*Channel, error)

LockThread locks or unlocks a thread.

func (*Client) Member

func (c *Client) Member(ctx context.Context, guildID, userID string) (*Member, error)

Member fetches a single guild member.

func (*Client) Members

func (c *Client) Members(ctx context.Context, guildID, after string, limit int) ([]Member, error)

Members lists one page of guild members, starting after the user ID given in after. An empty after starts from the beginning, and a limit of zero or less requests the maximum page size of 1000.

func (*Client) Message

func (c *Client) Message(ctx context.Context, channelID, messageID string) (*Message, error)

Message fetches a single message.

func (*Client) Messages

func (c *Client) Messages(ctx context.Context, channelID string, q MessageQuery) ([]Message, error)

Messages fetches a page of messages from a channel as selected by q.

func (*Client) MessagesBefore

func (c *Client) MessagesBefore(ctx context.Context, channelID, before string) iter.Seq2[Message, error]

MessagesBefore iterates over a channel's messages older than the message ID before, fetching 100 at a time. An empty before starts with the newest message. Iteration ends after a short page or after yielding the first error.

func (*Client) ModifyChannel

func (c *Client) ModifyChannel(ctx context.Context, channelID string, e ChannelEdit) (*Channel, error)

ModifyChannel applies e to a channel and returns the updated channel.

func (*Client) ModifyChannelPositions

func (c *Client) ModifyChannelPositions(ctx context.Context, guildID string, positions []ChannelPosition) error

ModifyChannelPositions reorders or moves several guild channels in one request.

func (*Client) ModifyCurrentMember

func (c *Client) ModifyCurrentMember(ctx context.Context, guildID string, e MemberEdit) (*Member, error)

ModifyCurrentMember applies e to the client's own member object in a guild.

func (*Client) ModifyForumTag

func (c *Client) ModifyForumTag(ctx context.Context, channelID string, tag ForumTag) (*Channel, error)

ModifyForumTag replaces the forum tag with ID tag.ID and returns the updated channel.

func (*Client) ModifyGuild

func (c *Client) ModifyGuild(ctx context.Context, guildID string, e GuildEdit) (*Guild, error)

ModifyGuild applies e to a guild and returns the updated guild.

func (*Client) ModifyMember

func (c *Client) ModifyMember(ctx context.Context, guildID, userID string, e MemberEdit) (*Member, error)

ModifyMember applies e to a guild member and returns the updated member.

func (*Client) ModifyRole

func (c *Client) ModifyRole(ctx context.Context, guildID, roleID string, e RoleEdit) (*Role, error)

ModifyRole applies e to a role and returns the updated role.

func (*Client) ModifyRoleHoistPositions

func (c *Client) ModifyRoleHoistPositions(ctx context.Context, guildID string, positions []RoleHoistPosition) error

ModifyRoleHoistPositions sets the member list order of hoisted roles.

func (*Client) ModifyRolePositions

func (c *Client) ModifyRolePositions(ctx context.Context, guildID string, positions []RolePosition) ([]Role, error)

ModifyRolePositions reorders roles in a guild and returns the guild's roles after the change.

func (*Client) ModifySticker

func (c *Client) ModifySticker(ctx context.Context, guildID, stickerID string, e StickerEdit) (*Sticker, error)

ModifySticker applies e to a sticker and returns the updated sticker.

func (*Client) ModifyWebhook

func (c *Client) ModifyWebhook(ctx context.Context, webhookID string, e WebhookEdit) (*Webhook, error)

ModifyWebhook changes a webhook. Setting ChannelID moves it to another channel.

func (*Client) ModifyWebhookWithToken

func (c *Client) ModifyWebhookWithToken(ctx context.Context, w Webhook, name, avatar *string) (*Webhook, error)

ModifyWebhookWithToken changes the name or avatar of w through its token route. A nil argument leaves that field unchanged.

func (*Client) MoveMember

func (c *Client) MoveMember(ctx context.Context, guildID, userID, channelID string) (*Member, error)

MoveMember moves a member who is in voice to another voice channel.

func (*Client) OAuthApplication

func (c *Client) OAuthApplication(ctx context.Context) (*Application, error)

OAuthApplication returns the application of the current token. It calls GET /oauth2/applications/@me.

func (*Client) Pin

func (c *Client) Pin(ctx context.Context, channelID, messageID string) error

Pin pins a message in its channel (PUT /channels/{id}/pins/{message}).

func (*Client) PinDM

func (c *Client) PinDM(ctx context.Context, channelID string) error

PinDM pins a DM or group DM in the current user's channel list.

func (*Client) Pins

func (c *Client) Pins(ctx context.Context, channelID string, before time.Time, limit int) (*ChannelPins, error)

Pins lists pinned messages pinned before the given time (GET /channels/{id}/messages/pins). A zero before starts with the newest pin, and a limit of zero or less uses the server default.

func (*Client) PostData

func (c *Client) PostData(ctx context.Context, forumID string, threadIDs []string) (map[string]PostData, error)

PostData fetches owner and first-message data for several posts in a forum channel, keyed by thread ID.

func (*Client) PrivateChannels

func (c *Client) PrivateChannels(ctx context.Context) ([]Channel, error)

PrivateChannels lists the DM and group DM channels of the current user.

func (*Client) PublicApplication

func (c *Client) PublicApplication(ctx context.Context, applicationID string) (*PublicApplication, error)

PublicApplication returns the public information of an application. It calls GET /oauth2/applications/{id}/public.

func (*Client) PurgeEmoji added in v0.2.0

func (c *Client) PurgeEmoji(ctx context.Context, guildID, emojiID string) error

PurgeEmoji removes a custom emoji from a guild and deletes its image from storage as well. The guild needs FeatureExpressionPurgeAllowed.

func (*Client) PurgeSticker added in v0.2.0

func (c *Client) PurgeSticker(ctx context.Context, guildID, stickerID string) error

PurgeSticker removes a custom sticker from a guild and deletes its image from storage. The guild needs FeatureExpressionPurgeAllowed.

func (*Client) Reactions

func (c *Client) Reactions(ctx context.Context, channelID, messageID, emoji, after string, limit int) ([]User, error)

Reactions lists users who reacted to a message with emoji, after the user ID in after. An empty after and a limit of zero or less leave paging to the server. ReactionsPage returns the same list with paging information.

func (*Client) ReactionsPage

func (c *Client) ReactionsPage(ctx context.Context, channelID, messageID, emoji, after string, limit int) (*ReactionPage, error)

ReactionsPage lists users who reacted to a message with emoji, after the user ID in after. An empty after and a limit of zero or less leave paging to the server defaults.

func (*Client) RefreshAttachmentURLs

func (c *Client) RefreshAttachmentURLs(ctx context.Context, urls []string) (map[string]string, error)

RefreshAttachmentURLs requests new signed URLs for the given attachment URLs with POST /attachments/refresh-urls. The result maps each original URL to its new URL; URLs the API did not refresh are missing from the map.

func (*Client) RemoveAllReactions

func (c *Client) RemoveAllReactions(ctx context.Context, channelID, messageID string) error

RemoveAllReactions removes every reaction from a message.

func (*Client) RemoveEmojiReactions

func (c *Client) RemoveEmojiReactions(ctx context.Context, channelID, messageID, emoji string) error

RemoveEmojiReactions removes all reactions with emoji from a message.

func (*Client) RemoveMember

func (c *Client) RemoveMember(ctx context.Context, guildID, userID string) error

RemoveMember kicks a member from a guild. Use WithReason on ctx to record an audit log reason.

func (*Client) RemoveMemberRole

func (c *Client) RemoveMemberRole(ctx context.Context, guildID, userID, roleID string) error

RemoveMemberRole takes a role away from a guild member.

func (*Client) RemoveOwnReaction

func (c *Client) RemoveOwnReaction(ctx context.Context, channelID, messageID, emoji string) error

RemoveOwnReaction removes the current user's reaction with emoji from a message.

func (*Client) RemoveReaction

func (c *Client) RemoveReaction(ctx context.Context, channelID, messageID, emoji, userID string) error

RemoveReaction removes another user's reaction with emoji from a message.

func (*Client) RemoveRecipient

func (c *Client) RemoveRecipient(ctx context.Context, channelID, userID string, silent bool) error

RemoveRecipient removes a user from a group DM. With silent set, the request carries silent=true.

func (*Client) RemoveThreadMember

func (c *Client) RemoveThreadMember(ctx context.Context, threadID, userID string) error

RemoveThreadMember removes a user from a thread.

func (*Client) RenameEmoji

func (c *Client) RenameEmoji(ctx context.Context, guildID, emojiID, name string) (*Emoji, error)

RenameEmoji changes the name of a custom emoji.

func (*Client) Reply

func (c *Client) Reply(ctx context.Context, to *Message, m MessageSend) (*Message, error)

Reply sends m to the channel of to as a reply to it, replacing any MessageReference already set on m.

func (*Client) ResetRoleHoistPositions

func (c *Client) ResetRoleHoistPositions(ctx context.Context, guildID string) error

ResetRoleHoistPositions removes all custom hoist positions in a guild, so hoisted roles are listed by their regular position again.

func (*Client) Roles

func (c *Client) Roles(ctx context.Context, guildID string) ([]Role, error)

Roles lists the roles of a guild.

func (*Client) SearchDiscovery

func (c *Client) SearchDiscovery(ctx context.Context, q DiscoverySearch) (*DiscoveryResult, error)

SearchDiscovery searches the public guild directory (GET /discovery/guilds).

func (*Client) SearchMembers

func (c *Client) SearchMembers(ctx context.Context, guildID string, q MemberSearch) (*MemberSearchPage, error)

SearchMembers runs a member search in a guild (POST /guilds/{id}/members-search).

func (*Client) SearchMessages

func (c *Client) SearchMessages(ctx context.Context, q MessageSearch) (*MessageSearchResult, error)

SearchMessages runs a full-text message search (POST /search/messages). Because it is a POST without a nonce, it is only retried on rate limits.

func (*Client) SearchThreads

func (c *Client) SearchThreads(ctx context.Context, channelID string, q ThreadSearch) (*ThreadSearchResult, error)

SearchThreads searches the threads of a channel (GET /channels/{id}/threads/search).

func (*Client) SendMessage

func (c *Client) SendMessage(ctx context.Context, channelID string, m MessageSend) (*Message, error)

SendMessage posts a message to a channel. It sets a random nonce when m.Nonce is empty, so transient failures are retried without risking duplicate messages.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/invaliduser231/fluxer-go"
)

func main() {
	client := fluxer.NewClient(os.Getenv("FLUXER_TOKEN"))
	embed := fluxer.Embed{Title: "Status"}
	embed.SetColor(0x43b581).AddField("API", "up", true).AddField("Gateway", "up", true)
	msg, err := client.SendMessage(context.Background(), "1189375284394692610", fluxer.MessageSend{
		Content: "Hourly check",
		Embeds:  []fluxer.Embed{embed},
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(msg.ID)
}

func (*Client) SendMessageFiles

func (c *Client) SendMessageFiles(ctx context.Context, channelID string, m MessageSend, files []File) (*Message, error)

SendMessageFiles posts a message with file uploads as multipart form data. Without files it behaves like SendMessage.

func (*Client) SendMessageUploads

func (c *Client) SendMessageUploads(ctx context.Context, channelID string, m MessageSend, files []File) (*Message, error)

SendMessageUploads uploads files with Upload and sends m to channelID with the uploaded files appended to its attachments.

func (*Client) SendText

func (c *Client) SendText(ctx context.Context, channelID, content string) (*Message, error)

SendText posts a message with plain text content.

func (*Client) SetNickname

func (c *Client) SetNickname(ctx context.Context, guildID, userID, nick string) (*Member, error)

SetNickname sets a member's guild nickname. The nick is always sent, including an empty string.

func (*Client) SetPermission

func (c *Client) SetPermission(ctx context.Context, channelID string, o Overwrite) error

SetPermission creates or replaces the permission overwrite o.ID on a channel.

func (*Client) SetTimeout

func (c *Client) SetTimeout(ctx context.Context, guildID, userID string, until time.Time) (*Member, error)

SetTimeout times a member out until the given time. A zero time sends null, which removes an active timeout.

func (*Client) SetVanityURL

func (c *Client) SetVanityURL(ctx context.Context, guildID, code string) (*VanityURL, error)

SetVanityURL changes the vanity invite code of a guild.

func (*Client) Slowmode

func (c *Client) Slowmode(ctx context.Context, channelID string) (*SlowmodeState, error)

Slowmode fetches the current user's slowmode state in a channel.

func (*Client) StartThread

func (c *Client) StartThread(ctx context.Context, channelID string, t ThreadStart) (*Channel, error)

StartThread starts a thread in a channel that is not tied to a message. A zero t.Type defaults to ThreadPublic.

func (*Client) StartThreadFromMessage

func (c *Client) StartThreadFromMessage(ctx context.Context, channelID, messageID string, t ThreadStart) (*Channel, error)

StartThreadFromMessage starts a thread attached to an existing message. Any Type set in t is cleared before sending.

func (*Client) StickerMetadata

func (c *Client) StickerMetadata(ctx context.Context, stickerID string) (*ExpressionMetadata, error)

StickerMetadata fetches metadata for any sticker by ID (GET /stickers/{id}/metadata).

func (*Client) StickerSource

func (c *Client) StickerSource(ctx context.Context, stickerID string) (*ExpressionSource, error)

StickerSource fetches the guild a sticker belongs to (GET /stickers/{id}/source).

func (*Client) Stickers

func (c *Client) Stickers(ctx context.Context, guildID string) ([]Sticker, error)

Stickers lists the custom stickers of a guild.

func (*Client) TagTaken

func (c *Client) TagTaken(ctx context.Context, username, discriminator string) (bool, error)

TagTaken reports whether the combination of username and discriminator is already in use. It calls GET /users/check-tag.

func (*Client) ThreadMember

func (c *Client) ThreadMember(ctx context.Context, threadID, userID string) (*ThreadMember, error)

ThreadMember fetches one user's membership in a thread.

func (*Client) ThreadMembers

func (c *Client) ThreadMembers(ctx context.Context, threadID string, withMember bool, after string, limit int) ([]ThreadMember, error)

ThreadMembers lists the members of a thread after the user ID in after. With withMember set, each entry includes the guild Member. An empty after and a limit of zero or less leave paging to the server.

func (*Client) TransferOwnership

func (c *Client) TransferOwnership(ctx context.Context, guildID, newOwnerID string) (*Guild, error)

TransferOwnership makes newOwnerID the owner of a guild and returns the updated guild.

func (*Client) Typing

func (c *Client) Typing(ctx context.Context, channelID string) error

Typing shows the typing indicator for the current user in a channel.

func (*Client) Unban

func (c *Client) Unban(ctx context.Context, guildID, userID string) error

Unban lifts a user's ban.

func (*Client) Unpin

func (c *Client) Unpin(ctx context.Context, channelID, messageID string) error

Unpin unpins a message.

func (*Client) UnpinDM

func (c *Client) UnpinDM(ctx context.Context, channelID string) error

UnpinDM unpins a DM or group DM from the current user's channel list.

func (*Client) Upload

func (c *Client) Upload(ctx context.Context, channelID string, files []File) ([]UploadedFile, error)

Upload uploads files to storage through presigned URLs and returns them in a form that can be attached to a message in channelID. It requests an upload plan with POST /channels/{id}/attachments, PUTs each file or part, and finishes multipart uploads with POST /channels/{id}/attachments/complete. At most 10 files are accepted per call. The content type is guessed from the file extension, falling back to the data.

The PUT requests use the transport of the Client's HTTP client but neither its timeout nor the Authorization header, so bound them with ctx.

func (*Client) User

func (c *Client) User(ctx context.Context, userID string) (*User, error)

User fetches a user by ID.

func (*Client) UserProfile

func (c *Client) UserProfile(ctx context.Context, userID, guildID string) (*UserProfile, error)

UserProfile returns the profile of userID. With a non-empty guildID the profile includes the user's membership in that guild. It calls GET /users/{id}/profile.

func (*Client) VanityURL

func (c *Client) VanityURL(ctx context.Context, guildID string) (*VanityURL, error)

VanityURL fetches the vanity invite of a guild.

func (*Client) Webhook

func (c *Client) Webhook(ctx context.Context, webhookID string) (*Webhook, error)

Webhook returns a webhook by ID. It calls GET /webhooks/{id}.

func (*Client) WebhookMessage

func (c *Client) WebhookMessage(ctx context.Context, w Webhook, threadID, messageID string) (*Message, error)

WebhookMessage returns a message that w has sent. Pass threadID when the message is in a thread.

func (*Client) WebhookWithToken

func (c *Client) WebhookWithToken(ctx context.Context, w Webhook) (*Webhook, error)

WebhookWithToken returns w through its token route, GET /webhooks/{id}/{token}.

func (*Client) WithdrawDiscovery

func (c *Client) WithdrawDiscovery(ctx context.Context, guildID string) error

WithdrawDiscovery withdraws a guild's discovery application or removes its listing.

type CloseError

type CloseError struct {
	Code   int
	Reason string
}

CloseError carries the close code and reason the gateway sent when it closed the connection.

func (*CloseError) Error

func (e *CloseError) Error() string

Error returns the close code and reason.

type CrosspostSource

type CrosspostSource struct {
	Guild DiscoveryGuild `json:"guild"`
}

CrosspostSource identifies the guild a crossposted message came from.

type CustomStatus

type CustomStatus struct {
	Text          *string    `json:"text,omitempty"`
	ExpiresAt     *time.Time `json:"expires_at,omitempty"`
	EmojiID       *string    `json:"emoji_id,omitempty"`
	EmojiName     *string    `json:"emoji_name,omitempty"`
	EmojiAnimated bool       `json:"emoji_animated,omitempty"`
}

CustomStatus is the custom status text and emoji of a presence.

type DefaultReaction

type DefaultReaction struct {
	EmojiID   string `json:"emoji_id,omitempty"`
	EmojiName string `json:"emoji_name,omitempty"`
}

DefaultReaction is the emoji shown as a reaction button on new forum posts, given either as a custom EmojiID or a Unicode EmojiName.

type DiscoveryApplication

type DiscoveryApplication struct {
	GuildID         string     `json:"guild_id,omitempty"`
	Status          string     `json:"status,omitempty"`
	Description     string     `json:"description"`
	CategoryType    int        `json:"category_type"`
	PrimaryLanguage string     `json:"primary_language,omitempty"`
	CustomTags      []string   `json:"custom_tags,omitempty"`
	AppliedAt       *time.Time `json:"applied_at,omitempty"`
	ReviewedAt      *time.Time `json:"reviewed_at,omitempty"`
	ReviewReason    string     `json:"review_reason,omitempty"`
	RemovedAt       *time.Time `json:"removed_at,omitempty"`
	RemovalReason   string     `json:"removal_reason,omitempty"`
}

DiscoveryApplication is a guild's request to be listed in discovery. When passed to ApplyForDiscovery only Description, CategoryType, PrimaryLanguage and CustomTags are used; the rest is filled in by the server.

type DiscoveryCategory

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

DiscoveryCategory is a category guilds can be listed under in discovery.

type DiscoveryEdit

type DiscoveryEdit struct {
	Description     *string   `json:"description,omitempty"`
	CategoryType    *int      `json:"category_type,omitempty"`
	PrimaryLanguage *string   `json:"primary_language,omitempty"`
	CustomTags      *[]string `json:"custom_tags,omitempty"`
}

DiscoveryEdit holds the fields to change on a discovery application. Only non-nil fields are sent.

type DiscoveryGuild

type DiscoveryGuild struct {
	ID              string   `json:"id"`
	Name            string   `json:"name"`
	Icon            string   `json:"icon,omitempty"`
	Banner          string   `json:"banner,omitempty"`
	Description     string   `json:"description,omitempty"`
	CategoryType    int      `json:"category_type"`
	PrimaryLanguage string   `json:"primary_language,omitempty"`
	CustomTags      []string `json:"custom_tags,omitempty"`
	MemberCount     int      `json:"member_count"`
	OnlineCount     int      `json:"online_count"`
	Features        []string `json:"features,omitempty"`
}

DiscoveryGuild is a guild as it appears in discovery listings. CategoryType is a DiscoveryCategory ID.

type DiscoveryResult

type DiscoveryResult struct {
	Guilds []DiscoveryGuild `json:"guilds"`
	Total  int              `json:"total"`
}

DiscoveryResult is one page of SearchDiscovery results and the total number of matches.

type DiscoverySearch

type DiscoverySearch struct {
	Query    string
	Category *int
	Language string
	Tag      string
	SortBy   string
	Limit    int
	Offset   int
}

DiscoverySearch filters SearchDiscovery. Empty strings and zero Limit and Offset are not sent. Category is a pointer so that category 0 can be requested; nil means any.

type DiscoveryStatus

type DiscoveryStatus struct {
	Application    *DiscoveryApplication `json:"application"`
	Eligible       bool                  `json:"eligible"`
	MinMemberCount int                   `json:"min_member_count"`
}

DiscoveryStatus reports whether a guild is eligible for discovery and its current application, which is nil if it never applied.

type Embed

type Embed struct {
	Type        string         `json:"type,omitempty"`
	Title       string         `json:"title,omitempty"`
	URL         string         `json:"url,omitempty"`
	Description string         `json:"description,omitempty"`
	Color       *int           `json:"color,omitempty"`
	Timestamp   string         `json:"timestamp,omitempty"`
	Author      *EmbedAuthor   `json:"author,omitempty"`
	Image       *EmbedMedia    `json:"image,omitempty"`
	Thumbnail   *EmbedMedia    `json:"thumbnail,omitempty"`
	Video       *EmbedMedia    `json:"video,omitempty"`
	Audio       *EmbedMedia    `json:"audio,omitempty"`
	Footer      *EmbedFooter   `json:"footer,omitempty"`
	Provider    *EmbedProvider `json:"provider,omitempty"`
	Fields      []EmbedField   `json:"fields,omitempty"`
	HTML        string         `json:"html,omitempty"`
	HTMLWidth   int            `json:"html_width,omitempty"`
	HTMLHeight  int            `json:"html_height,omitempty"`
	NSFW        bool           `json:"nsfw,omitempty"`
	Children    []Embed        `json:"children,omitempty"`
}

Embed is rich content attached to a message. Timestamp is an RFC 3339 string; use SetTimestamp to fill it from a time.Time. Color is nil when no color is set. HTML, NSFW and Children are only set on embeds Fluxer generates from links: HTML is sanitized oEmbed markup and Children holds nested embeds of the same link.

func (*Embed) AddField

func (e *Embed) AddField(name, value string, inline bool) *Embed

AddField appends a field to the embed and returns e.

func (*Embed) SetColor

func (e *Embed) SetColor(rgb int) *Embed

SetColor sets the embed color to rgb, given as 0xRRGGBB, and returns e.

func (*Embed) SetTimestamp

func (e *Embed) SetTimestamp(t time.Time) *Embed

SetTimestamp sets the embed timestamp to t in UTC and returns e.

type EmbedAuthor

type EmbedAuthor struct {
	Name         string `json:"name"`
	URL          string `json:"url,omitempty"`
	IconURL      string `json:"icon_url,omitempty"`
	ProxyIconURL string `json:"proxy_icon_url,omitempty"`
}

EmbedAuthor is the author line of an embed.

type EmbedField

type EmbedField struct {
	Name   string `json:"name"`
	Value  string `json:"value"`
	Inline bool   `json:"inline"`
}

EmbedField is a name and value pair shown in an embed. Inline fields may be placed side by side.

type EmbedFooter

type EmbedFooter struct {
	Text         string `json:"text"`
	IconURL      string `json:"icon_url,omitempty"`
	ProxyIconURL string `json:"proxy_icon_url,omitempty"`
}

EmbedFooter is the footer of an embed.

type EmbedMedia

type EmbedMedia struct {
	URL         string `json:"url"`
	ProxyURL    string `json:"proxy_url,omitempty"`
	ContentType string `json:"content_type,omitempty"`
	ContentHash string `json:"content_hash,omitempty"`
	Width       int    `json:"width,omitempty"`
	Height      int    `json:"height,omitempty"`
	Description string `json:"description,omitempty"`
	Placeholder string `json:"placeholder,omitempty"`
	Duration    int    `json:"duration,omitempty"`
	Flags       int    `json:"flags,omitempty"`
}

EmbedMedia is an image, thumbnail, video or audio item in an embed. ProxyURL, the dimensions, ContentHash, Placeholder, Duration in seconds and Flags, which uses the AttachmentExplicitMedia and AttachmentAnimated bits, are filled in by the server.

type EmbedProvider

type EmbedProvider struct {
	Name string `json:"name"`
	URL  string `json:"url,omitempty"`
}

EmbedProvider names the site an embed was generated from.

type Emoji

type Emoji struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	Animated bool   `json:"animated,omitempty"`
	NSFW     bool   `json:"nsfw,omitempty"`
	User     *User  `json:"user,omitempty"`
}

Emoji is a custom guild emoji. User is the uploader and is nil when the API leaves it out.

func (Emoji) APIName

func (e Emoji) APIName() string

APIName returns name:id, the form the reaction endpoints expect.

func (Emoji) String

func (e Emoji) String() string

String returns the emoji in message content form, <:name:id> or <a:name:id> when animated.

type EmojiBulkResult

type EmojiBulkResult struct {
	Success []Emoji       `json:"success"`
	Failed  []BulkFailure `json:"failed"`
}

EmojiBulkResult is the outcome of CreateEmojis: the emoji that were created and the ones that failed.

type EntranceSoundPlay

type EntranceSoundPlay struct {
	UserID      string `json:"user_id"`
	ChannelID   string `json:"channel_id"`
	GuildID     string `json:"guild_id,omitempty"`
	SoundID     string `json:"sound_id"`
	Hash        string `json:"hash"`
	URL         string `json:"url"`
	DurationMS  int    `json:"duration_ms"`
	ContentType string `json:"content_type"`
}

EntranceSoundPlay is the ENTRANCE_SOUND_PLAY dispatch.

func (EntranceSoundPlay) EventName

func (EntranceSoundPlay) EventName() string

type Event

type Event interface{ EventName() string }

Event is implemented by every typed dispatch. EventName returns the dispatch name, such as MESSAGE_CREATE.

func Decode

func Decode(event string, data json.RawMessage) (Event, error)

Decode decodes dispatch data into the typed event registered for its name. It returns nil and no error for names without a type, and a zero value for empty or null data.

type ExpressionMetadata

type ExpressionMetadata struct {
	ID           string `json:"id"`
	GuildID      string `json:"guild_id"`
	Name         string `json:"name"`
	Animated     bool   `json:"animated"`
	AllowCloning bool   `json:"allow_cloning"`
}

ExpressionMetadata describes an emoji or sticker by ID, including the guild it belongs to and whether other guilds may clone it.

type ExpressionSource

type ExpressionSource struct {
	ID       string   `json:"id"`
	Name     string   `json:"name"`
	Icon     string   `json:"icon,omitempty"`
	Features []string `json:"features"`
}

ExpressionSource is the guild an emoji or sticker comes from.

type FieldError

type FieldError struct {
	Path    string `json:"path"`
	Code    string `json:"code"`
	Message string `json:"message"`
}

FieldError describes a validation problem with one field of a request body. Path names the field.

type File

type File struct {
	Name        string
	Title       string
	Description string
	Flags       int
	Duration    int
	Waveform    string
	Data        []byte
}

File is a file sent with DoFiles or Upload. Name is the file name. Title, Description and Flags, for example AttachmentSpoiler, are sent with the attachment. Duration in seconds and the base64 Waveform describe a voice message.

type FollowedChannel

type FollowedChannel struct {
	ChannelID string `json:"channel_id"`
	WebhookID string `json:"webhook_id"`
}

FollowedChannel is the result of FollowChannel: the target channel and the webhook created in it.

type FollowerStats

type FollowerStats struct {
	ChannelCount int `json:"channel_count"`
	GuildCount   int `json:"guild_count"`
}

FollowerStats counts the channels and guilds following an announcement channel.

type ForumTag

type ForumTag struct {
	ID        string `json:"id,omitempty"`
	Name      string `json:"name"`
	Moderated bool   `json:"moderated"`
	EmojiID   string `json:"emoji_id,omitempty"`
	EmojiName string `json:"emoji_name,omitempty"`
}

ForumTag is a tag that can be applied to posts in a forum channel. The emoji is set either by EmojiID for a custom emoji or by EmojiName for a Unicode one.

type GatewayBot

type GatewayBot struct {
	URL               string            `json:"url"`
	Shards            int               `json:"shards"`
	SessionStartLimit SessionStartLimit `json:"session_start_limit"`
}

GatewayBot is the gateway URL, the recommended number of shards and the session start limit for a bot.

type GatewayError

type GatewayError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

GatewayError is the payload of a gateway error (op 12), which Session passes to Handler as GATEWAY_ERROR. It is both an Event and an error.

func (*GatewayError) Error

func (e *GatewayError) Error() string

Error returns the code and message.

func (GatewayError) EventName

func (GatewayError) EventName() string

type Guild

type Guild struct {
	ID                          string      `json:"id"`
	Name                        string      `json:"name"`
	Icon                        string      `json:"icon,omitempty"`
	Banner                      string      `json:"banner,omitempty"`
	BannerWidth                 int         `json:"banner_width,omitempty"`
	BannerHeight                int         `json:"banner_height,omitempty"`
	Splash                      string      `json:"splash,omitempty"`
	SplashWidth                 int         `json:"splash_width,omitempty"`
	SplashHeight                int         `json:"splash_height,omitempty"`
	SplashCardAlignment         int         `json:"splash_card_alignment,omitempty"`
	EmbedSplash                 string      `json:"embed_splash,omitempty"`
	EmbedSplashWidth            int         `json:"embed_splash_width,omitempty"`
	EmbedSplashHeight           int         `json:"embed_splash_height,omitempty"`
	VanityURLCode               string      `json:"vanity_url_code,omitempty"`
	OwnerID                     string      `json:"owner_id"`
	SystemChannelID             string      `json:"system_channel_id,omitempty"`
	SystemChannelFlags          int         `json:"system_channel_flags,omitempty"`
	RulesChannelID              string      `json:"rules_channel_id,omitempty"`
	AFKChannelID                string      `json:"afk_channel_id,omitempty"`
	AFKTimeout                  int         `json:"afk_timeout,omitempty"`
	Features                    []string    `json:"features,omitempty"`
	VerificationLevel           int         `json:"verification_level,omitempty"`
	MFALevel                    int         `json:"mfa_level,omitempty"`
	NSFWLevel                   int         `json:"nsfw_level,omitempty"`
	NSFW                        bool        `json:"nsfw,omitempty"`
	ContentWarningLevel         int         `json:"content_warning_level,omitempty"`
	ContentWarningText          string      `json:"content_warning_text,omitempty"`
	ExplicitContentFilter       int         `json:"explicit_content_filter,omitempty"`
	DefaultMessageNotifications int         `json:"default_message_notifications,omitempty"`
	DisabledOperations          int         `json:"disabled_operations,omitempty"`
	MessageHistoryCutoff        *time.Time  `json:"message_history_cutoff,omitempty"`
	Permissions                 Permissions `json:"permissions,omitempty"`
	Roles                       []Role      `json:"roles,omitempty"`
	Emojis                      []Emoji     `json:"emojis,omitempty"`
	Stickers                    []Sticker   `json:"stickers,omitempty"`
	Channels                    []Channel   `json:"channels,omitempty"`
	MemberCount                 int         `json:"member_count,omitempty"`
	OnlineCount                 int         `json:"online_count,omitempty"`
	ApproximateMemberCount      int         `json:"approximate_member_count,omitempty"`
	ApproximatePresenceCount    int         `json:"approximate_presence_count,omitempty"`
	ThreadsActive               bool        `json:"threads_active,omitempty"`
	Visiting                    bool        `json:"visiting,omitempty"`
}

Guild is a Fluxer guild (server). Roles, Emojis, Stickers and Channels are only filled in by endpoints and events that include them, and the count fields depend on the request, for example GuildQuery.WithCounts. MessageHistoryCutoff limits how far back members without Read Message History can read. ThreadsActive is true when threads, forums and media channels are enabled, Visiting when the current user visits the guild without being a member.

func (Guild) HasFeature

func (g Guild) HasFeature(feature string) bool

HasFeature reports whether the guild has the named feature flag.

func (Guild) IconURL

func (g Guild) IconURL(media string) string

IconURL returns the URL of the guild icon on the media host, or an empty string when the guild has no icon.

type GuildAuditLogEntryCreate

type GuildAuditLogEntryCreate struct {
	AuditLogEntry
	GuildID string `json:"guild_id"`
}

GuildAuditLogEntryCreate is the gateway event sent when a new audit log entry is written in a guild.

func (GuildAuditLogEntryCreate) EventName

func (GuildAuditLogEntryCreate) EventName() string

EventName returns the gateway event name GUILD_AUDIT_LOG_ENTRY_CREATE.

type GuildBan

type GuildBan struct {
	User        User       `json:"user"`
	Reason      string     `json:"reason,omitempty"`
	ModeratorID string     `json:"moderator_id,omitempty"`
	BannedAt    time.Time  `json:"banned_at,omitzero"`
	ExpiresAt   *time.Time `json:"expires_at,omitempty"`
}

GuildBan is a ban entry. ExpiresAt is nil for a permanent ban.

type GuildBanAdd

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

GuildBanAdd is the GUILD_BAN_ADD dispatch.

func (GuildBanAdd) EventName

func (GuildBanAdd) EventName() string

type GuildBanRemove

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

GuildBanRemove is the GUILD_BAN_REMOVE dispatch.

func (GuildBanRemove) EventName

func (GuildBanRemove) EventName() string

type GuildCount

type GuildCount struct {
	GuildID     string `json:"guild_id"`
	MemberCount int    `json:"member_count"`
	OnlineCount int    `json:"online_count"`
}

GuildCount holds the member and online count of one guild.

type GuildCountsUpdate

type GuildCountsUpdate struct {
	Counts []GuildCount `json:"counts"`
	Nonce  string       `json:"nonce,omitempty"`
}

GuildCountsUpdate is the GUILD_COUNTS_UPDATE dispatch, the answer to Session.RequestGuildCounts.

func (GuildCountsUpdate) EventName

func (GuildCountsUpdate) EventName() string

type GuildCreate

type GuildCreate struct{ GuildState }

GuildCreate is the GUILD_CREATE dispatch. For bot sessions, members in the guilds sent after READY carry only the user ID.

func (GuildCreate) EventName

func (GuildCreate) EventName() string

type GuildDelete

type GuildDelete struct {
	ID          string `json:"id"`
	Unavailable bool   `json:"unavailable,omitempty"`
}

GuildDelete is the GUILD_DELETE dispatch. Unavailable is set when the guild is down; without it the bot left or was removed.

func (GuildDelete) EventName

func (GuildDelete) EventName() string

type GuildEdit

type GuildEdit struct {
	Name                        *string    `json:"name,omitempty"`
	Icon                        *string    `json:"icon,omitempty"`
	Banner                      *string    `json:"banner,omitempty"`
	Splash                      *string    `json:"splash,omitempty"`
	EmbedSplash                 *string    `json:"embed_splash,omitempty"`
	SplashCardAlignment         *int       `json:"splash_card_alignment,omitempty"`
	SystemChannelID             *string    `json:"system_channel_id,omitempty"`
	SystemChannelFlags          *int       `json:"system_channel_flags,omitempty"`
	AFKChannelID                *string    `json:"afk_channel_id,omitempty"`
	AFKTimeout                  *int       `json:"afk_timeout,omitempty"`
	VerificationLevel           *int       `json:"verification_level,omitempty"`
	MFALevel                    *int       `json:"mfa_level,omitempty"`
	NSFW                        *bool      `json:"nsfw,omitempty"`
	ContentWarningLevel         *int       `json:"content_warning_level,omitempty"`
	ContentWarningText          *string    `json:"content_warning_text,omitempty"`
	DefaultMessageNotifications *int       `json:"default_message_notifications,omitempty"`
	ExplicitContentFilter       *int       `json:"explicit_content_filter,omitempty"`
	Features                    *[]string  `json:"features,omitempty"`
	MessageHistoryCutoff        *time.Time `json:"message_history_cutoff,omitempty"`
}

GuildEdit holds the fields to change on a guild. Only non-nil fields are sent. Image fields take a data URI from ImageData. Features is the complete feature list the guild should have; Fluxer only changes the features owners may toggle.

type GuildEmojisUpdate

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

GuildEmojisUpdate is the GUILD_EMOJIS_UPDATE dispatch.

func (GuildEmojisUpdate) EventName

func (GuildEmojisUpdate) EventName() string

type GuildHealthUpdate added in v0.2.0

type GuildHealthUpdate struct {
	GuildID  string `json:"guild_id"`
	Degraded bool   `json:"degraded"`
}

GuildHealthUpdate is the GUILD_HEALTH_UPDATE dispatch. Degraded is true while the gateway process of the guild takes more than two seconds to answer health probes, so events for the guild may arrive late, and false again once it answers within half a second. Fluxer sends it on changes and, for guilds that are degraded, after READY.

func (GuildHealthUpdate) EventName added in v0.2.0

func (GuildHealthUpdate) EventName() string

type GuildMemberAdd

type GuildMemberAdd struct{ Member }

GuildMemberAdd is the GUILD_MEMBER_ADD dispatch.

func (GuildMemberAdd) EventName

func (GuildMemberAdd) EventName() string

type GuildMemberListUpdate added in v0.2.0

type GuildMemberListUpdate struct {
	GuildID     string            `json:"guild_id"`
	ID          string            `json:"id"`
	ChannelID   string            `json:"channel_id,omitempty"`
	MemberCount int               `json:"member_count"`
	OnlineCount int               `json:"online_count"`
	Groups      []MemberListGroup `json:"groups"`
	Ops         []MemberListOp    `json:"ops"`
}

GuildMemberListUpdate is the GUILD_MEMBER_LIST_UPDATE dispatch, sent for the member list ranges subscribed with Session.Subscribe. ID is the channel ID of the list.

func (GuildMemberListUpdate) EventName added in v0.2.0

func (GuildMemberListUpdate) EventName() string

EventName returns the gateway event name GUILD_MEMBER_LIST_UPDATE.

type GuildMemberRemove

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

GuildMemberRemove is the GUILD_MEMBER_REMOVE dispatch.

func (GuildMemberRemove) EventName

func (GuildMemberRemove) EventName() string

type GuildMemberUpdate

type GuildMemberUpdate struct{ Member }

GuildMemberUpdate is the GUILD_MEMBER_UPDATE dispatch.

func (GuildMemberUpdate) EventName

func (GuildMemberUpdate) EventName() string

type GuildMembersChunk

type GuildMembersChunk struct {
	GuildID    string     `json:"guild_id"`
	Members    []Member   `json:"members"`
	ChunkIndex int        `json:"chunk_index"`
	ChunkCount int        `json:"chunk_count"`
	Presences  []Presence `json:"presences,omitempty"`
	Nonce      string     `json:"nonce,omitempty"`
}

GuildMembersChunk is the GUILD_MEMBERS_CHUNK dispatch, one part of the answer to Session.RequestGuildMembers.

func (GuildMembersChunk) EventName

func (GuildMembersChunk) EventName() string

type GuildQuery

type GuildQuery struct {
	Before     string
	After      string
	Limit      int
	WithCounts bool
}

GuildQuery pages through the current user's guilds in Guilds. Before and After are guild IDs, a zero Limit leaves the page size to the server, and WithCounts asks for approximate member and presence counts.

type GuildRoleCreate

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

GuildRoleCreate is the GUILD_ROLE_CREATE dispatch.

func (GuildRoleCreate) EventName

func (GuildRoleCreate) EventName() string

type GuildRoleDelete

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

GuildRoleDelete is the GUILD_ROLE_DELETE dispatch.

func (GuildRoleDelete) EventName

func (GuildRoleDelete) EventName() string

type GuildRoleUpdate

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

GuildRoleUpdate is the GUILD_ROLE_UPDATE dispatch.

func (GuildRoleUpdate) EventName

func (GuildRoleUpdate) EventName() string

type GuildRoleUpdateBulk

type GuildRoleUpdateBulk struct {
	GuildID string `json:"guild_id"`
	Roles   []Role `json:"roles"`
}

GuildRoleUpdateBulk is the GUILD_ROLE_UPDATE_BULK dispatch.

func (GuildRoleUpdateBulk) EventName

func (GuildRoleUpdateBulk) EventName() string

type GuildState

type GuildState struct {
	ID          string       `json:"id"`
	Properties  Guild        `json:"properties"`
	Roles       []Role       `json:"roles"`
	Channels    []Channel    `json:"channels"`
	Emojis      []Emoji      `json:"emojis"`
	Stickers    []Sticker    `json:"stickers"`
	Members     []Member     `json:"members"`
	MemberCount int          `json:"member_count"`
	OnlineCount int          `json:"online_count"`
	VoiceStates []VoiceState `json:"voice_states"`
	JoinedAt    *time.Time   `json:"joined_at,omitempty"`
	Unavailable bool         `json:"unavailable,omitempty"`
	Threads     []Channel    `json:"threads,omitempty"`
}

GuildState is the full guild payload of GUILD_CREATE and GUILD_SYNC. The guild settings are in Properties, the collections sit next to it.

func (GuildState) Guild

func (g GuildState) Guild() Guild

Guild combines Properties with the ID, roles, channels, emojis, stickers and counts. Members, voice states and threads are not included.

type GuildStickersUpdate

type GuildStickersUpdate struct {
	GuildID  string    `json:"guild_id"`
	Stickers []Sticker `json:"stickers"`
}

GuildStickersUpdate is the GUILD_STICKERS_UPDATE dispatch.

func (GuildStickersUpdate) EventName

func (GuildStickersUpdate) EventName() string

type GuildSubscription

type GuildSubscription struct {
	Active             *bool               `json:"active,omitempty"`
	Sync               *bool               `json:"sync,omitempty"`
	Typing             *bool               `json:"typing,omitempty"`
	MemberListChannels map[string][][2]int `json:"member_list_channels,omitempty"`
	Members            []string            `json:"members,omitempty"`
	Threads            *bool               `json:"threads,omitempty"`
	ThreadMemberLists  *[]string           `json:"thread_member_lists,omitempty"`
}

GuildSubscription is what the session subscribes to in one guild through Subscribe. MemberListChannels maps channel IDs to member list index ranges, answered with GuildMemberListUpdate. Threads subscribes to events and messages of every thread the session can view. ThreadMemberLists names up to 10 threads whose member lists arrive as ThreadMemberListUpdate; it replaces the earlier list, and an empty slice clears it. Nil pointer fields are left out of the request.

type GuildSync

type GuildSync struct{ GuildState }

GuildSync is the GUILD_SYNC dispatch.

func (GuildSync) EventName

func (GuildSync) EventName() string

type GuildUpdate

type GuildUpdate struct{ Guild }

GuildUpdate is the GUILD_UPDATE dispatch.

func (GuildUpdate) EventName

func (GuildUpdate) EventName() string

type Instance

type Instance struct {
	Origin      string
	API         string
	Gateway     string
	Media       string
	Webapp      string
	Invite      string
	UploadRelay string
	CodeVersion int
	Features    InstanceFeatures
	HTTP        *http.Client
}

Instance holds the endpoints and features of a Fluxer instance, as read from its discovery document at /.well-known/fluxer. API already includes the /v1 suffix. HTTP, when non-nil, is used by clients and sessions created from the Instance.

func Discover

func Discover(ctx context.Context, origin string) (*Instance, error)

Discover reads the discovery document of the instance at origin with http.DefaultClient. See DiscoverWith.

func DiscoverWith

func DiscoverWith(ctx context.Context, client *http.Client, origin string) (*Instance, error)

DiscoverWith fetches origin + "/.well-known/fluxer" with client and returns the instance it describes. origin should already be normalized, see NormalizeOrigin. The request times out after 10 seconds. It fails when the server does not answer 200, the document is larger than 256 KiB, or it lacks the api_public or gateway endpoint. For an https origin it also fails when a redirect leaves https or when the API is not served over https or the gateway over wss, so the token never travels in plain text. A client other than http.DefaultClient is kept in Instance.HTTP.

func (*Instance) NewClient

func (i *Instance) NewClient(token string) *Client

NewClient returns a Client for the instance's API, using the instance's HTTP client if it has one.

func (*Instance) NewSession

func (i *Instance) NewSession(token string) *Session

NewSession returns a gateway Session for the instance's gateway URL, using the instance's HTTP client for the connection. Unlike NewClient, it does not strip a "Bot " prefix from token.

type InstanceFeatures

type InstanceFeatures struct {
	VoiceEnabled               bool `json:"voice_enabled"`
	SelfHosted                 bool `json:"self_hosted"`
	PresignedAttachmentUploads bool `json:"presigned_attachment_uploads"`
	DiscoveryEnabled           bool `json:"discovery_enabled"`
}

InstanceFeatures lists the optional features an instance reports in its discovery document.

type Instances

type Instances struct {
	HTTP                *http.Client
	TTL                 time.Duration
	FailureTTL          time.Duration
	IdentifiesPerMinute int
	// contains filtered or unexported fields
}

Instances caches discovered instances by origin and hands out clients and gateway sessions for them. Successful lookups are cached for TTL, one hour by default, and failed ones for FailureTTL, one minute by default. IdentifiesPerMinute sets the gateway identify rate per instance and defaults to 60. The zero value is ready to use, and an Instances is safe for concurrent use.

func NewInstances

func NewInstances() *Instances

NewInstances returns an empty Instances with default settings.

func (*Instances) Client

func (r *Instances) Client(ctx context.Context, origin, token string) (*Client, error)

Client returns a Client for the instance at origin that authenticates with token.

func (*Instances) Forget

func (r *Instances) Forget(origin string)

Forget drops the cache entry for origin, so the next Get runs discovery.

func (*Instances) Get

func (r *Instances) Get(ctx context.Context, origin string) (*Instance, error)

Get returns the instance at origin, running discovery unless a fresh cache entry exists. origin is normalized with NormalizeOrigin. When discovery fails and an earlier result is cached, Get keeps returning that result until discovery succeeds again. Concurrent calls for the same origin share one discovery, which keeps running when the caller that started it gives up, so ctx only bounds how long Get waits.

func (*Instances) Origins

func (r *Instances) Origins() []string

Origins returns the sorted origins that have a cached instance, including entries past their TTL.

func (*Instances) Pacer

func (r *Instances) Pacer(origin string) *Pacer

Pacer returns the identify pacer shared by all sessions of origin and creates it on first use. origin is normalized like in Get; when that fails, it is used as given.

func (*Instances) Session

func (r *Instances) Session(ctx context.Context, origin, token string) (*Session, error)

Session returns a gateway Session for the instance at origin. All sessions of one instance share the same identify Pacer.

type Invite

type Invite struct {
	Code          string     `json:"code"`
	Type          int        `json:"type"`
	Inviter       *User      `json:"inviter,omitempty"`
	ExpiresAt     *time.Time `json:"expires_at,omitempty"`
	Temporary     bool       `json:"temporary"`
	Guild         *Guild     `json:"guild,omitempty"`
	Channel       *Channel   `json:"channel,omitempty"`
	MemberCount   int        `json:"member_count,omitempty"`
	PresenceCount int        `json:"presence_count,omitempty"`
	CreatedAt     time.Time  `json:"created_at,omitzero"`
	Uses          int        `json:"uses,omitempty"`
	MaxUses       int        `json:"max_uses,omitempty"`
	MaxAge        int        `json:"max_age,omitempty"`
}

Invite is a guild or group DM invite. ExpiresAt is nil for invites that do not expire. Uses, MaxUses and MaxAge are only included when the caller may manage the invite.

func (Invite) URL

func (i Invite) URL(base string) string

URL returns the invite link for the given base, such as the instance's invite host.

type InviteCreate

type InviteCreate struct{ Invite }

InviteCreate is the INVITE_CREATE dispatch.

func (InviteCreate) EventName

func (InviteCreate) EventName() string

type InviteDelete

type InviteDelete struct {
	Code      string `json:"code"`
	ChannelID string `json:"channel_id,omitempty"`
	GuildID   string `json:"guild_id,omitempty"`
}

InviteDelete is the INVITE_DELETE dispatch.

func (InviteDelete) EventName

func (InviteDelete) EventName() string

type Member

type Member struct {
	User                       *User      `json:"user,omitempty"`
	Nick                       *string    `json:"nick,omitempty"`
	Avatar                     *string    `json:"avatar,omitempty"`
	Banner                     *string    `json:"banner,omitempty"`
	AccentColor                *int       `json:"accent_color,omitempty"`
	Roles                      []string   `json:"roles"`
	JoinedAt                   time.Time  `json:"joined_at,omitzero"`
	Mute                       bool       `json:"mute,omitempty"`
	Deaf                       bool       `json:"deaf,omitempty"`
	CommunicationDisabledUntil *time.Time `json:"communication_disabled_until,omitempty"`
	ProfileFlags               int        `json:"profile_flags,omitempty"`
	MentionFlags               int        `json:"mention_flags,omitempty"`
	GuildID                    string     `json:"guild_id,omitempty"`
}

Member is a user's membership in a guild. User may be nil in payloads that omit it, and GuildID is only set in some gateway events.

func (Member) DisplayName

func (m Member) DisplayName() string

DisplayName returns the member's guild nickname, falling back to the user's display name. It returns an empty string when neither is available.

func (Member) TimedOut

func (m Member) TimedOut() bool

TimedOut reports whether the member's timeout is still in effect.

type MemberEdit

type MemberEdit struct {
	Nick                       *string   `json:"nick,omitempty"`
	Avatar                     *string   `json:"avatar,omitempty"`
	Banner                     *string   `json:"banner,omitempty"`
	Bio                        *string   `json:"bio,omitempty"`
	Pronouns                   *string   `json:"pronouns,omitempty"`
	AccentColor                *int      `json:"accent_color,omitempty"`
	ProfileFlags               *int      `json:"profile_flags,omitempty"`
	MentionFlags               *int      `json:"mention_flags,omitempty"`
	Roles                      *[]string `json:"roles,omitempty"`
	Mute                       *bool     `json:"mute,omitempty"`
	Deaf                       *bool     `json:"deaf,omitempty"`
	CommunicationDisabledUntil *string   `json:"communication_disabled_until,omitempty"`
	TimeoutReason              *string   `json:"timeout_reason,omitempty"`
	ChannelID                  *string   `json:"channel_id,omitempty"`
	ConnectionID               *string   `json:"connection_id,omitempty"`
}

MemberEdit holds the fields to change on a member. Only non-nil fields are sent. CommunicationDisabledUntil cannot be cleared through this struct; use SetTimeout with a zero time to lift a timeout. ChannelID moves the member to another voice channel. Avatar, Banner, Bio, Pronouns and AccentColor set the guild profile, Avatar and Banner as data URIs; they are mostly useful for the bot's own profile with ModifyCurrentMember.

type MemberListGroup added in v0.2.0

type MemberListGroup struct {
	ID    string `json:"id"`
	Count int    `json:"count"`
}

MemberListGroup is a group header in a member list: a hoisted role ID, online or offline, with the number of members in it.

type MemberListItem added in v0.2.0

type MemberListItem struct {
	Group  *MemberListGroup  `json:"group,omitempty"`
	Member *MemberListMember `json:"member,omitempty"`
}

MemberListItem is one position of a member list. Exactly one of Group and Member is set.

type MemberListMember added in v0.2.0

type MemberListMember struct {
	Member
	Presence *Presence `json:"presence,omitempty"`
}

MemberListMember is a member in a member list together with its presence. The presence has status offline when the member is not visibly online.

type MemberListOp added in v0.2.0

type MemberListOp struct {
	Op    string           `json:"op"`
	Range [2]int           `json:"range"`
	Items []MemberListItem `json:"items"`
}

MemberListOp replaces the inclusive index range Range of a member list with Items. Op is SYNC.

type MemberSearch

type MemberSearch struct {
	Query             string   `json:"query,omitempty"`
	Limit             int      `json:"limit,omitempty"`
	Offset            int      `json:"offset,omitempty"`
	RoleIDs           []string `json:"role_ids,omitempty"`
	IsBot             *bool    `json:"is_bot,omitempty"`
	JoinedAfter       int64    `json:"joined_at_gte,omitempty"`
	JoinedBefore      int64    `json:"joined_at_lte,omitempty"`
	UserCreatedAfter  int64    `json:"user_created_at_gte,omitempty"`
	UserCreatedBefore int64    `json:"user_created_at_lte,omitempty"`
	JoinSourceTypes   []int    `json:"join_source_type,omitempty"`
	SourceInviteCodes []string `json:"source_invite_code,omitempty"`
	SortBy            string   `json:"sort_by,omitempty"`
	SortOrder         string   `json:"sort_order,omitempty"`
}

MemberSearch is the query for SearchMembers. Zero values are omitted, which leaves paging, sorting and filtering to the server defaults. IsBot filters by bot accounts when set. The time filters are inclusive Unix seconds: JoinedAfter and JoinedBefore bound when the member joined, UserCreatedAfter and UserCreatedBefore how old the account is.

type MemberSearchExtra added in v0.2.0

type MemberSearchExtra struct {
	JoinSourceType   *int    `json:"join_source_type"`
	SourceInviteCode *string `json:"source_invite_code"`
	InviterID        *string `json:"inviter_id"`
}

MemberSearchExtra tells how a member found by SearchMembers joined.

type MemberSearchPage

type MemberSearchPage struct {
	GuildID          string               `json:"guild_id"`
	Members          []MemberSearchResult `json:"members"`
	PageResultCount  int                  `json:"page_result_count"`
	TotalResultCount int                  `json:"total_result_count"`
	Indexing         bool                 `json:"indexing"`
}

MemberSearchPage is one page of SearchMembers results. Indexing is true while the server is still building the guild's search index, in which case results may be incomplete.

type MemberSearchResult

type MemberSearchResult struct {
	ID            string            `json:"id"`
	GuildID       string            `json:"guild_id"`
	UserID        string            `json:"user_id"`
	Username      string            `json:"username"`
	Discriminator string            `json:"discriminator"`
	GlobalName    *string           `json:"global_name"`
	Nickname      *string           `json:"nickname"`
	RoleIDs       []string          `json:"role_ids"`
	JoinedAt      int64             `json:"joined_at"`
	IsBot         bool              `json:"is_bot"`
	Supplemental  MemberSearchExtra `json:"supplemental"`
}

MemberSearchResult is a single member entry returned by SearchMembers.

type Message

type Message struct {
	ID                string            `json:"id"`
	ChannelID         string            `json:"channel_id"`
	GuildID           string            `json:"guild_id,omitempty"`
	Author            User              `json:"author"`
	Member            *Member           `json:"member,omitempty"`
	WebhookID         string            `json:"webhook_id,omitempty"`
	Type              int               `json:"type,omitempty"`
	Flags             int               `json:"flags,omitempty"`
	Content           string            `json:"content"`
	Timestamp         time.Time         `json:"timestamp,omitzero"`
	EditedTimestamp   *time.Time        `json:"edited_timestamp,omitempty"`
	Pinned            bool              `json:"pinned,omitempty"`
	MentionEveryone   bool              `json:"mention_everyone,omitempty"`
	TTS               bool              `json:"tts,omitempty"`
	Mentions          []User            `json:"mentions,omitempty"`
	MentionRoles      []string          `json:"mention_roles,omitempty"`
	MentionChannels   []ChannelMention  `json:"mention_channels,omitempty"`
	Embeds            []Embed           `json:"embeds,omitempty"`
	Attachments       []Attachment      `json:"attachments,omitempty"`
	Stickers          []MessageSticker  `json:"stickers,omitempty"`
	Reactions         []MessageReaction `json:"reactions,omitempty"`
	MessageReference  *MessageReference `json:"message_reference,omitempty"`
	ReferencedMessage *Message          `json:"referenced_message,omitempty"`
	MessageSnapshots  []MessageSnapshot `json:"message_snapshots,omitempty"`
	Users             []User            `json:"users,omitempty"`
	Call              *CallInfo         `json:"call,omitempty"`
	Nonce             string            `json:"nonce,omitempty"`
	Thread            *Channel          `json:"thread,omitempty"`
}

Message is a message in a channel. GuildID is empty for messages in DMs, and Member is only set for guild messages that carry the author's member data.

func (Message) URL

func (m Message) URL(webapp string) string

URL returns a link to the message in the web app at webapp, using @me in place of the guild ID for DM messages.

type MessageCreate

type MessageCreate struct {
	Message
	ChannelType int  `json:"channel_type"`
	MentionHere bool `json:"mention_here,omitempty"`
}

MessageCreate is the MESSAGE_CREATE dispatch.

func (MessageCreate) EventName

func (MessageCreate) EventName() string

type MessageDelete

type MessageDelete struct {
	ID        string  `json:"id"`
	ChannelID string  `json:"channel_id"`
	GuildID   string  `json:"guild_id,omitempty"`
	Content   *string `json:"content,omitempty"`
	AuthorID  string  `json:"author_id,omitempty"`
	Member    *Member `json:"member,omitempty"`
}

MessageDelete is the MESSAGE_DELETE dispatch.

func (MessageDelete) EventName

func (MessageDelete) EventName() string

type MessageDeleteBulk

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

MessageDeleteBulk is the MESSAGE_DELETE_BULK dispatch.

func (MessageDeleteBulk) EventName

func (MessageDeleteBulk) EventName() string

type MessageEdit

type MessageEdit struct {
	Content         *string           `json:"content,omitempty"`
	Embeds          *[]Embed          `json:"embeds,omitempty"`
	AllowedMentions *AllowedMentions  `json:"allowed_mentions,omitempty"`
	Flags           *int              `json:"flags,omitempty"`
	Attachments     *[]AttachmentEdit `json:"-"`
	Uploads         []UploadedFile    `json:"-"`
}

MessageEdit holds the fields to change on a message. Only non-nil fields are sent, so a pointer to an empty string or an empty slice removes the content or the embeds.

Setting Attachments or Uploads replaces the attachments of the message with the existing ones listed in Attachments followed by the files in Uploads, so list every attachment that should stay. EditMessageUploads fills Uploads.

func (MessageEdit) MarshalJSON added in v0.2.0

func (m MessageEdit) MarshalJSON() ([]byte, error)

MarshalJSON encodes the edit, merging Attachments and Uploads into one attachments array.

type MessageQuery

type MessageQuery struct {
	Before string
	After  string
	Around string
	Limit  int
}

MessageQuery selects the messages returned by Messages. Before, After and Around are message IDs and are only sent when non-empty; a Limit of zero leaves the page size to the server.

type MessageReaction

type MessageReaction struct {
	Emoji ReactionEmoji `json:"emoji"`
	Count int           `json:"count"`
	Me    bool          `json:"me,omitempty"`
}

MessageReaction is the aggregated count of one emoji on a message. Me reports whether the current user is among the reactors.

type MessageReactionAdd

type MessageReactionAdd struct {
	UserID    string        `json:"user_id"`
	ChannelID string        `json:"channel_id"`
	MessageID string        `json:"message_id"`
	GuildID   string        `json:"guild_id,omitempty"`
	Emoji     ReactionEmoji `json:"emoji"`
	Member    *Member       `json:"member,omitempty"`
}

MessageReactionAdd is the MESSAGE_REACTION_ADD dispatch.

func (MessageReactionAdd) EventName

func (MessageReactionAdd) EventName() string

type MessageReactionAddMany

type MessageReactionAddMany struct {
	ChannelID string             `json:"channel_id"`
	MessageID string             `json:"message_id"`
	GuildID   string             `json:"guild_id,omitempty"`
	Reactions []ReactionAddition `json:"reactions"`
}

MessageReactionAddMany is the MESSAGE_REACTION_ADD_MANY dispatch.

func (MessageReactionAddMany) EventName

func (MessageReactionAddMany) EventName() string

type MessageReactionRemove

type MessageReactionRemove struct {
	UserID    string        `json:"user_id"`
	ChannelID string        `json:"channel_id"`
	MessageID string        `json:"message_id"`
	GuildID   string        `json:"guild_id,omitempty"`
	Emoji     ReactionEmoji `json:"emoji"`
	Member    *Member       `json:"member,omitempty"`
}

MessageReactionRemove is the MESSAGE_REACTION_REMOVE dispatch. Member is set in guild channels.

func (MessageReactionRemove) EventName

func (MessageReactionRemove) EventName() string

type MessageReactionRemoveAll

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

MessageReactionRemoveAll is the MESSAGE_REACTION_REMOVE_ALL dispatch.

func (MessageReactionRemoveAll) EventName

func (MessageReactionRemoveAll) EventName() string

type MessageReactionRemoveEmoji

type MessageReactionRemoveEmoji struct {
	ChannelID string        `json:"channel_id"`
	MessageID string        `json:"message_id"`
	GuildID   string        `json:"guild_id,omitempty"`
	Emoji     ReactionEmoji `json:"emoji"`
}

MessageReactionRemoveEmoji is the MESSAGE_REACTION_REMOVE_EMOJI dispatch.

func (MessageReactionRemoveEmoji) EventName

func (MessageReactionRemoveEmoji) EventName() string

type MessageReference

type MessageReference struct {
	MessageID     string   `json:"message_id,omitempty"`
	ChannelID     string   `json:"channel_id,omitempty"`
	GuildID       string   `json:"guild_id,omitempty"`
	Type          int      `json:"type,omitempty"`
	AttachmentIDs []string `json:"attachment_ids,omitempty"`
	EmbedIndices  []int    `json:"embed_indices,omitempty"`
}

MessageReference points at another message, for replies and forwards. A forward can be limited to some of the original's media with AttachmentIDs and EmbedIndices.

type MessageSearch

type MessageSearch struct {
	Content                     string   `json:"content,omitempty"`
	Contents                    []string `json:"contents,omitempty"`
	ExactPhrases                []string `json:"exact_phrases,omitempty"`
	ChannelIDs                  []string `json:"channel_id,omitempty"`
	ExcludeChannelIDs           []string `json:"exclude_channel_id,omitempty"`
	AuthorIDs                   []string `json:"author_id,omitempty"`
	ExcludeAuthorIDs            []string `json:"exclude_author_id,omitempty"`
	AuthorTypes                 []string `json:"author_type,omitempty"`
	ExcludeAuthorTypes          []string `json:"exclude_author_type,omitempty"`
	Mentions                    []string `json:"mentions,omitempty"`
	ExcludeMentions             []string `json:"exclude_mentions,omitempty"`
	MentionEveryone             *bool    `json:"mention_everyone,omitempty"`
	Has                         []string `json:"has,omitempty"`
	ExcludeHas                  []string `json:"exclude_has,omitempty"`
	EmbedTypes                  []string `json:"embed_type,omitempty"`
	ExcludeEmbedTypes           []string `json:"exclude_embed_type,omitempty"`
	EmbedProviders              []string `json:"embed_provider,omitempty"`
	ExcludeEmbedProviders       []string `json:"exclude_embed_provider,omitempty"`
	LinkHostnames               []string `json:"link_hostname,omitempty"`
	ExcludeLinkHostnames        []string `json:"exclude_link_hostname,omitempty"`
	AttachmentFilenames         []string `json:"attachment_filename,omitempty"`
	ExcludeAttachmentFilenames  []string `json:"exclude_attachment_filename,omitempty"`
	AttachmentExtensions        []string `json:"attachment_extension,omitempty"`
	ExcludeAttachmentExtensions []string `json:"exclude_attachment_extension,omitempty"`
	IncludeNSFW                 bool     `json:"include_nsfw,omitempty"`
	Pinned                      *bool    `json:"pinned,omitempty"`
	MinID                       string   `json:"min_id,omitempty"`
	MaxID                       string   `json:"max_id,omitempty"`
	SortBy                      string   `json:"sort_by,omitempty"`
	SortOrder                   string   `json:"sort_order,omitempty"`
	Scope                       string   `json:"scope,omitempty"`
	ContextGuildID              string   `json:"context_guild_id,omitempty"`
	ContextChannelID            string   `json:"context_channel_id,omitempty"`
	HitsPerPage                 int      `json:"hits_per_page,omitempty"`
	Page                        int      `json:"page,omitempty"`
	Cursor                      []string `json:"cursor,omitempty"`
}

MessageSearch is the query for SearchMessages. Zero values are omitted. Scope together with ContextGuildID or ContextChannelID decides where the search runs. Results can be paged with Page or, when the server returns one, by passing the previous result's Cursor. AuthorTypes takes user, bot and webhook; Has takes image, sound, video, file, sticker, embed, link, poll and snapshot; EmbedTypes takes image, video, sound and article. Each Exclude field drops messages that match it.

type MessageSearchResult

type MessageSearchResult struct {
	Messages    []Message      `json:"messages"`
	Channels    []Channel      `json:"channels"`
	Threads     []Channel      `json:"threads,omitempty"`
	Members     []ThreadMember `json:"members,omitempty"`
	Total       int            `json:"total"`
	HitsPerPage int            `json:"hits_per_page"`
	Page        int            `json:"page"`
	Cursor      []string       `json:"cursor,omitempty"`
}

MessageSearchResult is one page of SearchMessages hits plus the channels and threads they were found in, with the current user's membership in those threads. Cursor is set when another page can be requested by cursor.

type MessageSend

type MessageSend struct {
	Content          string            `json:"content,omitempty"`
	Embeds           []Embed           `json:"embeds,omitempty"`
	MessageReference *MessageReference `json:"message_reference,omitempty"`
	AllowedMentions  *AllowedMentions  `json:"allowed_mentions,omitempty"`
	StickerIDs       []string          `json:"sticker_ids,omitempty"`
	Attachments      []UploadedFile    `json:"attachments,omitempty"`
	Flags            int               `json:"flags,omitempty"`
	TTS              bool              `json:"tts,omitempty"`
	Nonce            string            `json:"nonce,omitempty"`
}

MessageSend is the body of a new message. Zero fields are omitted. If Nonce is empty, SendMessage and SendMessageFiles fill in a random one, which lets the client retry the request without creating duplicates.

type MessageSnapshot added in v0.2.0

type MessageSnapshot struct {
	Content         string           `json:"content"`
	Timestamp       time.Time        `json:"timestamp"`
	EditedTimestamp *time.Time       `json:"edited_timestamp,omitempty"`
	Mentions        []string         `json:"mentions,omitempty"`
	MentionRoles    []string         `json:"mention_roles,omitempty"`
	MentionChannels []ChannelMention `json:"mention_channels,omitempty"`
	Embeds          []Embed          `json:"embeds,omitempty"`
	Attachments     []Attachment     `json:"attachments,omitempty"`
	Stickers        []MessageSticker `json:"stickers,omitempty"`
	Type            int              `json:"type"`
	Flags           int              `json:"flags"`
}

MessageSnapshot is the copy of a forwarded message that Fluxer stores with the forward. Mentions holds user IDs. The author and the origin of the message are not part of it; MessageReference of the forward points at the original.

type MessageSticker

type MessageSticker struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	Animated bool   `json:"animated"`
}

MessageSticker is the short form of a sticker attached to a message.

type MessageUpdate

type MessageUpdate struct{ Message }

MessageUpdate is the MESSAGE_UPDATE dispatch.

func (MessageUpdate) EventName

func (MessageUpdate) EventName() string

type MuteConfig added in v0.2.0

type MuteConfig struct {
	EndTime            *time.Time `json:"end_time"`
	SelectedTimeWindow int        `json:"selected_time_window"`
}

MuteConfig says until when a thread is muted, nil EndTime meaning until unmuted, and the duration in seconds that was picked.

type NewChannel

type NewChannel struct {
	Name                          string           `json:"name"`
	Type                          int              `json:"type"`
	Topic                         string           `json:"topic,omitempty"`
	URL                           string           `json:"url,omitempty"`
	ParentID                      string           `json:"parent_id,omitempty"`
	Bitrate                       int              `json:"bitrate,omitempty"`
	UserLimit                     int              `json:"user_limit,omitempty"`
	VoiceConnectionLimit          int              `json:"voice_connection_limit,omitempty"`
	RateLimitPerUser              int              `json:"rate_limit_per_user,omitempty"`
	NSFW                          bool             `json:"nsfw,omitempty"`
	NSFWOverride                  *bool            `json:"nsfw_override,omitempty"`
	ContentWarningLevel           int              `json:"content_warning_level,omitempty"`
	ContentWarningText            string           `json:"content_warning_text,omitempty"`
	PermissionOverwrites          []Overwrite      `json:"permission_overwrites,omitempty"`
	Flags                         int              `json:"flags,omitempty"`
	DefaultAutoArchiveDuration    int              `json:"default_auto_archive_duration,omitempty"`
	DefaultThreadRateLimitPerUser int              `json:"default_thread_rate_limit_per_user,omitempty"`
	AvailableTags                 []ForumTag       `json:"available_tags,omitempty"`
	DefaultReactionEmoji          *DefaultReaction `json:"default_reaction_emoji,omitempty"`
	DefaultSortOrder              *int             `json:"default_sort_order,omitempty"`
	DefaultForumLayout            int              `json:"default_forum_layout,omitempty"`
	DefaultTagSetting             string           `json:"default_tag_setting,omitempty"`
}

NewChannel is the request body for CreateChannel. Name and Type are always sent; zero values of the other fields are omitted. The Default* fields, AvailableTags and DefaultReactionEmoji set up a forum or media channel.

type NewEmoji

type NewEmoji struct {
	Name  string `json:"name"`
	Image string `json:"image"`
}

NewEmoji is the body for CreateEmoji and CreateEmojis. Image is a data URI, see ImageData.

type NewInvite

type NewInvite struct {
	MaxUses   int  `json:"max_uses,omitempty"`
	MaxAge    *int `json:"max_age,omitempty"`
	Unique    bool `json:"unique,omitempty"`
	Temporary bool `json:"temporary,omitempty"`
}

NewInvite configures CreateInvite. A zero MaxUses is omitted and leaves the limit to the server. MaxAge is in seconds; nil uses the server default, while a pointer to 0 is sent as is.

type NewPost

type NewPost struct {
	Name                string      `json:"name"`
	Message             PostMessage `json:"message"`
	AppliedTags         []string    `json:"applied_tags,omitempty"`
	AutoArchiveDuration int         `json:"auto_archive_duration,omitempty"`
	RateLimitPerUser    int         `json:"rate_limit_per_user,omitempty"`
}

NewPost is the body for CreatePost. Name is the post title and AppliedTags holds ForumTag IDs.

type NewRole

type NewRole struct {
	Name        string      `json:"name"`
	Color       int         `json:"color,omitempty"`
	Permissions Permissions `json:"permissions,omitempty"`
}

NewRole is the body for CreateRole. Zero Color and Permissions are omitted, so the server applies its defaults for them.

type NewSticker

type NewSticker struct {
	Name        string   `json:"name"`
	Description string   `json:"description,omitempty"`
	Tags        []string `json:"tags,omitempty"`
	Image       string   `json:"image"`
}

NewSticker is the body for CreateSticker and CreateStickers. Image is a data URI, see ImageData.

type OAuth

type OAuth struct {
	API          string
	ClientID     string
	ClientSecret string
	RedirectURI  string
	Scopes       []string
	HTTP         *http.Client
}

OAuth is an OAuth2 client for a Fluxer application. API is the API base URL and defaults to DefaultAPI. Scopes defaults to ScopeIdentify. ClientSecret may be empty for a public client that uses PKCE. HTTP defaults to a client with a 15 second timeout. Requests made through OAuth are not rate limited or retried.

func (*OAuth) AuthorizeURL

func (o *OAuth) AuthorizeURL(state, verifier string) string

AuthorizeURL returns the authorization URL to send the user to. state is added when non-empty. When verifier is non-empty, its S256 challenge is added for PKCE.

func (*OAuth) Exchange

func (o *OAuth) Exchange(ctx context.Context, code, verifier string) (*OAuthToken, error)

Exchange trades an authorization code for a token at POST /oauth2/token. verifier is the PKCE verifier given to AuthorizeURL, or empty if PKCE was not used. Errors are *OAuthError when the server answers in the OAuth2 format and *APIError otherwise.

func (*OAuth) Introspect

func (o *OAuth) Introspect(ctx context.Context, token string) (*TokenInfo, error)

Introspect asks the server about token at POST /oauth2/introspect, authenticating with the client credentials.

func (*OAuth) Refresh

func (o *OAuth) Refresh(ctx context.Context, refreshToken string) (*OAuthToken, error)

Refresh trades a refresh token for a new token at POST /oauth2/token.

func (*OAuth) Revoke

func (o *OAuth) Revoke(ctx context.Context, token string) error

Revoke revokes an access or refresh token at POST /oauth2/token/revoke.

func (*OAuth) User

func (o *OAuth) User(ctx context.Context, accessToken string) (*User, error)

User returns the user an access token belongs to. It calls GET /oauth2/userinfo.

type OAuthError

type OAuthError struct {
	Code        string `json:"error"`
	Description string `json:"error_description"`
}

OAuthError is an error response in the OAuth2 format. Code holds the error field, such as invalid_grant.

func (*OAuthError) Error

func (e *OAuthError) Error() string

Error returns the OAuth2 error code and description.

type OAuthToken

type OAuthToken struct {
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int    `json:"expires_in"`
	RefreshToken string `json:"refresh_token"`
	Scope        string `json:"scope"`
}

OAuthToken is the response of the token endpoint. ExpiresIn is in seconds.

func (OAuthToken) Expiry

func (t OAuthToken) Expiry(issued time.Time) time.Time

Expiry returns when the access token expires, given the time it was issued.

type Overwrite

type Overwrite struct {
	ID    string      `json:"id"`
	Type  int         `json:"type"`
	Allow Permissions `json:"allow"`
	Deny  Permissions `json:"deny"`
}

Overwrite is a permission overwrite on a channel. Type is OverwriteRole or OverwriteMember, and ID is the role or user it applies to.

type Pacer

type Pacer struct {
	Reserve Reserve
	Key     string
	// contains filtered or unexported fields
}

Pacer spaces out events, such as gateway identifies, at a fixed interval. When Reserve is set, Wait asks it for a slot under Key and falls back to pacing within the process if Reserve fails or takes longer than two seconds.

func NewPacer

func NewPacer(perMinute int) *Pacer

NewPacer returns a Pacer that allows perMinute events per minute, evenly spaced. Values below 1 count as 1.

func (*Pacer) Wait

func (p *Pacer) Wait(ctx context.Context) error

Wait blocks until the caller's slot has come or ctx is done. Every call takes the next slot, so callers proceed one interval apart.

type PassiveUpdates

type PassiveUpdates struct {
	GuildID     string            `json:"guild_id"`
	Channels    map[string]string `json:"channels"`
	VoiceStates []VoiceState      `json:"voice_states,omitempty"`
}

PassiveUpdates is the PASSIVE_UPDATES dispatch.

func (PassiveUpdates) EventName

func (PassiveUpdates) EventName() string

type Permissions

type Permissions uint64

Permissions is a set of permission bits. In JSON it is a decimal string, the form the Fluxer API uses.

const (
	PermCreateInstantInvite   Permissions = 1 << 0
	PermKickMembers           Permissions = 1 << 1
	PermBanMembers            Permissions = 1 << 2
	PermAdministrator         Permissions = 1 << 3
	PermManageChannels        Permissions = 1 << 4
	PermManageGuild           Permissions = 1 << 5
	PermAddReactions          Permissions = 1 << 6
	PermViewAuditLog          Permissions = 1 << 7
	PermPrioritySpeaker       Permissions = 1 << 8
	PermStream                Permissions = 1 << 9
	PermViewChannel           Permissions = 1 << 10
	PermSendMessages          Permissions = 1 << 11
	PermSendTTSMessages       Permissions = 1 << 12
	PermManageMessages        Permissions = 1 << 13
	PermEmbedLinks            Permissions = 1 << 14
	PermAttachFiles           Permissions = 1 << 15
	PermReadMessageHistory    Permissions = 1 << 16
	PermMentionEveryone       Permissions = 1 << 17
	PermUseExternalEmojis     Permissions = 1 << 18
	PermConnect               Permissions = 1 << 20
	PermSpeak                 Permissions = 1 << 21
	PermMuteMembers           Permissions = 1 << 22
	PermDeafenMembers         Permissions = 1 << 23
	PermMoveMembers           Permissions = 1 << 24
	PermUseVAD                Permissions = 1 << 25
	PermChangeNickname        Permissions = 1 << 26
	PermManageNicknames       Permissions = 1 << 27
	PermManageRoles           Permissions = 1 << 28
	PermManageWebhooks        Permissions = 1 << 29
	PermManageExpressions     Permissions = 1 << 30
	PermManageThreads         Permissions = 1 << 34
	PermCreatePublicThreads   Permissions = 1 << 35
	PermCreatePrivateThreads  Permissions = 1 << 36
	PermUseExternalStickers   Permissions = 1 << 37
	PermSendMessagesInThreads Permissions = 1 << 38
	PermModerateMembers       Permissions = 1 << 40
	PermCreateExpressions     Permissions = 1 << 43
	PermPinMessages           Permissions = 1 << 51
	PermBypassSlowmode        Permissions = 1 << 52
	PermUpdateRTCRegion       Permissions = 1 << 53
	PermViewChannelMembers    Permissions = 1 << 54

	// PermAll has every bit set. BasePermissions returns it for the guild owner
	// and for members with PermAdministrator.
	PermAll Permissions = 1<<64 - 1
)

Permission bits used by the Fluxer API.

func BasePermissions

func BasePermissions(g Guild, userID string, roleIDs []string) Permissions

BasePermissions computes the guild-wide permissions of a user with the given roles by combining the @everyone role, whose ID is the guild ID, with every listed role. The guild owner and anyone with PermAdministrator get PermAll. Role IDs missing from g.Roles are ignored.

func ChannelPermissions

func ChannelPermissions(g Guild, userID string, roleIDs []string, ch Channel) Permissions

ChannelPermissions computes a user's permissions in ch by applying its overwrites to BasePermissions: first the @everyone overwrite, then the combined overwrites of the user's roles, then the overwrite for the user. Overwrites do not affect PermAll.

Example
package main

import (
	"fmt"

	"github.com/invaliduser231/fluxer-go"
)

func main() {
	g := fluxer.Guild{ID: "1", OwnerID: "9", Roles: []fluxer.Role{
		{ID: "1", Permissions: fluxer.PermViewChannel | fluxer.PermSendMessages},
	}}
	ch := fluxer.Channel{ID: "5", PermissionOverwrites: []fluxer.Overwrite{
		{ID: "1", Type: fluxer.OverwriteRole, Deny: fluxer.PermSendMessages},
	}}
	perms := fluxer.ChannelPermissions(g, "7", nil, ch)
	fmt.Println(perms.Has(fluxer.PermSendMessages), perms)
}

func MemberPermissions

func MemberPermissions(g Guild, m Member, ch *Channel) Permissions

MemberPermissions returns the permissions of m in g, or in ch when ch is non-nil. A member without User is never treated as the guild owner.

func (Permissions) Add

func (p Permissions) Add(perms Permissions) Permissions

Add returns p with the bits of perms set.

func (Permissions) Has

func (p Permissions) Has(perms Permissions) bool

Has reports whether p contains every bit of perms.

func (Permissions) MarshalJSON

func (p Permissions) MarshalJSON() ([]byte, error)

MarshalJSON encodes p as a quoted decimal number.

func (Permissions) Missing

func (p Permissions) Missing(perms Permissions) Permissions

Missing returns the bits of perms that p lacks.

func (Permissions) Names

func (p Permissions) Names() []string

Names returns the API names of the bits set in p, such as SEND_MESSAGES, from the lowest bit up. Bits without a known name are skipped.

func (Permissions) Remove

func (p Permissions) Remove(perms Permissions) Permissions

Remove returns p with the bits of perms cleared.

func (Permissions) String

func (p Permissions) String() string

String returns the names of the set bits joined by "|", or "NONE" when p is zero.

func (*Permissions) UnmarshalJSON

func (p *Permissions) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts a decimal number, quoted or not. null and an empty string decode as zero.

type PinnedMessage

type PinnedMessage struct {
	Message  Message   `json:"message"`
	PinnedAt time.Time `json:"pinned_at"`
}

PinnedMessage is a pinned message together with the time it was pinned.

type Post

type Post struct {
	Channel
	Message *Message `json:"message,omitempty"`
}

Post is a forum post: the thread channel and, when returned, its first message.

type PostData

type PostData struct {
	Owner        *Member  `json:"owner"`
	FirstMessage *Message `json:"first_message"`
}

PostData holds the owner and first message of a forum post. Either field may be nil.

type PostMessage

type PostMessage struct {
	Content         string           `json:"content,omitempty"`
	Embeds          []Embed          `json:"embeds,omitempty"`
	AllowedMentions *AllowedMentions `json:"allowed_mentions,omitempty"`
	StickerIDs      []string         `json:"sticker_ids,omitempty"`
	Flags           int              `json:"flags,omitempty"`
}

PostMessage is the first message of a new forum post.

type Presence

type Presence struct {
	User         User          `json:"user"`
	Status       string        `json:"status"`
	Mobile       bool          `json:"mobile"`
	AFK          bool          `json:"afk"`
	CustomStatus *CustomStatus `json:"custom_status"`
	GuildID      string        `json:"guild_id,omitempty"`
}

Presence is the status of one user.

type PresenceUpdate

type PresenceUpdate struct{ Presence }

PresenceUpdate is the PRESENCE_UPDATE dispatch.

func (PresenceUpdate) EventName

func (PresenceUpdate) EventName() string

type PresenceUpdateBulk

type PresenceUpdateBulk struct {
	GuildID   string     `json:"guild_id"`
	Presences []Presence `json:"presences"`
}

PresenceUpdateBulk is the PRESENCE_UPDATE_BULK dispatch.

func (PresenceUpdateBulk) EventName

func (PresenceUpdateBulk) EventName() string

type PublicApplication

type PublicApplication struct {
	ID           string   `json:"id"`
	Name         string   `json:"name"`
	Icon         string   `json:"icon,omitempty"`
	Description  string   `json:"description,omitempty"`
	RedirectURIs []string `json:"redirect_uris"`
	Scopes       []string `json:"scopes"`
	BotPublic    bool     `json:"bot_public"`
	Bot          *User    `json:"bot,omitempty"`
}

PublicApplication is the public information about an application.

type RTCRegion

type RTCRegion struct {
	ID    string `json:"id"`
	Name  string `json:"name"`
	Emoji string `json:"emoji"`
}

RTCRegion is a voice region listed in READY.

type RateLimited

type RateLimited struct {
	Opcode     int               `json:"opcode"`
	RetryAfter float64           `json:"retry_after"`
	Meta       map[string]string `json:"meta"`
}

RateLimited is the RATE_LIMITED dispatch. Opcode is the gateway command that hit the limit.

func (RateLimited) EventName

func (RateLimited) EventName() string

type ReactionAddition

type ReactionAddition struct {
	UserID string        `json:"user_id"`
	Emoji  ReactionEmoji `json:"emoji"`
	Member *Member       `json:"member,omitempty"`
}

ReactionAddition is one reaction in MESSAGE_REACTION_ADD_MANY.

type ReactionEmoji

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

ReactionEmoji is the emoji of a reaction. ID is empty for Unicode emoji.

func (ReactionEmoji) APIName

func (e ReactionEmoji) APIName() string

APIName returns the emoji in the form the reaction endpoints expect: the Unicode emoji, or name:id for a custom emoji.

func (ReactionEmoji) String

func (e ReactionEmoji) String() string

String returns the emoji as it is written in message content: the Unicode emoji itself, or <:name:id> for a custom emoji.

type ReactionPage

type ReactionPage struct {
	Items     []User `json:"items"`
	HasMore   bool   `json:"has_more"`
	NextAfter string `json:"next_after,omitempty"`
}

ReactionPage is one page of users who reacted with an emoji. Pass NextAfter to ReactionsPage to fetch the next page while HasMore is true.

type Ready

type Ready struct {
	SessionID       string             `json:"session_id"`
	Version         int                `json:"version"`
	User            User               `json:"user"`
	Guilds          []UnavailableGuild `json:"guilds"`
	PrivateChannels []Channel          `json:"private_channels"`
	RTCRegions      []RTCRegion        `json:"rtc_regions"`
	CountryCode     string             `json:"country_code"`
	Shard           []int              `json:"shard,omitempty"`
}

Ready is the READY dispatch. Session keeps SessionID for resuming and User for Session.User.

func (Ready) EventName

func (Ready) EventName() string

type RequestMembers

type RequestMembers struct {
	GuildID   string   `json:"guild_id"`
	Query     string   `json:"query,omitempty"`
	Limit     int      `json:"limit"`
	UserIDs   []string `json:"user_ids,omitempty"`
	Presences bool     `json:"presences,omitempty"`
	Nonce     string   `json:"nonce,omitempty"`
}

RequestMembers is the payload of RequestGuildMembers. Fluxer answers with GUILD_MEMBERS_CHUNK dispatches that carry the same Nonce.

type Reserve

type Reserve func(ctx context.Context, key string, step time.Duration) (time.Duration, error)

Reserve claims the next free slot for key in a rate limiter shared between processes, for example one backed by Redis, and returns how long the caller has to wait for that slot. step is the spacing between slots.

type Resumed

type Resumed struct{}

Resumed is the RESUMED dispatch. It carries no data.

func (Resumed) EventName

func (Resumed) EventName() string

type Role

type Role struct {
	ID            string      `json:"id"`
	Name          string      `json:"name"`
	Color         int         `json:"color,omitempty"`
	Position      int         `json:"position"`
	HoistPosition *int        `json:"hoist_position,omitempty"`
	Permissions   Permissions `json:"permissions"`
	Hoist         bool        `json:"hoist,omitempty"`
	Mentionable   bool        `json:"mentionable,omitempty"`
	UnicodeEmoji  string      `json:"unicode_emoji,omitempty"`
}

Role is a guild role. HoistPosition is nil unless the role has its own position in the member list.

func (Role) Mention

func (r Role) Mention() string

Mention returns the <@&id> mention string for the role.

type RoleEdit

type RoleEdit struct {
	Name          *string      `json:"name,omitempty"`
	Color         *int         `json:"color,omitempty"`
	Permissions   *Permissions `json:"permissions,omitempty"`
	Hoist         *bool        `json:"hoist,omitempty"`
	HoistPosition *int         `json:"hoist_position,omitempty"`
	Mentionable   *bool        `json:"mentionable,omitempty"`
}

RoleEdit holds the fields to change on a role. Only non-nil fields are sent.

type RoleHoistPosition

type RoleHoistPosition struct {
	ID            string `json:"id"`
	HoistPosition int    `json:"hoist_position"`
}

RoleHoistPosition sets where one hoisted role appears in the member list, independent of its permission position.

type RolePosition

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

RolePosition sets the position of one role in ModifyRolePositions.

type Router

type Router struct {
	// OnError, when set, receives decode failures and recovered handler panics.
	OnError func(event string, err error)
	// contains filtered or unexported fields
}

Router decodes dispatches into typed events and calls the handlers registered for them. Its Handle method fits Session.Handler. The zero value is ready to use.

func NewRouter

func NewRouter() *Router

NewRouter returns an empty Router.

func (*Router) Handle

func (r *Router) Handle(event string, data json.RawMessage)

Handle passes one dispatch to the OnAny handlers and then to the typed handlers for its name, each in registration order. Typed handlers are skipped when decoding fails. A panicking handler is recovered and reported to OnError, and the remaining handlers still run. Handlers added or removed during Handle take effect with the next dispatch.

func (*Router) OnAny

func (r *Router) OnAny(fn func(event string, data json.RawMessage)) func()

OnAny registers fn for every dispatch and returns a function that removes it. OnAny handlers run before the typed handlers.

type Session

type Session struct {
	// URL is the gateway base URL. Empty means DefaultGateway. The session adds the version,
	// encoding and compression query parameters.
	URL   string
	Token string
	// Shard is sent with IDENTIFY when Shard.Count is above zero.
	Shard Shard
	// Flags is a bitmask of the Flag constants, sent with IDENTIFY when non-zero.
	Flags int
	// Compress negotiates zstd-stream compression. Outgoing commands are compressed once the server
	// has sent its first binary frame.
	Compress bool
	// Presence is the initial presence sent with IDENTIFY.
	Presence *StatusUpdate
	// IgnoredEvents lists dispatch names Fluxer should not send to this session.
	IgnoredEvents []string
	// Handler receives every dispatch with its name and raw data, and op 12 errors as
	// GATEWAY_ERROR. It runs on the gateway read goroutine, so a handler that blocks delays all
	// later events and heartbeat ACKs and can make the session drop the connection as dead.
	Handler func(event string, data json.RawMessage)
	// Logger receives a warning for each ended connection. Nil uses slog.Default.
	Logger *slog.Logger
	// MinBackoff and MaxBackoff bound the jittered delay between reconnect attempts, by default one
	// second and one minute. The delay doubles after each attempt and starts over at MinBackoff
	// once a connection reached READY. MinBackoff is also the wait before identifying again after
	// INVALID_SESSION.
	MinBackoff time.Duration
	MaxBackoff time.Duration
	// ReadyTimeout is how long the session waits for READY or RESUMED before it drops the
	// connection and starts over, 65 seconds by default. Fluxer holds an IDENTIFY while it is busy
	// and drops one over the per-IP budget without a reply for 60 seconds, so a shorter timeout
	// gives up on identifies that would still succeed.
	ReadyTimeout time.Duration
	// Pacer, when set, spaces out IDENTIFY calls, for example across shards that share one identify
	// limit. Resumes are not paced.
	Pacer *Pacer
	// Observe is called at connection milestones with one of connect, connect_failed, identify,
	// resume or disconnect.
	Observe func(step string)
	// HTTP is the client for the WebSocket handshake. Nil uses http.DefaultClient.
	HTTP *http.Client
	// ReadLimit caps the size of a single WebSocket message in bytes, 32 MiB by default.
	ReadLimit int64
	// contains filtered or unexported fields
}

Session is a single gateway connection that reconnects and resumes on its own. Set the exported fields before calling Run and leave them alone while it runs.

func (*Session) Checkpoint

func (s *Session) Checkpoint() Checkpoint

Checkpoint returns the current session ID and sequence number. It is safe to call while Run is active.

func (*Session) Latency

func (s *Session) Latency() time.Duration

Latency returns the round trip time of the last acknowledged heartbeat, or zero before the first ACK.

func (*Session) RequestChannelMemberCounts

func (s *Session) RequestChannelMemberCounts(ctx context.Context, guildID string, channelIDs []string, nonce string) error

RequestChannelMemberCounts asks for the member and online counts of channels in one guild. The answer arrives as CHANNEL_MEMBER_COUNTS_UPDATE. An empty nonce is left out.

func (*Session) RequestGuildCounts

func (s *Session) RequestGuildCounts(ctx context.Context, guildIDs []string, nonce string) error

RequestGuildCounts asks for the member and online counts of the given guilds. The answer arrives as GUILD_COUNTS_UPDATE. An empty nonce is left out.

func (*Session) RequestGuildMembers

func (s *Session) RequestGuildMembers(ctx context.Context, r RequestMembers) error

RequestGuildMembers asks for members of one guild. Only the first 100 UserIDs are sent and the rest are dropped.

func (*Session) Restore

func (s *Session) Restore(c Checkpoint)

Restore replaces the stored session ID and sequence number. Call it before Run to resume from an earlier Checkpoint. An empty Checkpoint makes the next connection identify from scratch.

func (*Session) Run

func (s *Session) Run(ctx context.Context) error

Run connects to the gateway and keeps the session alive until ctx ends. After a dropped connection it waits with jittered backoff and reconnects, resuming when it holds a session ID. Close code 4007 discards the session so the next attempt identifies. Run returns ctx.Err() once ctx ends, ErrInvalidToken when a new session is closed with 4004, a *BanError when the handshake reports an IP ban, and a *CloseError for close codes 4001, 4002, 4003, 4005, 4010, 4011 and 4012, which point at a client bug or a setting that another attempt would not fix. Every other error leads to another attempt.

func (*Session) Send

func (s *Session) Send(ctx context.Context, op int, d any) error

Send writes a gateway command with opcode op and payload d on the live connection. It returns ErrNotConnected until the session has received READY or RESUMED, and again while it reconnects or identifies after INVALID_SESSION.

func (*Session) Subscribe

func (s *Session) Subscribe(ctx context.Context, subscriptions map[string]GuildSubscription) error

Subscribe sends a lazy guild request with subscriptions keyed by guild ID.

func (*Session) UpdateStatus

func (s *Session) UpdateStatus(ctx context.Context, st StatusUpdate) error

UpdateStatus changes the bot's presence.

func (*Session) UpdateVoiceState

func (s *Session) UpdateVoiceState(ctx context.Context, v VoiceStateCommand) error

UpdateVoiceState sends a voice state update. Fluxer reports a refusal as a GATEWAY_ERROR dispatch, for example with VoiceChannelFull.

func (*Session) User

func (s *Session) User() User

User returns the bot user from the most recent READY.

type SessionStartLimit

type SessionStartLimit struct {
	Total          int `json:"total"`
	Remaining      int `json:"remaining"`
	ResetAfter     int `json:"reset_after"`
	MaxConcurrency int `json:"max_concurrency"`
}

SessionStartLimit reports how many gateway sessions the bot may still start before the limit resets after ResetAfter. MaxConcurrency is the number of shards that may identify at the same time.

type Shard

type Shard struct {
	ID    int
	Count int
}

Shard identifies one shard by its ID and the total shard count. A zero Count leaves the shard out of IDENTIFY.

type Shards

type Shards struct {
	// URL is the gateway URL for every shard.
	URL   string
	Token string
	// Count is the number of shards. When Count is zero or URL is empty, Run fetches
	// Client.GatewayBot and fills in what is missing, with at least one shard.
	Count int
	// Client is only needed when Count or URL is unset.
	Client *Client
	// Handler receives the dispatches of all shards together with the shard ID. It runs on the
	// gateway read goroutine of that shard.
	Handler func(shard int, event string, data json.RawMessage)
	// Configure is called for each Session before it starts, for options such as Compress or
	// IgnoredEvents. It may also replace the Handler and Pacer set by Shards.
	Configure func(s *Session)
	// Pacer spaces out identifies across all shards. Nil uses NewPacer(60).
	Pacer *Pacer
	// contains filtered or unexported fields
}

Shards runs one Session per shard with a shared identify Pacer.

Example
package main

import (
	"context"
	"encoding/json"
	"log"
	"os"

	"github.com/invaliduser231/fluxer-go"
)

func main() {
	token := os.Getenv("FLUXER_TOKEN")
	router := fluxer.NewRouter()
	shards := &fluxer.Shards{
		Token:  token,
		Client: fluxer.NewClient(token),
		Handler: func(shard int, event string, data json.RawMessage) {
			router.Handle(event, data)
		},
	}
	log.Fatal(shards.Run(context.Background()))
}

func (*Shards) ForGuild

func (m *Shards) ForGuild(guildID string) *Session

ForGuild returns the session of the shard that owns guildID, or nil before Run has started.

func (*Shards) Run

func (m *Shards) Run(ctx context.Context) error

Run starts every shard and blocks until ctx ends or a shard's Session.Run returns an error. That error stops the other shards and is returned. Without Count and URL, Run fails if Client is nil or GatewayBot fails.

func (*Shards) Sessions

func (m *Shards) Sessions() []*Session

Sessions returns a copy of the shard sessions indexed by shard ID. It is empty until Run has started.

type SlackMessage

type SlackMessage struct {
	Text        string           `json:"text,omitempty"`
	Username    string           `json:"username,omitempty"`
	IconURL     string           `json:"icon_url,omitempty"`
	Attachments []map[string]any `json:"attachments,omitempty"`
}

SlackMessage is a Slack-compatible webhook payload for ExecuteSlackWebhook.

type SlowmodeState

type SlowmodeState struct {
	RateLimitPerUser  int        `json:"rate_limit_per_user"`
	RetryAfterMS      int        `json:"retry_after_ms"`
	NextSendAllowedAt *time.Time `json:"next_send_allowed_at,omitempty"`
	CanBypass         bool       `json:"can_bypass"`
}

SlowmodeState describes the slowmode for the current user in a channel. NextSendAllowedAt is nil when the server does not report a wait.

type StatusUpdate

type StatusUpdate struct {
	Status       string        `json:"status"`
	AFK          bool          `json:"afk"`
	Mobile       bool          `json:"mobile"`
	CustomStatus *CustomStatus `json:"custom_status,omitempty"`
}

StatusUpdate is the presence the bot sends with UpdateStatus or Session.Presence.

type Sticker

type Sticker struct {
	ID          string   `json:"id"`
	Name        string   `json:"name"`
	Description string   `json:"description,omitempty"`
	Tags        []string `json:"tags,omitempty"`
	Animated    bool     `json:"animated,omitempty"`
	NSFW        bool     `json:"nsfw,omitempty"`
	User        *User    `json:"user,omitempty"`
}

Sticker is a custom guild sticker.

type StickerBulkResult

type StickerBulkResult struct {
	Success []Sticker     `json:"success"`
	Failed  []BulkFailure `json:"failed"`
}

StickerBulkResult is the outcome of CreateStickers: the stickers that were created and the ones that failed.

type StickerEdit

type StickerEdit struct {
	Name        string    `json:"name"`
	Description *string   `json:"description,omitempty"`
	Tags        *[]string `json:"tags,omitempty"`
}

StickerEdit holds the changes for ModifySticker. Name is always sent, so it must be set even when only Description or Tags change. Nil Description and Tags are left unchanged.

type ThreadCreate

type ThreadCreate struct {
	Channel
	NewlyCreated bool `json:"newly_created,omitempty"`
}

ThreadCreate is the THREAD_CREATE dispatch.

func (ThreadCreate) EventName

func (ThreadCreate) EventName() string

type ThreadDelete

type ThreadDelete struct {
	ID       string `json:"id"`
	GuildID  string `json:"guild_id"`
	ParentID string `json:"parent_id"`
	Type     int    `json:"type"`
}

ThreadDelete is the THREAD_DELETE dispatch.

func (ThreadDelete) EventName

func (ThreadDelete) EventName() string

type ThreadList

type ThreadList struct {
	Threads []Channel      `json:"threads"`
	Members []ThreadMember `json:"members"`
	HasMore bool           `json:"has_more,omitempty"`
}

ThreadList is a set of threads along with the current user's ThreadMember entries for them. HasMore is set by the archived thread listings.

type ThreadListSync

type ThreadListSync struct {
	GuildID    string         `json:"guild_id"`
	ChannelIDs []string       `json:"channel_ids,omitempty"`
	Threads    []Channel      `json:"threads"`
	Members    []ThreadMember `json:"members"`
}

ThreadListSync is the THREAD_LIST_SYNC dispatch.

func (ThreadListSync) EventName

func (ThreadListSync) EventName() string

type ThreadMember

type ThreadMember struct {
	ID            string      `json:"id,omitempty"`
	UserID        string      `json:"user_id,omitempty"`
	JoinTimestamp time.Time   `json:"join_timestamp,omitzero"`
	Flags         int         `json:"flags"`
	Muted         bool        `json:"muted,omitempty"`
	MuteConfig    *MuteConfig `json:"mute_config,omitempty"`
	Member        *Member     `json:"member,omitempty"`
}

ThreadMember is a user's membership in a thread. Muted and MuteConfig are only set for the current user.

type ThreadMemberListItem added in v0.2.0

type ThreadMemberListItem struct {
	ThreadMember
	Presence *Presence `json:"presence,omitempty"`
}

ThreadMemberListItem is a member of a thread member list with its presence.

type ThreadMemberListUpdate added in v0.2.0

type ThreadMemberListUpdate struct {
	GuildID  string                 `json:"guild_id"`
	ThreadID string                 `json:"thread_id"`
	Members  []ThreadMemberListItem `json:"members"`
}

ThreadMemberListUpdate is the THREAD_MEMBER_LIST_UPDATE dispatch with the full member list, at most 1,000 members, of a thread subscribed through GuildSubscription.ThreadMemberLists. Resuming does not replay it.

func (ThreadMemberListUpdate) EventName added in v0.2.0

func (ThreadMemberListUpdate) EventName() string

EventName returns the gateway event name THREAD_MEMBER_LIST_UPDATE.

type ThreadMemberUpdate

type ThreadMemberUpdate struct {
	ThreadMember
	GuildID string `json:"guild_id"`
}

ThreadMemberUpdate is the THREAD_MEMBER_UPDATE dispatch.

func (ThreadMemberUpdate) EventName

func (ThreadMemberUpdate) EventName() string

type ThreadMembersUpdate

type ThreadMembersUpdate struct {
	ID               string         `json:"id"`
	GuildID          string         `json:"guild_id"`
	MemberCount      int            `json:"member_count"`
	AddedMembers     []ThreadMember `json:"added_members,omitempty"`
	RemovedMemberIDs []string       `json:"removed_member_ids,omitempty"`
}

ThreadMembersUpdate is the THREAD_MEMBERS_UPDATE dispatch.

func (ThreadMembersUpdate) EventName

func (ThreadMembersUpdate) EventName() string

type ThreadMetadata

type ThreadMetadata struct {
	Archived            bool      `json:"archived"`
	AutoArchiveDuration int       `json:"auto_archive_duration,omitempty"`
	ArchiveTimestamp    time.Time `json:"archive_timestamp,omitzero"`
	Locked              bool      `json:"locked"`
	Invitable           bool      `json:"invitable,omitempty"`
	CreateTimestamp     time.Time `json:"create_timestamp,omitzero"`
}

ThreadMetadata holds the archive and lock state of a thread.

type ThreadSearch

type ThreadSearch struct {
	Name       string
	Archived   *bool
	Tags       []string
	TagSetting string
	SortBy     string
	SortOrder  string
	AfterID    string
	BeforeID   string
	Limit      int
	Offset     int
}

ThreadSearch filters SearchThreads. Empty fields are not sent: a nil Archived matches both states, and zero Limit and Offset use the server defaults. Each entry in Tags is sent as its own tag parameter, and TagSetting, TagsMatchSome or TagsMatchAll, decides whether a post needs one of them or all. SortBy is one of the ThreadSort constants and SortOrder asc or desc. AfterID and BeforeID limit the results by thread ID.

type ThreadSearchResult

type ThreadSearchResult struct {
	ThreadList
	TotalResults  int       `json:"total_results"`
	FirstMessages []Message `json:"first_messages,omitempty"`
}

ThreadSearchResult is the result of SearchThreads, with the total number of matches. In forum and media channels FirstMessages holds the first message of each post.

type ThreadStart

type ThreadStart struct {
	Name                string `json:"name"`
	Type                int    `json:"type,omitempty"`
	AutoArchiveDuration int    `json:"auto_archive_duration,omitempty"`
	RateLimitPerUser    int    `json:"rate_limit_per_user,omitempty"`
	Invitable           *bool  `json:"invitable,omitempty"`
}

ThreadStart configures StartThread and StartThreadFromMessage. Zero values are omitted. Type selects ThreadPublic or ThreadPrivate and is ignored when starting from a message.

type ThreadUpdate

type ThreadUpdate struct{ Channel }

ThreadUpdate is the THREAD_UPDATE dispatch.

func (ThreadUpdate) EventName

func (ThreadUpdate) EventName() string

type TokenInfo

type TokenInfo struct {
	Active    bool   `json:"active"`
	Scope     string `json:"scope,omitempty"`
	ClientID  string `json:"client_id,omitempty"`
	Username  string `json:"username,omitempty"`
	TokenType string `json:"token_type,omitempty"`
	Expires   int64  `json:"exp,omitempty"`
	IssuedAt  int64  `json:"iat,omitempty"`
	Subject   string `json:"sub,omitempty"`
}

TokenInfo is the result of token introspection. Active reports whether the token is valid. Expires and IssuedAt are Unix times in seconds.

type TypingStart

type TypingStart struct {
	ChannelID string  `json:"channel_id"`
	UserID    string  `json:"user_id"`
	Timestamp int64   `json:"timestamp"`
	GuildID   string  `json:"guild_id,omitempty"`
	Member    *Member `json:"member,omitempty"`
}

TypingStart is the TYPING_START dispatch.

func (TypingStart) EventName

func (TypingStart) EventName() string

type UnavailableGuild

type UnavailableGuild struct {
	ID          string `json:"id"`
	Unavailable bool   `json:"unavailable"`
}

UnavailableGuild is a guild entry in READY. The full guild follows as GUILD_CREATE.

type UploadPart

type UploadPart struct {
	PartNumber int    `json:"part_number"`
	UploadURL  string `json:"upload_url"`
}

UploadPart is one part of a multipart upload and the presigned URL it is sent to. PartNumber starts at 1.

type UploadPlan

type UploadPlan struct {
	ID             int          `json:"id"`
	Filename       string       `json:"filename"`
	FileSize       int64        `json:"file_size"`
	ContentType    string       `json:"content_type"`
	UploadFilename string       `json:"upload_filename"`
	UploadMode     string       `json:"upload_mode"`
	UploadURL      string       `json:"upload_url,omitempty"`
	UploadID       string       `json:"upload_id,omitempty"`
	PartSize       int64        `json:"part_size,omitempty"`
	Parts          []UploadPart `json:"parts,omitempty"`
}

UploadPlan is the server's upload instruction for one file. UploadMode is "singlepart", where the whole file goes to UploadURL, or "multipart", where the file is split into Parts of PartSize bytes.

type UploadedFile

type UploadedFile struct {
	ID             int    `json:"id"`
	Filename       string `json:"filename"`
	ContentType    string `json:"content_type"`
	UploadFilename string `json:"upload_filename"`
	FileSize       int64  `json:"file_size"`
	Title          string `json:"title,omitempty"`
	Description    string `json:"description,omitempty"`
	Flags          int    `json:"flags,omitempty"`
	Duration       int    `json:"duration,omitempty"`
	Waveform       string `json:"waveform,omitempty"`
}

UploadedFile describes a file uploaded with Upload. Add it to MessageSend.Attachments to attach the file to a message.

type User

type User struct {
	ID            string  `json:"id"`
	Username      string  `json:"username"`
	Discriminator string  `json:"discriminator"`
	GlobalName    *string `json:"global_name"`
	Avatar        *string `json:"avatar,omitempty"`
	AvatarColor   *int    `json:"avatar_color,omitempty"`
	Bot           bool    `json:"bot,omitempty"`
	System        bool    `json:"system,omitempty"`
	Flags         int64   `json:"flags,omitempty"`
	MentionFlags  int     `json:"mention_flags,omitempty"`
}

User is a Fluxer user account. GlobalName and Avatar are nil when the user has not set them. MentionFlags is the user's reply mention preference, one of the Mention constants.

func (User) AvatarURL

func (u User) AvatarURL(media string) string

AvatarURL returns the URL of the user's avatar on the given media host, or an empty string when the user has no avatar.

func (User) DisplayName

func (u User) DisplayName() string

DisplayName returns the user's global name, or the username when no global name is set.

func (User) Mention

func (u User) Mention() string

Mention returns the <@id> mention string for the user.

func (User) Tag

func (u User) Tag() string

Tag returns username#discriminator, or the plain username when the discriminator is empty or "0".

type UserProfile

type UserProfile struct {
	User           User              `json:"user"`
	Profile        map[string]any    `json:"user_profile"`
	Member         *Member           `json:"guild_member,omitempty"`
	MutualGuilds   []json.RawMessage `json:"mutual_guilds,omitempty"`
	TimezoneOffset *int              `json:"timezone_offset"`
	Limited        bool              `json:"profile_limited,omitempty"`
}

UserProfile is a user's profile. Profile holds the raw profile fields, Member is set when the profile was requested for a guild, and Limited reports that the API returned a limited profile.

func (UserProfile) Bio

func (p UserProfile) Bio() string

Bio returns the bio from the profile fields, or an empty string.

type UserUpdate

type UserUpdate struct{ User }

UserUpdate is the USER_UPDATE dispatch.

func (UserUpdate) EventName

func (UserUpdate) EventName() string

type VanityURL

type VanityURL struct {
	Code string `json:"code,omitempty"`
	Uses int    `json:"uses"`
}

VanityURL is a guild's custom invite code and how often it has been used. Code is empty when none is set.

type VoiceServerUpdate

type VoiceServerUpdate struct {
	Token        string `json:"token"`
	Endpoint     string `json:"endpoint"`
	ConnectionID string `json:"connection_id"`
	ChannelID    string `json:"channel_id"`
	GuildID      string `json:"guild_id,omitempty"`
	E2EEKey      string `json:"e2ee_key,omitempty"`
}

VoiceServerUpdate is the VOICE_SERVER_UPDATE dispatch with the endpoint and token for a voice connection.

func (VoiceServerUpdate) EventName

func (VoiceServerUpdate) EventName() string

type VoiceState

type VoiceState struct {
	GuildID          string   `json:"guild_id,omitempty"`
	ChannelID        string   `json:"channel_id,omitempty"`
	UserID           string   `json:"user_id"`
	ConnectionID     string   `json:"connection_id,omitempty"`
	SessionID        string   `json:"session_id,omitempty"`
	Member           *Member  `json:"member,omitempty"`
	Mute             bool     `json:"mute"`
	Deaf             bool     `json:"deaf"`
	SelfMute         bool     `json:"self_mute"`
	SelfDeaf         bool     `json:"self_deaf"`
	SelfVideo        bool     `json:"self_video"`
	SelfStream       bool     `json:"self_stream"`
	IsMobile         bool     `json:"is_mobile"`
	Suppress         bool     `json:"suppress"`
	ViewerStreamKeys []string `json:"viewer_stream_keys,omitempty"`
	E2EECapable      bool     `json:"e2ee_capable,omitempty"`
	P2P              bool     `json:"p2p,omitempty"`
	Version          int64    `json:"version"`
}

VoiceState is the voice connection state of one user. E2EECapable reports whether the user's app supports end-to-end encrypted voice, P2P whether the connection sends media directly to the other participants.

type VoiceStateCommand

type VoiceStateCommand struct {
	GuildID      string
	ChannelID    string
	ConnectionID string
	SelfMute     bool
	SelfDeaf     bool
	SelfVideo    bool
	SelfStream   bool
}

VoiceStateCommand joins, moves or leaves voice through UpdateVoiceState. An empty ChannelID is sent as null and leaves voice, an empty GuildID is sent as null for calls outside a guild. ConnectionID is sent only when set.

func (VoiceStateCommand) MarshalJSON

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

MarshalJSON encodes an empty GuildID or ChannelID as null and leaves out an empty ConnectionID.

type VoiceStateUpdate

type VoiceStateUpdate struct{ VoiceState }

VoiceStateUpdate is the VOICE_STATE_UPDATE dispatch.

func (VoiceStateUpdate) EventName

func (VoiceStateUpdate) EventName() string

type Webhook

type Webhook struct {
	ID            string         `json:"id"`
	GuildID       string         `json:"guild_id,omitempty"`
	ChannelID     string         `json:"channel_id"`
	Name          string         `json:"name"`
	Avatar        string         `json:"avatar,omitempty"`
	Type          int            `json:"type"`
	Token         string         `json:"token,omitempty"`
	User          *User          `json:"user,omitempty"`
	SourceGuild   *WebhookSource `json:"source_guild,omitempty"`
	SourceChannel *WebhookSource `json:"source_channel,omitempty"`
}

Webhook is a Fluxer webhook. ExecuteWebhook and the methods ending in WithToken need ID and Token; ParseWebhookURL extracts both from a webhook URL. SourceGuild and SourceChannel name the followed announcement channel of a WebhookChannelFollower webhook while its creator can see it.

func ParseWebhookURL

func ParseWebhookURL(raw string) (Webhook, error)

ParseWebhookURL extracts the webhook ID and token from a URL that contains /webhooks/{id}/{token}. Further path segments after the token are allowed.

Example
package main

import (
	"context"
	"log"
	"os"

	"github.com/invaliduser231/fluxer-go"
)

func main() {
	hook, err := fluxer.ParseWebhookURL(os.Getenv("FLUXER_WEBHOOK_URL"))
	if err != nil {
		log.Fatal(err)
	}
	client := fluxer.NewClient("")
	_, err = client.ExecuteWebhook(context.Background(), hook, "", fluxer.WebhookMessage{
		MessageSend: fluxer.MessageSend{Content: "Build passed"},
		Username:    "CI",
	}, nil)
	if err != nil {
		log.Fatal(err)
	}
}

type WebhookEdit

type WebhookEdit struct {
	Name      *string `json:"name,omitempty"`
	Avatar    *string `json:"avatar,omitempty"`
	ChannelID *string `json:"channel_id,omitempty"`
}

WebhookEdit holds the changes for ModifyWebhook. Nil fields are left unchanged.

type WebhookMessage

type WebhookMessage struct {
	MessageSend
	Username    string   `json:"username,omitempty"`
	AvatarURL   string   `json:"avatar_url,omitempty"`
	ThreadName  string   `json:"thread_name,omitempty"`
	AppliedTags []string `json:"applied_tags,omitempty"`
}

WebhookMessage is a message sent through a webhook. Username and AvatarURL replace the webhook's name and avatar for this message only.

type WebhookSource added in v0.2.0

type WebhookSource struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	Icon string `json:"icon,omitempty"`
}

WebhookSource is the guild or channel a follower webhook copies messages from. Icon is only set for guilds.

type WebhooksUpdate

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

WebhooksUpdate is the WEBHOOKS_UPDATE dispatch.

func (WebhooksUpdate) EventName

func (WebhooksUpdate) EventName() string

Directories

Path Synopsis
examples
multi command
ping command
webhook command
Package fluxertest runs a fake Fluxer server for tests.
Package fluxertest runs a fake Fluxer server for tests.
Package state keeps the guilds, channels, roles, members, messages and voice states a bot sees, built from gateway events.
Package state keeps the guilds, channels, roles, members, messages and voice states a bot sees, built from gateway events.
redis module
voice module

Jump to

Keyboard shortcuts

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