npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

node-telegram-bot-api-middleware

v0.1.3

Published

Package that helps using middleware with generators in node-telegram-bot-api

Downloads

34

Readme

Build Status

Using middleware for node-telegram-bot-api from yagop: https://github.com/yagop/node-telegram-bot-api

Why?

So, you happened to be here. And I assume you like writing telegram bots using yagop-s library node-telegram-bot-api. But sometimes you end making multiple promises, generators by hand, async/await constructions and all that. I present you the way of using power of generators and co library by tj by adding middleware before executing bot message callback

Installation

npm i node-telegram-bot-api-middleware --save

Then you can use it like this:

    const TelegramBot = require('node-telegram-bot-api');
    const bot = new TelegramBot(TOKEN, { polling: true });
    const use = require('node-telegram-bot-api-middleware').use;
    
    // Simple middleware that adds random method to your context
    function randomMiddleware() {
      this.random = (number) => Math.floor(Math.random() * number)
    }
    
    let response = use(randomMiddleware);
    
    bot.onText(/\/command/, response(function() {
      bot.sendMessage(this.chatId, this.random(10));
    });
    
    // or
    response = response.use(function() {
      bot.sendMessage(this.chatId, this.random());
    });
    
    bot.onText(/\/command/, response);
    
    // or
    
    response = response(function() {
      bot.sendMessage(this.chatId, this.random());
    });
    
    bot.onText(/\/command/, response);

Available at the moment middleware

Usage

  const use = require('node-telegram-bot-api-middleware').use;
  // Your configured bot
  const bot = require('./bot');
  
  // You can use simple functions
  function middleware2() {
    // You will already have msg, chatId in context. This is achieved by added already inside
    // library default middleware, that populates context with those things, as well as method .stop()
    // (see further down about .stop)
    
    this.quickResponse = function* (text) {
      yield bot.sendMessage(this.chatId, text);
    }.bind(this);
  }
  
  // You can use generators
  function* middleware2() {
    yield this.quickResponse('You wrote something to this bot!');
    
    console.log('Answer sent');
  }
  
  // You cannot use short functions if you're going to use context passed from
  // previous middleware. `This wont't work: `
  const notWorkingResponse = use(() => { console.log(this.msg.chat.id); });
  
  // Be aware of adding middlewares in proper order,
  // because they will be executed in order in which you added them
  const response = use(middleware).use(middleware2);
  
  // You can also add more middleware to variable that already has set of middlewares
  // Adding more, it will create new set of middleware, not affecting old set of
  // middlewares. response still will have 2 middlewares.
  const checkAuth = response.use(function() {
    // Imagine, this also can be method from other middleware,
    // e.g.: this.isAuthenticated()
    const userIsAuthenticated = false;
    
    if (!userIsAuthenticated) {
      this.quickResponse('You are not authenticated to do that');
      
      // If you want to prevent executing next middlewares, use .stop()
      this.stop();
    }
  });
  
  bot.onText(/\/need_auth/, checkAuth(function() {
    // Give some info only to authenticated user
  }));

Handling errors.

Default error handler built in will console.error all errors from middleware and proceed to next one.

You can also set your own global error handler like this (WARNING: this will replace default error handler, if you need to combine default handler with your - use middleware.getDefaultErrorHandler()):

  const middleware = require('middleware');
  const use = middleware.use;
  
  middleware.setErrorHandler(err => {
    // Your own logic for handling errors
  });

Sometime you might need to set custom error handler to your middleware. This done line this:

  function yourCustomMiddleware() {
    this.methodWithPossibilityOfErrorOccuring();
  }
  
  yourCustomMiddleware.onErrorHandler = err => {
    // Log or do some other things with error
  }

How does it work

use - is just a function, that returns another function, that accepts middleware as arguments or object with message data on bot.onText executiong. It also has .use method, that is just copy of function itself. Useful when writing code like use(middleware).use(middleware)(yourCallbackFunction)

Basically you can write even like this:

    use(middleware)(middleware).use(middleware)(botCallbackArguments); // botCallbackArguments will be passed by bot, and executed function will be also by bot.

For more information on this topic look into index.js file. There are many comments explaining how does it work.

Help yourself and everyone build better bots!

As you can see, this is cool opportunity to create many different middleware libraries for different purposes. For database connection, for special file uploaders or many other things. Join the opensource! (if you did not yet) Create middleware for some other libraries or for your special case and share with everyone! Create an issue or send pull request and I will add link to your middleware in the list.