Functions
Functions are underappreciated. In general, not just in templates. // Rob Pike
Every function having both cases possible for an argument - ID/name, then this name is handled case insensitive, for example getRole "yagpdb"
and getRole "yAgPdB"
would have same responses even if server has both of these roles, so using IDs is better.
Channel
The ratelimit for editing a channel is 2 requests per 10 minutes per channel.
Function | Description |
| Adds a member to an existing thread. Does nothing if either thread or member arguments are invalid. Argument |
| Creates a new forum post in forum |
| Creates a new thread in Optional Returns *templates.CtxChannel upon success. Example: |
| Deletes existing post in the forum - |
| Deletes existing thread - |
| Function edits channel's name. |
| Function edits channel's topic/description.
|
| Function returns full channel object of given |
| Returns type *templates.CtxChannel corresponding to Channel object. |
| Returns a slice of all pinned message objects in targeted channel. |
| Returns the count of pinned messages in given channel which can be either its ID, name or |
| Returns type *templates.CtxChannel corresponding to Channel object. |
| Removes a member from an existing thread. Does nothing if either thread or user are invalid. Argument |
Database
Function | Description |
| Returns |
| Returns the count of all database entries which are not expired. Optional arguments: if
|
| Deletes the specified key for the specified value from the database. |
| Deletes database entry by its ID. |
| Deletes
Returns the number of rows that got deleted or an error. |
| Retrieves a value from the database for the specified user, this returns DBEntry object. Does not fetch member data as user object for .User like |
| Retrieves up to |
| Retrieves |
| Increments the value for specified key for the specified user, if there was no value then it will be set to |
| Returns the rank of the entry specified by the user ID and key provided in the set of entries matching the criteria provided.
|
| Sets the value for the specified |
| Same as |
| Returns |
Patterns are basic PostgreSQL patterns, not Regexp: An underscore (_)
matches any single character; a percent sign (%)
matches any sequence of zero or more characters.
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 convert the number to type string before saving and later 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 |
| Cancels a previously scheduled custom command execution using |
| Function that executes another custom command specified by |
| Same as 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.
Math
Boolean logic (and, not, or) and comparison operators (eq, gt, lt, etc.) are covered in conditional branching.
Function | Description |
| Returns x + y + z + ..., detects first number's type - is it int or float and based on that adds. (use |
| The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of an operand is 0, the result of corresponding bit is evaluated to 0. Example: |
| This function is called bit clear because of AND NOT. For example in the expression z = x AND NOT y, each bit of z is 0 if the corresponding bit of y is 1; otherwise it equals to the corresponding bit of x. |
| The bitwise NOT operator inverts the bits of the argument. Example: |
| The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. Example: |
| The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. Example: |
| Left shift operator shifts all bits towards left by a certain number of specified bits. The bit positions that have been vacated by the left shift operator are filled with 0. Example: |
| Right shift operator shifts all bits towards right by certain number of specified bits. Example: |
| Returns the cube root of given argument in type float64 e.g. |
| Division, like |
| Meant specifically for floating point numbers division. |
| 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. |
| Function returns all constants available in golang's math package as float64. |
| Returns the larger of x or y as type float64. |
| Returns the smaller of x or y as type float64. |
| Mod returns the floating-point remainder of the division of x by y. For example, |
| Multiplication, like |
| Pow returns x**y, the base-x exponential of y which have to be both numbers. Type is returned as float64. |
| Returns a random integer between 0 and stop, or start - stop if two args are provided. Result will be |
| Returns the nearest integer, rounding half away from zero. Regular rounding > 10.4 is |
| Returns the least integer value greater than or equal to input or rounds up. |
| Returns the nearest integer, rounding ties to even.
|
| Returns the greatest integer value less than or equal to input or rounds down. |
| Returns the square root of a number as type float64.
|
| 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 |
| Returns target’s permissions in the given channel. |
| 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 and bot can't edit owner's nickname. |
| Returns true/false on whether triggering user has the permission bit int64 that is also set in .Permissions. |
| Function returns Member object having above methods.
|
| Returns the count of online users/members on current server. |
| Returns true/false on whether targeted member has the permission bit int64. |
Permissions are covered here. For example to get permission bit for "use application commands" {{bitwiseLeftShift 1 32}}
would return int64 4294967296
.
Mentions
Function | Description |
| Mentions |
| Mentions |
| Mentions the role found with the provided ID. |
| Mentions the first role found with the provided name (case-insensitive). |
There is also .Mention method available for channel, role, user structs/objects.
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.</cmdName:cmdID>
Mentions a slash command, and makes it clickable and interactive with proper arguments e.g.</howlongtobeat:842397645104087061>
.
Message
Function | Description |
| Same as Emojis can be presented as a cslice. Example in section's Snippets. |
| Adds each emoji as a reaction to the message that triggered the command (recognizes Unicode emojis and |
| Adds each emoji as a reaction to the response message (recognizes Unicode emojis and |
|
Example in this section's Snippets. |
| Special case for |
| Deletes all reactions pointed message has. |
| Deletes message with given |
| Deletes reaction(s) from a message. |
| Deletes the response after a certain time from optional |
| Deletes the trigger after a certain time from optional |
| Edits the message in channel, channel can be either |
| Edits the message in channel and has same logic in escaping characters as |
| Returns a Message object. |
| Pins a message by its ID in given channel. |
| Publishes a message by its ID in given announcement channel. |
| Publishes the response when executed in an announcement channel. This function will not work for leave or join messages. |
| Sends the user a direct message, only one DM can be sent per custom command (accepts embed objects). YAG will only DM triggering user. This function will not work for leave messages. |
| Sends |
| Sends |
| Same as |
| Same as |
| Unpins the message by its ID in given channel. |
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 (cslice "👍" "👎") "
❤️" }} {{deleteMessage nil $x 5}}
To demonstrate
sleep
and slightly alsoeditMessage
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
withsendMessage
.{{sendMessage nil (complexMessage "reply" .Message.ID "content" "Who rules?" "embed" (cembed "description" "YAGPDB of course!" "color" 0x89aa00) "file" "Here we print something nice - you all are doing awesome!" "filename" currentTime.Weekday)}}
To demonstrate usage of
complexMessageEdit
witheditMessage
.{{$mID := sendMessageRetID nil (complexMessage "content" "You know what is..." "silent" true "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" "Will delete this message in a sec, goodbye YAG!")}}{{deleteMessage nil $mID 3}}
Miscellaneous
if
, range
, try-catch
, while
, with
actions are all covered here.
Function | Description |
| Returns a random adjective. |
| Function to generate embed inside custom command. More in-depth here. |
| Creates a new ticket with the author and topic provided. Covered in its own section here. |
| These functions are covered in their own section here. |
| 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 |
| Executes a YAGPDB command (e.g. roll, kick etc) in a custom command. Exec can be run max 5 times per CC. If real command returns an embed - exec syntax is |
| Functions same way as |
| Executes the associated template, optionally with data. A more detailed treatment of this function can be found in the Associated Templates section. |
| Returns a slice of warnings of type []*moderation.WarningModel given to user argument which can be its ID or user object. |
|
|
| hasSuffix tests whether the given Example > |
| This function places comma to separate groups of thousands of a number. |
| Returns bool true/false whether case-sensitive value is in list/slice. |
| Returns the result by indexing its first argument with following arguments. Each indexed item must be a map, slice or array. Indexed string returns value in uint8. Example: More than one positional keys can be used, in pseudo-code:
|
| Same as |
| This function helps to determine what kind of data type we are dealing with. |
| Returns the integer length of its argument. arg can be an array, slice, map, or string.
returns |
| Returns a random noun. |
| Checks the arguments for a specific type. Has methods
More in depth here and an example in Custom Command Examples. |
| Function sends a formulated template to another channel and returns sent response's messageID.
Channel is like always either name, number or nil; and returns messageID. Example: Now we call that "logs" in the same custom command. |
| Works the same way as function above. Only channel's name is not in the arguments. YAGPDB will only DM the triggering user. This function will not work for leave messages. |
| Creates a new slice of type int, beginning from start number, increasing in sequence and ending at stop (not included). |
| Returns a shuffled, randomized version of a list/slice. |
| Pauses execution of template's action-structure inside custom command for max 60 seconds combined. Argument |
| Sorts a slice of same type values with optional arguments. These arguments are presented in an Example > Sorting mixed types is not supported. Previous sorting options Sort function is limited to 1/3 CC calls regular/premium. |
| Returns a random verb. |
Role functions
In all role functions where userID is required as argument to target a user, it can also be full user object.
Function | Description |
| Adds the role with the given ID to the user that triggered the command (use the |
| Adds the role with given name to the user that triggered the command (use the |
| Returns a role object of type *discordgo.Role. |
| Gives a role by ID to the target. |
| Gives a role by name to the target. |
| Returns true if the triggering user has the role with the specified ID (use the listroles command for a list of roles). |
| Returns true if the triggering user has the role with the specified name (case-insensitive). |
| Removes the role with the given ID from the user that triggered the command (use the listroles command for a list of roles). |
| Removes the role with given name from the user that triggered the command (use the listroles command for a list of 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: |
| Takes away a role by ID from the target. |
| Takes away a role by name from the target. |
| Returns true if the given/targeted user has the role with the specified ID (use the listroles command for a list of roles). Example in section's Snippets. |
| Returns true if the given/targeted user has the role with the specified name (case-insensitive). |
String manipulation
All regexp functions are limited to 10 different pattern calls per CC.
Function | Description |
| Joins several strings into one, separated by the first argument |
| Converts the string to lowercase. |
| These are GO template package's predefined functions and are aliases for fmt.Sprint, fmt.Sprintf and fmt.Sprintln. Formatting is also discussed here. |
| Compares "string" to regex pattern and returns first match. |
| Adds all regex matches from the "string" to a slice. Example in section's Snippets. Optional |
| Returns whole-pattern matches and also the sub-matches within those matches as slices inside a slice. |
|
|
| Replaces "string1" contents with "string2" at regex match point. Inside "string2" dollar-sign, $ with numeric name like $1 or ${1} are interpreted as referrals to the submatches in "regex" pattern, so for instance $1 represents the text of the first submatch. To insert a literal $ in the output, use $$. |
|
Example:
|
| Detects accented and confusable characters in input and turns these characters to normal, ISO-Latin ones. |
| Function's first argument must be of type string or slice. Outputs the This |
| Splits given |
| Returns the string with the first letter of each word capitalized. |
| Returns the string with all leading and trailing white space removed. |
| Converts the string to uppercase. |
| Escapes the string so it can be safely placed inside a URL path segment - e.g. "Hello, YAGPDB!" becomes "Hello%2C%20YAGPDB%21"
There's also predefined template package function |
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: {{println "Only" (index $re2 0) "YAGPDB and already" (index $re2 1) "servers captured."}}
Time
Function | Description |
| Gets the current time, value is of type time.Time which can be used in a custom embed. More info here. |
| Outputs given time in RFC822 formatting, first argument |
| 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. |
| Same as |
| Same as both humanize functions above, this time duration is returned in seconds - e.g. |
| Returns time passed since given argument of type time.Time in human readable format - e.g. |
| Retruns value of type *time.Location which can be used further in other golang's time functions, for example |
| Returns type time.Time object in UTC using given syntax (all required arguments need to be of type int), for example >
|
|
|
| Converts given snowflake to type time.Time e.g. using bot's ID |
| Converts UNIX timestamp to time.Time. Example: {{timestampToTime 1420070400}} would return same time as |
| Returns the week number as int of given argument |
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 likewhois
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 |
| Traverses given |
| Returns |
| 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: |
| Function converts input to a slice of bytes - meaning []uint8. |
| 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) |
| Converts argument (int or string type of a number) to type float64. Usage: |
| Converts something into an integer of type int. Usage: |
| Converts something into an int64. Usage: |
| Function converts input to a slice of runes - meaning []int32. |
| Has alias |
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 |
| The account age of the current user in more human readable format. |
| The account age of the current user in minutes. |
| Returns value of type time.Time and shows when the current user was created. |
~ | Same as |
~ | Returns a slice of type [ ]*logs.CCNameChange having fields .Name and .Time of previous 15 usernames and skips
|
| Function that can be used to retrieve .User object from a mention or userID.
|
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 updated