Skip to content

Latest commit

 

History

History
474 lines (448 loc) · 103 KB

functions.org

File metadata and controls

474 lines (448 loc) · 103 KB

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 “pagstdb” and getRole “pAgStDb” would have same responses even if server has both of these roles, so using IDs is better.

Index

Table of Contents

Channel

ProTip™
When channel argument is required for a function, it is always either nil for triggering channel, channel’s “name” or its ID.

NB!
The ratelimit for editing a channel is 2 requests per 10 minutes per channel.

FunctionDescription
editChannelName channel newNameFunction edits channel’s name. newName has to be of type string. For example > {{editChannelName nil (joinStr "" "PAGST - " (randInt 1000))}}
editChannelTopic channel newTopicFunction edits channel’s topic/description. newTopic has to be of type string. For example > {{editChannelTopic nil "PAGST is cool"}}
getChannel channelFunction returns full channel object of given channel argument, and is of type *templates.CtxChannel. For example > {{(getChannel nil).Name}} returns the name of the channel command was triggered in.
getChannelPins channelFunction returns a slice of all messages pinned to targeted channel. that
getChannelOrThread channelReturns type *templates.CtxChannel corresponding to channel object.
getPinCount channelReturns the count of pinned messages in given channel. Can be called 2 times for regular and 4 for premium servers.
getThread channelReturns type *templates.CtxChannel corresponding to channel object.

back to TOC

Database

FunctionDescriptionPAGST
dbBottomEntries pattern amount nSkipReturns amount (max 100)top entries of keys determined by the pattern from the database, sorted by the value in a ascending order.
dbCount (userID, pattern, query)Returns the count of all database entries which are not expired. Optional arguments userID, key, and query of type sdict.
dbDel userID IDDeletes the specified key for the specified value from the database.
dbDelByID userID IDDeletes database entry by its ID.
dbDelMultiple query amount skipDeletes amount (max 100) entries from the database matching the criteria provided. query should be an sdict with the following options. Function returns the number of rows that got deleted or an error.
dbGetPattern userID pattern amount nSkipRetrieves up to amount (max 100) entries from the database in ascending order.
dbGetPatternReverse userID pattern amount nSkipRetrieves up to amount (max 100) entries from the database in ascending order.
dbDecr userID key decryByDecrements the value for specified key for the specified user, if there was no value then it will be set to decrBy. Also returns the entry’s current, increased value.
dbIncr userID key incrByIncrements 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 keyReturns the rank of the entry specified by the user ID and key provided in the set of entries matching the criteria provided. query should be a sdict with the following options.
dbSet userID key valueSets 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 ttlSame as dbSet but with an expiration ttl which is an int and represents seconds.
dbTopEntries pattern amount nSkipReturns amount (max 100) top entries of keys determined by the pattern from the database, sorted by the value in a descending order

back to TOC

dbCount optional arguments

Optional arguments: if userID is given, counts entries for that userID;
if pattern, only those keys are counted that match the pattern; and if query is provided, it should be an sdict with the following keys:

 * userID - only counts entries with that userID, 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.

dbDelMultiple query options

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

dbRank query options

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

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 convert the number to type string 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).

back to TOC

ExecCC

All execCC calls are limited to 1 / CC for non-premium users and 10 / CC for premium users.

FunctionDescription
cancelSheduledUniqueCC ccID keyCancels a previously scheduled custom command execution using scheduleUniqueCC.
execCC ccID channel delay dataFunction that executes another custom command specified by ccID. With delay 0 the max recursion depth is 2 (using .StackDepth shows the current depth). execCC is 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. The delay argument is execution delay of another CC in seconds. The data argument is a 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.
sheduleUniqueCC ccID channel delay key dataSame as execCC except 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.

{{ $pag := "PAGSTDB rules! " }}
{{ $ctr := 0 }} {{ $yourCCID := .CCID }}
{{ if .ExecData }}
    {{ $ctr = add .ExecData.number 1 }}
    {{ $pag = joinStr "" $pag $ctr }} {{ .ExecData.PAGSTDB }}
{{ else }}
    So, someone rules.
    {{ $ctr = add $ctr 1 }} {{ $pag = joinStr "" $pag 1 }}
{{ end }}
{{ if lt $ctr 5 }}
    {{ execCC $yourCCID nil 10 (sdict "PAGSTDB" $pag "number" $ctr) }}
{{ else }} FUN'S OVER! {{ end }}

back to TOC

Math

FunctionDescriptionPAGST
absReturns absolute value of the argument as type float64.
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.
bitwiseAndThe 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: {{bitwiseAnd 12 25}} returns 8, that in binary 00001100 AND 00011001 is 00001000.
bitwiseAndNotHas an alias of bitwiseClear. 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. {{bitwiseClear 7 12}} returns 3, that is 0111 AND NOT 1100 is 11.
bitwiseNotThe bitwise NOT operator inverts the bits of the argument. Example: {{bitwiseNot 7}} returns -8. that in binary 0111 to 1000
bitwiseOr x y z …The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. Example: {{bitwiseOr 12 25}} returns 29, that in binary 00001100 OR 00011001 is 00011101.
bitwiseXorThe result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. Example: {{bitwiseXor 12 25}} returns 21, that in binary 00001100 OR 00011001 is 00010101.
bitwiseLeftShiftHas an alias of shiftLeft. 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: {{range seq 0 3}} {{shiftLeft 212 .}} {{end}} returns 212 424 848
bitwiseRightShiftHas an alias of shiftLeft. Right shift operator shifts all bits towards right by certain number of specified bits. Example: {{range seq 0 3}} {{shiftRight 212 .}} {{end}} returns 212 106 53.
cbrtReturns the cube root of given argument in type float64 e.g. {{cbrt 64}} returns 4.
cosReturns the cosine of the given radian argument as type float64.
div x y z …Division, like add or mult, function detects first number’s type first. {{div 11 3}} returns 3 whereas {{div 11.1 3}} returns 3.6999999999999997.
divMod numerator denominatorReturns a templates.Slice having quotient and remainder of given arguments.
expReturn e**x, the base-e componential of given argument as type float64.
exp2Returns 2**x, the base-2 exponential of given argument as type float64.
fdiv x y z …Meant specifically for floating point numbers division.
log x baseLog 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. {{log "123" 2}} will return 6.94251450533924.
mathConst “arg”Function returns all constants and integer, floating-point limit values available in golang’s math package as float64. “arg” has to be a case-insensitive string from math constants list.
max x yReturns the larger of x or y as type float64.
min x yReturns the smaller of x or y as type float64.
mod x yMod (modulo) 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 yPow 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.
randFloat (stop, start stop)Returns a random float64 between 0 and stop, or start - stop if two args are provided. Result will be start <= random number < stop
randInt (stop, 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.
roundReturns 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.
roundCeilReturns the least integer value greater than or equal to input or rounds up. {{roundCeil 1.1}} returns 2.
roundEvenReturns the nearest integer, rounding ties to even. {{roundEven 10.5}} returns 10, {{roundEven 11.5}} returns 12.
roundFloorReturns the greatest integer value less than or equal to input or rounds down. {{roundFloor 1.9}} returns 1.
sinReturns the sine of the given radian argument as type float64.
sqrtReturns the square root of a number as type float64. {{sqrt 49}} returns 7, {{printf "%.4f" (sqrt 12.34)}} returns 3.5128.
sub x y z …Returns x - y -z - … Works like add, just subtracts.
tanReturns the tangent of the given radian argument as type float64.

back to TOC

Math section’s snippets

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

Notice on bitwise functions

The bitwise logical and shift operators apply to integers only of which both can be signed and unsigned. The right-hand side of a shift operator, however, must be an unsigned integer.
Shift operators implement arithmetic shifts if the left operand is a signed integer and logical shifts if it is an unsigned integer.

back to TOC

Member

FunctionDescriptionPAGST
getTargetPermissionsIn memberID channelIDReturns target’s permissions in the given channel.
editNickname “newNick”Edits triggering user’s nickname, argument has to be of type string. PAGSTDB’s highest role has to be above the highest role of the member.
hasPermissions argReturns true/false on whether triggering user has the permission bit int64.
getBotCountReturns int count of members who are as .User.Bot.
getMember mention/userIDFunction returns Member object. {{(getMember .User.ID).JoinedAt}} is the same as {{.Member.JoinedAt}}.
getMemberCountReturns int count of members who are not .User.Bot.
onlineCountReturns the count of online users/members on current server.
targetHasPermissions memberID argReturns true/false on whether targeted member has the permission bit int64.

back to TOC

Mentions

FunctionDescriptionPAGST
mentionEveryoneMentions @everyone.
mentionHereMentions @here.
mentionRole roleMentions the role. Argument can be either role’s ID or its name. Replaces still working, but deprecated functions mentionRoleID and mentionRoleName.

There is also .Mention method available for role 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.

back to TOC

Message

FunctionDescriptionPAGST
addMessageReactions channel messageID emojis…Same as addReactions or addResponseReactions, but can be used on any messages using its ID. Example in section’s snippets.
addReactions “♥” “♦” …Adds each emoji as a reaction 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 “allowed_mentions” “content” arg “embed” arg “file” arg “filename” arg “reply” argFunction 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 type string keys allowed_mentions parses for allowed mentions, content for regular text, embed for embed arguments created by cembed or sdict, file for printing out content as a file with default name attachment_YYYY-MM-DD_HH-MM-SS.txt (max size 100 000 characters ca 100kB). filename lets you define a custom file name if file is used with max length of 64 characters, extension’s name remains .txt, reply replies to given messageID argument, more here. Example in this section’s snippets.
complexMessageEdit “content” arg “embed” argSpecial case for editMessage function - either if complexMessage is involved or works even with regular message. Has two type string parameters content, embed and allowed_mentions to edit message’s regular text part or its embed part. If embed key is set to nil, it deletes the whole embed. Example in this section’s snippets.
deleteAllMessageReactions channel messageID (emojis…)Deletes all reactions pointed message has. 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. (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. emojis argument can be up to 10 emojis, syntax is emojiName for Unicode/Discord’s default emojis and emojiName:emojiID for custom emotes. 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 newMessageContentEdits the message in given channel. Light example in section’s snippets.
editMessageNoEscape channel messageID newMessageContentEdits the message in given channel and has same logic in escaping characters as sendMessageNoEscape.
getMessage channel messageIDReturns requested Message object by its ID from given channel. channel.
lastMessages channel (limiter)Returns up to 25 last messages on channel, deleted not included, as type []*dstate.MessageState.
pinMessage channel messageIDPins a message by its ID in given channel. Can be called 5 times.
sendDM messageSends the user a direct/personal message, only one DM can be sent per custom command (accepts embed objects). PAGST will only DM triggering user.
sendMessage channel messageSends a message (string or embed) in given channel. Does not mention-ping users, roles, everyone and here. complexMessage to enables such mentions.
sendMessageNoEscape channel messageSends a message (string or embed) n given channel. Doesn’t escape mentions (e.g. user, role mentions or @here/@everyone) and reply-pings (no need for complexMessage “allowed_mentions”).
sendMessageNoEscapeRetID channel messageSame as sendMessageNoEscape, but also returns messageID for later use.
sendMessageRetID channel messageSame as sendMessage, but also returns messageID for later use. Example in section’s snippets.
sendTargetDM userID messageSends DM message to targeted user, this function can only be enabled by PAGST owner.
unpinMessage channel messageIDUnpins the message by its ID in given channel. Can be called 5 times.

back to TOC

complexMessage keys

"allowed_mentions"
    sdict with keys
    "parse" one string or a cslise of strings "users" "roles" "everyone" (for everyone and here),
    stating what general group to mention.

    "roles" roleID or a cslice of roleIDs
    "users" userID or a cslice of userIDs
    "reply" bool (enables reply-ping)
"content" - typical message content1
"embed" - for making embed(s) either single cembed or a slice or cembeds, max 10
"file" - content to output as a file
"filename" - logical, its name
"reply" - messageID to reply to

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 ":hearts:" ":diamonds:"}} {{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}}
  PAGSTDB rules!

* To demonstrate usage of complexMessage with sendMessage.
  {{sendMessage nil
      (complexMessage "content" "Who rules?"
      "embed" (cembed "description" "PAGST member 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" "PAGSTDB!" "color" 0x89aa00)
           "content" "Yes, it's always working with...")}}
   {{sleep 3}}
   {{editMessage nil $mID
       (complexMessageEdit "embed" nil
       "content" "Embed deleted, goodbye PAGST!")}}
   {{deleteMessage nil $mID 3}}

back to TOC

Miscellaneous

NB!
if, range, try-catch, while, with actions are all covered here.

FunctionDescriptionPAGST
adjectiveReturns a random adjective.
ccCountersReturns all running counters for CC as a map (keys are there).
cembed “embed fields and values”Function to generate embed inside custom command. More in-depth here.
createTicket author topicCreates a new ticket with the author and topic provided. Covered in its own section here.
cslice, sdictThese functions are covered in their own section here.
derefPointerDereferences pointer value.
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. 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.
editCCTriggerType ccID ccTypeChanges custom command’s trigger type, ccType is the name of the trigge type (“none”.”command”,”regex”, etc.)
exec “command” “arg” “arg” …Executes a PAGSTDB command (e.g. kick, roll etc) in a custom command. exec can be run max 5 times per CC. If real command returns an embed - exec will return raw data of type embed, so you can use embed fields for better formatting. NB! This will not work for commands with paginated embed returns, like un\nn commands! commands! exec syntax is explained here.
execAdmin “command” “arg” “arg” …Functions same way as exec but effectively runs the command as the bot user (PAGSTDB). This has essentially the same effect as if a user with the same permissions and roles as PAGSTDB ran the command.
execTemplate templateName dataExecutes the associated template with the given name using the data provided, returning the return value of the template, otherwise nil. {{define "cookies"}} {{return (println "people say:" .)}} {{end}} {{execTemplate "cookies" "DZ wants cookies!!!"}} returns people say: DZ wants cookies!!!.
getAuditLogEntriesRetrieves audit log entries struct. Has optional arguments “userid” int64 “before” int64 “action_type” int “limit” int.
hasPrefix string prefixhasPrefix tests whether the given string begins with prefix and returns bool. Example > {{hasPrefix "PAGSTDB" "PAG"}} returns true.
hasSuffix string suffixhasSuffix tests whether the given string ends with suffix and returns bool.
humanizeThousands arg (dotSeparator)This function places comma to separate groups of thousands of a number. arg can be int or string, has to be a whole number, the optional dotSeparator argument is a bool and defaults to false, if set true thousands are separated by a dot, not comma.
in list valueReturns bool true/false whether case-sensitive value is in a slice. {{in (cslice "PAGST" "member is cool") "pagst"}} returns false.
index arg keys…Returns the result by indexing its first argument arg with the following arguments, keys. Each indexed item must be a map, slice or array, indexed string returns value in uint8. 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 valueSimilar to in, but is case-insensitive. {{inFold (cslice "PAGST" "member is cool") "pagst"}} returns true.
kindOf arg (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 arg points to. Example: {{kindOf cembed false}} and {{kindOf cembed true}} will return ptr and struct.
len argReturns the integer length of its argument. arg can be an array, slice, map, or string. {{len (cslice 1 2 3)}} returns 3.
nounReturns a random noun.
ordinalize argReturns English ordinal numbers (st,nd,rd,th) for given arg.
parseArgs numRequiredArgs errorMessage …cargChecks the arguments for a specific type. Has methods .Get and .IsSet. carg “type” “name” is required by parseArgs and it defines the type of arguments for parseArgs function. More in depth here.
sendTemplate channel templateName dataFunction sends a formulated template to another channel and returns messageID. Template definitions are discussed here. Example snippets.
sendTemplateDM templateName dataWorks the same way as function above. Only channel’s name is not in the arguments. PAGSTDB will only DM the triggering user.
seq start stopCreates 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 100 000.
shuffle listReturns a shuffled, randomized version of a list/slice.
sleep argPauses execution of template’s action-structure inside custom command for max 60 seconds combined. Argument arg is an integer (whole number).
sort slice (…args)Sorts a slice with optional arguments. Numbers are sorted before strings. Arguments are presented in a sdict with keys having bool values. Sort function is limited to 1/10 CC calls regular/premium. More about sort arguments here.
verbReturns a random verb.

back to TOC

exec syntax

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

Sort arguments

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

 * Example:
   {{sort (cslice "PAGSTDB" 42 "Alphabet" 111 33.3)
          (sdict
                  "reverse" true
                  "subslices" true
                  "emptyslices" false)}}
   would return [111 42 33.3 PAGSTDB Alphabet]

Miscellaneous snippets

* sendTemplate 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" "PAGST members rule!"}}.

back to TOC

Role functions

NB!
Every role argument can be either role’s ID or its name. Delay is always optional and in seconds. Deprecated functions having ID/Name pairs, like giveRoleID/Name still all work and follow their old logic.

FunctionDescriptionPAGST
addRole role (delay)Adds the role to triggering user.
getRole roleReturns a role object of type *discordgo.Role.
giveRole userID role (delay)Gives a role to targeted userID.
hasRole roleReturns true if the triggerin user has the role.
removeRole role (delay)Removes the role from the user that triggered the command.
roleAbove role1 role2Compares two role objects e.g. getRole returns and gives true/false is role1 positioned higher than role2 or not.
setRoles userID rolesOverwrites the roles of the given user using the slice of role IDs. IDs can be ints or strings. Empty slice would clear the roles of the targeted user.
takeRole userID role (delay)Takes away a role from the targeted userID.
targetHasRole userID roleReturns true if the given user argument has the role.

back to TOC

String manipulation

FunctionDescriptionPAGST
joinStr “sepr” args…Joins arguments that have string, []string or easily converitble value into one string, separated by the first sepr argument.
lower “string”Converts the string to lowercase.
print, printf, printlnThese 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 is sheet here.
reFind “regex” “string”Compares “string” to regex pattern and returns first match. {{reFind "AG" "PAGST 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)p([a-z]+)g" "prancing PAGST"}} returns [[prancing rancin] [PAG A]] (regex pattern here is case insensitive). Optional count works the same way as for reFindAll.
reQuoteMeta “string”reQuoteMeta returns a string that escapes all regular expression metacharacters inside the argument text; the returned string is a regular expression matching the literal text.
reReplace “regex” “string1” “string2”Replaces string1 contents with string2 at regex match point. {{reReplace "I am" "I am cool!" "PAGSTDB is"}} returns PAGSTDB 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" "pagstdb has a lot of fame" 5}}{{$x}} {{index $x 3}} would return [p gstdb h s lot of f me] lot of f.
slice “string”|slice integer1 (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 integer1 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. This slice function is not the same as basic dynamically-sized slice data type discussed in this rtfm. Also it’s custom, not having 3-indices as the default one from text/template package. Example in section’s snippets.
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 "PAG, is cool!" ","}} returns [PAG is cool!] slice where PAG is at index position 0 and is cool! at index position 1. Example also in section’s snippets.
title “string”Returns the string with the first letter of each word capitalized.
trim, trimLeft, trimRight string cutsetTrim returns the string with all leading and/or trailing Unicode code points contained in cutset removed.
trimSpace stringReturns the string with all leading and trailing white space removed.
upper “string”Converts the string to uppercase.
urlescape, urlunescape “string”Escapes or unescapes the string so it can be safely placed inside a URL path segment. There’s also predefined template package function urlquery which is covered here.

back to TOC

Escape sequences

Special information we can always 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’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, PAGST, here!"}} {{range $k, $v := (split $x ", ")}}Word {{$k}}: __{{$v}}__ {{end}}
* To demonstrate usage of reFindAll. >
  Before regex: {{$msg := "1 PAGSTDB and over 100 servers conquered."}} {{$re2 := reFindAll "[0-9]+" $msg}} {{$msg}}
  After regex matches: {{joinStr " " "Only" (index $re2 0) "PAGSTDB and already" (index $re2 1) "servers captured."}}

back to TOC

Time

FunctionDescriptionPAGST
currentTimeReturns the current time, value is of type time.Time.
formatTime time (“layout arg”)Outputs given time in RFC822 formatting, first argument time 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, humanizeDurationMinutes, humanizeDurationMinutes, humanizeTimeSinceDaysFunctions return given integer (whole number) or time.Duration argument in nanoseconds in human readable format.
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. timezone is an optional argument of type string which uses golang’s LoadLocation function and ZONEINFO syntax.
parseTime timeString layout (location)parseTime function uses golang’s time.ParseInLocation function. location must be a slice of strings or a single string. Max number of layouts is 50.
snowflakeToTime snowflakeConverts given snowflake to type time.Time e.g. using PAGSTDB’s ID {{snowflakeToTime .BotUser.ID}} returns 2018-10-29 06:58:14 +0000 UTC.
weekNumber timeReturns 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.

back to TOC

Type conversion

FunctionDescriptionPAGST
decodeStringToHex argReturns the bytes as []byte represented by the hexadecimal string arg. Function expects that arg contains only hexadecimal characters and that arg has even length. Good for finding RGB decimal values : )
hexToDecimalConverts hex presentation to decimal value, returned as int.
json valueTraverses given value through MarshalJSON (more here) and returns it as type string. Basically it’s good to use if multistep type conversion is needed and for struct layouts.
jsonToSdict valueFunction converts given value in JSON formatting to templates.SDict. Good to use for example with cembed.
structToSdict structFunction converts exported field-value pairs of a struct to a sdict. For example it is useful for editing embeds, rather than having to reconstruct the embed field by field manually.
toByte argFunction converts input to a slice of bytes - meaning []uint8. {{toByte "PAGST€"}} would output [80 65 71 83 84 226 130 172]. toString is capable of converting that slice back to string.
toDurationConverts 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.
toFloatConverts argument (int or string type of a number) to type float64. Function will return 0, if type can’t be converted to float64.
toIntConverts argument into an integer of type int. Function will return 0, if type can’t be converted to int.
toInt64Converts argument into an int64. Function will return 0, if type can’t be converted to int64.
toInt64Base16Converts argument to int64 in base16. Function will return 0, if type can’t be converted to int64
toRune argFunction converts input to a slice of runes - meaning []int32. {{toRune "PAGST€"}} would output [80 65 71 83 84 8364]. toString is capable of converting that slice back to string.
toSHA256Returns the SHA256 checksum of given argument. Function does not return anything if argument can’t be converted to SHA256 checksum.
toString, strtoString and its alias str, both convert the argument into a string.

back to TOC

User

FunctionDescriptionPAGST
currentUserAgeHumanThe account age of the current user in more human readable format.
currentUserAgeMinutesThe account age of the current user in minutes.
currentUserCreatedReturns value of type time.Time and shows when the current user was created.
pastNicknames userID offsetSame as pastUsernames.
pastUsernames userID offsetReturns a slice of type [ ]*logs.CCNameChange having fields .Name and .Time of previous 15 usernames and skips offset number in that list.
userArg mention/userIDFunction that can be used to retrieve .User object from a mention or userID. userArg has no call limits. call-limits.

back to TOC