Utils
@lunibee/utils provides a small set of general-purpose helpers.
import { sleep, randomInt, isSnowflake } from "lunibee";// or from the sub-package:import { sleep, randomInt, isSnowflake } from "@lunibee/utils";import { sleep, randomInt, isSnowflake } from "lunibee";// or from the sub-package:import { sleep, randomInt, isSnowflake } from "@lunibee/utils";sleep(ms)
Section titled βsleep(ms)βReturns a Promise that resolves after ms milliseconds.
async function delayedGreet(channel, name: string) { await channel.send({ content: `Hey ${name}, starting up...` }); await sleep(2000); // wait 2 seconds await channel.send({ content: "Ready! π" });}async function delayedGreet(channel, name) { await channel.send({ content: `Hey ${name}, starting up...` }); await sleep(2000); // wait 2 seconds await channel.send({ content: "Ready π" });}Signature:
function sleep(ms: number): Promise<void>function sleep(ms)randomInt(min, max)
Section titled βrandomInt(min, max)βReturns a random integer in the inclusive range [min, max].
const roll = randomInt(1, 6); // dice roll: 1β6const item = items[randomInt(0, items.length - 1)];const roll = randomInt(1, 6); // dice roll: 1β6const item = items[randomInt(0, items.length - 1)];Signature:
function randomInt(min: number, max: number): numberfunction randomInt(min, max)isSnowflake(value)
Section titled βisSnowflake(value)βReturns true if the string looks like a Discord snowflake: 16 to 20 decimal digits. A snowflake is an unsigned 64-bit number, so it never has more than 20 digits; the minimum keeps short numbers in text from being read as IDs (Routes, which only validates IDs it is given, accepts 1 to 20). Prefix-command argument parsing uses the same rule for mentions and IDs.
isSnowflake("123456789012345678") // β trueisSnowflake("not-a-snowflake") // β falseisSnowflake("12345") // β false (too short)isSnowflake("99999999999999999999") // β true (20 digits)isSnowflake("123456789012345678") // β trueisSnowflake("not-a-snowflake") // β falseisSnowflake("12345") // β false (too short)isSnowflake("99999999999999999999") // β true (20 digits)Signature:
function isSnowflake(value: string): booleanfunction isSnowflake(value)Examples
Section titled βExamplesβValidate user input before fetching
client.on("messageCreate", async (message) => { if (!message.content.startsWith("!user ")) return; const id = message.content.slice(6).trim(); if (!isSnowflake(id)) { return message.reply("Invalid user ID."); } const user = await client.users.fetch(id); await message.reply(`Found: ${user.displayName}`);});client.on("messageCreate", async (message) => { if (!message.content.startsWith("!user ")) return; const id = message.content.slice(6).trim(); if (!isSnowflake(id)) { return message.reply("Invalid user ID."); } const user = await client.users.fetch(id); await message.reply(`Found: ${user.displayName}`);});Rate-limit friendly bulk operation with delay
async function sendAll(channels: Channel[], content: string) { for (const channel of channels) { await channel.send({ content }); await sleep(500); // 500ms between each send to avoid rate limits }}async function sendAll(channels, content) { for (const channel of channels) { await channel.send({ content }); await sleep(500); // 500ms between each send to avoid rate limits }}Random pick from a list
const jokes = ["Why do bees hum? Because they don't know the words. π΅", "What do you call a bee that can't make up its mind? A maybee! π"];const joke = jokes[randomInt(0, jokes.length - 1)];await channel.send({ content: joke });const jokes = ["Why do bees hum? Because they don't know the words. π΅", "What do you call a bee that can't make up its mind? A maybee π"];const joke = jokes[randomInt(0, jokes.length - 1)];await channel.send({ content: joke });Prefix-command arguments (0.2.1)
Section titled βPrefix-command arguments (0.2.1)βRead the text after a prefix command as typed values, the way slash-command options are read.
| Function | Description |
|---|---|
tokenizeArgs(text) |
Splits on whitespace; "double" or 'single' quotes keep spaces; \ escapes. |
parsePrefixArgs(text | args, specs) |
Reads arguments by position. Returns { ok: true, values } or { ok: false, arg, error }, and never throws on user input. |
argsFromCommandOptions(options, restLast?) |
Specs from a slash commandβs options, so one definition serves /command and the prefix command. With restLast, the last string option takes the rest of the message. |
parseUserMention, parseRoleMention, parseChannelMention |
The ID in <@id> / <@&id> / <#id>, or a bare ID; null otherwise. |
parseMentionable(value) |
{ id, type: "user" | "role" }; a bare ID reads as a user. |
A spec is { name, type, required?, min?, max?, maxLength?, choices? } where type is string, integer, number, boolean (yes/no, on/off, true/falseβ¦), user, role, channel, mentionable or rest (everything left, one string; must be last).
import { parsePrefixArgs } from "lunibee";
const result = parsePrefixArgs(message.content.slice("!timeout".length), [ { name: "user", type: "user", required: true }, { name: "minutes", type: "integer", min: 1, max: 40320 }, { name: "reason", type: "rest", maxLength: 500 },]);if (!result.ok) return message.reply(`\`${result.arg}\` ${result.error}.`);const { user, minutes = 10, reason } = result.values;