router

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2022 License: MIT Imports: 24 Imported by: 1

README

router

A high level Postcord interactions router. This code implements a modified version of the binary tree from httprouter (see tree.go). This is licensed under the BSD license.

How does this work?

This package consists of 2 routers (a components router and a commands router), and a function to bootstrap the routers and set any global configurations which affect them both. Each router has been designed to work well for its specific usecase.

Components Router

Routing components was traditionally quite complicated. You could use a standard map, but then you would lose the ability to track state. You could put the state in the string, but then you would either need to make a cache lookup, or you would need to do complicated and expensive string splitting.

Postcord gets around this by using a fork of the tree that httprouter/fasthttprouter uses for our component routes. This means that we have the ability to track state whilst making the application performant.

To begin with, we will go ahead and define the router somewhere where any of the components that wish to access it can see.

var componentRouter = &router.ComponentRouter{}

Note that we can directly initialise this object. There's no new function. From here, we can go ahead and add functionality to this router.

There are 2 functions we can use to add components:

  • RegisterButton(route string, cb ButtonFunc): The job of this is to allow you to register button components. The signature for ButtonFunc takes *ComponentRouterCtx as the first argument and returns an error. See creating responses with the context to see how you would make a response with the context handed down for this button.
  • RegisterSelectMenu(route string, cb SelectMenuFunc): The job of this is to allow you to register select menu components. The signature for SelectMenuFunc takes *ComponentRouterCtx as the first argument, and []string as the second (this will contian the choices that the user made). It will then return an error. See creating responses with the context to see how you would make a response with the context handed down for this button.

It is important to note that in both instances, we can use parameters in the path. This is awesome for inputting user data, however it is important to validate the data! Do not trust this input as it can be manipulated by users! As with httprouter, this can be done with :paramName in the path. For example, we could go ahead and register the following button:

componentRouter.RegisterButton("/name/:name", func(ctx *router.ComponentRouterCtx) error {
	ctx.SetEmbed(&objects.Embed{Description: "my name " + ctx.Params["name"]})
	return nil
})

From here, we could go ahead and import this path in a component with the custom ID /name/Jeff and when clicked it would reply with an embed saying my name Jeff.

Commands Router

One thing that is even more difficult to route than components is commands. Routing through sub-commands requires a lot of mind bending iteration, but don't worry, we have your back and have created a high level commands router too!

The same as with interactions, you will firstly want to go ahead and make the commands router:

var commandRouter = &router.CommandRouter{}

Now we have a commands router created, we can now add to it.

To register a group, both CommandRouter and CommandGroup (to allow for one sub-group as per Discord's nesting rules) have the NewCommandGroup and MustNewCommandGroup functions. This will allow you to make a command group, which will then allow you to create commands/groups to be nested inside of it.

To register a command, we can go ahead and call NewCommandBuilder on either a router or group with the argument being the name of the command. From here, we can set the following options:

TODO

Options

TODO

Creating Responses with the Context

TODO

Router Loader

So we went ahead and created both our routers. Awesome! But we need to get these into the application somehow. Don't worry, we thought of a very elegant way to do this. The RouterLoader function will create a builder which we can use to go ahead to build and execute the loader. We can use the following options in our chain:

  • ComponentRouter(*ComponentRouter) LoaderBuilder: Adds the component router specified into the loader.
  • CommandRouter(*CommandRouter) LoaderBuilder: Adds the commands router specified into the loader.
  • ErrorHandler(ErrorHandler) LoaderBuilder: See error handling.
  • AllowedMentions(*objects.AllowedMentions) LoaderBuilder: See allowed mentions.

At the end of this, just call Build with your interactions application (you probably want a *interactions.App from Postcord/interactions). This will automatically inject the routers into your application and build them with the appropriate allowed mentions configuration.

Error Handling

So how does error handling work? Error handling is done at a global scope with an error handler that takes a error parameter and returns a *objects.InteractionResponse. This can be used to write your own error handling code for actions. Note that there are a few errors that are dispatched by this codebase, and these are documented in the godoc for this project.

Allowed Mentions

Allowed mention configurations can be set on a command, group, and global scope. Note that it takes affect in that order, so a command level allowed mentions configuration will override a global one.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var CommandDoesNotExist = errors.New("the command does not exist")

CommandDoesNotExist is thrown when the command specified does not exist.

View Source
var CommandIsNotSubcommand = errors.New("expected *Command, found *CommandGroup")

CommandIsNotSubcommand is thrown when the router expects a command and gets a command group.

View Source
var CommandIsSubcommand = errors.New("expected *CommandGroup, found *Command")

CommandIsSubcommand is thrown when the router expects a command group and gets a command.

View Source
var GroupNestedTooDeep = errors.New("sub-command group would be nested too deep")

GroupNestedTooDeep is thrown when the sub-command group would be nested too deep.

View Source
var InvalidTarget = errors.New("wrong or no target specified")

InvalidTarget is thrown when the command target is not valid.

View Source
var MiddlewareChainExhausted = errors.New("the middleware chain has been exhausted")

MiddlewareChainExhausted is called when the middleware chain has been exhausted.

View Source
var MismatchedOption = errors.New("mismatched interaction option")

MismatchedOption is thrown when the option types mismatch.

View Source
var ModalPathNotFound = errors.New("modal path not found")

ModalPathNotFound is thrown when the modal path is not found.

View Source
var MultipleModalResponses = errors.New("multiple modal responses")

MultipleModalResponses is thrown when a modal response is triggered within another.

View Source
var NoAutoCompleteFunc = errors.New("discord sent auto-complete for argument without auto-complete function")

NoAutoCompleteFunc is thrown when Discord sends a focused argument without an autocomplete function.

View Source
var NoCommandResponse = errors.New("expected data for command response")

NoCommandResponse is thrown when the application doesn't respond for a command.

View Source
var NonExistentOption = errors.New("interaction option doesn't exist on command")

NonExistentOption is thrown when an option is provided in an interaction that doesn't exist in the command.

View Source
var NotButton = errors.New("the data returned is not that of a button")

NotButton is returned when Discord returns data that is not a button.

View Source
var NotSelectionMenu = errors.New("the data returned is not that of a selection menu")

NotSelectionMenu is returned when Discord returns data that is not a selection menu.

View Source
var UnknownContextType = errors.New("unknown context type")

UnknownContextType is thrown when a context type is not from Postcord.

View Source
var UnsetModalRouter = errors.New("modal router is unset")

UnsetModalRouter is thrown when the modal router is unset.

Functions

func TestAutocomplete added in v0.1.0

func TestAutocomplete(t TestingT, b LoaderBuilder, commandRoute ...string)

TestAutocomplete is used to run unit tests against the specified commands auto-complete.

func TestCommand added in v0.1.0

func TestCommand(t TestingT, b LoaderBuilder, commandRoute ...string)

TestCommand is used to run unit tests against the specified command.

func TestComponent added in v0.1.0

func TestComponent(t TestingT, b LoaderBuilder, path string)

TestComponent is used to run unit tests against the specified component.

Types

type ButtonFunc

type ButtonFunc func(ctx *ComponentRouterCtx) error

ButtonFunc is the function dispatched when a button is used.

type CombinedRouter

type CombinedRouter struct {
	CommandRouter
	ComponentRouter
	ModalRouter
}

CombinedRouter is an extension of both CommandRouter and ComponentRouter to combine the two. I'm personally not a huge fan of using this, but it might be appealing to some people who wish to treat it as one router.

type Command

type Command struct {

	// Name is the commands name.
	Name string `json:"name"`

	// Description is the description for the command.
	Description string `json:"description"`

	// AllowedMentions is used to set a command level rule on allowed mentions. If this is not nil, it overrides the last configuration.
	AllowedMentions *objects.AllowedMentions `json:"allowed_mentions"`

	// DefaultPermissions indicates which users should be allowed to use this command based on their permissions.  Set to 0 to disable by default. (default: all allowed)
	DefaultPermissions *permissions.PermissionBit `json:"default_member_permissions,omitempty"`

	// UseInDMs determines if the command should be usable in DMs (default: true)
	UseInDMs *bool `json:"dm_permission,omitempty"`

	// Options defines the options which are required for a command.
	Options []*objects.ApplicationCommandOption `json:"options"`

	// Function is used to define the command being called.
	Function func(*CommandRouterCtx) error `json:"-"`
	// contains filtered or unexported fields
}

Command is used to define a Discord (sub-)command. DO NOT MAKE YOURSELF! USE CommandGroup.NewCommandBuilder OR CommandRouter.NewCommandBuilder!

func (*Command) Groups

func (c *Command) Groups() []*CommandGroup

Groups is used to get the command groups that this belongs to.

type CommandBuilder

type CommandBuilder interface {

	// DefaultPermissions is used to set the default command permissions for this command.
	DefaultPermissions(permissions.PermissionBit) CommandBuilder

	// GuildCommand is used to forbid this from running in DMs.
	GuildCommand() CommandBuilder

	// Description is used to define the commands description.
	Description(string) CommandBuilder

	// TextCommand is used to define that this should be a text command builder.
	TextCommand() TextCommandBuilder

	// MessageCommand is used to define that this should be a message command builder.
	MessageCommand() MessageCommandBuilder

	// UserCommand is used to define that this should be a message command builder.
	UserCommand() UserCommandBuilder

	// AllowedMentions is used to set a command level rule on allowed mentions. If this is not nil, it overrides the last configuration.
	AllowedMentions(*objects.AllowedMentions) CommandBuilder

	// Handler is used to add a command handler.
	Handler(func(*CommandRouterCtx) error) CommandBuilder

	// Build is used to build the command and insert it into the command router.
	Build() (*Command, error)

	// MustBuild is used to define when a command must build or panic.
	MustBuild() *Command
	// contains filtered or unexported methods
}

CommandBuilder is used to define a builder for a Command object where the type isn't known.

type CommandGroup

type CommandGroup struct {

	// Middleware defines all of the groups middleware.
	Middleware []MiddlewareFunc `json:"middleware"`

	// Description is the description for the command group.
	Description string `json:"description"`

	// DefaultPermissions indicates which users should be allowed to use this command based on their permissions.  Set to 0 to disable by default. (default: all allowed)
	DefaultPermissions *permissions.PermissionBit `json:"default_member_permissions,omitempty"`

	// UseInDMs determines if the command should be usable in DMs (default: true)
	UseInDMs *bool `json:"dm_permission,omitempty"`

	// AllowedMentions is used to set a group level rule on allowed mentions. If this is not nil, it overrides the last configuration.
	AllowedMentions *objects.AllowedMentions `json:"allowed_mentions"`

	// Subcommands is a map of all of the subcommands. It is a any since it can be *Command or *CommandGroup. DO NOT ADD TO THIS! USE THE ATTACHED FUNCTIONS!
	Subcommands map[string]any `json:"subcommands"`
	// contains filtered or unexported fields
}

CommandGroup is a group of commands. DO NOT MAKE YOURSELF! USE CommandGroup.NewCommandGroup OR CommandRouter.NewCommandGroup!

func (*CommandGroup) MustNewCommandGroup

func (c *CommandGroup) MustNewCommandGroup(name, description string, opts *CommandGroupOptions) *CommandGroup

MustNewCommandGroup calls NewCommandGroup but must succeed. If not, it will panic.

func (*CommandGroup) NewCommandBuilder

func (c *CommandGroup) NewCommandBuilder(name string) SubCommandBuilder

NewCommandBuilder is used to create a builder for a *Command object.

func (*CommandGroup) NewCommandGroup

func (c *CommandGroup) NewCommandGroup(name, description string, opts *CommandGroupOptions) (*CommandGroup, error)

NewCommandGroup is used to create a sub-command group.

func (*CommandGroup) Use

func (c *CommandGroup) Use(f MiddlewareFunc)

Use is used to add middleware to the group.

type CommandGroupOptions added in v0.2.0

type CommandGroupOptions struct {
	DefaultPermissions permissions.PermissionBit
	UseInDMs           bool
}

type CommandRouter

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

CommandRouter is used to route commands.

func (*CommandRouter) FormulateDiscordCommands

func (c *CommandRouter) FormulateDiscordCommands() []*objects.ApplicationCommand

FormulateDiscordCommands is used to formulate the commands in such a way that they can be uploaded to Discord.

func (*CommandRouter) MarshalJSON

func (c *CommandRouter) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*CommandRouter) MustNewCommandGroup

func (c *CommandRouter) MustNewCommandGroup(name, description string, opts *CommandGroupOptions) *CommandGroup

MustNewCommandGroup calls NewCommandGroup but must succeed. If not, it will panic.

func (*CommandRouter) NewCommandBuilder

func (c *CommandRouter) NewCommandBuilder(name string) CommandBuilder

NewCommandBuilder is used to create a builder for a *Command object.

func (*CommandRouter) NewCommandGroup

func (c *CommandRouter) NewCommandGroup(name, description string, opts *CommandGroupOptions) (*CommandGroup, error)

NewCommandGroup is used to create a sub-command group. Works the same as CommandGroup.NewCommandGroup.

func (*CommandRouter) Use

func (c *CommandRouter) Use(f MiddlewareFunc)

Use is used to add middleware to the router.

type CommandRouterCtx

type CommandRouterCtx struct {

	// Defines the interaction which started this.
	*objects.Interaction

	// Context is a context.Context passed from the HTTP handler.
	Context context.Context

	// Command defines the command that was invoked.
	Command *Command `json:"command"`

	// Options is used to define any options that were set in the context. Note that if an option is unset from Discord, it will not be in the map.
	// Note that for User, Channel, Role, and Mentionable from Discord; a "*Resolvable<option type>" type is used. This will allow you to get the ID as a Snowflake, string, or attempt to get from resolved.
	Options map[string]any `json:"options"`

	// RESTClient is used to define the REST client.
	RESTClient rest.RESTClient `json:"rest_client"`
	// contains filtered or unexported fields
}

CommandRouterCtx is used to define the commands context from the router.

func (*CommandRouterCtx) AddComponentRow

func (c *CommandRouterCtx) AddComponentRow(row []*objects.Component) T

AddComponentRow is used to add a row of components.

func (*CommandRouterCtx) AddEmbed

func (c *CommandRouterCtx) AddEmbed(embed *objects.Embed) T

AddEmbed is used to append the embed, joining any previously.

func (*CommandRouterCtx) AttachBytes added in v0.1.3

func (c *CommandRouterCtx) AttachBytes(data []byte, filename, description string) T

AttachBytes adds a file attachment to the response from a byte array

func (*CommandRouterCtx) AttachFile added in v0.1.3

func (c *CommandRouterCtx) AttachFile(file *objects.DiscordFile) T

AttachFile adds a file attachment to the response from an *objects.DiscordFile

func (*CommandRouterCtx) Bind

func (c *CommandRouterCtx) Bind(data any) error

Bind allows you to bind the option values to a struct for easy access

func (*CommandRouterCtx) ChannelMessageWithSource

func (c *CommandRouterCtx) ChannelMessageWithSource() T

ChannelMessageWithSource is used to respond to the interaction with a message.

func (*CommandRouterCtx) ClearComponents

func (c *CommandRouterCtx) ClearComponents() T

ClearComponents is used to clear the components in a response.

func (*CommandRouterCtx) DeferredChannelMessageWithSource

func (c *CommandRouterCtx) DeferredChannelMessageWithSource(f func(*CommandRouterCtx) error)

DeferredChannelMessageWithSource is used to handle updating the response later. The user sees a loading state. Note that the chain does not continue after this since it is impossible to attach additional data.

func (*CommandRouterCtx) Ephemeral

func (c *CommandRouterCtx) Ephemeral() T

Ephemeral is used to set the response as ephemeral.

func (*CommandRouterCtx) SetAllowedMentions

func (c *CommandRouterCtx) SetAllowedMentions(config *objects.AllowedMentions) T

SetAllowedMentions is used to set the allowed mentions of a response. This will override your global configuration.

func (*CommandRouterCtx) SetComponentRows

func (c *CommandRouterCtx) SetComponentRows(rows [][]*objects.Component) T

SetComponentRows is used to set rows of components.

func (*CommandRouterCtx) SetContent

func (c *CommandRouterCtx) SetContent(content string) T

SetContent is used to set the content of a response.

func (*CommandRouterCtx) SetContentf added in v0.1.0

func (c *CommandRouterCtx) SetContentf(content string, args ...any) T

SetContentf is used to set the content of a response using fmt.Sprintf.

func (*CommandRouterCtx) SetEmbed

func (c *CommandRouterCtx) SetEmbed(embed *objects.Embed) T

SetEmbed is used to set the embed, overwriting any previously.

func (*CommandRouterCtx) SetTTS

func (c *CommandRouterCtx) SetTTS(tts bool) T

SetTTS is used to set the TTS configuration for your response.

func (*CommandRouterCtx) TargetMember

func (c *CommandRouterCtx) TargetMember() *objects.GuildMember

TargetMember is used to try and get the target member. If this was not targeted at a member, returns nil.

func (*CommandRouterCtx) TargetMessage

func (c *CommandRouterCtx) TargetMessage() *objects.Message

TargetMessage is used to try and get the target message. If this was not targeted at a message, returns nil.

func (*CommandRouterCtx) UpdateLater

func (c *CommandRouterCtx) UpdateLater(f func(*CommandRouterCtx) error) *CommandRouterCtx

UpdateLater is used to spawn the function specified in a goroutine. When the function is returned, the result is set as a message update.

func (*CommandRouterCtx) VoidCustomID

func (g *CommandRouterCtx) VoidCustomID() string

VoidCustomID is used to return a unique custom ID for this context that resolves to a void.

func (*CommandRouterCtx) WithModalPath added in v0.1.4

func (c *CommandRouterCtx) WithModalPath(path string) error

WithModalPath is used to set the response to the modal path specified.

type ComponentRouter

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

ComponentRouter is used to route components.

func (*ComponentRouter) RegisterButton

func (c *ComponentRouter) RegisterButton(route string, cb ButtonFunc)

RegisterButton is used to register a button route.

func (*ComponentRouter) RegisterSelectMenu

func (c *ComponentRouter) RegisterSelectMenu(route string, cb SelectMenuFunc)

RegisterSelectMenu is used to register a select menu route.

type ComponentRouterCtx

type ComponentRouterCtx struct {

	// Context is a context.Context passed from the HTTP handler.
	Context context.Context

	// Defines the interaction which started this.
	*objects.Interaction

	// Params are any URL params which were in the path.
	Params map[string]string `json:"params"`

	// RESTClient is used to define the REST client.
	RESTClient rest.RESTClient `json:"rest_client"`
	// contains filtered or unexported fields
}

ComponentRouterCtx is used to define a components router context.

func (*ComponentRouterCtx) AddComponentRow

func (c *ComponentRouterCtx) AddComponentRow(row []*objects.Component) T

AddComponentRow is used to add a row of components.

func (*ComponentRouterCtx) AddEmbed

func (c *ComponentRouterCtx) AddEmbed(embed *objects.Embed) T

AddEmbed is used to append the embed, joining any previously.

func (*ComponentRouterCtx) AttachBytes added in v0.1.3

func (c *ComponentRouterCtx) AttachBytes(data []byte, filename, description string) T

AttachBytes adds a file attachment to the response from a byte array

func (*ComponentRouterCtx) AttachFile added in v0.1.3

func (c *ComponentRouterCtx) AttachFile(file *objects.DiscordFile) T

AttachFile adds a file attachment to the response from an *objects.DiscordFile

func (*ComponentRouterCtx) ChannelMessageWithSource

func (c *ComponentRouterCtx) ChannelMessageWithSource() T

ChannelMessageWithSource is used to respond to the interaction with a message.

func (*ComponentRouterCtx) ClearComponents

func (c *ComponentRouterCtx) ClearComponents() T

ClearComponents is used to clear the components in a response.

func (*ComponentRouterCtx) DeferredChannelMessageWithSource

func (c *ComponentRouterCtx) DeferredChannelMessageWithSource(f func(*ComponentRouterCtx) error)

DeferredChannelMessageWithSource is used to handle updating the response later. The user sees a loading state. Note that the chain does not continue after this since it is impossible to attach additional data.

func (*ComponentRouterCtx) DeferredMessageUpdate

func (c *ComponentRouterCtx) DeferredMessageUpdate() *ComponentRouterCtx

DeferredMessageUpdate sets the response type to DeferredMessageUpdate For components, ACK an interaction and edit the original message later; the user does not see a loading state

func (*ComponentRouterCtx) Ephemeral

func (c *ComponentRouterCtx) Ephemeral() T

Ephemeral is used to set the response as ephemeral.

func (*ComponentRouterCtx) SetAllowedMentions

func (c *ComponentRouterCtx) SetAllowedMentions(config *objects.AllowedMentions) T

SetAllowedMentions is used to set the allowed mentions of a response. This will override your global configuration.

func (*ComponentRouterCtx) SetComponentRows

func (c *ComponentRouterCtx) SetComponentRows(rows [][]*objects.Component) T

SetComponentRows is used to set rows of components.

func (*ComponentRouterCtx) SetContent

func (c *ComponentRouterCtx) SetContent(content string) T

SetContent is used to set the content of a response.

func (*ComponentRouterCtx) SetContentf added in v0.1.0

func (c *ComponentRouterCtx) SetContentf(content string, args ...any) T

SetContentf is used to set the content of a response using fmt.Sprintf.

func (*ComponentRouterCtx) SetEmbed

func (c *ComponentRouterCtx) SetEmbed(embed *objects.Embed) T

SetEmbed is used to set the embed, overwriting any previously.

func (*ComponentRouterCtx) SetTTS

func (c *ComponentRouterCtx) SetTTS(tts bool) T

SetTTS is used to set the TTS configuration for your response.

func (*ComponentRouterCtx) UpdateLater

UpdateLater is used to spawn the function specified in a goroutine. When the function is returned, the result is set as a message update.

func (*ComponentRouterCtx) UpdateMessage

func (c *ComponentRouterCtx) UpdateMessage() *ComponentRouterCtx

UpdateMessage sets the response type to UpdateMessage For components, edit the message the component was attached to

func (*ComponentRouterCtx) VoidCustomID

func (g *ComponentRouterCtx) VoidCustomID() string

VoidCustomID is used to return a unique custom ID for this context that resolves to a void.

func (*ComponentRouterCtx) WithModalPath added in v0.1.4

func (c *ComponentRouterCtx) WithModalPath(path string) error

WithModalPath is used to set the response to the modal path specified.

type DoubleAutoCompleteFunc added in v0.0.2

type DoubleAutoCompleteFunc = func(*CommandRouterCtx) ([]DoubleChoice, error)

DoubleAutoCompleteFunc is used to define the auto-complete function for DoubleChoice. Note that the command context is a special case in that the response is not used.

type DoubleChoice

type DoubleChoice struct {
	// Name is the name of the choice.
	Name string `json:"name"`

	// Value is the double that is the resulting value.
	Value float64 `json:"value"`
}

DoubleChoice is used to define a choice of the double type.

type DoubleChoiceBuilder added in v0.0.2

type DoubleChoiceBuilder = func(addStaticOptions func([]DoubleChoice), addAutocomplete func(DoubleAutoCompleteFunc))

DoubleChoiceBuilder is used to choose how this choice is handled. This can be nil, or it can pass to one of the functions. The first function adds static choices to the router. The second option adds an autocomplete function. Note that you cannot call both functions.

func DoubleAutoCompleteFuncBuilder added in v0.0.2

func DoubleAutoCompleteFuncBuilder(f DoubleAutoCompleteFunc) DoubleChoiceBuilder

DoubleAutoCompleteFuncBuilder is used to create a shorthand for adding a auto-complete function.

func DoubleStaticChoicesBuilder added in v0.0.2

func DoubleStaticChoicesBuilder(choices []DoubleChoice) DoubleChoiceBuilder

DoubleStaticChoicesBuilder is used to create a shorthand for adding choices.

type ErrorHandler added in v0.1.0

type ErrorHandler = func(error) *objects.InteractionResponse

ErrorHandler defines the error handler function used within Postcord.

type HandlerAccepter

type HandlerAccepter interface {
	ComponentHandler(handler interactions.HandlerFunc)
	CommandHandler(handler interactions.HandlerFunc)
	AutocompleteHandler(handler interactions.HandlerFunc)
	ModalHandler(handler interactions.HandlerFunc)
	Rest() *rest.Client
}

HandlerAccepter is an interface for an object which accepts Postcord handler functions. In most cases, you probably want to pass through *interactions.App here.

type IntAutoCompleteFunc added in v0.0.2

type IntAutoCompleteFunc = func(*CommandRouterCtx) ([]IntChoice, error)

IntAutoCompleteFunc is used to define the auto-complete function for IntChoice. Note that the command context is a special case in that the response is not used.

type IntChoice

type IntChoice struct {
	// Name is the name of the choice.
	Name string `json:"name"`

	// Value is the int that is the resulting value.
	Value int `json:"value"`
}

IntChoice is used to define a choice of the int type.

type IntChoiceBuilder added in v0.0.2

type IntChoiceBuilder = func(addStaticOptions func([]IntChoice), addAutocomplete func(IntAutoCompleteFunc))

IntChoiceBuilder is used to choose how this choice is handled. This can be nil, or it can pass to one of the functions. The first function adds static choices to the router. The second option adds an autocomplete function. Note that you cannot call both functions.

func IntAutoCompleteFuncBuilder added in v0.0.2

func IntAutoCompleteFuncBuilder(f IntAutoCompleteFunc) IntChoiceBuilder

IntAutoCompleteFuncBuilder is used to create a shorthand for adding a auto-complete function.

func IntStaticChoicesBuilder added in v0.0.2

func IntStaticChoicesBuilder(choices []IntChoice) IntChoiceBuilder

IntStaticChoicesBuilder is used to create a shorthand for adding choices.

type LoaderBuilder

type LoaderBuilder interface {
	// ComponentRouter is used to add a component router to the load process.
	ComponentRouter(*ComponentRouter) LoaderBuilder

	// CommandRouter is used to add a command router to the load process.
	CommandRouter(*CommandRouter) LoaderBuilder

	// ModalRouter is used to add a modal router to the load process.
	ModalRouter(*ModalRouter) LoaderBuilder

	// CombinedRouter is used to add a combined router to the load process.
	CombinedRouter(*CombinedRouter) LoaderBuilder

	// ErrorHandler is used to add an error handler to the load process.
	ErrorHandler(ErrorHandler) LoaderBuilder

	// AllowedMentions allows you to set a global allowed mentions configuration.
	AllowedMentions(*objects.AllowedMentions) LoaderBuilder

	// Build is used to execute the build.
	Build(app HandlerAccepter) LoaderBuilder

	// CurrentChain is used to get the current chain of items. Note that for obvious reasons, this is not chainable.
	// Used internally by Postcord for our testing mechanism.
	CurrentChain() (componentRouter *ComponentRouter, commandRouter *CommandRouter, modalRouter *ModalRouter, errHandler ErrorHandler, restClient rest.RESTClient, allowedMentions *objects.AllowedMentions)
}

LoaderBuilder is the interface for a router loader builder.

func RouterLoader

func RouterLoader() LoaderBuilder

RouterLoader is used to create a new router loader builder.

type MessageCommandBuilder

type MessageCommandBuilder interface {
	// DefaultPermissions is used to set the default command permissions for this command.
	DefaultPermissions(permissions.PermissionBit) MessageCommandBuilder

	// GuildCommand is used to forbid this from running in DMs.
	GuildCommand() MessageCommandBuilder

	// AllowedMentions is used to set a command level rule on allowed mentions. If this is not nil, it overrides the last configuration.
	AllowedMentions(*objects.AllowedMentions) MessageCommandBuilder

	// Handler is used to add a command handler.
	Handler(func(*CommandRouterCtx, *objects.Message) error) MessageCommandBuilder

	// Build is used to build the command and insert it into the command router.
	Build() (*Command, error)

	// MustBuild is used to define when a command must build or panic.
	MustBuild() *Command
}

MessageCommandBuilder is used to define a builder for a Message object where the type is a user command.

type MiddlewareCtx

type MiddlewareCtx struct {
	// Defines the command context.
	*CommandRouterCtx
	// contains filtered or unexported fields
}

MiddlewareCtx is used to define the additional context that is shared between middleware.

func (MiddlewareCtx) AddComponentRow added in v0.2.0

func (c MiddlewareCtx) AddComponentRow(row []*objects.Component) T

AddComponentRow is used to add a row of components.

func (MiddlewareCtx) AddEmbed added in v0.2.0

func (c MiddlewareCtx) AddEmbed(embed *objects.Embed) T

AddEmbed is used to append the embed, joining any previously.

func (MiddlewareCtx) AttachBytes added in v0.2.0

func (c MiddlewareCtx) AttachBytes(data []byte, filename, description string) T

AttachBytes adds a file attachment to the response from a byte array

func (MiddlewareCtx) AttachFile added in v0.2.0

func (c MiddlewareCtx) AttachFile(file *objects.DiscordFile) T

AttachFile adds a file attachment to the response from an *objects.DiscordFile

func (MiddlewareCtx) ChannelMessageWithSource added in v0.2.0

func (c MiddlewareCtx) ChannelMessageWithSource() T

ChannelMessageWithSource is used to respond to the interaction with a message.

func (MiddlewareCtx) ClearComponents added in v0.2.0

func (c MiddlewareCtx) ClearComponents() T

ClearComponents is used to clear the components in a response.

func (MiddlewareCtx) Ephemeral added in v0.2.0

func (c MiddlewareCtx) Ephemeral() T

Ephemeral is used to set the response as ephemeral.

func (MiddlewareCtx) Next

func (m MiddlewareCtx) Next() error

Next is used to call the next function in the middleware chain.

func (MiddlewareCtx) SetAllowedMentions added in v0.2.0

func (c MiddlewareCtx) SetAllowedMentions(config *objects.AllowedMentions) T

SetAllowedMentions is used to set the allowed mentions of a response. This will override your global configuration.

func (MiddlewareCtx) SetComponentRows added in v0.2.0

func (c MiddlewareCtx) SetComponentRows(rows [][]*objects.Component) T

SetComponentRows is used to set rows of components.

func (MiddlewareCtx) SetContent added in v0.2.0

func (c MiddlewareCtx) SetContent(content string) T

SetContent is used to set the content of a response.

func (MiddlewareCtx) SetContentf added in v0.2.0

func (c MiddlewareCtx) SetContentf(content string, args ...any) T

SetContentf is used to set the content of a response using fmt.Sprintf.

func (MiddlewareCtx) SetEmbed added in v0.2.0

func (c MiddlewareCtx) SetEmbed(embed *objects.Embed) T

SetEmbed is used to set the embed, overwriting any previously.

func (MiddlewareCtx) SetTTS added in v0.2.0

func (c MiddlewareCtx) SetTTS(tts bool) T

SetTTS is used to set the TTS configuration for your response.

func (MiddlewareCtx) VoidCustomID

func (g MiddlewareCtx) VoidCustomID() string

VoidCustomID is used to return a unique custom ID for this context that resolves to a void.

type MiddlewareFunc

type MiddlewareFunc func(ctx MiddlewareCtx) error

MiddlewareFunc is used to define a middleware function.

type ModalContent added in v0.1.4

type ModalContent struct {
	// Path is used to define the path to the modal.
	Path string `json:"path"`

	// Contents is used to define the contents of the modal.
	Contents func(*ModalGenerationCtx) (name string, contents []ModalContentItem) `json:"-"`

	// Function is the function that will be called when the modal is executed.
	Function func(*ModalRouterCtx) error `json:"-"`
}

ModalContent defines the content of the modal.

type ModalContentItem added in v0.1.4

type ModalContentItem struct {
	// Short defines if the content of the modal is short text.
	Short bool `json:"short"`

	// Label is used to define the label of the item.
	Label string `json:"label"`

	// Key is used to define the key in the map.
	Key string `json:"key"`

	// Placeholder is used to define the placeholder for the input.
	// If this is blank, there will be no placeholder.
	Placeholder string `json:"placeholder"`

	// Value defines what the field should be pre-filled with.
	Value string `json:"value"`

	// Required defines if the content is required.
	Required bool `json:"required"`

	// MinLength defines the minimum length of the content.
	MinLength uint `json:"min_length"`

	// MaxLength defines the maximum length of the content.
	MaxLength uint `json:"max_length"`
}

ModalContentItem is used to define a item in a modal.

type ModalGenerationCtx added in v0.1.4

type ModalGenerationCtx struct {
	// Defines the interaction which started this.
	*objects.Interaction

	// Path is used to define the path of the modal.
	Path string `json:"path"`
}

ModalGenerationCtx is used to generate a modal.

type ModalRouter added in v0.1.4

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

ModalRouter is used to route modals.

func (*ModalRouter) AddModal added in v0.1.4

func (f *ModalRouter) AddModal(modal *ModalContent)

AddModal is used to add a modal to the router.

func (*ModalRouter) SendModalResponse added in v0.1.4

func (f *ModalRouter) SendModalResponse(ctx ResponseDataBuilder, path string) error

SendModalResponse is used to send the modal response with the given context. The passed through context is expected to be one of a valid Postcord type. The router will need to be built before you can use this function.

type ModalRouterCtx added in v0.1.4

type ModalRouterCtx struct {

	// Context is a context.Context passed from the HTTP handler.
	Context context.Context

	// Defines the interaction which started this.
	*objects.Interaction

	// Params is used to define any URL parameters.
	Params map[string]string `json:"params"`

	// ModalItems is used to define the modal items.
	ModalItems map[string]string `json:"modal_items"`

	// RESTClient is used to define the REST client.
	RESTClient rest.RESTClient `json:"rest_client"`
	// contains filtered or unexported fields
}

ModalRouterCtx is used to define the context for the modal event.

func (*ModalRouterCtx) AddComponentRow added in v0.1.4

func (c *ModalRouterCtx) AddComponentRow(row []*objects.Component) T

AddComponentRow is used to add a row of components.

func (*ModalRouterCtx) AddEmbed added in v0.1.4

func (c *ModalRouterCtx) AddEmbed(embed *objects.Embed) T

AddEmbed is used to append the embed, joining any previously.

func (*ModalRouterCtx) AttachBytes added in v0.1.4

func (c *ModalRouterCtx) AttachBytes(data []byte, filename, description string) T

AttachBytes adds a file attachment to the response from a byte array

func (*ModalRouterCtx) AttachFile added in v0.1.4

func (c *ModalRouterCtx) AttachFile(file *objects.DiscordFile) T

AttachFile adds a file attachment to the response from an *objects.DiscordFile

func (*ModalRouterCtx) ChannelMessageWithSource added in v0.1.4

func (c *ModalRouterCtx) ChannelMessageWithSource() T

ChannelMessageWithSource is used to respond to the interaction with a message.

func (*ModalRouterCtx) ClearComponents added in v0.1.4

func (c *ModalRouterCtx) ClearComponents() T

ClearComponents is used to clear the components in a response.

func (*ModalRouterCtx) DeferredChannelMessageWithSource added in v0.1.4

func (c *ModalRouterCtx) DeferredChannelMessageWithSource(f func(*ModalRouterCtx) error)

DeferredChannelMessageWithSource is used to handle updating the response later. The user sees a loading state. Note that the chain does not continue after this since it is impossible to attach additional data.

func (*ModalRouterCtx) Ephemeral added in v0.1.4

func (c *ModalRouterCtx) Ephemeral() T

Ephemeral is used to set the response as ephemeral.

func (*ModalRouterCtx) SetAllowedMentions added in v0.1.4

func (c *ModalRouterCtx) SetAllowedMentions(config *objects.AllowedMentions) T

SetAllowedMentions is used to set the allowed mentions of a response. This will override your global configuration.

func (*ModalRouterCtx) SetComponentRows added in v0.1.4

func (c *ModalRouterCtx) SetComponentRows(rows [][]*objects.Component) T

SetComponentRows is used to set rows of components.

func (*ModalRouterCtx) SetContent added in v0.1.4

func (c *ModalRouterCtx) SetContent(content string) T

SetContent is used to set the content of a response.

func (*ModalRouterCtx) SetContentf added in v0.1.4

func (c *ModalRouterCtx) SetContentf(content string, args ...any) T

SetContentf is used to set the content of a response using fmt.Sprintf.

func (*ModalRouterCtx) SetEmbed added in v0.1.4

func (c *ModalRouterCtx) SetEmbed(embed *objects.Embed) T

SetEmbed is used to set the embed, overwriting any previously.

func (*ModalRouterCtx) SetTTS added in v0.1.4

func (c *ModalRouterCtx) SetTTS(tts bool) T

SetTTS is used to set the TTS configuration for your response.

func (*ModalRouterCtx) UpdateLater added in v0.1.4

func (c *ModalRouterCtx) UpdateLater(f func(*ModalRouterCtx) error) *ModalRouterCtx

UpdateLater is used to spawn the function specified in a goroutine. When the function is returned, the result is set as a message update.

func (*ModalRouterCtx) VoidCustomID added in v0.1.4

func (g *ModalRouterCtx) VoidCustomID() string

VoidCustomID is used to return a unique custom ID for this context that resolves to a void.

type Resolvable added in v0.2.0

type Resolvable[T any] interface {
	// Snowflake is used to return the ID as a snowflake.
	Snowflake() objects.Snowflake

	// MarshalJSON implements the json.Marshaler interface.
	MarshalJSON() ([]byte, error)

	// String is used to return the ID as a string.
	String() string

	// RawData exposes the underlying data.
	RawData() *objects.ApplicationCommandInteractionData

	// Resolve is used to attempt to resolve the item to its type. Returns nil if it doesn't exist.
	Resolve() *T
}

Resolvable is the type which is used for all resolvable items.

type ResolvableAttachment added in v0.1.4

type ResolvableAttachment Resolvable[objects.Attachment]

ResolvableAttachment is used to define an attachment in a command option that is potentially resolvable.

type ResolvableChannel

type ResolvableChannel Resolvable[objects.Channel]

ResolvableChannel is used to define a channel in a command option that is potentially resolvable.

type ResolvableMentionable

type ResolvableMentionable interface {
	// Snowflake is used to return the ID as a snowflake.
	Snowflake() objects.Snowflake

	// MarshalJSON implements the json.Marshaler interface.
	MarshalJSON() ([]byte, error)

	// String is used to return the ID as a string.
	String() string

	// RawData exposes the underlying data.
	RawData() *objects.ApplicationCommandInteractionData

	// Resolve is used to try and resolve the ID into an any type. Nil is returned if it wasn't resolved, or a *objects.<type> if it was.
	Resolve() any
}

ResolvableMentionable is a special type that *mostly* implements the Resolvable interface but does not return a pointer for resolve.

type ResolvableMessage

type ResolvableMessage Resolvable[objects.Message]

ResolvableMessage is used to define a message in a command option that is potentially resolvable.

type ResolvableRole

type ResolvableRole Resolvable[objects.Role]

ResolvableRole is used to define a role in a command option that is potentially resolvable.

type ResolvableUser

type ResolvableUser interface {
	Resolvable[objects.User]

	// ResolveMember is used to attempt to resolve the item to a member. Returns nil if not a member.
	ResolveMember() *objects.GuildMember
}

ResolvableUser is used to define a user in a command option that is potentially resolvable.

type ResponseDataBuilder added in v0.1.4

type ResponseDataBuilder interface {
	ResponseData() *objects.InteractionApplicationCommandCallbackData
}

ResponseDataBuilder is used to

type SelectMenuFunc

type SelectMenuFunc func(ctx *ComponentRouterCtx, values []string) error

SelectMenuFunc is the function dispatched when a select menu is used.

type StringAutoCompleteFunc added in v0.0.2

type StringAutoCompleteFunc = func(*CommandRouterCtx) ([]StringChoice, error)

StringAutoCompleteFunc is used to define the auto-complete function for StringChoice. Note that the command context is a special case in that the response is not used.

type StringChoice

type StringChoice struct {
	// Name is the name of the choice.
	Name string `json:"name"`

	// Value is the string that is the resulting value.
	Value string `json:"value"`
}

StringChoice is used to define a choice of the string type.

type StringChoiceBuilder added in v0.0.2

type StringChoiceBuilder = func(addStaticOptions func([]StringChoice), addAutocomplete func(StringAutoCompleteFunc))

StringChoiceBuilder is used to choose how this choice is handled. This can be nil, or it can pass to one of the functions. The first function adds static choices to the router. The second option adds an autocomplete function. Note that you cannot call both functions.

func StringAutoCompleteFuncBuilder added in v0.0.2

func StringAutoCompleteFuncBuilder(f StringAutoCompleteFunc) StringChoiceBuilder

StringAutoCompleteFuncBuilder is used to create a shorthand for adding a auto-complete function.

func StringStaticChoicesBuilder added in v0.0.2

func StringStaticChoicesBuilder(choices []StringChoice) StringChoiceBuilder

StringStaticChoicesBuilder is used to create a shorthand for adding choices.

type SubCommandBuilder

type SubCommandBuilder interface {

	// Description is used to define the commands description.
	Description(string) SubCommandBuilder

	// AllowedMentions is used to set a command level rule on allowed mentions. If this is not nil, it overrides the last configuration.
	AllowedMentions(*objects.AllowedMentions) SubCommandBuilder

	// Handler is used to add a command handler.
	Handler(func(*CommandRouterCtx) error) SubCommandBuilder

	// Build is used to build the command and insert it into the command router.
	Build() (*Command, error)

	// MustBuild is used to define when a command must build or panic.
	MustBuild() *Command
	// contains filtered or unexported methods
}

SubCommandBuilder is similar to TextCommandBuilder but doesn't allow default permissions to be set.

type TestingT added in v0.1.0

type TestingT interface {
	require.TestingT
	Fatal(args ...any)
	Fatalf(format string, args ...any)
	Log(args ...any)
	Helper()
}

TestingT is our internal requirements from *testing.T. The weird edgecase is Run since the return type can be different.

type TextCommandBuilder

type TextCommandBuilder interface {

	// DefaultPermissions is used to set the default command permissions for this command.
	DefaultPermissions(permissions.PermissionBit) TextCommandBuilder

	// GuildCommand is used to forbid this from running in DMs.
	GuildCommand() TextCommandBuilder

	// Description is used to define the commands description.
	Description(string) TextCommandBuilder

	// AllowedMentions is used to set a command level rule on allowed mentions. If this is not nil, it overrides the last configuration.
	AllowedMentions(*objects.AllowedMentions) TextCommandBuilder

	// Handler is used to add a command handler.
	Handler(func(*CommandRouterCtx) error) TextCommandBuilder

	// Build is used to build the command and insert it into the command router.
	Build() (*Command, error)

	// MustBuild is used to define when a command must build or panic.
	MustBuild() *Command
	// contains filtered or unexported methods
}

TextCommandBuilder is used to define a builder for a Command object where the type is a text command.

type UserCommandBuilder

type UserCommandBuilder interface {
	// DefaultPermissions is used to set the default command permissions for this command.
	DefaultPermissions(permissions.PermissionBit) UserCommandBuilder

	// GuildCommand is used to forbid this from running in DMs.
	GuildCommand() UserCommandBuilder

	// AllowedMentions is used to set a command level rule on allowed mentions. If this is not nil, it overrides the last configuration.
	AllowedMentions(*objects.AllowedMentions) UserCommandBuilder

	// Handler is used to add a command handler.
	Handler(func(*CommandRouterCtx, *objects.GuildMember) error) UserCommandBuilder

	// Build is used to build the command and insert it into the command router.
	Build() (*Command, error)

	// MustBuild is used to define when a command must build or panic.
	MustBuild() *Command
}

UserCommandBuilder is used to define a builder for a Command object where the type is a user command.

Jump to

Keyboard shortcuts

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