📚
YAGPDB
  • YAGPDB Coding System - Documentation
  • Getting Started
  • Useful Functions
  • Primary Level
    • The Dot and Variables
      • User
      • Guild / Server
      • Member
      • Channel
      • Message
      • Reaction
      • Time
    • Custom Types
    • Functions
      • Type Conversion
      • String Manipulation
      • Math Functions
      • Message Functions
      • Mentions
      • Role Functions
      • Current User
      • Miscellaneous
      • ExecCC
    • Conditional Branching
  • Intermediate Level
  • Database
  • Range Action
  • With Action
  • Custom Embeds
  • Advanced Level
    • Using RegEx
  • Custom Commands Examples
    • Texas Hold'em
Powered by GitBook
On this page
  • Functions
  • Conditional Branching

Was this helpful?

Useful Functions

Before starting to write codes, you should know these useful and important functions first

Functions

The following functions are the most useful functions when you make custom commands. Try to understand all of them, or you may get trouble when you are writing codes.

Be sure that you have known the type of arguments the specific function needs, or it may outputs errors.

Function

Description

toDuration

toFloat

Converts argument (int or string type of a number) to type float64. Returns 0 if the argument can't be converted to float64.

Usage: toFloat x

toInt

Converts something into an integer of type int. Returns 0 if the argument can't be converted to int. Usage: toInt x

toInt64

Converts something into an int64. Returns 0 if the argument can't be converted to int64. Usage: toInt64 x

toString/str

Converts some other type into a string. Usage: toString x/str x

joinStr "separator" "str1" (arg1) (arg2) "str2" ...

Joins several strings into one, separated by the first argument"separator", example:{{joinStr "" "1" "2" "3"}} returns 123; {{joinStr " " "1" "2" "3"}} returns 1 2 3. Also if functions have string or easily convertible return, they can be used inside joinStr. e.g.{{joinStr "" "Let's calculate " (add 1 2)}}

printf

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 2 -1}} sums all these numbers and returns 6.

sub x y z ...

Returns x - y - z - ..., works like add, just subtracts.

mult x y z ...

Multiplication, like add or div, detects first number's type.{{mult 3.14 2}}returns 6.28, while{{mult 2 3.14}}returns 6.

div x y z ...

Division, like add or mult, detects 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'll use natural logarithm (base e - The Euler's constant) as default.{{log 4 2}}returns 2.

mod x y

Returns the floating-point remainder of x/y.{{mod 17 3}}returns 2 of type float64.

pow x y

Returns x**y as float64, the base-x exponential of y which have to be both numbers.{{pow 2 3}}returns 8.

randInt stop/randInt start stop

round

roundCeil

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

addMessageReactions channel messageID reactions

addResponseReactions "👍" "👎" ...

Adds each emoji as a reaction to the response message (recognizes Unicode emojis and emojiName:emojiID).

deleteAllMessageReactions channel messageID

Deletes all reactions pointed message has. channel can be ID, "name" or nil.

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).

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.

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".

getMessage channelID messageID

Returns a Message object.

sendDM "message here"

Sends the user a direct message, only 1 DM can be sent per custom command (accepts embed objects). YAG will only DM triggering user.

sendMessage channel message

Sends a message (string or embed) in channel, channel can be either nil, the channel ID or the channel's "name".

sendMessageRetID channel message

mentionRoleID roleID

Mentions the role found with the provided ID. Also, you can use <@&roleID> to mention the role.

addRoleID roleID

Adds the role with the given ID to the user that triggered the command (-listroles to get a list of roles in the server).

giveRoleID userID roleID

Gives a role by ID to the target.

hasRoleID roleID

Returns true if the user has the role with the specified ID (-listroles to get a list of roles in the server).

removeRoleID roleID (delay)

Removes the role with the given ID from the user triggering the command (-listroles to get a list of roles in the server).Delay is optional argument in seconds.

takeRoleID userID roleID (delay)

Takes away a role by ID from the target.

(-listroles to get a list of roles in the server).Delay is optional argument in seconds.

targetHasRoleID userID roleID

Returns true if the given user has the role with the specified ID (-listroles to get a list of roles in the server).

index

Returns the result of indexing its first argument by the following arguments. Each indexed item must be a map, slice or array.

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.

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 0 1]. Sequence's max length is 10000.

execAdmin "command" "args" "args" "args" ...

Functions same way as exec but will override any permission requirement (such as the kick permission to use kick command etc.).

parseArgs required_args error_message ...carg

Checks the arguments for a specific type. Has methods.Get and .IsSet.

carg "type" "name"

Defines type of argument for parseArgs.

sleep seconds

Pauses execution of template's action-structure inside custom command for max 60 seconds combined. Argument seconds is an integer (whole number).

execCC ccID channel delay data

Function that executes another custom command specified by ccID,max recursion depth is 2 (.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. The delay argument is execution delay of another CC in seconds. The data argument is content that you pass to the other executed custom command. To retrieve that data, use .ExecData.

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 in seconds.

dbGet userID key

Retrieves a value from the database for the specified user, this returns DBEntry object.

dbGetPattern userID pattern amount nSkip

Retrieves up to amount (max 100)entries from the database in ascending order.

dbGetPatternReverse userID pattern amount nSkip

Retrieves amount (max 100)entries from the database in descending order.

dbDel userID key

Deletes the specified key for the specified value from the database.

dbDelByID userID ID

Deletes database entry by it's ID.

dbTopEntries pattern amount nSkip

Returns amount (max 100)top entries from the database, sorted by the value in a descending order.

dbBottomEntries pattern amount nSkip

Returns amount (max 100)top entries from the database, sorted by the value in a ascending order.

dbCount (userID|key)

Returns the count of all database entries which are not expired. Optional arguments: if userID is given, counts entries for that userID or if key, then only those keys are counted.

Example:

  • To demonstrate toDuration, outputs 12 hours. {{toDuration 43200000000000}}, {{toDuration "12h"}} will output 12h0m0s.

  • printf example: {{printf "%T" "Hello"}} will return string because it is of type string.

  • {{$d := randInt 10}} Stores random int into variable $d (a random number from 0-9). And

    {{$d := randInt 3 10}} Stores random int into variable $d (a random number from 3-9).

  • To demonstrate round, roundCeil, and roundFloor . {{round 12.49}} returns 12; {{round 12.50}} returns 13; {{roundCeil 12.000000000001}} returns 13; {{roundFloor 12.99999999999}} returns 12.

  • Sends message to current channel nil and gets messageID to variable $x. Also adds reactions to this message. After 20 seconds, deletes that message. {{$x := sendMessageRetID nil "Hello"}} {{addMessageReactions nil $x "👍" "👎"}} {{deleteMessage nil $x 20}}

  • To demonstrate index and seq, index the 3rd object of the slice. {{$x := seq 3 10}} {{index $x 2}} returns 5.

  • To demonstrate parseArgs.

{{$args := parseArgs 2 "Require at least two arguments" 
  (carg "int" "need to be of type int") 
  (carg "string" "need to be of type string")
  (carg "string" "optional")}}
{{$args.Get 0}} --- The first argument; {{$args.Get 1}} --- The second argument.
{{if $args.IsSet 2}}
Only runs if the third argument was provided
{{end}}

Conditional Branching

Branching using if action's pipeline and comparison operators - these operators don't need to be inside if branch. if statements always need to have an enclosing end.

Comparison operators always require the same type: i.e comparing 1.23 and 1 would throw incompatible types for comparison error as they are not the same type (one is float, the other int). To fix this, you should convert both to the same type -> for example, toFloat 1.

Case

Example

if

{{if (condition)}} output {{end}}

Initialization statement can also be inside if statement with conditional statement, limiting the initialized scope to that if statement. {{$x := 24}} {{if eq ($x := 42) 42}} Inside: {{$x}} {{end}} Outside: {{$x}}

else if

{{if (condition)}} output1 {{else if (condition)}} output2 {{end}}

You can have as manyelse ifstatements as many different conditionals you have.

else

{{if (condition)}} output1 {{else}} output2 {{end}}

not

{{if not (condition)}} output {{end}}

and

{{if and (cond1) (cond2) (cond3)}} output {{end}}

or

{{if or (cond1) (cond2) (cond3)}} output {{end}}

Equal: eq

{{if eq .Channel.ID ########}} output {{end}}

Not equal: ne

{{$x := 7}} {{$y := 8}} {{ne $x $y}} returns true

Less than: lt

{{if lt (len .Args) 5}} output {{end}}

Less than or equal: le

{{$x := 7}} {{$y := 8}} {{le $x $y}} returns true

Greater than: gt

{{if gt (len .Args) 1}} output {{end}}

Greater than or equal: ge

{{$x := 7}} {{$y := 8}} {{ge $x $y}} returns false

and, or have more functions than you imagine. We'll explain them in the future.

PreviousGetting StartedNextThe Dot and Variables

Last updated 3 years ago

Was this helpful?

Converts the argument, number or string to type time.Duration. Number represents nanoseconds. String can be with time modifier: s (second), m (minute), h (hour), d (day), w (week), mo (month), y (year). Without a modifier, string will be converted to minutes. Example .

printf is usable for example to determine the type of the value:{{printf "%T" currentTime}}. In many cases, printf is a great alternative to joinStr for concatenating strings. Example .

Returns a random integer between 0 and stop, or start~stop if two arguments are provided. Result will be start <= random number < stop. Example .

Returns the nearest integer, rounding half away from zero.10.4 is 10 and 10.5 is 11. All round functions return type float64, so use conversion functions to get integers. Example .

Returns the least integer value greater than or equal to input or rounds up.{{roundCeil 1.1}}returns 2. Example .

Example .

Can be used on any message using its ID. channel can be either nil, channel's ID or its name. Example .

Same as sendMessage, but also returns messageID to assigned variable for later use. Example .

Example: {{index .Args 1}} returns first argument after trigger which is always at position 0. Example .

Example .

Example .

The carg should be one of the following types. int --- whole numbers, you can also optionally specify min and max after the name. Example: {{carg "int" "integer" 2 9}} required argument has to be a number from 2 to 9. float --- decimal numbers, you can also optionally specify min and max after the name similar to int. It is parsed as float64 datatype. string --- text. user --- user mentions, will have the type of User (more info ). userid --- user IDs, this user may not exist at all, both mentions and plain IDs are accepted, will have the type of int64. channel --- channel mentions, will have the type of Channel (more info ). member --- guild's member struct (object) to use later with .Member methods, like .JoinedAt (more info ). duration --- converts given integer number starting from minutes or string with modifier (s, m, h, w etc) to type Duration - e.g. 10 is 10m0s and 123s is 2m3s. Has additional options after the name for min and max range of duration presented in nanoseconds.

here
here
here
here
here
here
here
here
here
here
here
here
here
here