Telegraf
Один из старейших Node.js-фреймворков для Bot API. Express-style middleware.
Установка
npm install telegraf
Подключение к Telefon
import { Telegraf } from 'telegraf';
const bot = new Telegraf(process.env.BOT_TOKEN!, {
telegram: { apiRoot: 'https://api.telefon.chat' }
});
bot.start((ctx) => ctx.reply('Привет!'));
bot.help((ctx) => ctx.reply('Помощь'));
bot.on('text', (ctx) => ctx.reply(ctx.message.text));
bot.launch();
// Корректно завершаемся при SIGINT/SIGTERM
process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));
Сцены (Wizard)
import { Scenes } from 'telegraf';
const wizard = new Scenes.WizardScene(
'register',
(ctx) => { ctx.reply('Как зовут?'); return ctx.wizard.next(); },
(ctx) => {
ctx.scene.state.name = ctx.message.text;
ctx.reply('Сколько лет?');
return ctx.wizard.next();
},
(ctx) => {
const { name } = ctx.scene.state;
ctx.reply(\`\${name}, \${ctx.message.text} лет — записал!\`);
return ctx.scene.leave();
}
);
const stage = new Scenes.Stage([wizard]);
bot.use(session()).use(stage.middleware());
bot.command('register', (ctx) => ctx.scene.enter('register'));
Документация
telegraf.js.org — guides, API, примеры.