Skip to main content

Class: Args

The argument parser to be used in Command.

Constructors

constructor

new Args(message, command, parser, context): Args

Parameters

NameType
messageMessage<boolean>
commandMessageCommand
parserArgumentStream
contextMessageCommandContext

Returns

Args

Defined in

projects/framework/src/lib/parsers/Args.ts:59

Properties

command

Readonly command: MessageCommand

The command that is being run.

Defined in

projects/framework/src/lib/parsers/Args.ts:40


commandContext

Readonly commandContext: MessageCommandContext

The context of the command being run.

Defined in

projects/framework/src/lib/parsers/Args.ts:45


message

Readonly message: Message<boolean>

The original message that triggered the command.

Defined in

projects/framework/src/lib/parsers/Args.ts:35


parser

Protected Readonly parser: ArgumentStream

The internal Lexure parser.

Defined in

projects/framework/src/lib/parsers/Args.ts:50


states

Private Readonly states: State[] = []

The states stored in the args.

See

  • Args#save
  • Args#restore

Defined in

projects/framework/src/lib/parsers/Args.ts:57

Accessors

finished

get finished(): boolean

Whether all arguments have been consumed.

Returns

boolean

Defined in

projects/framework/src/lib/parsers/Args.ts:725

Methods

getFlags

getFlags(...keys): boolean

Checks if one or more flag were given.

Parameters

NameTypeDescription
...keysreadonly string[]The name(s) of the flag.

Returns

boolean

Example

// Suppose args are from '--f --g'.
console.log(args.getFlags('f'));
// >>> true

console.log(args.getFlags('g', 'h'));
// >>> true

console.log(args.getFlags('h'));
// >>> false

Defined in

projects/framework/src/lib/parsers/Args.ts:615


getOption

getOption(...keys): null | string

Gets the last value of one or more options. Similar to Args.getOptionResult but returns the value on success, or null if not.

Parameters

NameTypeDescription
...keysreadonly string[]The name(s) of the option.

Returns

null | string

Example

// Suppose args are from '--a=1 --b=2 --c=3'.
console.log(args.getOption('a'));
// >>> '1'

console.log(args.getOption('b', 'c'));
// >>> '2'

console.log(args.getOption('d'));
// >>> null

Defined in

projects/framework/src/lib/parsers/Args.ts:658


getOptionResult

getOptionResult(...keys): Option<string>

Gets the last value of one or more options as an Option. If you do not care about safely handling non-existing values you can use Args.getOption to get string | null as return type

Parameters

NameTypeDescription
...keysreadonly string[]The name(s) of the option.

Returns

Option<string>

Example

// Suppose args are from '--a=1 --b=2 --c=3'.
console.log(args.getOptionResult('a'));
// >>> Some { value: '1' }

console.log(args.getOptionResult('b', 'c'));
// >>> Some { value: '2' }

console.log(args.getOptionResult('d'));
// >>> None {}

Defined in

projects/framework/src/lib/parsers/Args.ts:637


getOptions

getOptions(...keys): null | readonly string[]

Gets all the values of one or more option. Similar to Args.getOptionsResult but returns the value on success, or null if not.

Parameters

NameTypeDescription
...keysreadonly string[]The name(s) of the option.

Returns

null | readonly string[]

Example

// Suppose args are from '--a=1 --a=1 --b=2 --c=3'.
console.log(args.getOptions('a'));
// >>> ['1', '1']

console.log(args.getOptions('b', 'c'));
// >>> ['2', '3']

console.log(args.getOptions('d'));
// >>> null

Defined in

projects/framework/src/lib/parsers/Args.ts:702


getOptionsResult

getOptionsResult(...keys): Option<readonly string[]>

Gets all the values of one or more option.

Parameters

NameTypeDescription
...keysreadonly string[]The name(s) of the option.

Returns

Option<readonly string[]>

Example

// Suppose args are from '--a=1 --a=1 --b=2 --c=3'.
console.log(args.getOptionsResult('a'));
// >>> Some { value: [ '1' ] }

console.log(args.getOptionsResult('a', 'd'));
// >>> Some { value: [ '1' ] }

console.log(args.getOptionsResult('b', 'c'));
// >>> Some { value: [ '2', '3' ] }

console.log(args.getOptionsResult('d'));
// >>> None {}

Defined in

projects/framework/src/lib/parsers/Args.ts:681


missingArguments

missingArguments(): Err<UserError>

Returns

Err<UserError>

Defined in

projects/framework/src/lib/parsers/Args.ts:747


next

next(): string

Similar to Args.nextMaybe but returns the value on success, null otherwise.

Returns

string

Example

// !numbers 1 2 3

console.log(args.next());
// -> '1'

Defined in

projects/framework/src/lib/parsers/Args.ts:576

next<T>(cb): T

Similar to Args.nextMaybe but returns the value on success, null otherwise.

Type parameters

Name
T

Parameters

NameTypeDescription
cbArgsNextCallback<T>Gives an option of either the resulting value, or nothing if failed.

Returns

T

Typeparam

T Output type of the callback.

Example

// !numbers 1 2 3
const parse = (x: string) => {
const n = Number(x);
return Number.isNaN(n) ? none() : some(n);
};

console.log(args.nextMaybe(parse));
// -> 1

Defined in

projects/framework/src/lib/parsers/Args.ts:593


nextMaybe

nextMaybe(): Option<string>

Retrieves the next raw argument from the parser.

Returns

Option<string>

Example

// !numbers 1 2 3

console.log(args.nextMaybe());
// -> { exists: true, value: '1' }

Defined in

projects/framework/src/lib/parsers/Args.ts:543

nextMaybe<T>(cb): Option<T>

Retrieves the value of the next unused ordered token, but only if it could be transformed. That token will now be used if the transformation succeeds.

Type parameters

Name
T

Parameters

NameTypeDescription
cbArgsNextCallback<T>Gives an option of either the resulting value, or nothing if failed.

Returns

Option<T>

Typeparam

T Output type of the callback.

Example

// !numbers 1 2 3
const parse = (x: string) => {
const n = Number(x);
return Number.isNaN(n) ? none() : some(n);
};

console.log(args.nextMaybe(parse));
// -> { exists: true, value: 1 }

Defined in

projects/framework/src/lib/parsers/Args.ts:561


peek

peek<T>(type): Promise<T>

Similar to Args.peekResult but returns the value on success, throwing otherwise.

Type parameters

Name
T

Parameters

NameTypeDescription
type() => Result<T>The function, custom argument, or argument name.

Returns

Promise<T>

Example

// !bigintsumthensquarefirst 25 50 75
const resolver = Args.make((arg, { argument }) => {
try {
return Args.ok(BigInt(arg));
} catch {
return Args.error({ parameter: arg, argument, identifier: 'InvalidBigInt', message: 'You must specify a valid number for a bigint.' })
}
});

const peeked = await args.repeatResult(resolver);
await peeked.inspectAsync((value) => message.channel.send(`Sum: **${value.reduce((x, y) => x + y, 0n)}**`)); // Sum: 150n

const first = await args.pick(resolver);
await message.channel.send(`First bigint squared: ${first**2n}`); // First bigint squared: 625

Defined in

projects/framework/src/lib/parsers/Args.ts:481

peek<T>(type, options?): Promise<T>

Similar to Args.peekResult but returns the value on success, throwing otherwise.

Type parameters

Name
T

Parameters

NameTypeDescription
typeIArgument<T>The function, custom argument, or argument name.
options?ArgOptionsThe peek options.

Returns

Promise<T>

Example

import { SnowflakeRegex } from '@sapphire/discord.js-utilities';
import { DiscordSnowflake } from '@sapphire/snowflake';

// !createdat 730159185517477900
const snowflakeResolver = Args.make<bigint>((arg, { argument }) => {
return SnowflakeRegex.test(arg)
? Args.ok(BigInt(arg))
: Args.error({ parameter: arg, argument, identifier: 'InvalidSnowflake', message: 'You must specify a valid snowflake.' });
});

const snowflake = await args.peek(snowflakeResolver);
const timestamp = Number((snowflake >> 22n) + DiscordSnowflake.epoch);
const createdAt = new Date(timestamp);

await message.channel.send(
`The snowflake ${snowflake} was registered on ${createdAt.toUTCString()}.`
); // The snowflake 730159185517477900 was registered on Tue, 07 Jul 2020 20:31:55 GMT.

const id = await args.pick('string');
await message.channel.send(`Your ID, reversed: ${id.split('').reverse().join('')}`); // Your ID, reversed: 009774715581951037

Defined in

projects/framework/src/lib/parsers/Args.ts:510

peek<K>(type, options?): Promise<ArgType[K]>

Similar to Args.peekResult but returns the value on success, throwing otherwise.

Type parameters

NameType
Kextends keyof ArgType

Parameters

NameTypeDescription
typeK | () => Result<ArgType[K]>The function, custom argument, or argument name.
options?ArgOptionsThe peek options.

Returns

Promise<ArgType[K]>

Example

// !messagelink https://discord.com/channels/737141877803057244/737142209639350343/791843123898089483
const remoteMessage = await args.peek('message');
await message.channel.send(
`${remoteMessage.author.tag}: ${remoteMessage.content}`
); // RealShadowNova#7462: Yeah, Sapphire has been a great experience so far, especially being able to help and contribute.

const url = await args.pick('hyperlink');
await message.channel.send(`Hostname: ${url.hostname}`); // Hostname: discord.com

Defined in

projects/framework/src/lib/parsers/Args.ts:527


peekResult

peekResult<T>(type): Promise<ResultType<T>>

Peeks the following parameter(s) without advancing the parser's state. Passing a function as a parameter allows for returning Args.pickResult, Args.repeatResult, or Args.restResult; otherwise, passing the custom argument or the argument type with options will use Args.pickResult and only peek a single argument.

Type parameters

Name
T

Parameters

NameTypeDescription
type() => Result<T>The function, custom argument, or argument name.

Returns

Promise<ResultType<T>>

Example

// !reversedandscreamfirst hello world
const resolver = Args.make((arg) => Args.ok(arg.split('').reverse().join('')));

const result = await args.repeatResult(resolver);
await result.inspectAsync((value) =>
message.channel.send(`Reversed ${value.length} word(s): ${value.join(' ')}`)
); // Reversed 2 word(s): olleh dlrow

const firstWord = await args.pickResult('string');
await firstWord.inspectAsync((value) =>
message.channel.send(firstWord.value.toUpperCase())
); // HELLO

Defined in

projects/framework/src/lib/parsers/Args.ts:403

peekResult<T>(type, options?): Promise<ResultType<T>>

Peeks the following parameter(s) without advancing the parser's state. Passing a function as a parameter allows for returning Args.pickResult, Args.repeatResult, or Args.restResult; otherwise, passing the custom argument or the argument type with options will use Args.pickResult and only peek a single argument.

Type parameters

Name
T

Parameters

NameTypeDescription
typeIArgument<T>The function, custom argument, or argument name.
options?ArgOptionsThe peekResult options.

Returns

Promise<ResultType<T>>

Example

// !reverseandscreamfirst sapphire community
const resolver = Args.make((arg) => Args.ok(arg.split('').reverse().join('')));

const peekedWord = await args.peekResult(resolver);
await peekedWord.inspectAsync((value) => message.channel.send(value)); // erihppas

const firstWord = await args.pickResult('string');
await firstWord.inspectAsync((value) => message.channel.send(value.toUpperCase())); // SAPPHIRE

Defined in

projects/framework/src/lib/parsers/Args.ts:423

peekResult<K>(type, options?): Promise<ResultType<ArgType[K]>>

Peeks the following parameter(s) without advancing the parser's state. Passing a function as a parameter allows for returning Args.pickResult, Args.repeatResult, or Args.restResult; otherwise, passing the custom argument or the argument type with options will use Args.pickResult and only peek a single argument.

Type parameters

NameType
Kextends keyof ArgType

Parameters

NameTypeDescription
typeK | () => Awaitable<Result<ArgType[K]>>The function, custom argument, or argument name.
options?ArgOptionsThe peekResult options.

Returns

Promise<ResultType<ArgType[K]>>

Example

// !datethenaddtwo 1608867472611
const date = await args.peekResult('date');
await date.inspectAsync((value) =>
message.channel.send(`Your date (in UTC): ${value.toUTCString()}`)
); // Your date (in UTC): Fri, 25 Dec 2020 03:37:52 GMT

const result = await args.pickResult('number', { maximum: Number.MAX_SAFE_INTEGER - 2 });
await result.inspectAsync((value) =>
message.channel.send(`Your number plus two: ${value + 2}`)
); // Your number plus two: 1608867472613

Defined in

projects/framework/src/lib/parsers/Args.ts:445


pick

pick<T>(type, options?): Promise<T>

Similar to Args.pickResult but returns the value on success, throwing otherwise.

Type parameters

Name
T

Parameters

NameTypeDescription
typeIArgument<T>The type of the argument.
options?ArgOptionsThe pick options.

Returns

Promise<T>

Example

// !square 5
const resolver = Args.make((parameter, { argument }) => {
const parsed = Number(parameter);
if (Number.isNaN(parsed)) {
return Args.error({ argument, parameter, identifier: 'ArgumentNumberNaN', message: 'You must write a valid number.' });
}

return Args.ok(parsed);
});

const a = await args.pick(resolver);

await message.channel.send(`The result is: ${a ** 2}!`);
// Sends "The result is: 25"

Defined in

projects/framework/src/lib/parsers/Args.ts:165

pick<K>(type, options?): Promise<ArgType[K]>

Similar to Args.pickResult but returns the value on success, throwing otherwise.

Type parameters

NameType
Kextends keyof ArgType

Parameters

NameTypeDescription
typeKThe type of the argument.
options?ArgOptionsThe pick options.

Returns

Promise<ArgType[K]>

Example

// !add 1 2
const a = await args.pick('integer');
const b = await args.pick('integer');
await message.channel.send(`The result is: ${a + b}!`);
// Sends "The result is: 3"

Defined in

projects/framework/src/lib/parsers/Args.ts:179


pickResult

pickResult<T>(type, options?): Promise<ResultType<T>>

Retrieves the next parameter and parses it. Advances index on success.

Type parameters

Name
T

Parameters

NameTypeDescription
typeIArgument<T>The type of the argument.
options?ArgOptionsThe pickResult options.

Returns

Promise<ResultType<T>>

Example

// !square 5
const resolver = Args.make((parameter, { argument }) => {
const parsed = Number(parameter);
if (Number.isNaN(parsed)) {
return Args.error({ argument, parameter, identifier: 'ArgumentNumberNaN', message: 'You must write a valid number.' });
}

return Args.ok(parsed);
});

const a = await args.pickResult(resolver);
if (!a.success) {
throw new UserError({ identifier: 'ArgumentNumberNaN', message: 'You must write a valid number.' });
}

await message.channel.send(`The result is: ${a.value ** 2}!`);
// Sends "The result is: 25"

Defined in

projects/framework/src/lib/parsers/Args.ts:99

pickResult<K>(type, options?): Promise<ResultType<ArgType[K]>>

Retrieves the next parameter and parses it. Advances index on success.

Type parameters

NameType
Kextends keyof ArgType

Parameters

NameTypeDescription
typeKThe type of the argument.
options?ArgOptionsThe pickResult options.

Returns

Promise<ResultType<ArgType[K]>>

Example

// !add 1 2
const a = await args.pickResult('integer');
if (!a.success) {
throw new UserError({ identifier: 'AddArgumentError', message: 'You must write two numbers, but the first one did not match.' });
}

const b = await args.pickResult('integer');
if (!b.success) {
throw new UserError({ identifier: 'AddArgumentError', message: 'You must write two numbers, but the second one did not match.' });
}

await message.channel.send(`The result is: ${a.value + b.value}!`);
// Sends "The result is: 3"

Defined in

projects/framework/src/lib/parsers/Args.ts:121


repeat

repeat<T>(type, options?): Promise<T[]>

Similar to Args.repeatResult but returns the value on success, throwing otherwise.

Type parameters

Name
T

Parameters

NameTypeDescription
typeIArgument<T>The type of the argument.
options?RepeatArgOptionsThe repeat options.

Returns

Promise<T[]>

Example

// !reverse-each 2 Hello World!
const resolver = Args.make((arg) => Args.ok(arg.split('').reverse()));
const result = await args.repeat(resolver, { times: 5 });
await message.channel.send(`You have written ${result.length} word(s): ${result.join(' ')}`);
// Sends "You have written 2 word(s): Hello World!"

Defined in

projects/framework/src/lib/parsers/Args.ts:362

repeat<K>(type, options?): Promise<ArgType[K][]>

Similar to Args.repeatResult but returns the value on success, throwing otherwise.

Type parameters

NameType
Kextends keyof ArgType

Parameters

NameTypeDescription
typeKThe type of the argument.
options?RepeatArgOptionsThe repeat options.

Returns

Promise<ArgType[K][]>

Example

// !add 2 Hello World!
const words = await args.repeat('string', { times: 5 });
await message.channel.send(`You have written ${words.length} word(s): ${words.join(' ')}`);
// Sends "You have written 2 word(s): Hello World!"

Defined in

projects/framework/src/lib/parsers/Args.ts:375


repeatResult

repeatResult<T>(type, options?): Promise<ArrayResultType<T>>

Retrieves all the following arguments.

Type parameters

Name
T

Parameters

NameTypeDescription
typeIArgument<T>The type of the argument.
options?RepeatArgOptionsThe repeatResult options.

Returns

Promise<ArrayResultType<T>>

Example

// !add 2 Hello World!
const resolver = Args.make((arg) => Args.ok(arg.split('').reverse()));
const result = await args.repeatResult(resolver, { times: 5 });
if (!result.success) {
throw new UserError({ identifier: 'CountArgumentError', message: 'You must write up to 5 words.' });
}

await message.channel.send(`You have written ${result.value.length} word(s): ${result.value.join(' ')}`);
// Sends "You have written 2 word(s): olleH !dlroW"

Defined in

projects/framework/src/lib/parsers/Args.ts:295

repeatResult<K>(type, options?): Promise<ArrayResultType<ArgType[K]>>

Retrieves all the following arguments.

Type parameters

NameType
Kextends keyof ArgType

Parameters

NameTypeDescription
typeKThe type of the argument.
options?RepeatArgOptionsThe repeatResult options.

Returns

Promise<ArrayResultType<ArgType[K]>>

Example

// !reverse-each 2 Hello World!
const result = await args.repeatResult('string', { times: 5 });
if (!result.success) {
throw new UserError({ identifier: 'CountArgumentError', message: 'You must write up to 5 words.' });
}

await message.channel.send(`You have written ${result.value.length} word(s): ${result.value.join(' ')}`);
// Sends "You have written 2 word(s): Hello World!"

Defined in

projects/framework/src/lib/parsers/Args.ts:312


resolveArgument

resolveArgument<T>(arg): undefined | IArgument<T>

Resolves an argument.

Type parameters

Name
T

Parameters

NameTypeDescription
argkeyof ArgType | IArgument<T>The argument name or IArgument instance.

Returns

undefined | IArgument<T>

Defined in

projects/framework/src/lib/parsers/Args.ts:755


rest

rest<T>(type, options?): Promise<T>

Similar to Args.restResult but returns the value on success, throwing otherwise.

Type parameters

Name
T

Parameters

NameTypeDescription
typeIArgument<T>The type of the argument.
options?ArgOptionsThe rest options.

Returns

Promise<T>

Example

// !reverse Hello world!
const resolver = Args.make((arg) => Args.ok(arg.split('').reverse()));
const a = await args.rest(resolver);
await message.channel.send(`The reversed value is... ${a}`);
// Sends "The reversed value is... !dlrow olleH"

Defined in

projects/framework/src/lib/parsers/Args.ts:258

rest<K>(type, options?): Promise<ArgType[K]>

Similar to Args.restResult but returns the value on success, throwing otherwise.

Type parameters

NameType
Kextends keyof ArgType

Parameters

NameTypeDescription
typeKThe type of the argument.
options?ArgOptionsThe rest options.

Returns

Promise<ArgType[K]>

Example

// !add 2 Hello World!
const a = await args.pick('integer');
const b = await args.rest('string', { minimum: 1 });
await message.channel.send(`The repeated value is... ${b.repeat(a)}!`);
// Sends "The repeated value is... Hello World!Hello World!"

Defined in

projects/framework/src/lib/parsers/Args.ts:272


restResult

restResult<T>(type, options?): Promise<ResultType<T>>

Retrieves all the following arguments.

Type parameters

Name
T

Parameters

NameTypeDescription
typeIArgument<T>The type of the argument.
options?ArgOptionsThe restResult options.

Returns

Promise<ResultType<T>>

Example

// !reverse Hello world!
const resolver = Args.make((parameter) => Args.ok(parameter.split('').reverse()));

const a = await args.restResult(resolver);
if (!a.success) {
throw new UserError({ identifier: 'AddArgumentError', message: 'You must write some text.' });
}

await message.channel.send(`The reversed value is... ${a.value}`);
// Sends "The reversed value is... !dlrow olleH"

Defined in

projects/framework/src/lib/parsers/Args.ts:203

restResult<K>(type, options?): Promise<ResultType<ArgType[K]>>

Retrieves all the following arguments.

Type parameters

NameType
Kextends keyof ArgType

Parameters

NameTypeDescription
typeKThe type of the argument.
options?ArgOptionsThe restResult options.

Returns

Promise<ResultType<ArgType[K]>>

Example

// !add 2 Hello World!
const a = await args.pickResult('integer');
if (!a.success) {
throw new UserError({ identifier: 'AddArgumentError', message: 'You must write a number and a text, but the former did not match.' });
}

const b = await args.restResult('string', { minimum: 1 });
if (!b.success) {
throw new UserError({ identifier: 'AddArgumentError', message: 'You must write a number and a text, but the latter did not match.' });
}

await message.channel.send(`The repeated value is... ${b.value.repeat(a.value)}!`);
// Sends "The repeated value is... Hello World!Hello World!"

Defined in

projects/framework/src/lib/parsers/Args.ts:225


restore

restore(): void

Restores the previously saved state from the stack.

Returns

void

See

Args#save

Defined in

projects/framework/src/lib/parsers/Args.ts:718


save

save(): void

Saves the current state into the stack following a FILO strategy (first-in, last-out).

Returns

void

See

Args#restore

Defined in

projects/framework/src/lib/parsers/Args.ts:710


start

start(): Args

Sets the parser to the first token.

Returns

Args

Defined in

projects/framework/src/lib/parsers/Args.ts:69


toJSON

toJSON(): ArgsJson

Defines the JSON.stringify override.

Returns

ArgsJson

Defined in

projects/framework/src/lib/parsers/Args.ts:732


unavailableArgument

unavailableArgument<T>(type): Err<UserError>

Type parameters

Name
T

Parameters

NameType
typestring | IArgument<T>

Returns

Err<UserError>

Defined in

projects/framework/src/lib/parsers/Args.ts:736


error

error<T>(options): Err<ArgumentError<T>>

Constructs an Err result containing an ArgumentError.

Type parameters

Name
T

Parameters

NameTypeDescription
optionsOptions<T>The options for the argument error.

Returns

Err<ArgumentError<T>>

Defined in

projects/framework/src/lib/parsers/Args.ts:781


make

make<T>(cb, name?): IArgument<T>

Converts a callback into a usable argument.

Type parameters

Name
T

Parameters

NameTypeDefault valueDescription
cb(parameter: string, context: Context<T>) => AwaitableResult<T>undefinedThe method which is called when invoking the argument.
namestring''The name of the argument.

Returns

IArgument<T>

Defined in

projects/framework/src/lib/parsers/Args.ts:765


ok

ok<T>(value): Ok<T>

Constructs an Ok result.

Type parameters

Name
T

Parameters

NameTypeDescription
valueTThe value to pass.

Returns

Ok<T>

Defined in

projects/framework/src/lib/parsers/Args.ts:773