templates

package
v2.94.5 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 36 Imported by: 9

Documentation

Index

Constants

View Source
const (
	MaxOpsNormal      = 1000000
	MaxOpsPremium     = 2500000
	MaxOpsEvalNormal  = 200000
	MaxOpsEvalPremium = 500000
	MaxSliceLength    = 10000

	MaxAllocNormal      = 200 << 20
	MaxAllocPremium     = 500 << 20
	MaxAllocEvalNormal  = 40 << 20
	MaxAllocEvalPremium = 100 << 20

	// Runs allocating more than this are logged so the caps above can be tightened from real usage.
	LogAllocAbove = 25 << 20
)
View Source
const DiscordRoleLimit = 250
View Source
const MaxStringLength = 1000000
View Source
const TemplateCustomIDPrefix = "templates-"

Variables

View Source
var (
	ErrTooManyCalls    = errors.New("too many calls to this function")
	ErrFuncOnCooldown  = errors.New("function is on cooldown")
	ErrTooManyAPICalls = errors.New("too many potential Discord API calls")
	ErrRegexCacheLimit = errors.New("too many unique regular expressions (regex)")
)
View Source
var ErrStringTooLong = errors.NewPlain("String is too long (max 1MB)")
View Source
var ErrTooManyInteractionResponses = errors.New("cannot respond to an interaction > 1 time; consider using a followup")
View Source
var ErrValueTooLarge = errors.NewPlain("Value is too large (max 1MB)")
View Source
var GuildPremiumFunc func(guildID int64) (bool, error)

set by the premium package to return wether this guild is premium or not

View Source
var (
	StandardFuncMap = map[string]any{

		"str":        ToString,
		"toString":   ToString,
		"toInt":      tmplToInt,
		"toInt64":    ToInt64,
		"toFloat":    ToFloat64,
		"toDuration": ToDuration,
		"toRune":     ToRune,
		"toByte":     ToByte,

		"hasPrefix":    strings.HasPrefix,
		"hasSuffix":    strings.HasSuffix,
		"joinStr":      joinStrings,
		"lower":        strings.ToLower,
		"slice":        slice,
		"split":        strings.Split,
		"title":        titleCaser.String,
		"trimSpace":    strings.TrimSpace,
		"upper":        strings.ToUpper,
		"urlescape":    url.PathEscape,
		"urlunescape":  url.PathUnescape,
		"print":        withOutputLimit(fmt.Sprint, MaxStringLength),
		"println":      withOutputLimit(fmt.Sprintln, MaxStringLength),
		"printf":       withOutputLimitF(fmt.Sprintf, MaxStringLength),
		"sanitizeText": confusables.SanitizeText,

		"reQuoteMeta": regexp.QuoteMeta,

		"abs":        tmplAbs,
		"add":        add,
		"cbrt":       tmplCbrt,
		"div":        tmplDiv,
		"fdiv":       tmplFDiv,
		"log":        tmplLog,
		"mathConst":  tmplMathConstant,
		"max":        tmplMax,
		"min":        tmplMin,
		"mod":        tmplMod,
		"mult":       tmplMult,
		"pow":        tmplPow,
		"round":      tmplRound,
		"roundCeil":  tmplRoundCeil,
		"roundEven":  tmplRoundEven,
		"roundFloor": tmplRoundFloor,
		"sqrt":       tmplSqrt,
		"sub":        tmplSub,

		"bitwiseAnd":        tmplBitwiseAnd,
		"bitwiseOr":         tmplBitwiseOr,
		"bitwiseXor":        tmplBitwiseXor,
		"bitwiseNot":        tmplBitwiseNot,
		"bitwiseAndNot":     tmplBitwiseAndNot,
		"bitwiseLeftShift":  tmplBitwiseLeftShift,
		"bitwiseRightShift": tmplBitwiseRightShift,

		"componentBuilder": CreateComponentBuilder,
		"modalBuilder":     CreateModalBuilder,
		"cbutton":          CreateButton,
		"cmenu":            CreateSelectMenu,
		"cmodal":           CreateModal,
		"clabel":           CreateLabel,
		"ctextInput":       CreateTextInput,
		"ctextDisplay":     CreateTextDisplay,
		"cradioGroup":      CreateRadioGroup,
		"ccheckboxGroup":   CreateCheckboxGroup,
		"ccheckbox":        CreateCheckbox,

		"cembed":             CreateEmbed,
		"complexMessage":     CreateComplexMessage,
		"complexMessageEdit": CreateComplexMessage,

		"humanizeThousands": tmplHumanizeThousands,
		"dict":              Dictionary,
		"sdict":             StringKeyDictionary,
		"structToSdict":     StructToSdict,

		"cslice": CreateSlice,

		"kindOf": KindOf,

		"adjective":   common.RandomAdjective,
		"in":          in,
		"inFold":      inFold,
		"json":        tmplJson,
		"jsonToSdict": tmplJSONToSDict,
		"noun":        common.RandomNoun,
		"randInt":     randInt,
		"randNorm":    randNorm,
		"roleAbove":   roleIsAbove,
		"seq":         sequence,

		"shuffle": shuffle,
		"verb":    common.RandomVerb,

		"currentTime":     tmplCurrentTime,
		"parseTime":       tmplParseTime,
		"formatTime":      tmplFormatTime,
		"loadLocation":    time.LoadLocation,
		"newDate":         tmplNewDate,
		"snowflakeToTime": tmplSnowflakeToTime,
		"timestampToTime": tmplTimestampToTime,
		"weekNumber":      tmplWeekNumber,

		"humanizeDurationHours":   tmplHumanizeDurationHours,
		"humanizeDurationMinutes": tmplHumanizeDurationMinutes,
		"humanizeDurationSeconds": tmplHumanizeDurationSeconds,
		"humanizeTimeSinceDays":   tmplHumanizeTimeSinceDays,
	}
)

Functions

func CreateButton added in v2.39.0

func CreateButton(values ...any) (*discordgo.Button, error)

func CreateCheckbox added in v2.74.0

func CreateCheckbox(values ...any) (*discordgo.Checkbox, error)

func CreateCheckboxGroup added in v2.74.0

func CreateCheckboxGroup(values ...any) (*discordgo.CheckboxGroup, error)

func CreateComplexMessage added in v2.76.0

func CreateComplexMessage(values ...any) (*discordgo.MessageSend, error)

func CreateComponent added in v2.39.0

func CreateComponent(expectedType discordgo.ComponentType, values ...any) (discordgo.MessageComponent, error)

func CreateComponentArray added in v2.55.0

func CreateComponentArray(msgFiles *[]*discordgo.File, values ...any) ([]discordgo.TopLevelComponent, error)

func CreateContainer added in v2.55.0

func CreateContainer(msgFiles *[]*discordgo.File, values ...any) (*discordgo.Container, error)

func CreateEmbed

func CreateEmbed(values ...any) (*discordgo.MessageEmbed, error)

func CreateFile added in v2.55.0

func CreateFile(msgFiles *[]*discordgo.File, values ...any) (*discordgo.ComponentFile, error)

func CreateGallery added in v2.55.0

func CreateGallery(values any) (*discordgo.MediaGallery, error)

func CreateLabel added in v2.66.0

func CreateLabel(values ...any) (*discordgo.Label, error)

func CreateModal added in v2.39.0

func CreateModal(values ...any) (*discordgo.InteractionResponse, error)

func CreateRadioGroup added in v2.74.0

func CreateRadioGroup(values ...any) (*discordgo.RadioGroup, error)

func CreateSection added in v2.55.0

func CreateSection(values ...any) (*discordgo.Section, error)

func CreateSelectMenu added in v2.39.0

func CreateSelectMenu(values ...any) (*discordgo.SelectMenu, error)

func CreateSeparator added in v2.55.0

func CreateSeparator(large any) *discordgo.Separator

func CreateTextDisplay added in v2.55.0

func CreateTextDisplay(value any) (*discordgo.TextDisplay, error)

func CreateTextInput added in v2.66.0

func CreateTextInput(values ...any) (*discordgo.TextInput, error)

func ExceedsEncodedSize added in v2.90.0

func ExceedsEncodedSize(v any, limit int) bool

ExceedsEncodedSize reports whether json or msgpack encoding v would produce more than limit bytes.

func InitCooldownTracker added in v2.74.5

func InitCooldownTracker()

func KindOf

func KindOf(input any, flag ...bool) (string, error)

func LimitWriter

func LimitWriter(w io.Writer, n int64) io.Writer

LimitWriter works like io.LimitReader. It writes at most n bytes to the underlying Writer. It returns io.ErrShortWrite if more than n bytes are attempted to be written, unless those bytes are exclusively whitespace, in which case it will not write them and return without error. It will not write leading whitespace.

func MaybeScheduledDeleteMessage

func MaybeScheduledDeleteMessage(guildID, channelID, messageID int64, delaySeconds int, token string)

func RegisterSetupFunc

func RegisterSetupFunc(f ContextSetupFunc)

func TargetUserID added in v2.24.0

func TargetUserID(input any) int64

func ToByte

func ToByte(from any) []byte

func ToDuration

func ToDuration(from any) time.Duration

func ToFloat64

func ToFloat64(from any) float64

func ToInt64

func ToInt64(from any, base ...int) int64

func ToRune

func ToRune(from any) []rune

func ToString

func ToString(from any) string

Types

type ComponentBuilder added in v2.55.0

type ComponentBuilder struct {
	Components []string
	Values     []any
}

func CreateComponentBuilder added in v2.55.0

func CreateComponentBuilder(values ...any) (compBuilder *ComponentBuilder, err error)

CreateComponentBuilder parses given input of key-value pairs but returns the keys and the values as separate slices. this is used when you need to have duplicate keys and therefore cannot use a map.

func (*ComponentBuilder) Add added in v2.55.0

func (s *ComponentBuilder) Add(key string, value any) (any, error)

func (*ComponentBuilder) AddSlice added in v2.55.0

func (s *ComponentBuilder) AddSlice(key string, slice any) (any, error)

func (*ComponentBuilder) DecodeMsgpack added in v2.89.0

func (s *ComponentBuilder) DecodeMsgpack(dec *msgpack.Decoder) error

func (*ComponentBuilder) EncodeMsgpack added in v2.89.0

func (s *ComponentBuilder) EncodeMsgpack(enc *msgpack.Encoder) error

func (*ComponentBuilder) Get added in v2.55.0

func (s *ComponentBuilder) Get(key string) (result []any)

func (*ComponentBuilder) Merge added in v2.55.0

func (s *ComponentBuilder) Merge(toMerge *ComponentBuilder) (any, error)

func (*ComponentBuilder) ToComplexMessage added in v2.59.0

func (s *ComponentBuilder) ToComplexMessage() (*discordgo.MessageSend, error)

func (*ComponentBuilder) ToComplexMessageEdit added in v2.59.0

func (s *ComponentBuilder) ToComplexMessageEdit() (*discordgo.MessageEdit, error)

type Context

type Context struct {
	Name string

	GS      *dstate.GuildSet
	MS      *dstate.MemberState
	Msg     *discordgo.Message
	BotUser *discordgo.User

	DisabledContextFuncs []string
	ContextFuncs         map[string]any
	Data                 map[string]any
	Counters             map[string]int

	FixedOutput string

	IsPremium bool

	RegexCache map[string]*regexp.Regexp

	CurrentFrame *ContextFrame

	ExecutedFrom ExecutedFromType
	// contains filtered or unexported fields
}

func NewContext

func NewContext(gs *dstate.GuildSet, cs *dstate.ChannelState, ms *dstate.MemberState) *Context

func (*Context) ChannelArg

func (c *Context) ChannelArg(v any) int64

ChannelArg converts a variety of types of argument into a channel, verifying that it exists

func (*Context) ChannelArgNoDM

func (c *Context) ChannelArgNoDM(v any) int64

ChannelArgNoDM is the same as ChannelArg but will not accept DM channels

func (*Context) ChannelArgNoDMNoThread

func (c *Context) ChannelArgNoDMNoThread(v any) int64

func (*Context) Execute

func (c *Context) Execute(source string) (string, error)

func (*Context) ExecuteAndSendWithErrors

func (c *Context) ExecuteAndSendWithErrors(source string, channelID int64) error

func (*Context) FindRole added in v2.39.0

func (c *Context) FindRole(role any, accept roleInputType) *discordgo.Role

FindRole tries to resolve the argument to a role. `accept` specifies the set of allowed input types, tested in the following order: ID, role mention, role name, role object.

func (*Context) IncreaseCheckCallCounter

func (c *Context) IncreaseCheckCallCounter(key string, limit int) bool

IncreaseCheckCallCounter Returns true if key is above the limit

func (*Context) IncreaseCheckCallCounterPremium

func (c *Context) IncreaseCheckCallCounterPremium(key string, normalLimit, premiumLimit int) bool

IncreaseCheckCallCounter Returns true if key is above the limit

func (*Context) IncreaseCheckGenericAPICall

func (c *Context) IncreaseCheckGenericAPICall() bool

func (*Context) LogEntry

func (c *Context) LogEntry() *logrus.Entry

func (*Context) MessageSend

func (c *Context) MessageSend(content string) *discordgo.MessageSend

func (*Context) Parse

func (c *Context) Parse(source string) (*template.Template, error)

func (*Context) SendResponse

func (c *Context) SendResponse(content string) (m *discordgo.Message, err error)

SendResponse sends the response and handles reactions and the like

func (*Context) SetCooldown added in v2.74.5

func (c *Context) SetCooldown(key string, duration time.Duration) bool

SetCooldown Sets a cooldown for a key, returns true if the key is already on cooldown

type ContextFrame added in v2.4.0

type ContextFrame struct {
	CS *dstate.ChannelState `json:"cs"`

	MentionEveryone bool    `json:"mention_everyone"`
	MentionHere     bool    `json:"mention_here"`
	MentionRoles    []int64 `json:"mention_roles"`

	DelResponse       bool `json:"del_response"`
	PublishResponse   bool `json:"publish_response"`
	EphemeralResponse bool `json:"ephemeral_response"`

	DelResponseDelay         int                           `json:"del_response_delay"`
	EmbedsToSend             []*discordgo.MessageEmbed     `json:"embeds_to_send"`
	ComponentsToSend         []discordgo.TopLevelComponent `json:"components_to_send"`
	AddResponseReactionNames []string                      `json:"add_response_reaction_names"`

	IsNestedTemplate bool `json:"is_nested_template"`

	SendResponseInDM bool `json:"send_response_in_dm"`

	Interaction *CustomCommandInteraction `json:"interaction"`
	// contains filtered or unexported fields
}

type ContextSetupFunc

type ContextSetupFunc func(ctx *Context)

type CtxChannel

type CtxChannel struct {
	// These fields never change
	ID        int64
	GuildID   int64
	IsPrivate bool
	IsThread  bool
	IsForum   bool

	Name                 string                           `json:"name"`
	Type                 discordgo.ChannelType            `json:"type"`
	Topic                string                           `json:"topic"`
	NSFW                 bool                             `json:"nsfw"`
	Position             int                              `json:"position"`
	Bitrate              int                              `json:"bitrate"`
	PermissionOverwrites []*discordgo.PermissionOverwrite `json:"permission_overwrites"`
	ParentID             int64                            `json:"parent_id"`
	OwnerID              int64                            `json:"owner_id"`

	AvailableTags  []discordgo.ForumTag      `json:"available_tags"`
	AppliedTags    []int64                   `json:"applied_tags"`
	Flags          discordgo.ChannelFlags    `json:"flags"`
	ThreadMetadata *discordgo.ThreadMetadata `json:"thread_metadata,omitempty"`
}

CtxChannel is almost a 1:1 copy of dstate.ChannelState, its needed because we cant axpose all those state methods we also cant use discordgo.Channel because that would likely break a lot of custom commands at this point.

func CtxChannelFromCS

func CtxChannelFromCS(cs *dstate.ChannelState) *CtxChannel

func (*CtxChannel) Mention

func (c *CtxChannel) Mention() (string, error)

type CustomCommandInteraction added in v2.39.0

type CustomCommandInteraction struct {
	*discordgo.Interaction `json:"interaction"`
	RespondedTo            bool `json:"responded_to"`
	Deferred               bool `json:"deferred"`
}

func (*CustomCommandInteraction) UnmarshalJSON added in v2.76.0

func (c *CustomCommandInteraction) UnmarshalJSON(data []byte) error

type Dict

type Dict map[any]any

func Dictionary

func Dictionary(values ...any) (Dict, error)

dictionary creates a map[string]interface{} from the given parameters by walking the parameters and treating them as key-value pairs. The number of parameters must be even.

func (Dict) Del

func (d Dict) Del(key any) string

func (Dict) Get

func (d Dict) Get(key any) any

func (Dict) HasKey

func (d Dict) HasKey(k any) (ok bool)

func (Dict) MarshalJSON

func (d Dict) MarshalJSON() ([]byte, error)

func (Dict) Set

func (d Dict) Set(key any, value any) (string, error)

type ExecutedFromType added in v2.30.0

type ExecutedFromType int

Defines where a template was executed from to enable certain restrictions

const (
	ExecutedFromStandard              ExecutedFromType = 0
	ExecutedFromJoin                  ExecutedFromType = 1
	ExecutedFromLeave                 ExecutedFromType = 2
	ExecutedFromEvalCC                ExecutedFromType = 3
	ExecutedFromCommandTemplate       ExecutedFromType = 4
	ExecutedFromNestedCommandTemplate ExecutedFromType = 5
)

type ModalBuilder added in v2.66.0

type ModalBuilder struct {
	Title      string
	CustomID   string
	Components []discordgo.TopLevelComponent
}

func CreateModalBuilder added in v2.66.0

func CreateModalBuilder(customID string, title string, components ...any) (*ModalBuilder, error)

func (*ModalBuilder) AddComponents added in v2.66.0

func (s *ModalBuilder) AddComponents(comps ...any) (*ModalBuilder, error)

func (*ModalBuilder) Set added in v2.66.2

func (s *ModalBuilder) Set(key string, value any) (*ModalBuilder, error)

type SDict

type SDict map[string]any

func StringKeyDictionary

func StringKeyDictionary(values ...any) (SDict, error)

func StructToSdict

func StructToSdict(value any) (SDict, error)

func (SDict) Del

func (d SDict) Del(key string) string

func (SDict) Get

func (d SDict) Get(key string) any

func (SDict) HasKey

func (d SDict) HasKey(k string) (ok bool)

func (SDict) Set

func (d SDict) Set(key string, value any) (string, error)

type Slice

type Slice []any

func CreateSlice

func CreateSlice(values ...any) (Slice, error)

func (Slice) Append

func (s Slice) Append(item any) (any, error)

func (Slice) AppendSlice

func (s Slice) AppendSlice(slice any) (any, error)

func (Slice) Set

func (s Slice) Set(index int, item any) (string, error)

func (Slice) StringSlice

func (s Slice) StringSlice(flag ...bool) any

type TemplateCooldowns added in v2.74.5

type TemplateCooldowns struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func (*TemplateCooldowns) Set added in v2.74.5

func (tc *TemplateCooldowns) Set(key string, duration time.Duration) bool

func (*TemplateCooldowns) Tick added in v2.74.5

func (tc *TemplateCooldowns) Tick()

Jump to

Keyboard shortcuts

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