customcommands

package
v2.49.1 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2024 License: MIT Imports: 55 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CCActionExecLimitNormal  = 3
	CCActionExecLimitPremium = 5
)
View Source
const (
	MinIntervalTriggerDurationMinutes = 5
	MinIntervalTriggerDurationHours   = 1
	MaxIntervalTriggerDurationHours   = 744
	MaxIntervalTriggerDurationMinutes = 44640
)

Setting it to 1 Month approx

View Source
const (
	ReactionModeBoth       = 0
	ReactionModeAddOnly    = 1
	ReactionModeRemoveOnly = 2
)
View Source
const (
	MaxCommands                 = 100
	MaxCommandsPremium          = 250
	MaxCCResponsesLength        = 10000
	MaxCCResponsesLengthPremium = 20000
	MaxUserMessages             = 20
	MaxGroups                   = 50
)
View Source
const RunCmdCooldownSeconds = 5

Variables

View Source
var (
	CCExecLock        = keylock.NewKeyLock[CCExecKey]()
	DelayedCCRunLimit = multiratelimit.NewMultiRatelimiter(0.1, 10)
	CCMaxDataLimit    = 1000000 // 1 MB max
)
View Source
var DBSchemas = []string{`

CREATE TABLE IF NOT EXISTS custom_command_groups (
	id BIGSERIAL PRIMARY KEY,
	guild_id BIGINT NOT NULL,

	name TEXT NOT NULL,

	ignore_roles BIGINT[],
	ignore_channels BIGINT[],
	whitelist_roles BIGINT[],
	whitelist_channels BIGINT[]
);
`, `
ALTER TABLE custom_command_groups ADD COLUMN IF NOT EXISTS disabled BOOLEAN NOT NULL DEFAULT false;
`, `
CREATE TABLE IF NOT EXISTS custom_commands (
	local_id BIGINT NOT NULL,
	guild_id BIGINT NOT NULL,
	group_id BIGINT references custom_command_groups(id) ON DELETE SET NULL,

	trigger_type INT NOT NULL,
	text_trigger TEXT NOT NULL,
	text_trigger_case_sensitive BOOL NOT NULL,

	time_trigger_interval INT NOT NULL,
	time_trigger_excluding_days SMALLINT[] NOT NULL,
	time_trigger_excluding_hours SMALLINT[] NOT NULL,

	last_run TIMESTAMP WITH TIME ZONE,
	next_run TIMESTAMP WITH TIME ZONE,

	responses TEXT[] NOT NULL,

	channels BIGINT[],
	channels_whitelist_mode BOOL NOT NULL,

	roles BIGINT[],
	roles_whitelist_mode BOOL NOT NULL,
	
	PRIMARY KEY(guild_id, local_id)
);
`, `
CREATE INDEX IF NOT EXISTS custom_commands_guild_idx ON custom_commands(guild_id);
`, `
CREATE INDEX IF NOT EXISTS custom_commands_next_run_idx ON custom_commands(next_run);
`, ` 
ALTER TABLE custom_commands ADD COLUMN IF NOT EXISTS context_channel BIGINT NOT NULL DEFAULT 0;
`, ` 
ALTER TABLE custom_commands ADD COLUMN IF NOT EXISTS redirect_errors_channel BIGINT NOT NULL DEFAULT 0;
`, `
ALTER TABLE custom_commands ADD COLUMN IF NOT EXISTS reaction_trigger_mode SMALLINT NOT NULL DEFAULT 0;
`, `
ALTER TABLE custom_commands ADD COLUMN IF NOT EXISTS last_error TEXT NOT NULL DEFAULT '';
`, `
ALTER TABLE custom_commands ADD COLUMN IF NOT EXISTS last_error_time TIMESTAMP WITH TIME ZONE;
`, `
ALTER TABLE custom_commands ADD COLUMN IF NOT EXISTS run_count INT NOT NULL DEFAULT 0;
`, `
ALTER TABLE custom_commands ADD COLUMN IF NOT EXISTS show_errors BOOLEAN NOT NULL DEFAULT true;
`, `
ALTER TABLE custom_commands ADD COLUMN IF NOT EXISTS disabled BOOLEAN NOT NULL DEFAULT false;
`, `
ALTER TABLE custom_commands ADD COLUMN IF NOT EXISTS trigger_on_edit BOOLEAN NOT NULL DEFAULT false;
`, `
ALTER TABLE custom_commands ADD COLUMN IF NOT EXISTS public_id TEXT NOT NULL DEFAULT '';
`, `
ALTER TABLE custom_commands ADD COLUMN IF NOT EXISTS name TEXT;
`, `
ALTER TABLE custom_commands ADD COLUMN IF NOT EXISTS public BOOLEAN NOT NULL DEFAULT false;
`, `
CREATE INDEX IF NOT EXISTS custom_commands_public_id_idx ON custom_commands(public_id);
`, `
ALTER TABLE custom_commands ADD COLUMN IF NOT EXISTS import_count INT NOT NULL DEFAULT 0;
`, `
CREATE TABLE IF NOT EXISTS templates_user_database (
	id BIGSERIAL PRIMARY KEY,

	created_at TIMESTAMP WITH TIME ZONE NOT NULL,
	updated_at TIMESTAMP WITH TIME ZONE NOT NULL,
	expires_at TIMESTAMP WITH TIME ZONE,

	guild_id BIGINT NOT NULL,
	user_id BIGINT NOT NULL,

	key TEXT NOT NULL,
	value_num DOUBLE PRECISION NOT NULL,
	value_raw BYTEA NOT NULL,

	UNIQUE(guild_id, user_id, key)
);

`, `
CREATE INDEX IF NOT EXISTS templates_user_database_combined_idx ON templates_user_database (guild_id, user_id, key, value_num);
`, `
CREATE INDEX IF NOT EXISTS templates_user_database_expires_idx ON templates_user_database (expires_at);
`}
View Source
var PageHTMLDatabase string
View Source
var PageHTMLEditCmd string
View Source
var PageHTMLMain string
View Source
var PageHTMLPublicCmd string
View Source
var (
	RegexCache = *ccache.New(ccache.Configure())
)

Functions

func BotCachedGetCommandsWithMessageTriggers

func BotCachedGetCommandsWithMessageTriggers(guildID int64, ctx context.Context) ([]*models.CustomCommand, error)

func CCActionExecLimit added in v2.42.0

func CCActionExecLimit(guildID int64) int

func CalcNextRunTime

func CalcNextRunTime(cc *models.CustomCommand, now time.Time) time.Time

CalcNextRunTime calculates the next run time for a custom command using the last ran time

func CheckGuildDBLimit

func CheckGuildDBLimit(gs *dstate.GuildSet) (bool, error)

returns true if were above db limit for the specified guild

func CheckLimits

func CheckLimits(in ...string) bool

func CheckMatch

func CheckMatch(globalPrefix string, cmd *models.CustomCommand, msg string) (match bool, stripped string, args []string)

CheckMatch returns true if the given cmd matches, as well as the arguments following the command trigger (arg 0 being the message up to, and including, the trigger).

func CheckMatchComponent added in v2.39.0

func CheckMatchComponent(cmd *models.CustomCommand, cID string) (match bool, stripped string, args []string)

func CheckMatchModal added in v2.39.0

func CheckMatchModal(cmd *models.CustomCommand, cID string) (match bool, stripped string, args []string)

func CheckMatchReaction

func CheckMatchReaction(cmd *models.CustomCommand, reaction *discordgo.MessageReaction, add bool) (match bool)

func CmdRunsForUser

func CmdRunsForUser(cc *models.CustomCommand, ms *dstate.MemberState) bool

func CmdRunsInChannel

func CmdRunsInChannel(cc *models.CustomCommand, channel int64) bool

func DelNextRunEvent

func DelNextRunEvent(guildID int64, cmdID int64) error

func ExecuteCustomCommand

func ExecuteCustomCommand(cmd *models.CustomCommand, tmplCtx *templates.Context) error

func ExecuteCustomCommand(cmd *models.CustomCommand, cmdArgs []string, stripped string, s *discordgo.Session, m *discordgo.MessageCreate) (resp string, tmplCtx *templates.Context, err error) {

func ExecuteCustomCommandFromComponent added in v2.39.0

func ExecuteCustomCommandFromComponent(cc *models.CustomCommand, gs *dstate.GuildSet, cs *dstate.ChannelState, cmdArgs []string, stripped string, interaction *templates.CustomCommandInteraction) error

func ExecuteCustomCommandFromMessage

func ExecuteCustomCommandFromMessage(gs *dstate.GuildSet, cmd *models.CustomCommand, member *dstate.MemberState, cs *dstate.ChannelState, cmdArgs []string, stripped string, m *discordgo.Message, isEdit bool) error

func ExecuteCustomCommandFromModal added in v2.39.0

func ExecuteCustomCommandFromModal(cc *models.CustomCommand, gs *dstate.GuildSet, cs *dstate.ChannelState, cmdArgs []string, stripped string, interaction *templates.CustomCommandInteraction) error

func ExecuteCustomCommandFromReaction

func ExecuteCustomCommandFromReaction(cc *models.CustomCommand, gs *dstate.GuildSet, ms *dstate.MemberState, cs *dstate.ChannelState, reaction *discordgo.MessageReaction, added bool, message *discordgo.Message) error

func FindCommands

func FindCommands(ccs []*models.CustomCommand, data *dcmd.Data) (foundCCS []*models.CustomCommand, provided bool)

func HandleMessageCreate

func HandleMessageCreate(evt *eventsystem.EventData)

func HandleMessageUpdate added in v2.28.0

func HandleMessageUpdate(evt *eventsystem.EventData)

func KeyCommands

func KeyCommands(guildID int64) string

func MaxCommandsForContext

func MaxCommandsForContext(ctx context.Context) int

func PublicCommandMW added in v2.36.0

func PublicCommandMW(inner http.Handler) http.Handler

func RegisterPlugin

func RegisterPlugin()

func StringCommands

func StringCommands(ccs []*models.CustomCommand, gMap map[int64]string) string

func UpdateCommandNextRunTime

func UpdateCommandNextRunTime(cc *models.CustomCommand, updateLastRun bool, clearOld bool) error

TODO: Run this all in a transaction?

func UpdateImportCount added in v2.36.0

func UpdateImportCount(cmd *models.CustomCommand)

Types

type CCExecKey

type CCExecKey struct {
	GuildID int64
	CCID    int64
}

type CommandTriggerType

type CommandTriggerType int
const (
	CommandTriggerNone CommandTriggerType = 10

	CommandTriggerCommand    CommandTriggerType = 0
	CommandTriggerStartsWith CommandTriggerType = 1
	CommandTriggerContains   CommandTriggerType = 2
	CommandTriggerRegex      CommandTriggerType = 3
	CommandTriggerExact      CommandTriggerType = 4
	CommandTriggerInterval   CommandTriggerType = 5
	CommandTriggerReaction   CommandTriggerType = 6
	CommandTriggerComponent  CommandTriggerType = 7
	CommandTriggerModal      CommandTriggerType = 8
	CommandTriggerCron       CommandTriggerType = 9
)

func (CommandTriggerType) String

func (t CommandTriggerType) String() string

type CustomCommand

type CustomCommand struct {
	TriggerType     CommandTriggerType `json:"trigger_type"`
	TriggerTypeForm string             `json:"-" schema:"type"`
	Trigger         string             `json:"trigger" schema:"trigger" valid:",0,1000"`
	Responses       []string           `json:"responses" schema:"responses" valid:"template,20000"`
	CaseSensitive   bool               `json:"case_sensitive" schema:"case_sensitive"`
	ID              int64              `json:"id"`
	Name            string             `json:"name" schema:"name" valid:",0,100"`
	IsEnabled       bool               `json:"is_enabled" schema:"is_enabled"`
	Public          bool               `json:"public" schema:"public"`
	PublicID        string             `json:"public_id" schema:"public_id"`

	ContextChannel        int64 `schema:"context_channel" valid:"channel,true"`
	RedirectErrorsChannel int64 `schema:"redirect_errors_channel" valid:"channel,true"`

	TimeTriggerInterval       int     `schema:"time_trigger_interval"`
	TimeTriggerExcludingDays  []int64 `schema:"time_trigger_excluding_days"`
	TimeTriggerExcludingHours []int64 `schema:"time_trigger_excluding_hours"`

	ReactionTriggerMode int `schema:"reaction_trigger_mode"`

	// If set, then the following channels are required, otherwise they are ignored
	RequireChannels bool    `json:"require_channels" schema:"require_channels"`
	Channels        []int64 `json:"channels" schema:"channels"`

	// If set, then one of the following channels are required, otherwise they are ignored
	RequireRoles  bool    `json:"require_roles" schema:"require_roles"`
	Roles         []int64 `json:"roles" schema:"roles"`
	TriggerOnEdit bool    `json:"trigger_on_edit" schema:"trigger_on_edit"`

	GroupID int64

	ShowErrors bool `schema:"show_errors"`
}

func (*CustomCommand) ToDBModel

func (cc *CustomCommand) ToDBModel() *models.CustomCommand

func (*CustomCommand) Validate

func (cc *CustomCommand) Validate(tmpl web.TemplateData, guild_id int64) (ok bool)

type CustomCommandSlice

type CustomCommandSlice []*CustomCommand

func (CustomCommandSlice) Len

func (c CustomCommandSlice) Len() int

Len is the number of elements in the collection.

func (CustomCommandSlice) Less

func (c CustomCommandSlice) Less(i, j int) bool

Less reports whether the element with index i should sort before the element with index j.

func (CustomCommandSlice) Swap

func (c CustomCommandSlice) Swap(i, j int)

Swap swaps the elements with indexes i and j.

type DelayedRunCCData

type DelayedRunCCData struct {
	ChannelID int64  `json:"channel_id"`
	CmdID     int64  `json:"cmd_id"`
	UserData  []byte `json:"data"`

	Message *discordgo.Message
	Member  *dstate.MemberState

	UserKey interface{} `json:"user_key"`

	ExecutedFrom templates.ExecutedFromType `json:"executed_from"`
}

type DelayedRunLimitKey

type DelayedRunLimitKey struct {
	GuildID   int64
	ChannelID int64
}

type GroupForm

type GroupForm struct {
	ID                int64
	Name              string  `valid:",100"`
	WhitelistChannels []int64 `valid:"channel,true"`
	BlacklistChannels []int64 `valid:"channel,true"`

	WhitelistRoles []int64 `valid:"role,true"`
	BlacklistRoles []int64 `valid:"role,true"`
	IsEnabled      bool
}

GroupForm is the form bindings used when creating or updating groups

type LightDBEntry

type LightDBEntry struct {
	ID      int64
	GuildID int64
	UserID  int64

	CreatedAt time.Time
	UpdatedAt time.Time

	Key   string
	Value interface{}

	ValueSize int

	User discordgo.User

	ExpiresAt time.Time
}

func ToLightDBEntry

func ToLightDBEntry(m *models.TemplatesUserDatabase) (*LightDBEntry, error)

type NextRunScheduledEvent

type NextRunScheduledEvent struct {
	CmdID int64 `json:"cmd_id"`
}

type ParsedArgs

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

func (*ParsedArgs) Get

func (pa *ParsedArgs) Get(index int) interface{}

func (*ParsedArgs) IsSet

func (pa *ParsedArgs) IsSet(index int) interface{}

type Plugin

type Plugin struct{}

func (*Plugin) AddCommands

func (p *Plugin) AddCommands()

func (*Plugin) AllFeatureFlags

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

func (*Plugin) BotInit

func (p *Plugin) BotInit()

func (*Plugin) InitWeb

func (p *Plugin) InitWeb()

InitWeb implements web.Plugin

func (*Plugin) LoadServerHomeWidget

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

func (*Plugin) OnRemovedPremiumGuild added in v2.17.0

func (p *Plugin) OnRemovedPremiumGuild(GuildID int64) error

func (*Plugin) PluginInfo

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

func (*Plugin) UpdateFeatureFlags

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

type Query

type Query struct {
	UserID  null.Int64  `json:"user_id"`
	Pattern null.String `json:"pattern"`
	Reverse bool        `json:"reverse"`
}

type SearchForm added in v2.32.0

type SearchForm struct {
	Query string
	Type  string
}

type TriggeredCC

type TriggeredCC struct {
	CC       *models.CustomCommand
	Stripped string
	Args     []string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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