Functions
Functions are underappreciated. In general, not just in templates. // Rob Pike

Channel

Function
Description
editChannelName channel "newName"
Function edits channel's name. channel can be either ID, "name" or even nil if triggered in that channel name change is intended to happen. "newName" has to be of type string. For example >{{editChannelName nil (joinStr "" "YAG - " (randInt 1000))}}
editChannelTopic channel "newTopic"
Function edits channel's topic/description. channel can be either ID, "name" or nil if triggered in that channel where name change is intended to happen. "newTopic" has to be of type string. For example >
{{editChannelTopic nil "YAG is cool"}}
getChannel channel
Function returns full channel object of given channel argument which can be either its ID, name or nil for triggering channel, and is of type *dstate.ChannelState. For example > {{(getChannel nil).Name}} returns the name of the channel command was triggered in.
getChannelOrThread channel
Returns type*templates.CtxChannel corresponding to Channel object.
getPinCount channel
Returns the count of pinned messages in given channel which can be either its ID, name or nil for triggering channel. Can be called 2 times for regular and 4 for premium servers.
getThread channel
Returns type *templates.CtxChannel corresponding to Channel object.

Database

Function
Description
dbBottomEntries pattern amount nSkip
Returns amount (max 100)top entries of keys determined by the pattern from the database, sorted by the value in a ascending order.
dbCount (userID|key|query)
Returns the count of all database entries which are not expired. Optional arguments: if userID is given, counts entries for that userID; if key, only those keys are counted; and if query is provided, it should be a sdict with the following options:
  • userID - only counts entries with that user ID, defaults to counting entries with any user ID
  • pattern - only counts entries with names matching the pattern given, defaults to counting entries with any name.
dbDel userID key
Deletes the specified key for the specified value from the database.
dbDelByID userID ID
Deletes database entry by its ID.
dbDelMultiple query amount skip
Deletes amount (max 100) entries from the database matching the criteria provided. query should be an sdict with the following options:
  • userID - only deletes entries with the dbEntry field .UserID provided, defaults to deleting entries with any ID.
  • pattern - only deletes entry keys with a name matching the pattern given.
  • reverse - if true, starts deleting entries with the lowest values first; otherwise starts deleting entries with the highest values first. Default is false.
Returns the number of rows that got deleted or an error.
dbGet userID key
Retrieves a value from the database for the specified user, this returns DBEntry object.
dbGetPattern userID pattern amount nSkip
Retrieves up toamount (max 100)entries from the database in ascending order.
dbGetPatternReverse userID pattern amount nSkip
Retrievesamount (max 100)entries from the database in descending order.
dbIncr userID key incrBy
Increments the value for specified key for the specified user, if there was no value then it will be set to incrBy . Also returns the entry's current, increased value.
dbRank query userID key
Returns the rank of the entry specified by the user ID and key provided in the set of entries matching the criteria provided. query specifies the set of entries that should be considered, and should be a sdict with the following options:
  • userID - only includes entries with that user ID, defaults to including entries with any user ID
  • pattern - only includes database's key entries with names matching the pattern given, defaults to counting entries with any name
  • reverse - if true, entries with lower value have higher rank; otherwise entries with higher value have higher rank. Default is false.
dbSet userID key value
Sets the value for the specified key for the specific userID to the specified value. userID can be any number of type int64. Values are stored either as of type float64 (for numbers, oct or hex) or as varying type in bytes (for slices, maps, strings etc) depending on input argument.
dbSetExpire userID key value ttl
Same as dbSet but with an expiration ttl in seconds.
dbTopEntries pattern amount nSkip
Returns amount (max 100)top entries of keys determined by the pattern from the database, sorted by the value in a descending order.
Note about saving numbers into database: As stated above, database stores numbers as type float64. If you save a large number into database like an int64 (which IDs are), the value will be truncated. To avoid this behavior, you can stringify the number before saving and convert it back to its original type when retrieving it. Example: {{$v := .User.ID}} {{dbSet 0 "userid" (str $v)}} {{$fromDB := toInt (dbGet 0 "user_id").Value}}
dict key values are also retrieved as int64, so to use them for indexing one has to e.g. index $x (toInt64 0)

ExecCC

execCC calls are limited to 1 / CC for non-premium users and 10 / CC for premium users.
Function
Description
cancelScheduledUniqueCC ccID key
Cancels a previously scheduled custom command execution using scheduleUniqueCC
execCC ccID channel delay data
Function that executes another custom command specified by ccID,max recursion depth is 2 (using .StackDepth shows the current depth) and it's rate-limited strictly at max 10 delayed custom commands executed per channel per minute, if you go over that it will be simply thrown away. Argument channel can be nil, channel's ID or name. Thedelay argument is execution delay of another CC is in seconds. The data argument is content that you pass to the other executed custom command. To retrieve that data you use .ExecData. This example is important > execCC example also next snippet which shows you same thing run using the same custom command > Snippets.
scheduleUniqueCC ccID channel delay key data
Same as execCCexcept there can only be 1 scheduled cc execution per server per key, if key already exists then it is overwritten with the new data and delay (as above, in seconds).
An example would be a mute command that schedules the unmute action sometime in the future. However, let's say you use the unmute command again on the same user, you would want to override the last scheduled unmute to the new one. This can be used for that.

ExecCC section's snippets:

  • To demonstrate execCC and .ExecData using the same CC.
1
{{ $yag := "YAGPDB rules! " }}
2
{{ $ctr := 0 }} {{ $yourCCID := .CCID }}
3
{{ if .ExecData }}
4
{{ $ctr = add .ExecData.number 1 }}
5
{{ $yag = joinStr "" $yag $ctr }} {{ .ExecData.YAGPDB }}
6
{{ else }}
7
So, someone rules.
8
{{ $ctr = add $ctr 1 }} {{ $yag = joinStr "" $yag 1 }}
9
{{ end }}
10
{{ if lt $ctr 5 }}
11
{{ execCC $yourCCID nil 10 (sdict "YAGPDB" $yag "number" $ctr) }}
12
{{ else }} FUN'S OVER! {{ end }}
Copied!

Math

Function
Description
add x y z ...
Returns x + y + z + ..., detects first number's type - is it int or float and based on that adds. (use toFloat on the first argument to force floating point math.){{add 5 4 3 2 -1}} sums all these numbers and returns 13.
cbrt
Returns the cube root of given argument in type float64 e.g. {{cbrt 64}} returns 4.
div x y z ...
Division, like add or mult, detects first number's type first. {{div 11 3}} returns 3 whereas {{div 11.1 3}} returns 3.6999999999999997
fdiv x y z ...
Meant specifically for floating point numbers division.
log x base
Log is a logarithm function using (log base of x). Arguments can be any type of numbers, as long as they follow logarithm logic. Return value is of type float64. If base argument is not given It is using natural logarithm (base e - The Euler's constant) as default, also is the default to change the base.{{ log "123" 2 }} will return 6.94251450533924.
mod x y
Mod returns the floating-point remainder of x/y. mod 17 3 returns 2 of type float64.
mult x y z ...
Multiplication, like add or div, detects first number's type. {{mult 3.14 2}} returns 6.28
pow x y
Pow returns x**y, the base-x exponential of y which have to be both numbers. Type is returned as float64. {{ pow 2 3 }} returns 8.
randInt (stop, or start stop)
Returns a random integer between 0 and stop, or start - stop if two args are provided.
Result will be start <= random number < stop. Example in section's Snippets.
round
Returns the nearest integer, rounding half away from zero. Regular rounding > 10.4 is 10 and 10.5 is 11. All round functions return type float64, so use conversion functions to get integers. For more complex rounding, example in section's Snippets.
roundCeil
Returns the least integer value greater than or equal to input or rounds up. {{roundCeil 1.1}} returns 2.
roundEven
Returns the nearest integer, rounding ties to even. {{roundEven 10.5}} returns 10 {{roundEven 11.5}} returns 12.
roundFloor
Returns the greatest integer value less than or equal to input or rounds down. {{roundFloor 1.9}} returns 1.
sqrt
Returns the square root of a number as type float64. {{sqrt 49}} returns 7, {{sqrt 12.34 | printf "%.4f"}} returns 3.5128
sub x y z ...
Returns x - y -z - ... Works like add, just subtracts.

Math section's snippets:

  • {{$d := randInt 10}} Stores random int into variable $d (a random number from 0-9).
  • To demonstrate rounding float to 2 decimal places. {{div (round (mult 12.3456 100)) 100}} returns 12.35 {{div (roundFloor (mult 12.3456 100)) 100}} returns 12.34

Member

Function
Description
editNickname "newNick"
Edits triggering user's nickname, argument has to be of type string. YAGPDB's highest role has to be above the highest role of the member.
getMember mention/userID
Function returns Member object having above methods.
{{(getMember .User.ID).JoinedAt}} is the same as {{.Member.JoinedAt}}
onlineCount
Returns the count of online users/members on current server.
onlineCountBots
(deprecated) This will no longer work properly and will likely be removed in a future update. Returns the count of online bots.

Mentions

Function
Description
mentionEveryone
Mentions @everyone.
mentionHere
Mentions @here.
mentionRoleID roleID
Mentions the role found with the provided ID.
mentionRoleName "rolename"
Mentions the first role found with the provided name (case-insensitive).

Mentions section's snippets:

  • <@{{.User.ID}}> Outputs a mention to the user that called the command and is the same as {{.User.Mention}}
  • <@###########> Mentions the user that has the ID ###### (See How to get IDs to get ID).
  • <#&&&&&&&&&&&> Mentions the channel that has ID &&&&&& (See How to get IDs to get ID).
  • <@&##########> Mentions the role with ID ######## (listroles command gives roleIDs). This is usable for example with {{sendMessageNoEscape nil "Welcome to role <@&11111111...>"}}. Mentioning that role has to be enabled server- side in Discord.

Message

Function
Description
addMessageReactions channel messageID emojis...
Same as addReactions or addResponseReactions, but can be used on any messages using its ID. channel can be either nil, channel's ID or its name. Example in section's Snippets.
addReactions "πŸ‘" "πŸ‘Ž" ...
Adds each emoji as a reanction to the message that triggered the command (recognizes Unicode emojis and emojiName:emojiID).
addResponseReactions "πŸ‘" "πŸ‘Ž" ...
Adds each emoji as a reaction to the response message (recognizes Unicode emojis and emojiName:emojiID).
complexMessage "content" args "embed" args "file" args
complexMessage creates a so-called bundle of different message fields for sendMessage... functions to send them out all together. Its arguments need to be preceded by predefined keys "content" for regular text, "embed" for embed arguments created by cembed or sdict, "file" for printing out content as a file (max 100 000 characters ca100kB). Example in this section's Snippets.
complexMessageEdit "content" args "embed" args
Special case for editMessage function - either if complexMessage is involved or works even with regular message. Has two parameters "content" and "embed" to edit regular text part or embed part. If "embed" is set to nil, it deletes whole embed. Example in this section's Snippets.
deleteAllMessageReactions channel messageID (emojis...)
Deletes all reactions pointed message has. channel can be ID, "name" or nil. emojis argument is optional and works like it's described for the function deleteMessageReaction.
deleteMessage channel messageID (delay)
Deletes message with given messageID from channel. Channel can be either nil, channel's ID or its name. (delay) is optional and like following two delete functions, it defaults to 10 seconds, max being 1 day or 86400 seconds. Example in section's Snippets.
deleteMessageReaction channel messageID userID emojis...
Deletes reaction(s) from a message. channel can be ID, "name" or nil. emojis argument can be up to 10 emojis, syntax is emojiName for Unicode/Discord's default emojis and emojiName:emojiID for custom emotes. Example: {{deleteMessageReaction nil (index .Args 1) .User.ID "πŸ‘" "πŸ‘Ž"}} will delete current user's reactions with thumbsUp/Down emotes from current running channel's message which ID is given to command as first argument (index .Args 1). Also usable with Reaction trigger.
deleteResponse (delay)
Deletes the response after a certain time from optional delay argument (max 86400 seconds = 1 day). Defaults to 10 seconds.
deleteTrigger (delay)
Deletes the trigger after a certain time from optional delay argument (max 86400 seconds = 1 day). Defaults to 10 seconds.
editMessage channel messageID newMessageContent
Edits the message in channel, channel can be either nil, channel's ID or "name". Light example in section's Snippets.
editMessageNoEscape channel messageID newMessageContent
Edits the message in channel and has same logic in escaping characters as sendMessageNoEscape.
getMessage channelID messageID
Returns a Message object.
pinMessage channel messageID
Pins a message by its ID in given channel. channel can be either its ID, name or nil for triggering channel. Can be called 5 times.
sendDM "message here"
Sends the user a direct message, only one DM can be sent per custom command (accepts embed objects). YAG will only DM triggering user.
sendMessage channel message
Sends message (string or embed) in channel, channel can be either nil, the channel ID or the channel's "name".
sendMessageNoEscape channel message
Sends message (string or embed) in channel, channel can be either nil, the channel ID or the channel "name". Doesn't escape mentions (e.g. role mentions or @here/@everyone).
sendMessageNoEscapeRetID channel message
Same as sendMessageNoEscape, but also returns messageID to assigned variable for later use.
sendMessageRetID channel message
Same as sendMessage, but also returns messageID to assigned variable for later use. Example in section's Snippets.
unpinMessage channel messageID
Unpins the message by its ID in given channel. channel can be either its ID, name or nil for triggering channel. Can be called 5 times.

Message section's snippets:

  • Sends message to current channel nil and gets messageID to variable $x. Also adds reactions to this message. After 5 seconds, deletes that message. >
    {{$x := sendMessageRetID nil "Hello there!"}} {{addMessageReactions nil $x "πŸ‘" "πŸ‘Ž"}} {{deleteMessage nil $x 5}}
  • To demonstrate sleep and slightly also editMessage functions. > {{$x := sendMessageRetID nil "Hello"}} {{sleep 3}} {{editMessage nil $x "There"}} {{sleep 3}} {{sendMessage nil "We all know, that"}} {{sleep 3}} YAGPDB rules!
  • To demonstrate usage of complexMessage with sendMessage. {{sendMessage nil (complexMessage "content" "Who rules?" "embed" (cembed "description" "YAGPDB of course!" "color" 0x89aa00) "file" "Here we print something nice - you all are doing awesome!")}}
  • To demonstrate usage of complexMessageEdit with editMessage. {{$mID := sendMessageRetID nil (complexMessage "content" "You know what is..." "embed" (cembed "title" "FUN!?" "color" 0xaa8900))}} {{sleep 3}} {{editMessage nil $mID (complexMessageEdit "embed" (cembed "title" "YAGPDB!" "color" 0x89aa00) "content" "Yes, it's always working with...")}}{{sleep 3}}{{editMessage nil $mID (complexMessageEdit "embed" nil "content" "Embed deleted, goodbye YAG!")}}{{deleteMessage nil $mID 3}}

Miscellaneous

Function
Description
adjective
Returns a random adjective.
cembed "list of embed values"
Function to generate embed inside custom command. More in-depth here.
createTicket author topic
Creates a new ticket with the author and topic provided. Covered in its own section here.
cslice, sdict
These functions are covered in their own section here.
dict key1 value1 key2 value2 ...
Creates an unordered collection of key-value pairs, a dictionary so to say. The number of parameters to form key-value pairs must be even. Example here. Keys and values can be of any type. Key is not restricted to string only as in case with sdict. dict also has helper methods .Del, .Get, .HasKey and .Set and they function the same way as sdict ones discussed here.
exec "command" "args" "args" "args" ...
Executes a YAGPDB command (e.g. roll, kick etc) in a custom command. Exec can be run max 5 times per command. If real command returns an embed - exec will return raw data of type embed, so you can use embed fields for better formatting - e.g. {{$resp := exec "whois"}} {{$resp.Title}} Joined at > {{(index $resp.Fields 4).Value}} will return the title (username#discriminator) and "Joined at" field's value from whois command. NB! This will not work commands with paginated embed returns, like un/nn commands!
​
exec syntax is exec "command" arguments - this means you format it the same way as you would type the command regularly, just without the prefix, e.g. if you want to clear 2 messages and avoiding the pinned message > {{exec "clear 2 -nopin"}}, where "command" part is whole "clear 2 -nopin". If you change that number inside CC somewhere then you have to use arguments part of exec formatting > {{$x := 2}} {{exec "clear" $x "-nopin"}} Here "clear" is the "command" and it is followed by arguments, one variable $x and one string "-nopin". Last example is the same as {{exec (joinStr " " "clear" $x "-nopin")}}(also notice the space in joinStr separator).
execAdmin "command" "args" "args" "args" ...
Functions same way as exec but effectively runs the command as the bot user (YAGPDB). This has essentially the same effect as if a user with the same permissions and roles as YAGPDB ran the command: for example, if YAGPDB had ban members permission but the user which ran the command did not, {{exec "ban" 12345}} would error due to insufficient permissions but {{execAdmin "ban" 12345}} would succeed.
hasPrefix string prefix
hasPrefix tests whether the given string begins with prefix and returns bool. Example > {{hasPrefix "YAGPDB" "YAG"}} returns true.
hasSuffix string suffix
hasSuffix tests whether the given string ends with suffix and returns bool.
Example > {{hasSuffix "YAGPDB" "YAG"}} returns false.
humanizeThousands arg
This function places comma to separate groups of thousands of a number. arg can be int or string, has to be a whole number, e.g. {{humanizeThousands "1234567890"}} will return 1,234,567,890
in list value
Returns bool true/false whether case-sensitive value is in list/slice. {{ in (cslice "YAGPDB" "is cool") "yagpdb" }} returns false.
index arg ...keys
Returns the result of indexing its first argument by the following arguments. Each indexed item must be a map, slice or array.
​
Example: {{index .Args 1}} returns first argument after trigger which is always at position 0.
​
More than one positional keys can be used, in pseudo-code:
index X 0 1 is equivalent to calling index (index X 0) 1
inFold list value
Same as in, but is case-insensitive. {{inFold (cslice "YAGPDB" "is cool") "yagpdb"}} returns true.
kindOf value (flag)
This function helps to determine what kind of data type we are dealing with. flag part is a bool and if set as true (false is optional) returns the value where given value points to. Example: {{kindOf cembed false}} {{kindOf cembed true}} will return ptr and struct.
len arg
Returns the integer length of its argument. arg can be an array, slice, map, or string.
{{ len (cslice 1 2 3) }}
returns 3.
noun
Returns a random noun.
parseArgs required_args error_message ...carg
Checks the arguments for a specific type. Has methods .Get and .IsSet.
carg "type" "name" is required by parseArgs and it defines the type of argument for parseArgs.
​
​More in depth here and an example in Custom Command Examples.​
range slice/array
Iterates (loops) over the given slice or array and sets successive elements as active data (the dot) to be further handled inside the range action. Example usage here. More in-depth here.
sendTemplate channel templateName data
Function sends a formulated template to another channel. Channel is like always either name, number or nil; and returns messageID.
Example: {{define "logsTemplate"}}This text will output on different channel, you can also use functions like {{currentTime}}. {{.TemplateArgs}} would be additional data sent out. {{end}}
Now we call that "logs" in the same custom command.{{sendTemplate "logs" "logsTemplate" "YAG rules!"}}. Template definitions are discussed here.
sendTemplateDM templateName data
Works the same way as function above. Only channel's name is not in the arguments. YAGPDB will only DM the triggering user.
seq start stop
Creates a new slice of type int, beginning from start number, increasing in sequence and ending at stop (not included). {{seq -4 2}} returns a slice [ -4 -3 -2 -1 0 1 ]. Sequence's max length is 10 000.
shuffle list
Returns a shuffled, randomized version of a list/slice.
sleep seconds
Pauses execution of template's action-structure inside custom command for max 60 seconds combined. Argumentsecondsis an integer (whole number). Example in snippets.
sort slice (...args)
Sorts a slice with optional arguments. Numbers are sorted before strings. Arguments are presented in a sdict as keys having bool values. Example > {{sort (cslice "YAGPDB" 42 "Alphabet" 111 33.3) (sdict "reverse" true "subslices" true "emptyslices" false)}}would return [111 42 33.3 YAGPDB Alphabet]
Argument keys:
"reverse" reverses the order if true.
"subslices" makes the function return a set of subslices based on input type/kind if true.
"Emptyslices" returns all possible slices if true, helpful for indexing. Sort function is limited to 1/3 CC calls regular/premium.

Role functions

Function
Description
addRoleID roleID
Adds the role with the given ID to the user that triggered the command (use the listroles command for a list of roles).
addRoleName roleName
Adds the role with given name to the user that triggered the command (use the listroles command for a list of roles).
getRole role
Returns a role object of type *discordgo.Role. role can be either role's ID or role's name.
giveRoleID userID roleID
Gives a role by ID to the target.
giveRoleName userID "roleName"
Gives a role by name to the target.
hasRoleID roleID
Returns true if the user has the role with the specified ID (use the listroles command for a list of roles).
hasRoleName "rolename"
Returns true if the user has the role with the specified name (case-insensitive).
removeRoleID roleID (delay)
Removes the role with the given ID from the user that triggered the command (use the listroles command for a list of roles). Delay is optional argument in seconds.
removeRoleName roleName (delay)
Removes the role with given name from the user that triggered the command (use the listroles command for a list of roles). Delay is optional argument in seconds.
roleAbove role1 role2
roleAbove compares two role objects e.g. getRolereturn and givestrue/false value is role1 positioned higher than role2 or not.
setRoles userID roles
Overwrites the roles of the given user using the slice of roles provided, which should be a slice of role IDs. IDs can be ints or strings. Example: {{setRoles .User.ID cslice}} would clear the roles of the triggering user.
takeRoleID userID roleID (delay)
Takes away a role by ID from the target. Delay is optional argument in seconds.
takeRoleName userID "roleName" (delay)
Takes away a role by name from the target. Delay is optional argument in seconds.
targetHasRoleID userID roleID
Returns true if the given user has the role with the specified ID (use the listroles command for a list of roles). Example in section's Snippets.
targetHasRoleName userID "roleName"
Returns true if the given user has the role with the specified name (case-insensitive).

String manipulation

Function
Description
joinStr "separator" "str1" (arg1)(arg2) "str2" ...
Joins several strings into one, separated by the first argument"separator", example:{{joinStr "" "1" "2" "3"}} returns 123. Also if functions have string, []string or easily convertible return, they can be used inside joinStr e.g. {{joinStr "" "Let's calculate " (add (mult 13 3) 1 2) ", was returned at " (currentTime.Format "15:04") "."}}
lower "string"
Converts the string to lowercase.
print, printf, println
These are GO template package's predefined functions and are aliases for fmt.Sprint, fmt.Sprintf and fmt.Sprintln. Formatting is also discussed here. printf cheat sheet here. printf is usable for example to determine the type of the value > {{printf "%T" currentTime}} outputs currentTime functions output value type of time.Time. In many cases, printf is a great alternative to joinStr for concatenate strings.
reFind "regex" "string"
Compares "string" to regex pattern and returns first match. {{reFind "AG" "YAGPDB is cool!"}}returns AG (regex pattern is case sensitive).
reFindAll "regex" "string" (count)
Adds all regex matches from the "string" to a slice. Example in section's Snippets. Optional count determines how many matches are made. Example: {{reFindAll "a*" "abaabaccadaaae" 4}} would return [a aa a ].
reFindAllSubmatches "regex" "string" (count)
Returns whole-pattern matches and also the sub-matches within those matches as slices inside a slice. {{reFindAllSubmatches "(?i)y([a-z]+)g" "youngish YAGPDB"}} returns [[young oun] [YAG A]] (regex pattern here is case insensitive). Optional count works the same way as for reFindAll. So example above with count set to 1 would return [[young oun]].
reReplace "regex" "string1" "string2"
Replaces "string1" contents with "string2" at regex match point. {{reReplace "I am" "I am cool!" "YAGPDB is"}}returns YAGPDB is cool! (regex pattern here is case sensitive).
reSplit "regex" "string" (count)
reSplit slices string into substrings separated by the regex expression and returns a slice of the substrings between those expression matches. The optional count determines the number of substrings to return. If count is negative number the function returns all substrings, if 0 then none. If count is bigger than 0 it returns at most n substrings, the last substring being the unsplit remainder.
Example: {{ $x := reSplit "a" "yagpdb has a lot of fame" 5}}
{{$x}} {{index $x 3}} would return [y gpdb h s lot of f me] and lot of f.
slice "string"|slice integer (integer2)
Function's first argument must be of type string or slice.
Outputs the "string" after cutting/slicing off integer (numeric) value of symbols (actually starting the string's index from integer through integer2) - e.g. {{slice "Fox runs" 2}}outputs x runs. When using also integer2 - e.g. {{slice "Fox runs" 1 7}}, it outputs ox run. For slicing whole arguments, let's say words, see example in section's Snippets.
​
This slice function is not the same as basic dynamically-sized slice data type discussed in this reference doc. Also it's custom, not having 3-indices as the default one from text/template package.
split "string" "sepr"
Splits given "string" to substrings separated by "sepr"arg and returns new slice of the substrings between given separator e.g. {{split "YAG, is cool!" ","}} returns [YAG is cool!] slice where YAG is at index position 0 and is cool! at index position 1. Example also in section's Snippets.
title "string"
Returns string with the first letter of each word capitalized.
upper "string"
Converts the string to uppercase.
urlescape "string"
Escapes the string so it can be safely placed inside a URL path segment - e.g. "Hello, YAGPDB!" becomes "Hello%2C%20YAGPDB%21"
Special information we can include in the string is escape sequences. Escape sequences are two (or more) characters, the first of which is a backslash \, which gives the remaining characters special meaning - let's call them metacharacters. The most common escape sequence you will encounter is \n, which means "newline".
With regular expression patterns - when using quotes you have to "double-escape" metacharacters starting with backslash. You can use backquotes/ticks to simplify this:{{reFind "\\d+" (toString 42)}} versus {{reFind `\d+` (toString 42)}}

String manipulation section's snippets:

  • {{$args:= (joinStr " " (slice .CmdArgs 1))}} Saves all the arguments except the first one to a variable $args.
  • To demonstrate usage of split function. > {{$x := "Hello, World, YAGPDB, here!"}} {{range $k, $v := (split $x ", ")}}Word {{$k}}: __{{$v}}__ {{end}}
  • To demonstrate usage of reFindAll. > Before regex: {{$msg := "1 YAGPDB and over 100000 servers conquered."}} {{$re2 := reFindAll "[0-9]+" $msg}} {{$msg}} After regex matches: {{joinStr " " "Only" (index $re2 0) "YAGPDB and already" (index $re2 1) "servers captured."}}

Time

Function
Description
currentTime
Gets the current time, value is of type time.Time which can be used in a custom embed. More info here.
formatTime Time ("layout arg")
Outputs given time in RFC822 formatting, first argument Time shows it needs to be of type time.Time, also with extra layout if second argument is given - e.g. {{formatTime currentUserCreated "3:04PM"}} would output 11:22AM if that would have been when user was created. Layout argument is covered here.
humanizeDurationHours
Returns given integer (whole number) or time.Duration argument in nanoseconds in human readable format - as how long it would take to get towards given time - e.g. {{humanizeDurationHours 9000000000000000000}} returns 285 years 20 weeks 6 days and 16 hours. More in Snippets.
humanizeDurationMinutes
Same as humanizeDurationHours, this time duration is returned in minutes - e.g. {{humanizeDurationMinutes 3500000000000}} would return 58 minutes.
humanizeDurationSeconds
Same as both humanize functions above, this time duration is returned in seconds - e.g. {{humanizeDurationSeconds 3500000000000}} would return 58 minutes and 20 seconds.
humanizeTimeSinceDays
Returns time passed since given argument of type time.Time in human readable format - e.g. {{humanizeTimeSinceDays currentUserCreated}}.
loadLocation "location"
Retruns value of type *time.Location which can be used further in other golang's time functions, for example {{currentTime.In (loadLocation "Asia/Kathmandu")}} would return current time in Nepal. location is of type string and has to be in ZONEINFO syntax.
newDate year month day hour minute second (timezone)
Returns type time.Time object in UTC using given syntax (all required arguments need to be of type int), for example > {{humanizeDurationHours ((newDate 2059 1 2 12 34 56).Sub currentTime)}} will give you how much time till year 2059 January 2nd 12:34:56. More examples in Snippets.
timezone is an optional argument of type string which uses golang's LoadLocation function and ZONEINFO syntax. For example: {{newDate 2020 4 20 12 34 56 "Atlantic/Reykjavik"}} would return that time in GMT+0.
snowflakeToTime snowflake
Converts given snowflake to type time.Time e.g. using YAGPDB's ID {{snowflakeToTime 204255221017214977}} returns 2016-07-17 15:17:19 +0000 UTC.
weekNumber time
Returns the week number as int of given argument time of type time.Time. {{weekNumber currentTime}} would return the week number of current time.
Discord Timestamp Styles referenced here can be done using print function e.g.
{{print "<t:" currentTime.Unix ":F>"}} for "Long Date/Time" formatting.

Time section's snippets:

  • To demonstrate humanizeDurationHours and also how to parse a timestamp, output will be like whois command shows user's join server age. {{humanizeDurationHours (currentTime.Sub .Member.JoinedAt.Parse)}}
  • To demonstrate newDate to get Epoch times. {{$unixEpoch := newDate 1970 1 1 0 0 0}} in seconds > {{$unixEpoch.Unix}} {{$discordEpoch := newDate 2015 1 1 0 0 0}} in seconds > {{$discordEpoch.Unix}}

Type conversion

Function
Description
json value
Traverses given value through MarshalJSON (more here) and returns it as type string. For example {{json .TimeHour}} outputs type string; before this .TimeHour was of type time.Duration. Basically it's good to use if multistep type conversion is needed (toString (toInt value) ) and certain parts of cembed need this for example.
structToSdict struct
Function converts exported field-value pairs of a struct to an sdict. For example it is useful for editing embeds, rather than having to reconstruct the embed field by field manually. Exampe: {{$x := cembed "title" "Something rules!" "color" 0x89aa00}} {{$x.Title}} {{$x = structToSdict $x}} {{- $x.Set "Title" "No, YAGPDB rules!!!" -}} {{$x.Title}} {{$x}} will return No, YAGPDB rules!!! and whole sdict-mapped cembed.
toByte "arg"
Function converts input to a slice of bytes - meaning []uint8. {{toByte "YAG€"}} would output [89 65 71 226 130 172]. toString is capable of converting that slice back to string.
toDuration
Converts the argument, number or string to type time.Duration - more duration related methods here. Number represents nanoseconds. String can be with time modifier (second, minute, hour, day etc) s, m, h, d, w, mo, y,without a modifier string will be converted to minutes. Usage:(toDuration x). Example in section's Snippets.
toFloat
Converts argument (int or string type of a number) to type float64. Usage: (toFloat x). Function will return 0, if type can't be converted to float64.
toInt
Converts something into an integer of type int. Usage: (toInt x). Function will return 0, if type can't be converted to int.
toInt64
Converts something into an int64. Usage: (toInt64 x). Function will return 0, if type can't be converted to int64.
toRune "arg"
Function converts input to a slice of runes - meaning []int32. {{toRune "YAG€"}}would output [89 65 71 8364]. These two functions - the one above, are good for further analysis of Unicode strings. toString is capable of converting that slice back to string.
toString
Has alias str. Converts some other types into a string. Usage: (toString x).

Type conversion section's snippets:

  • To demonstrate toDuration, outputs 12 hours from current time in UTC. {{(currentTime.Add (toDuration (mult 12 .TimeHour))).Format "15:04"}}is the same as{{(currentTime.Add (toDuration "12h")).Format "15:04"}} or{{(currentTime.Add (toDuration 43200000000000)).Format "15:04"}}
Tip: You can convert a Unicode code point back to its string equivalent using printf "%c". For example, printf "%c" 99 would result in the string c as 99 is the Unicode code point for c.printf is briefly covered later on in the next section, further documentation can be found here. Cheat sheet here.

User

Function
Description
currentUserAgeHuman
The account age of the current user in more human readable format (Eg:3 days 2 hours).
currentUserAgeMinutes
The account age of the current user in minutes.
currentUserCreated
Returns value of type time.Time and shows when the current user was created.
pastNicknames userID offset
Same as pastUsernames.
pastUsernames userID offset
Returns a slice of type [ ]*logs.CCNameChange having fields .Name and .Time of previous 15 usernames and skips offset number in that list.
{{range pastUsernames .User.ID 0}} {{.Name}} - {{.Time.Format "Jan _2 2006"}} {{end}}
userArg mention/userID
Function that can be used to retrieve .User object from a mention or userID.
{{(userArg .User.ID).Mention}} mentions triggering user. Explained more in this section's snippets. userArg is limited to 5 function calls.

User section's snippets:

{{(userArg .Guild.OwnerID).String}} this template's action-structure returns Guild/Server owner's username and discriminator as of type string. First, userArg function is given .Guild.OwnerID as argument (what it does, explained in templates section). The parentheses surrounding them make userArg function return .User as .User object which is handled further by .String method (ref..User.String), giving a result like > YAGPDB#8760.
Last modified 3d ago