# I18n

`class` in `plugin-i18n` · v0.1.0

<https://seedcord.org/docs/packages/plugin-i18n/0.1.0/classes/i18n>

Gives every handler `this.t`, which formats your Fluent messages in the user's language.

Put one `.ftl` file per Discord locale in `path`, like `en-US.ftl` and `pl.ftl`. In gates and
`Notice.render`, read the same function from `ctx.t`.

```ts
class I18n extends Plugin
```

## Examples

```ts
# locales/en-US.ftl
# the base file. add a message or variable here before you translate it

greeting = Hello { $user }!

items = { $count ->
    [one] You have { $count } item
   *[other] You have { $count } items
}
```

```ts
// seedcord.config.ts
export default defineConfig({
    files: ['./locales']
});

// bot.ts
seedcord.attach('i18n', I18n, { path: './locales', base: 'en-US' });
```

```ts
// in a handler after you edit a .ftl file,
// run seedcord codegen to update what t accepts
await this.reply(this.t('greeting', { user: this.event.user.username }));
await this.reply(this.t('items', { count: cart.length }));
```

```ts
// pass this.t to a component's constructor to translate inside it
import { BuilderComponent, type DispatchMemberValues } from '@seedcord/gateway';
import { TextDisplayBuilder } from '@discordjs/builders';

class CartSummary extends BuilderComponent<'container'> {
    constructor(t: DispatchMemberValues['t'], count: number) {
        super('container');

        const text = new TextDisplayBuilder().setContent(t('items', { count }));
        this.instance.addTextDisplayComponents(text);
    }
}

// in the handler
const summary = new CartSummary(this.t, cart.length);
await this.reply({ components: [summary.component] });
```

```ts
// in a Notice, read ctx.t. it formats in the same language as the handler's this.t
class EmptyCart extends Notice {
    constructor() {
        super('cart is empty');
    }

    override render(ctx: RenderContext): ReplyResponse {
        return { components: [new CartSummary(ctx.t, 0).component] };
    }
}
```

```ts
// return a language the user saved with your bot to use it over their Discord language
seedcord.attach('i18n', I18n, {
    resolveLocale: async ({ userId }) => {
        if (!userId) return undefined;
        return languages.get(userId);
    }
});
```

```ts
// t.locale is the locale t formats in. use it for dates and numbers
const joined = new Intl.DateTimeFormat(this.t.locale).format(member.joinedAt);
```

## Constructors

### constructor

```ts
I18n(
    host: CoreBase,
    { path: dir, base, resolveLocale }?,
    input?: I18nOptions
)
```

Constructs a new instance of the `I18n` class

## Properties

### core

```ts
protected core: TCore
```

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

### dispatchMembers

```ts
public readonly dispatchMembers: { t: (origin: DispatchOrigin) => Promise<Translate<Generated<typeof I18n>["messages"]>>; }
```

### id

```ts
public static readonly id
```

### kv

```ts
protected kv: 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.

### logger

```ts
protected readonly logger: Logger
```

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

## Methods

### codegen

```ts
public override async codegen(): Promise<{ messages: MessageTable }>
```

### dispose

```ts
dispose?(): Promisable<void>
```

Runs during teardown, in `ShutdownPhase.Disconnect` by default. seedcord skips it when `init()`
has thrown.

When `init()` outlasts its timeout, seedcord calls this once that `init()` resolves, outside any
shutdown phase. The process must still be alive for that call to happen.

### fetch

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

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.

### init

```ts
public async init(): Promise<void>
```

### onHmr

```ts
public override async onHmr(
    { file },
    input: HmrUpdateEvent
): Promise<void>
```

### prepareCommands

```ts
public override async prepareCommands(
    commands: readonly RESTPostAPIApplicationCommandsJSONBody[]
): Promise<void>
```

### ready

```ts
ready?(): Promisable<void>
```

Runs in the Ready phase after every attached plugin's `init()` has resolved. The other Ready
tasks run alongside it, including the http server binding its port.

Override it when your work needs a logged-in client or a resolved application id.

### registerCommandFiles

```ts
protected registerCommandFiles(patterns: string[]): void
```

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

### registerCriticalFiles

```ts
protected registerCriticalFiles(
    patterns: string[]
): void
```

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

### rejectOptions

```ts
protected rejectOptions(reason: string): never
```

Rejects the options this plugin got.
