vk-io-i18n
TypeScript icon, indicating that this package has built-in type declarations

0.0.1 • Public • Published

vk-io-i18n

Internationalization middleware for vk-io.

Installation

npm install vk-io-i18n

Example

yaml and json are ok
Example directory structure:
├── locales
│   ├── en.yaml
│   ├── en-US.yaml
│   ├── it.json
│   └── ru.yaml
└── index.ts
import { VK, MessageContext } from 'vk-io';
import { SessionManager } from '@vk-io/session';

import { I18n, I18nContext } from 'vk-io-i18n';

interface MyContext extends MessageContext {
    readonly i18n: I18nContext;
}

// I18n options
const i18n = new I18n({
  defaultLanguageOnMissing: true, // implies allowMissing = true
  directory: 'locales',
  useSession: true,
});

// Also you can provide i18n data directly
i18n.loadLocale('en', { greeting: 'Hello!' })
i18n.loadLocale('ru', { greeting: 'Привет, ${user.first_name}!' })

const vk = new VK({
    token: process.env['BOT_TOKEN']!,
});
const sessionManager = new SessionManager();

vk.updates.on('message_new', sessionManager.middleware);
vk.updates.on('message_new', i18n.middleware);

// Start message handler
vk.updates.on<MyContext>('message_new', async (ctx, next) => {
    if (ctx.text !== '/start') {
        return next();
    }

    const [user] = await vk.api.users.get({ user_ids: [ctx.senderId] });
    ctx.send(ctx.i18n.t('greeting', { user }));
});

vk.updates
    .start()
    .then(() => {
        console.log('Bot started');
    })
    .catch(console.error);

A full example for vk-io are in the example folder.

User context

Commonly used Context functions:

bot.use((ctx) => {
  ctx.i18n.locale()                // Get current locale
  ctx.i18n.locale(code)            // Set current locale
  ctx.i18n.t(resourceKey, { data })  // Get resource value (data will be used by template engine)
});

The code is taken from the grammyjs/i18n project

Package Sidebar

Install

npm i vk-io-i18n

Weekly Downloads

2

Version

0.0.1

License

MIT

Unpacked Size

20.6 kB

Total Files

14

Last publish

Collaborators

  • xtcry