telegraf / telegraf-i18n

Internationalization middleware for Telegraf
MIT License
84 stars 31 forks source link

i18n.t is undefined #32

Closed expelliamus closed 4 years ago

expelliamus commented 4 years ago

Hi,

I saw a similar issue but I can't get this working, hope you will help. Essentially I have app.js as entry point of my application, this file contains the following:

const express = require('express');
const app = express();

require('./config/server')(app, express);

const { Bot } = require('./controllers/bot.controller.js');

 let bot = new Bot(process.env.BOT_TOKEN);
 await bot.init();
 bot.start();

I load the server configuration passing in the constructor app and express:

const path = require('path');
const I18n = require('telegraf-i18n');
const session = require('telegraf/session');

module.exports = function (app, express) {

    // Session
    app.use(session());

    // Localization
    const i18n = new I18n({
        useSession: true,
        defaultLanguage: 'it',
        directory: path.join(__dirname, "../locales")
    });

    app.use(i18n.middleware());
}`

the main logic for the menu is on bot.controller which contains this definition:

` const Telegraf = require('telegraf'); const { MainMenu } = require('../middlewares/menu/mainMenu');

class Bot {
    constructor(token) {
    this.bot = new Telegraf(token);
    this.bot.catch(error => {
        console.error(`Bot error: ${error}`);
    });
}

async init() {
    this.bot.use(new MainMenu(this.bot));
}

start() {
    this.bot.startPolling();
}

}

exports.Bot = Bot;`

and here is the problem:

` const TelegrafInlineMenu = require('telegraf-inline-menu'); const SubscriptionMenu = require('./submenu/subscriptionMenu');

class MainMenu {

constructor(bot) {

    const menu = new TelegrafInlineMenu(ctx => ctx.i18n.t('welcomeMsg', {
        username: ctx.from.first_name
    }));
    menu.setCommand('start');

    bot.use(menu.init({
        backButtonText: '🔙 Back ...',
        mainMenuButtonText: '🏠 Main menu'
    }));
   }
}

exports.MainMenu = MainMenu;`

here I get:

Bot error: TypeError: Cannot read property 't' of undefined

what I did wrong? Thanks, and good holidays

gavrilin-remote commented 3 years ago

Hi @expelliamus! How did you solved this issue? I have two nested menus and i18n is missing in last one context.

EdJoPaTo commented 3 years ago

@gavrilin-remote I suggest switching over to @grammyjs/i18n as its an actively supported fork of this library.

If you are using typescript it might be that your second menu doesnt have the MyContext thingy which knows about the i18n stuff?

gavrilin-remote commented 3 years ago

I found a solution! Make sure that your i18n middleware is placed above that your menus middlewares.