Skip to content
Classplugin-tasksv0.1.0-next.1

Tasks

Runs the task classes in a folder. A task with a cron pattern runs on that schedule. Any task can also run once at a later time through schedule.

The plugin stores scheduled tasks in the bot's config.kv, under its attach key. With a driver that keeps its records, a pending job is still there after a restart. A job whose time passed while the bot was down runs as soon as the bot starts. If you rename the attach key, the plugin doesn't read or delete the jobs stored under the old one.

class Tasks extends Plugin<{ transport: "any"; runtime: "server" }>
seedcord.attach('tasks', Tasks, { path: './tasks', timezone: 'UTC' });

Member visibility

Filter class members by access level.

constructor

Constructs a new instance of the Tasks class

Tasks(host: CoreBase, options: TasksOptions)

core

The host, typed to the transport whose Plugin base this class extends.

protected core: TCore

Inherited from:Plugin

dispatchMembers

Adds values that every handler can read. Each key becomes a member, like this.tag, and its function returns the value. Gates and Notice.render read the same values on ctx.

Seedcord calls each function once per interaction, and once per event that has a handler.

attach() throws if seedcord already uses one of these keys, like reply, if another plugin on the bot uses it, or if the bot attaches this plugin twice.

readonly dispatchMembers?: DispatchMemberFunctions
public override readonly dispatchMembers = {
    tag: (origin: DispatchOrigin) => `${origin.guildId}:${origin.userId}`
};

Inherited from:Plugin

id

public static readonly id

kv

This plugin's records in the bot's config.kv, stored under its attach key. Two attachments of one plugin class each get their own records. Renaming the attach key leaves the records under the old key behind.

protected kv: Kv
// works in a field initializer, the constructor, and every method
private readonly jobs = this.kv.collection<Job>('job');

Inherited from:Plugin

Throws:

  • A SeedcordTypeError when something built the plugin with new outside attach().

logger

Logs under the plugin's class name, on the channel its attach key sets.

protected readonly logger: Logger

Inherited from:Plugin

cancel()

Deletes a job so it never runs.

public async cancel(id: string): Promise<boolean>

Throws:

A SeedcordError with CoreKvDriverFailed when the driver can't read or delete the job.

codegen()

Returns data that seedcord codegen writes into the bot's seedcord-gen.ts as a type. Read it back with Generated<typeof YourPlugin>. Return plain data, or classes and objects that a project file or your plugin's package exports. The class needs a static readonly id.

seedcord codegen calls this without running init(). Read only what the constructor stored and the bot's files.

async codegen?(): Promise<unknown>

Inherited from:Plugin

crons()

Every cron job and its state.

public crons(): CronStatus[]

dispose()

Stops every timer, aborts each run's signal, and waits for in-flight runs. The driver still holds pending jobs.

public override async dispose(): Promise<void>

fetch()

Answers a web request sent to the bot. seedcord calls this on each plugin in attach order and answers with the first Response. On an http bot, seedcord calls it for interactions too. Return undefined to pass the request on. If this method throws, seedcord logs the error on this plugin's logger and answers the request with a 500.

On an http bot, check the path before you await anything because every interaction waits for this method. On a server, requests reach it once the Ready phase begins. It can run before ready() finishes, and before an init() that you moved to Ready.

fetch?(
    request: Request
): Promisable<Response | undefined>

Throws:

seedcord throws a SeedcordError when this method reads or locks the body without answering the request.

public fetch(request: Request): Response | undefined {
    if (new URL(request.url).pathname !== '/status') return undefined;
    return Response.json({ ok: true });
}

Inherited from:Plugin

init()

Loads the task classes under path, then reads back the jobs that earlier runs of the bot stored.

public async init(): Promise<void>

Throws:

A SeedcordError when a task file throws while it imports.

Throws:

A SeedcordTypeError with CoreDuplicateName when two tasks share a key.

Throws:

A SeedcordTypeError with PluginTasksInvalidPattern when croner can't parse a task's cron pattern.

Throws:

A SeedcordTypeError with PluginTasksInvalidOption when a task's pattern is a date.

Throws:

A SeedcordTypeError with PluginTasksInvalidOption when a task's timezone isn't one Intl supports.

Throws:

A SeedcordTypeError with PluginTasksInvalidOption when croner can't read a task's startAt or stopAt.

Throws:

A SeedcordTypeError with PluginTasksInvalidOption when a task's stopAt isn't after its startAt.

Throws:

A SeedcordRangeError with PluginTasksInvalidOption when a task's maxRuns isn't a whole number of 1 or more.

Throws:

A SeedcordRangeError with PluginTasksInvalidOption when a task's every isn't whole seconds.

Throws:

A SeedcordTypeError with InvalidDuration when a task's every isn't a duration.

Throws:

A SeedcordError with CoreKvKeysUnsupported when the config.kv driver can't list its keys.

jobs()

The jobs waiting to run in this process.

public jobs(): ScheduledJob[]

nextRun()

When a cron job runs next, or null while it's paused or once it doesn't have any runs left.

public nextRun(Task: NoDataTaskClass): Date | null

Throws:

A SeedcordError with PluginTasksNotLoaded when the plugin did not load Task.

Throws:

A SeedcordTypeError with PluginTasksKeyTaken when a different class loaded under Task's key.

Throws:

A SeedcordTypeError with PluginTasksPatternMissing when Task doesn't have a cron pattern.

pause()

Stops a cron job's schedule until resume. Scheduled tasks and trigger() still run the task. The task is still paused after a save reloads it. After a restart, it follows its paused option again.

public pause(Task: NoDataTaskClass): void

Throws:

A SeedcordError with PluginTasksNotLoaded when the plugin did not load Task.

Throws:

A SeedcordTypeError with PluginTasksKeyTaken when a different class loaded under Task's key.

Throws:

A SeedcordTypeError with PluginTasksPatternMissing when Task doesn't have a cron pattern.

prepareCommands()

Changes commands before seedcord sends them to Discord. Write your changes onto these objects, like setting name_localizations. Each command appears once, even when it deploys to several guilds.

If it throws, the deploy stops, and so do seedcord codegen, a Workers build, seedcord commands deploy, and seedcord commands list.

The CLI calls this without running init(). Read only what the constructor stored and the bot's files.

prepareCommands?(
    commands: readonly RESTPostAPIApplicationCommandsJSONBody[]
): Promisable<void>

Inherited from:Plugin

ready()

Starts the cron jobs and the timers for pending jobs once the bot has logged in.

public override ready(): void

registerCommandFiles()

Tells seedcord dev which files your prepareCommands reads. Saving one of them in seedcord dev shows the command refresh prompt.

protected registerCommandFiles(patterns: string[]): void
Parameter: patterns

Glob patterns. A relative one resolves against root from seedcord.config.ts. A pattern that starts with ! excludes the files it matches.

Inherited from:Plugin

registerCriticalFiles()

Registers critical file patterns that should trigger a full restart when changed in Dev HMR.

protected registerCriticalFiles(
    patterns: string[]
): void
Parameter: patterns

Glob patterns. A relative one resolves against root from seedcord.config.ts. A pattern that starts with ! excludes the files it matches from the other patterns in this call.

Inherited from:Plugin

rejectOptions()

Rejects the options this plugin got.

protected rejectOptions(reason: string): never
Parameter: reason

Why the options are invalid.

Throws:

A SeedcordTypeError every time, with the plugin class name and reason in its message.

Inherited from:Plugin

resume()

Starts a cron job that pause(), the paused option, or seedcord dev stopped. It runs at its next match and skips the ones it missed.

public resume(Task: NoDataTaskClass): void

Throws:

A SeedcordError with PluginTasksNotLoaded when the plugin did not load Task.

Throws:

A SeedcordTypeError with PluginTasksKeyTaken when a different class loaded under Task's key.

Throws:

A SeedcordTypeError with PluginTasksPatternMissing when Task doesn't have a cron pattern.

schedule()

Stores a job that runs Task once, at the time options gives. If that time has passed, the job runs right away, or in ready() if the bot hasn't logged in yet. Once the promise resolves, the driver holds the job, and it's still there after a restart. It waits under seedcord dev unless you set runInDev.

If the process dies during a run, the job runs again after a restart. Write a task so a second run of one job is safe.

public async schedule<TTask, TIn>(
    Task: TTask,
    options: ScheduleOptions<DataOf<TTask>, TIn>
): Promise<ScheduledJob>
Parameter: Task

A class that the plugin loaded from path.

Parameter: options

in or at, plus data when the task declares it.

Throws:

A SeedcordError with PluginTasksNotLoaded when the plugin did not load Task.

Throws:

A SeedcordTypeError with PluginTasksKeyTaken when a different class loaded under Task's key.

Throws:

A SeedcordTypeError with InvalidDuration when in isn't a duration.

Throws:

A SeedcordTypeError with PluginTasksInvalidOption when at isn't a date.

Throws:

A SeedcordRangeError with PluginTasksAtTooEarly when at is a number too small to be milliseconds.

Throws:

A SeedcordRangeError with PluginTasksDurationTooLong when in ends past the last date a Date can hold.

Throws:

A SeedcordTypeError with CoreKvUnserializable when data holds a circular reference.

Throws:

A SeedcordError with CoreKvDriverFailed when the driver can't store the job.

const job = await this.core.tasks.schedule(Unban, { in: '1d', data: { guildId, userId } });
await this.core.tasks.cancel(job.id);

trigger()

Runs a task now, outside its schedule, even while it's paused. If a protected task is mid-run, it skips this run and calls onOverrun().

public async trigger(Task: NoDataTaskClass): Promise<void>

Throws:

A SeedcordError with PluginTasksNotLoaded when the plugin did not load Task.

Throws:

A SeedcordTypeError with PluginTasksKeyTaken when a different class loaded under Task's key.