L
L
Lynatik0012020-07-02 18:07:04
JavaScript
Lynatik001, 2020-07-02 18:07:04

Do I need a "scene" in telegraf when writing a bot?

I found an example code.
My bot schedules menus (or whatever) within a menu.

Task: to make a bot with little functionality. For example, Main menu (list of buttons) - sub menu, etc.
Various interactions with the database through mongoose are planned.
I also plan to use telegraf. There are "scenes" in this library, but I don't know if they are needed at all. I think that all the logic can be scattered across files, write the logic for working with the menu in the view folder, and then you can do without "scenes". But I'm not sure if this is the correct approach. Tell me, am I right?

There is also a question about the code:
How should it look if the bot launch is in the main file, and the scene is in the scene/mainMenuScene.js folder?

Although I think that hanging a scene on each menu is too much. Please help me figure this out.

The code below is an example implementation of the schema. And I have quite a lot of interaction with the bot in my index.js, for example, bot.action, bot.hears + handlers + functions for interacting with db/controll /db/model

const Telegraf = require('telegraf')
const RedisSession = require('telegraf-session-redis')
const Stage = require('telegraf/stage')
const Scene = require('telegraf/scenes/base')
const { enter, leave } = Stage

const session = new RedisSession({
  store: {
    host: process.env.TELEGRAM_SESSION_HOST || '127.0.0.1',
    port: process.env.TELEGRAM_SESSION_PORT || 32768
  }
})

// Greeter scene
const greeterScene = new Scene('greeter')
greeterScene.enter((ctx) => ctx.reply('Hi'))
greeterScene.leave((ctx) => ctx.reply('Bye'))
greeterScene.hears('hi', enter('greeter'))
greeterScene.on('message', (ctx) => ctx.replyWithMarkdown('Send `hi`'))

// Echo scene
const echoScene = new Scene('echo')
echoScene.enter((ctx) => ctx.reply('echo scene'))
echoScene.leave((ctx) => ctx.reply('exiting echo scene'))
echoScene.command('back', leave())
echoScene.on('text', (ctx) => ctx.reply(ctx.message.text))
echoScene.on('message', (ctx) => ctx.reply('Only text messages please'))

const bot = new Telegraf(process.env.BOT_TOKEN)
const stage = new Stage([greeterScene, echoScene], { ttl: 10 })
bot.use(session)
bot.use(stage.middleware())
bot.command('greeter', enter('greeter'))
bot.command('echo', enter('echo'))
bot.on('message', (ctx) => ctx.reply('Try /echo or /greeter'))
bot.startPolling()

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question