Search code examples
node.jsasynchronouseventemitter

EventEmitter Ignore next listeners if conditions are true


I'm creating a Telegram bot which uses node-telegram-bot-api package. That package uses EventEmitter3 for emitting events.

I have a listener that executes before all other listeners:

Bot.prependListener( 'message', ( msg ) =>
  if ( CHECK msg.from.id FOR AUTHORIZED USERS == false ) {
      // IGNORE ALL OTHER LISTENERS
  }
} );
‌Bot.onText( /\/start/i, ( msg ) => {
  Bot.sendMessage( msg.from.id, `You're an authorized user for sure!` );
} );

How can I make the EventEmitter ignore all other listeners?


Solution

  • You need something with true middleware support. For example: Telegraf

    const Telegraf = require('telegraf')
    const app = new Telegraf(process.env.BOT_TOKEN)
    
    app.use((ctx, next) => {
        if(AUTHORIZED_USERS.includes(ctx.from.id)){
            return next()
        }
    })
    
    app.command('/start', (ctx) => ctx.reply('You`re an authorized user for sure!'))
    app.startPolling()