commands

package
v1.24.17 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2020 License: MIT Imports: 36 Imported by: 0

README

The commands plugin handles the configuration of the global command settings.

Documentation

Index

Constants

View Source
const (
	ReasonError                    = "An error occured"
	ReasonCommandDisabaledSettings = "Command is disabled in the settings"
	ReasonMissingRole              = "Missing a required role for this command"
	ReasonIgnoredRole              = "Has a ignored role for this command"
	ReasonUserMissingPerms         = "User is missing one or more permissions to run this command"
	ReasonCooldown                 = "This command is on cooldown"
)

Variables

View Source
var (
	CategoryGeneral = &dcmd.Category{
		Name:        "General",
		Description: "General & informational commands",
		HelpEmoji:   "ℹ️",
		EmbedColor:  0xe53939,
	}
	CategoryTool = &dcmd.Category{
		Name:        "Tools & Utilities",
		Description: "Various miscellaneous commands",
		HelpEmoji:   "🔨",
		EmbedColor:  0xeaed40,
	}
	CategoryModeration = &dcmd.Category{
		Name:        "Moderation",
		Description: "Moderation commands",
		HelpEmoji:   "👮",
		EmbedColor:  0xdb0606,
	}
	CategoryFun = &dcmd.Category{
		Name:        "Fun",
		Description: "Various commands meant for entertainment",
		HelpEmoji:   "🎉",
		EmbedColor:  0x5ae26c,
	}
	CategoryDebug = &dcmd.Category{
		Name:        "Debug & Maintenance",
		Description: "Debug and other commands to inspect the bot",
		HelpEmoji:   "🖥",
		EmbedColor:  0,
	}
)
View Source
var (
	RKeyCommandCooldown      = func(uID int64, cmd string) string { return "cmd_cd:" + discordgo.StrID(uID) + ":" + cmd }
	RKeyCommandCooldownGuild = func(gID int64, cmd string) string { return "cmd_guild_cd:" + discordgo.StrID(gID) + ":" + cmd }
	RKeyCommandLock          = func(uID int64, cmd string) string { return "cmd_lock:" + discordgo.StrID(uID) + ":" + cmd }

	CommandExecTimeout = time.Minute
)
View Source
var (
	CommandSystem *dcmd.System
)
View Source
var DBSchemas = []string{`
CREATE TABLE IF NOT EXISTS commands_channels_overrides (
	id BIGSERIAL PRIMARY KEY,
	guild_id BIGINT NOT NULL,

	channels BIGINT[],
	channel_categories BIGINT[],
	global bool NOT NULL,

	commands_enabled BOOL NOT NULL,

	autodelete_response BOOL NOT NULL,
	autodelete_trigger BOOL NOT NULL,

	autodelete_response_delay INT NOT NULL,
	autodelete_trigger_delay INT NOT NULL,

	require_roles BIGINT[] NOT NULL,
	ignore_roles BIGINT[] NOT NULL
);
`, `
CREATE INDEX IF NOT EXISTS commands_channels_overrides_guild_idx ON commands_channels_overrides(guild_id);
`, `
CREATE UNIQUE INDEX IF NOT EXISTS commands_channels_overrides_global_uniquex ON commands_channels_overrides (guild_id) WHERE global;
`, `
CREATE TABLE IF NOT EXISTS commands_command_overrides (
	id BIGSERIAL PRIMARY KEY,
	guild_id BIGINT NOT NULL,
	commands_channels_overrides_id BIGINT references commands_channels_overrides(id) ON DELETE CASCADE NOT NULL,
	
	commands TEXT[] NOT NULL,

	commands_enabled BOOL NOT NULL,

	autodelete_response BOOL NOT NULL,
	autodelete_trigger BOOL NOT NULL,

	autodelete_response_delay INT NOT NULL,
	autodelete_trigger_delay INT NOT NULL,

	require_roles BIGINT[] NOT NULL,
	ignore_roles BIGINT[] NOT NULL
);
`, `
CREATE INDEX IF NOT EXISTS commands_command_groups_channels_override_idx ON commands_command_overrides(commands_channels_overrides_id);
`}
View Source
var MessageFilterFuncs []MessageFilterFunc

These functions are called on every message, and should return true if the message should be checked for commands, false otherwise

Functions

func AddRootCommands

func AddRootCommands(p common.Plugin, cmds ...*YAGCommand)

func AddRootCommandsWithMiddlewares added in v1.19.0

func AddRootCommandsWithMiddlewares(p common.Plugin, middlewares []dcmd.MiddleWareFunc, cmds ...*YAGCommand)

func BlockingAddRunningCommand added in v1.17.2

func BlockingAddRunningCommand(guildID int64, channelID int64, authorID int64, cmd *YAGCommand, timeout time.Duration) bool

func CensorError

func CensorError(err error) string

Keys and other sensitive information shouldnt be sent in error messages, but just in case it is

func ChannelOverrideMiddleware added in v1.4.1

func ChannelOverrideMiddleware(inner func(w http.ResponseWriter, r *http.Request, override *models.CommandsChannelsOverride) (web.TemplateData, error)) web.ControllerHandlerFunc

Channel override handlers

func CmdNotFound

func CmdNotFound(search string) string

func CommonContainerNotFoundHandler added in v1.13.0

func CommonContainerNotFoundHandler(container *dcmd.Container, fixedMessage string) func(data *dcmd.Data) (interface{}, error)

CommonContainerNotFoundHandler is a common "NotFound" handler that should be used with dcmd containers it ensures that no messages is sent if none of the commands in te container is enabeld if "fixedMessage" is empty, then it shows default generated container help

func FilterBadInvites added in v1.5.2

func FilterBadInvites(msg string, guildID int64, replacement string) string

func FilterResp added in v1.6.0

func FilterResp(in interface{}, guildID int64) interface{}

func GetCommandPrefixBotEvt added in v1.24.17

func GetCommandPrefixBotEvt(evt *eventsystem.EventData) (string, error)

func GetCommandPrefixRedis added in v1.24.17

func GetCommandPrefixRedis(guild int64) (string, error)

func GetOverridesForChannel added in v1.13.0

func GetOverridesForChannel(channelID, channelParentID, guildID int64) ([]*models.CommandsChannelsOverride, error)

func HandleCommands

func HandleCommands(w http.ResponseWriter, r *http.Request) (web.TemplateData, error)

Servers the command page with current config

func HandleCreateChannelsOverride added in v1.4.1

func HandleCreateChannelsOverride(w http.ResponseWriter, r *http.Request) (web.TemplateData, error)

func HandleCreateCommandOverride added in v1.4.1

func HandleCreateCommandOverride(w http.ResponseWriter, r *http.Request, channelOverride *models.CommandsChannelsOverride) (web.TemplateData, error)

Command handlers

func HandleDeleteChannelsOverride added in v1.4.1

func HandleDeleteChannelsOverride(w http.ResponseWriter, r *http.Request, currentOverride *models.CommandsChannelsOverride) (web.TemplateData, error)

func HandleDeleteCommandOverride added in v1.4.1

func HandleDeleteCommandOverride(w http.ResponseWriter, r *http.Request, channelOverride *models.CommandsChannelsOverride) (web.TemplateData, error)

func HandleGuildCreate

func HandleGuildCreate(evt *eventsystem.EventData)

func HandlePostCommands

func HandlePostCommands(w http.ResponseWriter, r *http.Request) (web.TemplateData, error)

Handles the updating of global and per channel command settings

func HandleUpdateChannelsOverride added in v1.4.1

func HandleUpdateChannelsOverride(w http.ResponseWriter, r *http.Request, currentOverride *models.CommandsChannelsOverride) (web.TemplateData, error)

func HandleUpdateCommandOVerride added in v1.4.1

func HandleUpdateCommandOVerride(w http.ResponseWriter, r *http.Request, channelOverride *models.CommandsChannelsOverride) (web.TemplateData, error)

func InitCommands added in v1.4.1

func InitCommands()

func NewUserError added in v1.22.2

func NewUserError(a ...interface{}) error

func NewUserErrorf added in v1.22.2

func NewUserErrorf(f string, a ...interface{}) error

func ParseDuration

func ParseDuration(str string) (time.Duration, error)

Parses a time string like 1day3h

func RegisterPlugin

func RegisterPlugin()

func TmplExecCmdFuncs

func TmplExecCmdFuncs(ctx *templates.Context, maxExec int, dryRun bool) (userCtxCommandExec cmdExecFunc, botCtxCommandExec cmdExecFunc)

Returns 2 functions to execute commands in user or bot context with limited about of commands executed

func YAGCommandMiddleware added in v1.4.1

func YAGCommandMiddleware(inner dcmd.RunFunc) dcmd.RunFunc

Types

type ChannelOverrideForm added in v1.4.1

type ChannelOverrideForm struct {
	Channels                []int64 `valid:"channel,true`
	ChannelCategories       []int64 `valid:"channel,true`
	Global                  bool
	CommandsEnabled         bool
	AutodeleteResponse      bool
	AutodeleteTrigger       bool
	AutodeleteResponseDelay int
	AutodeleteTriggerDelay  int
	RequireRoles            []int64 `valid:"role,true"`
	IgnoreRoles             []int64 `valid:"role,true"`
}

type CommandOverrideForm added in v1.4.1

type CommandOverrideForm struct {
	Commands                []string
	CommandsEnabled         bool
	AutodeleteResponse      bool
	AutodeleteTrigger       bool
	AutodeleteResponseDelay int
	AutodeleteTriggerDelay  int
	RequireRoles            []int64 `valid:"role,true"`
	IgnoreRoles             []int64 `valid:"role,true"`
}

type CommandProvider added in v1.4.1

type CommandProvider interface {
	// This is where you should register your commands, called on both the webserver and the bot
	AddCommands()
}

type CommandSettings added in v1.4.1

type CommandSettings struct {
	Enabled bool

	DelTrigger       bool
	DelResponse      bool
	DelTriggerDelay  int
	DelResponseDelay int

	RequiredRoles []int64
	IgnoreRoles   []int64
}

type ContextKey

type ContextKey int
const (
	CtxKeyRedisClient ContextKey = iota
)

type CtxKey added in v1.4.1

type CtxKey int
const (
	CtxKeyCmdSettings CtxKey = iota
	CtxKeyChannelOverride
)

type DurationArg

type DurationArg struct {
	Min, Max time.Duration
}

func (*DurationArg) HelpName

func (d *DurationArg) HelpName() string

func (*DurationArg) Matches

func (d *DurationArg) Matches(def *dcmd.ArgDef, part string) bool

func (*DurationArg) Parse

func (d *DurationArg) Parse(def *dcmd.ArgDef, part string, data *dcmd.Data) (interface{}, error)

type DurationOutOfRangeError added in v1.5.1

type DurationOutOfRangeError struct {
	Min, Max time.Duration
	Got      time.Duration
	ArgName  string
}

func (*DurationOutOfRangeError) Error added in v1.5.1

func (o *DurationOutOfRangeError) Error() string

type MemberArg added in v1.17.0

type MemberArg struct{}

MemberArg matches a id or mention and returns a MemberState object for the user

func (*MemberArg) ExtractID added in v1.17.0

func (ma *MemberArg) ExtractID(part string, data *dcmd.Data) int64

func (*MemberArg) HelpName added in v1.17.0

func (ma *MemberArg) HelpName() string

func (*MemberArg) Matches added in v1.17.0

func (ma *MemberArg) Matches(def *dcmd.ArgDef, part string) bool

func (*MemberArg) Parse added in v1.17.0

func (ma *MemberArg) Parse(def *dcmd.ArgDef, part string, data *dcmd.Data) (interface{}, error)

type MessageFilterFunc added in v1.4.8

type MessageFilterFunc func(evt *eventsystem.EventData, msg *discordgo.Message) bool

type Plugin

type Plugin struct{}

func (*Plugin) AllFeatureFlags added in v1.24.11

func (p *Plugin) AllFeatureFlags() []string

func (*Plugin) BotInit added in v1.4.1

func (p *Plugin) BotInit()

func (*Plugin) InitWeb

func (p *Plugin) InitWeb()

func (*Plugin) LoadServerHomeWidget added in v1.17.0

func (p *Plugin) LoadServerHomeWidget(w http.ResponseWriter, r *http.Request) (web.TemplateData, error)

func (*Plugin) PluginInfo added in v1.17.0

func (p *Plugin) PluginInfo() *common.PluginInfo

func (*Plugin) Prefix

func (p *Plugin) Prefix(data *dcmd.Data) string

func (*Plugin) StopBot added in v1.17.2

func (p *Plugin) StopBot(wg *sync.WaitGroup)

func (*Plugin) UpdateFeatureFlags added in v1.24.11

func (p *Plugin) UpdateFeatureFlags(guildID int64) ([]string, error)

type PublicError added in v1.5.1

type PublicError string

PublicError is a error that is both logged and returned as a response

func NewPublicError added in v1.5.1

func NewPublicError(a ...interface{}) PublicError

func NewPublicErrorF added in v1.5.1

func NewPublicErrorF(f string, a ...interface{}) PublicError

func (PublicError) Error added in v1.5.1

func (p PublicError) Error() string

type RunningCommand added in v1.17.2

type RunningCommand struct {
	GuildID   int64
	ChannelID int64
	AuthorID  int64

	Command *YAGCommand
}

type UserError added in v1.22.2

type UserError string

UserError is a special error type that is only sent as a response, and not logged

func (UserError) Error added in v1.22.2

func (ue UserError) Error() string

func (UserError) IsUserError added in v1.22.2

func (ue UserError) IsUserError() bool

type YAGCommand

type YAGCommand struct {
	Name            string   // Name of command, what its called from
	Aliases         []string // Aliases which it can also be called from
	Description     string   // Description shown in non targetted help
	LongDescription string   // Longer description when this command was targetted

	Arguments      []*dcmd.ArgDef // Slice of argument definitions, ctx.Args will always be the same size as this slice (although the data may be nil)
	RequiredArgs   int            // Number of reuquired arguments, ignored if combos is specified
	ArgumentCombos [][]int        // Slice of argument pairs, will override RequiredArgs if specified
	ArgSwitches    []*dcmd.ArgDef // Switches for the commadn to use

	AllowEveryoneMention bool

	HideFromCommandsPage bool   // Set to  hide this command from the commands page
	Key                  string // GuildId is appended to the key, e.g if key is "test:", it will check for "test:<guildid>"
	CustomEnabled        bool   // Set to true to handle the enable check itself
	Default              bool   // The default enabled state of this command

	Cooldown           int // Cooldown in seconds before user can use it again
	CmdCategory        *dcmd.Category
	GuildScopeCooldown int

	RunInDM      bool // Set to enable this commmand in DM's
	HideFromHelp bool // Set to hide from help

	RequireDiscordPerms []int64 // Require users to have one of these permission sets to run the command

	Middlewares []dcmd.MiddleWareFunc

	// Run is ran the the command has sucessfully been parsed
	// It returns a reply and an error
	// the reply can have a type of string, *MessageEmbed or error
	RunFunc dcmd.RunFunc

	Plugin common.Plugin
}

Slight extension to the simplecommand, it will check if the command is enabled in the HandleCommand func And invoke a custom handlerfunc with provided redis client

func (*YAGCommand) ArgDefs

func (yc *YAGCommand) ArgDefs(data *dcmd.Data) (args []*dcmd.ArgDef, required int, combos [][]int)

func (*YAGCommand) Category

func (yc *YAGCommand) Category() *dcmd.Category

CmdWithCategory puts the command in a category, mostly used for the help generation

func (*YAGCommand) Descriptions

func (yc *YAGCommand) Descriptions(data *dcmd.Data) (short, long string)

func (*YAGCommand) FindNameFromContainerChain added in v1.20.17

func (yc *YAGCommand) FindNameFromContainerChain(cc []*dcmd.Container) string

func (*YAGCommand) GetSettings added in v1.4.1

func (cs *YAGCommand) GetSettings(containerChain []*dcmd.Container, channelID, channelParentID, guildID int64) (settings *CommandSettings, err error)

GetSettings returns the settings from the command, generated from the servers channel and command overrides

func (*YAGCommand) GetSettingsWithLoadedOverrides added in v1.13.0

func (cs *YAGCommand) GetSettingsWithLoadedOverrides(containerChain []*dcmd.Container, guildID int64, channelOverrides []*models.CommandsChannelsOverride) (settings *CommandSettings, err error)

func (*YAGCommand) GetTrigger

func (yc *YAGCommand) GetTrigger() *dcmd.Trigger

func (*YAGCommand) GuildScopeCooldownLeft added in v1.20.17

func (cs *YAGCommand) GuildScopeCooldownLeft(cc []*dcmd.Container, guildID int64) (int, error)

GuildScopeCooldownLeft returns the number of seconds before a command can be used again on this server

func (*YAGCommand) Logger

func (yc *YAGCommand) Logger(data *dcmd.Data) *logrus.Entry

func (*YAGCommand) LongestCooldownLeft added in v1.20.17

func (cs *YAGCommand) LongestCooldownLeft(cc []*dcmd.Container, userID int64, guildID int64) (int, error)

LongestCooldownLeft returns the longest cooldown for this command, either user scoped or guild scoped

func (*YAGCommand) PostCommandExecuted added in v1.4.1

func (yc *YAGCommand) PostCommandExecuted(settings *CommandSettings, cmdData *dcmd.Data, resp interface{}, err error)

PostCommandExecuted sends the response and handles the trigger and response deletions

func (*YAGCommand) Run

func (yc *YAGCommand) Run(data *dcmd.Data) (interface{}, error)

func (*YAGCommand) SetCooldownGuild added in v1.20.17

func (cs *YAGCommand) SetCooldownGuild(cc []*dcmd.Container, guildID int64) error

SetCooldownGuild sets the guild scoped cooldown of the command as it's defined in the struct

func (*YAGCommand) SetCooldownUser added in v1.20.17

func (cs *YAGCommand) SetCooldownUser(cc []*dcmd.Container, userID int64) error

SetCooldownUser sets the user scoped cooldown of the command as it's defined in the struct

func (*YAGCommand) SetCooldowns added in v1.20.17

func (cs *YAGCommand) SetCooldowns(cc []*dcmd.Container, userID int64, guildID int64) error

SetCooldowns is a helper that serts both User and Guild cooldown

func (*YAGCommand) Switches

func (yc *YAGCommand) Switches() []*dcmd.ArgDef

func (*YAGCommand) UserScopeCooldownLeft added in v1.20.17

func (cs *YAGCommand) UserScopeCooldownLeft(cc []*dcmd.Container, userID int64) (int, error)

UserScopeCooldownLeft returns the number of seconds before a command can be used again by this user

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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