Skip to main content

Class: Args

The argument parser to be used in Command.

Constructors

constructor

โ€ข new Args(message, command, parser, context)

Parameters

NameType
messageMessage<boolean>
commandCommand<Args, CommandOptions>
parserArgs
contextCommandContext

Defined in

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

Properties

command

โ€ข Readonly command: Command<Args, CommandOptions>

The command that is being run.

Defined in

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


commandContext

โ€ข Readonly commandContext: CommandContext

The context of the command being run.

Defined in

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


message

โ€ข Readonly message: Message<boolean>

The original message that triggered the command.

Defined in

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


parser

โ€ข Protected Readonly parser: Args

The internal Lexure parser.

Defined in

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


states

โ€ข Private Readonly states: ArgsState[] = []

The states stored in the args.

see Args#save

see Args#restore

Defined in

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

Accessors

finished

โ€ข get finished(): boolean

Whether all arguments have been consumed.

Returns

boolean

Defined in

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

Methods

getFlags

โ–ธ getFlags(...keys): boolean

Checks if one or more flag were given.

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

Parameters

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

Returns

boolean

Defined in

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


getOption

โ–ธ getOption(...keys): null | string

Gets the last value of one or more options.

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

Parameters

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

Returns

null | string

Defined in

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


getOptions

โ–ธ getOptions(...keys): null | string[]

Gets all the values of one or more option.

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

Parameters

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

Returns

null | string[]

Defined in

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


missingArguments

โ–ธ Protected missingArguments(): Err<UserError>

Returns

Err<UserError>

Defined in

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


next

โ–ธ next(): string

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

example

// !numbers 1 2 3

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

Returns

string

Defined in

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

โ–ธ next<T>(cb): T

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

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

Type parameters

NameDescription
TOutput type of the callback.

Parameters

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

Returns

T

Defined in

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


nextMaybe

โ–ธ nextMaybe(): Maybe<string>

Retrieves the next raw argument from the parser.

example

// !numbers 1 2 3

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

Returns

Maybe<string>

Defined in

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

โ–ธ nextMaybe<T>(cb): Maybe<T>

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

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 }

Type parameters

NameDescription
TOutput type of the callback.

Parameters

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

Returns

Maybe<T>

Defined in

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


peek

โ–ธ peek<T>(type): Promise<T>

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

example

// !bigintsumthensquarefirst 25 50 75
const resolver = Args.make((arg) => {
try {
return ok(BigInt(arg));
} catch {
return err(new UserError('InvalidBigInt', 'You must specify a valid number for a bigint.'));
}
});

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

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

Type parameters

Name
T

Parameters

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

Returns

Promise<T>

Defined in

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

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

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

example

// !createdat 730159185517477900
const snowflakeResolver = Args.make((arg) =>
SnowflakeRegex.test(arg) ? ok(BigInt(arg)) : err(new UserError('InvalidSnowflake', '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

Type parameters

Name
T

Parameters

NameTypeDescription
typeIArgument<T>The function, custom argument, or argument name.
options?ArgOptions-

Returns

Promise<T>

Defined in

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

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

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

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

Type parameters

NameType
Kextends keyof ArgType

Parameters

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

Returns

Promise<ArgType[K]>

Defined in

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


peekResult

โ–ธ peekResult<T>(type): Promise<Result<T, UserError>>

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.

example

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

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

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

Type parameters

Name
T

Parameters

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

Returns

Promise<Result<T, UserError>>

Defined in

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

โ–ธ peekResult<T>(type, options?): Promise<Result<T, UserError>>

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.

example

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

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

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

Type parameters

Name
T

Parameters

NameTypeDescription
typeIArgument<T>The function, custom argument, or argument name.
options?ArgOptions-

Returns

Promise<Result<T, UserError>>

Defined in

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

โ–ธ peekResult<K>(type, options?): Promise<Result<ArgType[K], UserError>>

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.

example

// !datethenaddtwo 1608867472611
const date = await args.peekResult('date');
if (isOk(date)) await message.channel.send(
`Your date (in UTC): ${date.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 });
if (isOk(result)) await message.channel.send(`Your number plus two: ${result.value + 2}`); // Your number plus two: 1608867472613

Type parameters

NameType
Kextends keyof ArgType

Parameters

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

Returns

Promise<Result<ArgType[K], UserError>>

Defined in

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


pick

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

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

example

// !square 5
const resolver = Args.make((arg) => {
const parsed = Number(argument);
if (Number.isNaN(parsed)) return err(new UserError('ArgumentNumberNaN', 'You must write a valid number.'));
return ok(parsed);
});
const a = await args.pick(resolver);

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

Type parameters

Name
T

Parameters

NameTypeDescription
typeIArgument<T>The type of the argument.
options?ArgOptions-

Returns

Promise<T>

Defined in

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

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

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

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"

Type parameters

NameType
Kextends keyof ArgType

Parameters

NameTypeDescription
typeKThe type of the argument.
options?ArgOptions-

Returns

Promise<ArgType[K]>

Defined in

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


pickResult

โ–ธ pickResult<T>(type, options?): Promise<Result<T, UserError>>

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

example

// !square 5
const resolver = Args.make((arg) => {
const parsed = Number(argument);
if (Number.isNaN(parsed)) return err(new UserError('ArgumentNumberNaN', 'You must write a valid number.'));
return ok(parsed);
});
const a = await args.pickResult(resolver);
if (!a.success) throw new UserError('ArgumentNumberNaN', 'You must write a valid number.');

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

Type parameters

Name
T

Parameters

NameTypeDescription
typeIArgument<T>The type of the argument.
options?ArgOptions-

Returns

Promise<Result<T, UserError>>

Defined in

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

โ–ธ pickResult<K>(type, options?): Promise<Result<ArgType[K], UserError>>

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

example

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

const b = await args.pickResult('integer');
if (!b.success) throw new UserError('AddArgumentError', '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"

Type parameters

NameType
Kextends keyof ArgType

Parameters

NameTypeDescription
typeKThe type of the argument.
options?ArgOptions-

Returns

Promise<Result<ArgType[K], UserError>>

Defined in

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


repeat

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

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

example

// !reverse-each 2 Hello World!
const resolver = Args.make((arg) => 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!"

Type parameters

Name
T

Parameters

NameTypeDescription
typeIArgument<T>The type of the argument.
options?RepeatArgOptions-

Returns

Promise<T[]>

Defined in

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

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

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

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

Type parameters

NameType
Kextends keyof ArgType

Parameters

NameTypeDescription
typeKThe type of the argument.
options?RepeatArgOptions-

Returns

Promise<ArgType[K][]>

Defined in

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


repeatResult

โ–ธ repeatResult<T>(type, options?): Promise<Result<T[], UserError>>

Retrieves all the following arguments.

example

// !add 2 Hello World!
const resolver = Args.make((arg) => ok(arg.split('').reverse()));
const result = await args.repeatResult(resolver, { times: 5 });
if (!result.success) throw new UserError('CountArgumentError', '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"

Type parameters

Name
T

Parameters

NameTypeDescription
typeIArgument<T>The type of the argument.
options?RepeatArgOptions-

Returns

Promise<Result<T[], UserError>>

Defined in

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

โ–ธ repeatResult<K>(type, options?): Promise<Result<ArgType[K][], UserError>>

Retrieves all the following arguments.

example

// !reverse-each 2 Hello World!
const result = await args.repeatResult('string', { times: 5 });
if (!result.success) throw new UserError('CountArgumentError', '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!"

Type parameters

NameType
Kextends keyof ArgType

Parameters

NameTypeDescription
typeKThe type of the argument.
options?RepeatArgOptions-

Returns

Promise<Result<ArgType[K][], UserError>>

Defined in

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


resolveArgument

โ–ธ Private 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:657


rest

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

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

example

// !reverse Hello world!
const resolver = Args.make((arg) => 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"

Type parameters

Name
T

Parameters

NameTypeDescription
typeIArgument<T>The type of the argument.
options?ArgOptions-

Returns

Promise<T>

Defined in

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

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

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

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

Type parameters

NameType
Kextends keyof ArgType

Parameters

NameTypeDescription
typeKThe type of the argument.
options?ArgOptions-

Returns

Promise<ArgType[K]>

Defined in

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


restResult

โ–ธ restResult<T>(type, options?): Promise<Result<T, UserError>>

Retrieves all the following arguments.

example

// !reverse Hello world!
const resolver = Args.make((arg) => ok(arg.split('').reverse()));
const a = await args.restResult(resolver);
if (!a.success) throw new UserError('AddArgumentError', 'You must write some text.');

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

Type parameters

Name
T

Parameters

NameTypeDescription
typeIArgument<T>The type of the argument.
options?ArgOptions-

Returns

Promise<Result<T, UserError>>

Defined in

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

โ–ธ restResult<K>(type, options?): Promise<Result<ArgType[K], UserError>>

Retrieves all the following arguments.

example

// !add 2 Hello World!
const a = await args.pickResult('integer');
if (!a.success) throw new UserError('AddArgumentError', '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('AddArgumentError', '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!"

Type parameters

NameType
Kextends keyof ArgType

Parameters

NameTypeDescription
typeKThe type of the argument.
options?ArgOptions-

Returns

Promise<Result<ArgType[K], UserError>>

Defined in

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


restore

โ–ธ restore(): void

Restores the previously saved state from the stack.

see Args#save

Returns

void

Defined in

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


save

โ–ธ save(): void

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

see Args#restore

Returns

void

Defined in

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


start

โ–ธ start(): Args

Sets the parser to the first token.

Returns

Args

Defined in

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


toJSON

โ–ธ toJSON(): Object

Defines the JSON.stringify override.

Returns

Object

NameType
commandCommand<Args, CommandOptions>
commandContextCommandContext
messageMessage<boolean>

Defined in

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


unavailableArgument

โ–ธ Protected 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:638


error

โ–ธ Static 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:682


make

โ–ธ Static make<T>(cb, name?): IArgument<T>

Converts a callback into an usable argument.

Type parameters

Name
T

Parameters

NameTypeDefault valueDescription
cb(parameter: string, context: Context<T>) => Result<T>undefinedThe callback to convert into an IArgument.
namestring''-

Returns

IArgument<T>

Defined in

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


ok

โ–ธ Static 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:674