Kord Extensions Help

Converters

Converters are a core part of the Kord Extensions command framework. They provide a way to convert arguments provided by Discord into rich data types, handling parsing and validation, and making sure you get the types you expect.

Converter Types

As converters support multiple parsing strategies, they're divided into specific types. Each type handles its arguments in a different way, and some are limited to specific types of commands:

Type

Commands

Description

Single

All

The default converter type, which represents a single, mandatory command argument.

Defaulting

All

A converter type that represents an optional command argument, with a specified default value. The default value will be used when no argument is provided.

Optional

All

A converter type that represents an optional command argument, with a default value of null. The default value will be used when no argument is provided.

Coalescing

All

A converter type that attempts to consume as many arguments as possible, combining them into a single value. This converter type will stop at the first argument that it can't parse, passing control to the next converter.

Note: Coalescing converters will only ever parse a single value when used in a slash command, as Discord does not support argument types that accept multiple values.

List

All

A converter type that acts like a coalescing converter, but which returns a list of parsed arguments instead of a single combined value.

Note: List converters will only ever parse a single value when used in a slash command, as Discord does not support argument types that accept multiple values.

Choice

All

A converter type that represents a single argument that is limited to a predefined set of specific choices. When used with Slash Commands, user input will be limited to the given choices.

Usage

Converters provide builder functions that you can use to define your command arguments. These functions are available for use within classes that extend Arguments, as briefly explained on the commands overview page.

Once you've created your arguments class, you'll need to figure out which converter functions you'll need. You can figure out the name of the relevant function by following these rules:

  • Single converters simply use the name of the argument type — for example, string, int, message.

  • List converters use the single converter name with the List suffix — for example, stringList, intList, messageList.

  • All other converter types add prefixes to the single converter name — for example, coalescingString, defaultingInt, optionalMessage.

  • Defaulting and optional converters may be combined with other types, with an additional suffix added to the single converter name — for example, coalescingOptionalString.

inner class WelcomeArgs : Arguments() { val target by user { name = "target" description = "User to welcome" } val message by defaultingString { name = "message" description = "Message to send to the user" defaultValue = "Welcome to the server, {TARGET}!" } }

Converter Settings

All converters must be specified via delegation, as explained in the example above. Each converter builder function exposes a set of options that can be used to customize the behavior of the converter in question.

Common Settings

Properties

Name

Type

Description

Required Properties

description

Key

Required: Key object representing a short description of the argument, which explains what it's for.

name

Key

Required: Key object representing the argument's name.

For Chat Commands, this name is displayed in help commands and used to refer to the argument by name when specified as a keyword argument.

For Slash Commands, this name is displayed within the Discord client, where it's used to identify the argument.

Auto-Completion

When working with slash commands, Discord supports the ability to provide suggestions to the user when they're filling out specific arguments. You can use the autoComplete builder when defining your argument if you wish to support this.

The autoComplete builder is a receiver function against the AutoCompleteInteraction type, with an event argument of the AutoCompleteInteractionCreateEvent type. A number of APIs are available to make things easier.

class AutoCompleteArgs : Arguments() { private val optionsMap = mapOf( "One" to "1", "Two" to "2", "Three" to "3", "Four" to "4", "Five" to "5", "Six" to "6", "Seven" to "7", "Eight" to "8", "Nine" to "9", "Ten" to "10", ) val arg by string { name = "input" description = "Autocomplete argument" autoComplete { suggestStringMap(optionsMap) } } }

Functions

All the below functions are used to suggest potential argument values to the user. They automatically limit themselves to suggesting up to the maximum possible number of values, and they support the following arguments:

  • strategy - the filtering strategy to use, based on the data the user has entered so far. While it's possible to define your own, the following are provided:

    • FilterStrategy.Contains - Filter options based on whether they contain the provided data.

    • FilterStrategy.Prefix - Filter options based on whether they start with the provided data.

    • FilterStrategy.Suffix - Filter options based on whether they end with the provided data.

  • suggestInputWithoutMatches - When the given filtering strategy doesn't match anything, whether to suggest the user's provided data as a possible option. This may be useful for arguments that represent a form of data that will be created if an existing value isn't found.

    Defaults to false.

Name

Description

suggestDoubleCollection

Use a collection (such as a list) of doubles to suggest potential argument values to the user.

suggestDoubleMap

Use a map of strings to doubles to suggest potential argument values to the user.

The string keys are displayed to the user, and mapped to their corresponding value when the argument is filled. They should be a human-readable representation of the given value.

suggestIntCollection

Use a collection (such as a list) of integers to suggest potential argument values to the user.

suggestIntMap

Use a map of strings to integers to suggest potential argument values to the user.

The string keys are displayed to the user, and mapped to their corresponding value when the argument is filled. They should be a human-readable representation of the given value.

suggestLongCollection

Use a collection (such as a list) of longs to suggest potential argument values to the user.

suggestLongMap

Use a map of strings to longs to suggest potential argument values to the user.

The string keys are displayed to the user, and mapped to their corresponding value when the argument is filled. They should be a human-readable representation of the given value.

suggestNumberCollection

Use a collection (such as a list) of doubles (Discord's default number type) to suggest potential argument values to the user.

suggestNumberMap

Use a map of strings to doubles (Discord's default number type) to suggest potential argument values to the user.

The string keys are displayed to the user, and mapped to their corresponding value when the argument is filled. They should be a human-readable representation of the given value.

suggestStringCollection

Use a collection (such as a list) of strings to suggest potential argument values to the user.

suggestStringMap

Use a map of string keys to values to suggest potential argument values to the user.

The string keys are displayed to the user, and mapped to their corresponding value when the argument is filled. They should be a human-readable representation of the given value.

Properties

Name

Type

Description

focusedOption

OptionValue<*>

The argument that's currently being focused by the user. You can use this property to retrieve the data the user has entered for this argument so far.

Mutators

Mutators allow you to modify the argument's value after it's been filled. This is only useful in a limited number of use-cases, but may be handy for providing light customizations for existing converter types.

To define a mutator, call the mutate builder function. This builder takes the existing value as its first argument, expecting the modified value to be the return value.

No additional APIs are provided.

class MutatedArgs : Arguments() { val quoted by string { name = "input" description = "Mutated argument" mutate { value -> "Quoted: \"$value\"" } } }

Validators

Validators allow you to validate the argument's value after it's been filled, potentially returning an error to the user if the value fails to validate.

To define a validator, call the validate builder function. This builder is a receiver function against the ValidationContext type, which provides an API similar to that of a check context.

class ValidatedArgs : Arguments() { val odd by int { name = "input" description = "Validated argument" validate { failIf("Odd numbers only, please!") { value % 2 == 0 } } } }

Functions

Name

Description

fail

Mark this validator as having failed, optionally providing a message for the user.

failIf

If the given value (or result of the given callback) is true, mark this validator as having failed, optionally providing a message for the user.

failIfNot

If the given value (or result of the given callback) is false, mark this validator as having failed, optionally providing a message for the user.

pass

Mark this validator as having passed successfully. As this is the default state of a validator, this function is only useful when the validator may have failed previously.

passIf

If the given value (or result of the given callback) is true, mark this validator as having passed successfully. As this is the default state of a validator, this function is only useful when the validator may have failed previously.

passIfNot

If the given value (or result of the given callback) is false, mark this validator as having passed successfully. As this is the default state of a validator, this function is only useful when the validator may have failed previously.

Boolean.whenFalse

Call the given block only when the Boolean receiver is false. Returns null instead of the result of the block if the Boolean is true.

Boolean.whenTrue

Call the given block only when the Boolean receiver is true. Returns null instead of the result of the block if the Boolean is false.

Properties

Name

Type

Description

context

CommandContext

Context object representing the current command execution.

errorResponseKey

Key

Translation Key object, which is used to format the error message when validation fails.

A plain string may not work here, as a single replacement value (the error message) must be inserted by the translation system.

Defaults to checks.responseTemplate.

message

String?

Human-readable error message. This message is usually provided by the relevant API functions and isn't usually specified manually.

Defaults to null, which will result in a generic failure message.

passed

Boolean

Whether this validator has passed. This property is modified by the relevant API functions, and isn't usually modified manually.

value

T

The current argument's value.

Choice Converters

Choice converters allow you to specify a set of predefined command options via a simple API.

Functions

Name

Description

choice

Add a choice.

This function takes a Key object, which will be shown to the user on Discord when using Slash Commands.

When the command is submitted, the corresponding value will be provided as the value for your argument.

choices

If you have a pre-defined map of choices, this function will use that map as the predefined argument options. This will replace any choices that may have been defined previously.

This map's Key objects must represent a human-readable representation of their corresponding values, as they'll be shown to the user on Discord.

If preferred, the choices property may be set directly instead.

Coalescing Converters

Properties

Name

Type

Description

ignoreErrors

Boolean

Whether to ignore errors thrown while attempting to parse a given value, assuming no values have been parsed yet. This is true by default, but you may wish to set it to false for coalescing arguments at the end of the list.

Defaulting Converters

Properties

Name

Type

Description

defaultValue

T

Value to use when the user doesn't provide this argument, or when it fails to parse and ignoreErrors is set to true.

ignoreErrors

Boolean

Whether to ignore errors thrown while attempting to parse a given value. This is false by default. When set to true, the provided defaultValue will be used as the argument value instead of returning an error to the user.

List Converters

Properties

Name

Type

Description

ignoreErrors

Boolean

Whether to ignore errors thrown while attempting to parse a given value, assuming no values have been parsed yet. This is false by default. When set to true, an empty list will be used as the argument value instead of returning an error to the user.

Optional Converters

Properties

Name

Type

Description

ignoreErrors

Boolean

Whether to ignore errors thrown while attempting to parse a given value. This is false by default. When set to true, null will be used as the argument value instead of returning an error to the user.

Bundled Converters

Kord Extensions provides a number of converters for common data types, which you can make use of in your bots.

Type

Description

General Converters

Boolean

Boolean argument, with support for translated values.

Supported Inputs

The list below shows all supported inputs in English. Translated inputs are also supported.

  • Truthy responses: 1, y, yes, t, true

  • Falsey responses: 0, n, no, f, false

Color

Color argument, supporting hex codes prefixed with # or 0x, plain RGB integers, or color names matching Discord's branding colors.

The values returned by this converter will be Kord Color objects.

Converter functions matching both US English ("color") and UK English ("colour") are available. Translated color names are also supported.

Decimal

Decimal argument, parsing the provided value into a Double.

Converter Properties
  • maxValue (Double?) — Optionally, the maximum value that may be provided.

  • minValue (Double?) — Optionally, the minimum value that may be provided.

Duration

Duration argument, using a complex parsing strategy to transform the provided value into a DateTimePeriod object. This object is timezone-agnostic, and may need to be normalized against a specific timezone for some use-cases.

This is also available as a coalescing converter.

Converter Properties
  • longHelp (Boolean, default: true) — Whether to respond with a long help message explaining precisely how to specify a duration when the provided value cannot be parsed. If this has been set to false, only a short error stating that the duration could not be parsed will be provided.

  • positiveOnly (Boolean, default: true) — Whether a positive duration is required. This may be set to false if you wish to allow users to specify a negative duration.

In addition to Discord-formatted timestamps, this converter supports specifying durations as a series of units and durations.

Specification

Durations may be specified within a string, as pairs containing both a unit and a numeric value. Commas, spaces, and the plus character ("+") are removed from the provided string before parsing.

Pairs may be specified in any order, and duplicate pairs will be added together (or subtracted, in the case of a negative numeric value). Both ordered forms are supported to allow for natural input in right-to-left languages:

  • Value first: 12 days

  • Unit first: d12

Negative values may be specified by prefixing the numeric value with a minus sign ("-"). Only base-10 ASCII integers are supported.

Supported units

The list below shows all supported units, along with the names that may be used to refer to them in English. Translated names are also supported.

  • Seconds: s, sec, secs, second, seconds

  • Minutes: m, mi, min, mins, minute, minutes

  • Hours: h, hr, hour, hours

  • Days: d, day, days

  • Weeks: w, wk, week, weeks

  • Months: mo, mth, month, months

  • Years: y, yr, year, years

Examples

The following examples are valid duration strings:

  • 12d 4h 30m - 12 days, 4 hours and 30 minutes.

  • 12d 4h 30m -1 w - 5 days (12 - 7), 4 hours and 30 minutes.

  • -2d 1w 6h -2h - 5 days (7 - 2) and 4 hours (6 - 2).

  • 周3 日2 分30 - in Simplified Chinese, 23 days (3 * 7 + 2) and 30 minutes.

The following examples are invalid:

  • 12 - bare numbers are not supported, a unit is required.

  • 12m d w - all units require a numerical value.

  • -5 days with positiveOnly = true - the current converter only accepts positive durations.

Email

Email argument, validated using the Apache Commons email validator.

Enum

Arbitrary enum argument, allowing for the specification of enum value names. By default, enum value names will be matched case-insensitively. This is also available as a choice converter.

The enum to use is specified by providing a generic type parameter to the converter's builder function. This will be referred to as E below.

Converter Properties
  • Required: typeName (Key) — Key object representing a human-readable short name for whatever the given enum represents. Should be no more than two or three words.

  • getter (suspend (String) -> E?) — Optional getter function used to transform the input value into an enum value. By default, case-insensitively matches the input value against the enum value names.

Int

Integer argument, parsing the provided value into an Int.

Converter Properties
  • maxValue (Int?) — Optionally, the maximum value that may be provided.

  • minValue (Int?) — Optionally, the minimum value that may be provided.

  • radix (Int, default: 10) — Optionally, the radix (base) to use to parse the value.

Long

Long argument, parsing the provided value into a Long. This is also available as a choice converter, as a converter named number.

Converter Properties
  • maxValue (Int?) — Optionally, the maximum value that may be provided.

  • minValue (Int?) — Optionally, the minimum value that may be provided.

  • radix (Int, default: 10) — Optionally, the radix (base) to use to parse the value.

Regex

Regex argument, allowing users to specify a regular expression.

Converter Properties
  • options (MutableSet<RegexOption>) — Set of regular expression options. Options added to this set will be used when creating the Regex object.

Serialized

Serialized argument, converting values to the given type using kotlinx.serialization.

Converter Properties
  • Required: typeName (Key) — Key object representing a human-readable short name for whatever the given type represents. Should be no more than two or three words.

String

String argument, providing users' input verbatim. This is also available as a choice converter or coalescing converter.

Converter Properties
  • maxLength (Int?) — Maximum length for the input string.

  • minLength (Int?) — Minimum length for the input string.

Supported Locale

Supported locale argument, allowing users to provide one of Kord Extensions' supported locales. This converter will return a Locale object if the specified locale is one that Kord Extensions supports.

If a locale you need isn't supported, please feel free to contribute translations for it.

Discord Entities

Channel

Discord channel argument, supporting mentions, IDs, and names. Also supports "this" to refer to the current channel.

When working with slash commands, the Discord client resolves the channel object instead of the bot. This means that the converter will only ever return the channel object provided by the client, and cannot resolve the special name "this." It will also ignore the requiredGuild and requireSameGuild properties.

Converter Functions
  • requireChannelType(type: ChannelType) — Require that the resolved channel be of the specified type. May be called multiple times for multiple channel types.

Converter Properties
  • requiredChannelTypes (MutableSet<ChannelType>) — Require that the resolved channel be of one of the supplied types. Calls to requireChannelType will add the provided type to this set.

  • requiredGuild (suspend () -> Snowflake) — Limit channel resolution to a specific guild ID.

  • requireSameGuild (Boolean, default: true) — Limit channel resolution to channels on the same guild the command was executed within.

Emoji

Emoji argument, supporting Unicode emojis, guild emoji IDs, guild emoji names, and Unicode emoji names as used by Discord's emoji picker. Guild emoji IDs may be specified with or without surrounding colons, or specified using the emoji mentions that the Discord client inserts into messages.

When a guild emoji is specified, it must come from a guild the bot is present on. If a guild emoji is specified only by name, the first emoji the bot finds from its guilds is used.

Guild

Discord guild argument, supporting IDs and names. Also supports "this" to refer to the current guild.

The guild specified must be a guild the bot is present on.

Member

Discord guild member argument, supporting mentions, IDs, usernames, tags, and names. Also supports "me" to refer to the member running the command, and "you" to refer to the bot.

When working with slash commands, the Discord client resolves the member object instead of the bot. This means that the converter will only ever return the member object provided by the client, and cannot resolve the special names "me" or "you."

Converter Properties
  • requiredGuild (suspend () -> Snowflake) — Limit member resolution to a specific guild ID. This will additionally require the command to be run on the guild represented by that ID.

  • requireSameGuild (Boolean, default: true) — Limit member resolution to users on the same guild the command was executed within.

  • useReply (Boolean, default: true) — For Chat Commands, whether to use the author of the replied-to message (when there is one).

Message

Discord message argument, supporting message jump URLs and IDs. When a message ID is specified, it's assumed to be in the same channel the command was executed within.

Messages will be retrieved if they're not already in Kord's cache, which requires the bot to be able to see the message in question. When using a URL, the bot cannot resolve messages in DMs.

Converter Properties
  • requiredGuild (suspend () -> Snowflake) — Limit message resolution to a specific guild ID. This will additionally require the command to be run on the guild represented by that ID.

  • requireGuild (Boolean, default: true) — If requiredGuild is specified, limit message resolution to the guild returned by that property. Otherwise, limit message resolution to the same guild the command was executed within.

  • useReply (Boolean, default: true) — For Chat Commands, whether to use the replied-to message (when there is one).

Role

Discord role argument, supporting role mentions, names, and IDs. Role resolution via commands run in DMs is not supported.

When working with slash commands, the Discord client resolves the role object instead of the bot. This means that the converter will only ever return the role object provided by the client, and the requiredGuild property will be ignored.

Converter Properties
  • requiredGuild (suspend () -> Snowflake) — Limit role resolution to a specific guild ID. When omitted, this will default to the guild the command was executed within.

Snowflake

Discord snowflake argument. Parses the given value into a Snowflake object.

Tag

Discord forum channel tag argument. Provides built-in Auto-Completion support for tags based on the current channel or the channelGetter property.

Converter Properties
  • channelGetter (suspend () -> ForumChannel?) — Limit tag resolution to the given forum channel. This is used for both auto-completion and tag resolution on command execution.

Timestamp

Discord timestamp argument. Parses a Discord-formatted timestamp into a FormattedTimestamp object, which includes the corresponding Instant and TimestampType.

This converter only supports Discord-formatted timestamps, and is unable to parse any other form of timestamp.

User

Discord user argument supporting mentions, IDs, usernames, and tags. Also supports "me" to refer to the member running the command, and "you" to refer to the bot.

When working with slash commands, the Discord client resolves the user object instead of the bot. This means that the converter will only ever return the user object provided by the client, and cannot resolve the special names "me" or "you."

Converter Properties
  • useReply (Boolean, default: true) — For Chat Commands, whether to use the author of the replied-to message (when there is one).

Slash Commands Only

Attachment

A file attachment, as provided in a slash command invocation. Discord will display a drop target for this type of argument.

Last modified: 20 November 2024