templates

package
v0.0.0-...-be61b19 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2025 License: MIT Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MaxOpsNormal      = 1000000
	MaxOpsPremium     = 2500000
	MaxOpsEvalNormal  = 200000
	MaxOpsEvalPremium = 500000
)
View Source
const DiscordRoleLimit = 250
View Source
const MaxStringLength = 1000000

Variables

View Source
var (
	ErrTooManyCalls    = errors.New("too many calls to this function")
	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 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]interface{}{

		"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":        strings.Title,
		"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,

		"humanizeThousands":  tmplHumanizeThousands,
		"dict":               Dictionary,
		"sdict":              StringKeyDictionary,
		"structToSdict":      StructToSdict,
		"componentBuilder":   CreateComponentBuilder,
		"cembed":             CreateEmbed,
		"cbutton":            CreateButton,
		"cmenu":              CreateSelectMenu,
		"cmodal":             CreateModal,
		"cslice":             CreateSlice,
		"complexMessage":     CreateMessageSend,
		"complexMessageEdit": CreateMessageEdit,
		"kindOf":             KindOf,

		"adjective":   common.RandomAdjective,
		"in":          in,
		"inFold":      inFold,
		"json":        tmplJson,
		"jsonToSdict": tmplJSONToSDict,
		"noun":        common.RandomNoun,
		"randInt":     randInt,
		"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

func CreateButton(values ...interface{}) (*discordgo.Button, error)

func CreateComponent

func CreateComponent(expectedType discordgo.ComponentType, values ...interface{}) (discordgo.MessageComponent, error)

func CreateComponentArray

func CreateComponentArray(msgFiles *[]*discordgo.File, values ...interface{}) ([]discordgo.TopLevelComponent, error)

func CreateContainer

func CreateContainer(msgFiles *[]*discordgo.File, values ...interface{}) (*discordgo.Container, error)

func CreateEmbed

func CreateEmbed(values ...interface{}) (*discordgo.MessageEmbed, error)

func CreateFile

func CreateFile(msgFiles *[]*discordgo.File, values ...interface{}) (*discordgo.ComponentFile, error)

func CreateGallery

func CreateGallery(values ...interface{}) (*discordgo.MediaGallery, error)

func CreateMessageEdit

func CreateMessageEdit(values ...interface{}) (*discordgo.MessageEdit, error)

func CreateMessageSend

func CreateMessageSend(values ...interface{}) (*discordgo.MessageSend, error)

func CreateModal

func CreateModal(values ...interface{}) (*discordgo.InteractionResponse, error)

func CreateSection

func CreateSection(values ...interface{}) (*discordgo.Section, error)

func CreateSelectMenu

func CreateSelectMenu(values ...interface{}) (*discordgo.SelectMenu, error)

func CreateSeparator

func CreateSeparator(large interface{}) *discordgo.Separator

func CreateTextDisplay

func CreateTextDisplay(value interface{}) (*discordgo.TextDisplay, error)

func KindOf

func KindOf(input interface{}, 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

func TargetUserID(input interface{}) int64

func ToByte

func ToByte(from interface{}) []byte

func ToDuration

func ToDuration(from interface{}) time.Duration

func ToFloat64

func ToFloat64(from interface{}) float64

func ToInt64

func ToInt64(from interface{}) int64

func ToRune

func ToRune(from interface{}) []rune

func ToString

func ToString(from interface{}) string

Types

type ComponentBuilder

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

func CreateComponentBuilder

func CreateComponentBuilder(values ...interface{}) (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

func (s *ComponentBuilder) Add(key string, value interface{}) (interface{}, error)

func (*ComponentBuilder) AddSlice

func (s *ComponentBuilder) AddSlice(key string, slice interface{}) (interface{}, error)

func (*ComponentBuilder) Get

func (s *ComponentBuilder) Get(key string) (result []interface{})

func (*ComponentBuilder) Merge

func (s *ComponentBuilder) Merge(toMerge *ComponentBuilder) (interface{}, 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]interface{}
	Data                 map[string]interface{}
	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 interface{}) int64

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

func (*Context) ChannelArgNoDM

func (c *Context) ChannelArgNoDM(v interface{}) int64

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

func (*Context) ChannelArgNoDMNoThread

func (c *Context) ChannelArgNoDMNoThread(v interface{}) 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

func (c *Context) FindRole(role interface{}, 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

type ContextFrame

type ContextFrame struct {
	CS *dstate.ChannelState

	MentionEveryone bool
	MentionHere     bool
	MentionRoles    []int64

	DelResponse       bool
	PublishResponse   bool
	EphemeralResponse bool

	DelResponseDelay         int
	EmbedsToSend             []*discordgo.MessageEmbed
	ComponentsToSend         []discordgo.TopLevelComponent
	AddResponseReactionNames []string

	SendResponseInDM bool

	Interaction *CustomCommandInteraction
	// 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

type CustomCommandInteraction struct {
	*discordgo.Interaction
	RespondedTo bool
	Deferred    bool
}

type Dict

type Dict map[interface{}]interface{}

func Dictionary

func Dictionary(values ...interface{}) (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 interface{}) string

func (Dict) Get

func (d Dict) Get(key interface{}) interface{}

func (Dict) HasKey

func (d Dict) HasKey(k interface{}) (ok bool)

func (Dict) MarshalJSON

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

func (Dict) Set

func (d Dict) Set(key interface{}, value interface{}) (string, error)

type ExecutedFromType

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 SDict

type SDict map[string]interface{}

func StringKeyDictionary

func StringKeyDictionary(values ...interface{}) (SDict, error)

func StructToSdict

func StructToSdict(value interface{}) (SDict, error)

func (SDict) Del

func (d SDict) Del(key string) string

func (SDict) Get

func (d SDict) Get(key string) interface{}

func (SDict) HasKey

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

func (SDict) Set

func (d SDict) Set(key string, value interface{}) (string, error)

type Slice

type Slice []interface{}

func CreateSlice

func CreateSlice(values ...interface{}) (Slice, error)

func (Slice) Append

func (s Slice) Append(item interface{}) (interface{}, error)

func (Slice) AppendSlice

func (s Slice) AppendSlice(slice interface{}) (interface{}, error)

func (Slice) Set

func (s Slice) Set(index int, item interface{}) (string, error)

func (Slice) StringSlice

func (s Slice) StringSlice(flag ...bool) interface{}

Jump to

Keyboard shortcuts

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