crouter

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2021 License: BSD-3-Clause Imports: 10 Imported by: 0

README

crouter

Go Reference

A simple command handler for discordgo.

Usage

import "github.com/Starshine113/crouter"

// ... session initialisation code ...

// create the router
r := crouter.NewRouter(dg, []string{botOwner}, []string{"?", "!"})

// add the message create handler
dg.AddHandler(r.MessageCreate)

// add a command
r.AddCommand(&crouter.Command{
    Name: "Ping",

    Summary: "Check if the bot is running",

    Command: func(ctx *crouter.Ctx) (err error) {
        ping := ctx.Session.HeartbeatLatency().Round(time.Millisecond)
        _, err = ctx.Sendf("Ping! Average latency: %s", ping)
        return err
    },
})

// add intents (or just add crouter.RequiredIntents to your existing intents)
dg.Identify.Intents = discordgo.MakeIntent(crouter.RequiredIntents)

// open the session
err = dg.Open()

// ...

A more complete example can be found in the example/ directory.

Documentation

Overview

Package crouter provides a simple command handler for discordgo

Index

Constants

View Source
const (
	// SuccessEmoji is the emoji used to designate a successful action
	SuccessEmoji = "✅"
	// ErrorEmoji is the emoji used for errors
	ErrorEmoji = "❌"
	// WarnEmoji is the emoji used to warn that a command failed
	WarnEmoji = "⚠️"
)

RequiredIntents are the intents required for the router

Variables

View Source
var (
	ErrorNotEnoughArgs = errors.New("not enough arguments")
	ErrorTooManyArgs   = errors.New("too many arguments")
)

Errors

View Source
var (
	// ErrorUnknownType is returned when an unknown type argument is passed to Send
	ErrorUnknownType = errors.New("unknown type for ctx.Send")
	// ErrBotMissingPerms is returned when the bot is missing permissions required to send a message
	ErrBotMissingPerms = errors.New("bot is missing permissions")
)
View Source
var (
	ErrMemberNotFound  = errors.New("member not found")
	ErrChannelNotFound = errors.New("channel not found")
	ErrRoleNotFound    = errors.New("role not found")
	ErrNoID            = errors.New("input is not an ID")
	ErrBrokenMention   = errors.New("input is a broken/invalid mention")
)

Errors for parsing

View Source
var (
	ErrorNoDMs           = errors.New("this command cannot be run in DMs")
	ErrorMissingPerms    = errors.New("you are missing required permissions")
	ErrorMissingBotOwner = errors.New("you are not a bot owner")
)

Errors relating to missing permissions

View Source
var (
	ErrorNoBotUser = errors.New("bot user not found in state cache")
)

Errors when creating Context

Functions

func HasAnyPrefix

func HasAnyPrefix(s string, prefixes ...string) bool

HasAnyPrefix checks if the string has *any* of the given prefixes

func HasAnySuffix

func HasAnySuffix(s string, suffixes ...string) bool

HasAnySuffix checks if the string has *any* of the given suffixes

func PermToString

func PermToString(p int) string

PermToString turns a discordgo permission constant into a string

func PrettyDurationString

func PrettyDurationString(duration time.Duration) (out string)

PrettyDurationString turns a duration into a string representation (maximum of days)

func SprintfAll

func SprintfAll(template string, in []string) []string

SprintfAll takes a slice of strings and uses them as input for Sprintf, returning a slice of strings

func TrimPrefixesSpace

func TrimPrefixesSpace(s string, prefixes ...string) string

TrimPrefixesSpace trims all given prefixes as well as whitespace from the given string

func Version added in v0.5.1

func Version() string

Version returns the current crouter version

Types

type Command

type Command struct {
	Name    string
	Aliases []string
	Regex   *regexp.Regexp

	// Blacklistable commands use the router's blacklist function to check if they can be run
	Blacklistable bool

	// Summary is used in the command list
	Summary string
	// Description is used in the help command
	Description string
	// Usage is appended to the command name in help commands
	Usage string

	// Command is the actual command function
	Command func(*Ctx) error

	Permissions int

	CustomPermissions []func(*Ctx) (string, bool)

	GuildOnly bool
	OwnerOnly bool
	Cooldown  time.Duration

	Router *Router
}

Command is a single command

type Ctx

type Ctx struct {
	Command string
	Args    []string
	RawArgs string

	Session *discordgo.Session
	BotUser *discordgo.User

	Message *discordgo.MessageCreate
	Channel *discordgo.Channel
	Author  *discordgo.User

	Cmd    *Command
	Router *Router

	AdditionalParams map[string]interface{}
}

Ctx is the context for a command

func (*Ctx) AddMessageHandler added in v0.4.0

func (ctx *Ctx) AddMessageHandler(messageID string, f func(ctx *Ctx, m *discordgo.MessageCreate)) func()

AddMessageHandler adds a listener for a message from a specific user

func (*Ctx) AddReactionHandler

func (ctx *Ctx) AddReactionHandler(messageID, reaction string, f func(ctx *Ctx)) func()

AddReactionHandler adds a reaction handler function

func (*Ctx) AddReactionHandlerOnce

func (ctx *Ctx) AddReactionHandlerOnce(messageID, reaction string, f func(ctx *Ctx)) func()

AddReactionHandlerOnce adds a reaction handler function that is only called once

func (*Ctx) AddYesNoHandler

func (ctx *Ctx) AddYesNoHandler(messageID string, yesFunc, noFunc func(ctx *Ctx)) func()

AddYesNoHandler reacts with ✅ and ❌, and runs one of two functions depending on which one is used

func (*Ctx) Check

func (ctx *Ctx) Check() (err error)

Check checks if the user has permissions to run a command

func (*Ctx) CheckArgRange

func (ctx *Ctx) CheckArgRange(min, max int) (err error)

CheckArgRange checks if the number of arguments is within the given range

func (*Ctx) CheckMinArgs

func (ctx *Ctx) CheckMinArgs(c int) (err error)

CheckMinArgs checks if the argument count is less than the given count

func (*Ctx) CheckRequiredArgs

func (ctx *Ctx) CheckRequiredArgs(c int) (err error)

CheckRequiredArgs checks if the arg count is exactly the given count

func (*Ctx) CommandError

func (ctx *Ctx) CommandError(err error) error

CommandError sends an error message and optionally returns an error for logging purposes

func (*Ctx) Edit

func (ctx *Ctx) Edit(message *discordgo.Message, arg interface{}) (msg *discordgo.Message, err error)

Edit edits a message

func (*Ctx) EditEmbedf

func (ctx *Ctx) EditEmbedf(message *discordgo.Message, title, format string, args ...interface{}) (msg *discordgo.Message, err error)

EditEmbedf edits an embed with Embedf syntax

func (*Ctx) Editf

func (ctx *Ctx) Editf(message *discordgo.Message, format string, args ...interface{}) (msg *discordgo.Message, err error)

Editf edits a message with Sendf-like syntax

func (*Ctx) Embed

func (ctx *Ctx) Embed(title, description string, color int) (msg *discordgo.Message, err error)

Embed sends the input as an embed

func (*Ctx) EmbedAddXHandler

func (ctx *Ctx) EmbedAddXHandler(title, description string, color int) (msg *discordgo.Message, err error)

EmbedAddXHandler sends an embed, adding a handler for :x:

func (*Ctx) Embedf

func (ctx *Ctx) Embedf(title, format string, args ...interface{}) (msg *discordgo.Message, err error)

Embedf sends a fmt.Sprintf-like input string, in an embed

func (*Ctx) EmbedfAddXHandler

func (ctx *Ctx) EmbedfAddXHandler(title, format string, args ...interface{}) (msg *discordgo.Message, err error)

EmbedfAddXHandler wraps Embedf and adds an :x: handler

func (*Ctx) Match

func (ctx *Ctx) Match(cmds ...string) bool

Match checks if any of the given command aliases match

func (*Ctx) MatchPrefix

func (ctx *Ctx) MatchPrefix() bool

MatchPrefix checks if the message matched any prefix

func (*Ctx) MatchRegexp

func (ctx *Ctx) MatchRegexp(re *regexp.Regexp) bool

MatchRegexp checks if the command matches the given regex

func (*Ctx) PagedEmbed

func (ctx *Ctx) PagedEmbed(embeds []*discordgo.MessageEmbed) (msg *discordgo.Message, err error)

PagedEmbed sends a slice of embeds, and attaches reaction handlers to flip through them.

func (*Ctx) ParseChannel added in v0.2.0

func (ctx *Ctx) ParseChannel(channel string) (*discordgo.Channel, error)

ParseChannel takes a string and attempts to find a channel that matches that string

func (*Ctx) ParseMember added in v0.2.0

func (ctx *Ctx) ParseMember(member string) (*discordgo.Member, error)

ParseMember takes a string and attempts to find a member that matches that string

func (*Ctx) ParseRole added in v0.2.0

func (ctx *Ctx) ParseRole(role string) (*discordgo.Role, error)

ParseRole takes a string and attempts to find a role that matches that string

func (*Ctx) ParseUser added in v0.2.0

func (ctx *Ctx) ParseUser(user string) (*discordgo.User, error)

ParseUser parses a user

func (*Ctx) React

func (ctx *Ctx) React(emoji string) (err error)

React reacts to the triggering message

func (*Ctx) Send

func (ctx *Ctx) Send(arg interface{}) (message *discordgo.Message, err error)

Send sends a message to the channel the command was invoked in

func (*Ctx) SendAddXHandler

func (ctx *Ctx) SendAddXHandler(arg interface{}) (message *discordgo.Message, err error)

SendAddXHandler wraps around Send, adding a handler for :x: that deletes the response

func (*Ctx) Sendf

func (ctx *Ctx) Sendf(format string, args ...interface{}) (msg *discordgo.Message, err error)

Sendf sends a fmt.Sprintf-like input string

func (*Ctx) SendfAddXHandler

func (ctx *Ctx) SendfAddXHandler(format string, args ...interface{}) (msg *discordgo.Message, err error)

SendfAddXHandler adds a handler for :x:

func (*Ctx) TriggerTyping

func (ctx *Ctx) TriggerTyping() (err error)

TriggerTyping triggers typing in the channel the command was invoked in

type Group

type Group struct {
	Name        string
	Aliases     []string
	Regex       *regexp.Regexp
	Description string
	Command     *Command
	Subcommands []*Command
	Router      *Router
	Cooldowns   *ttlcache.Cache
}

Group is a group of subcommands

func (*Group) AddCommand

func (g *Group) AddCommand(cmd *Command)

AddCommand adds a command to a group

func (*Group) GetCommand

func (g *Group) GetCommand(name string) (c *Command)

GetCommand gets a command by name

type PermCache added in v0.7.0

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

PermCache is a cache of channel permissions. Expires after 2 minutes by default, other timeouts can be set by using the SetTimeout() function

func NewPermCache added in v0.7.0

func NewPermCache(s *discordgo.Session) *PermCache

NewPermCache returns a new initialised permission cache

func (*PermCache) Get added in v0.7.0

func (p *PermCache) Get(user, channel string) (perms int, err error)

Get gets the permissions in a channel

func (*PermCache) HasPermissions added in v0.7.0

func (p *PermCache) HasPermissions(user, channel string, required int) bool

HasPermissions checks if the user has the given permissions. If Get() returns an error, the user is assumed to not have the permissions.

type Router

type Router struct {
	Commands []*Command
	Groups   []*Group

	BotOwners []string
	Prefixes  []string

	Session *discordgo.Session

	Cooldowns *ttlcache.Cache
	Handlers  *ttlcache.Cache

	// PostFunc is called when a command completes
	PostFunc func(*Ctx)

	PermCache *PermCache
	// contains filtered or unexported fields
}

Router is the command router

func NewRouter

func NewRouter(s *discordgo.Session, owners, prefixes []string) *Router

NewRouter creates a Router object

func (*Router) AddCommand

func (r *Router) AddCommand(cmd *Command)

AddCommand adds a command to the router

func (*Router) AddGroup

func (r *Router) AddGroup(group *Group) *Group

AddGroup adds a group to the router

func (*Router) Blacklist added in v0.5.0

func (r *Router) Blacklist(f func(*Ctx) bool)

Blacklist sets the router's blacklist function

func (*Router) Context

func (r *Router) Context(m *discordgo.MessageCreate) (ctx *Ctx, err error)

Context creates a new Ctx

func (*Router) Execute

func (r *Router) Execute(ctx *Ctx) (err error)

Execute actually executes the router. You shouldn't have to use this most of the time, as the (*Router).MessageCreate function calls this, but if you want more control over what happens, you probably want to call this yourself.

func (*Router) GetCommand

func (r *Router) GetCommand(name string) (c *Command)

GetCommand gets a command by name

func (*Router) GetGroup

func (r *Router) GetGroup(name string) (group *Group)

GetGroup returns a group by name

func (*Router) Help

func (r *Router) Help(ctx *Ctx) (err error)

Help is the help command

func (*Router) MessageCreate

func (r *Router) MessageCreate(s *discordgo.Session, m *discordgo.MessageCreate)

MessageCreate handles message create events. If you want more control over what happens when the event is received, you can instead call the (*Router).Context() and (*Router).Execute() functions manually.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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