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

nubitel-telegram-api

v1.0.1

Published

NodeJs Telegram API

Downloads

8

Readme

Node.js Telegram API

Telegram API framework for Node.js


Features

✅ Explicit messages handlers ✅ Fallback messages handler (empty string) ✅ Regex matching on text messages ✅ Buttons support (inline keyboard, reply keyboard and remove reply keyboard) ✅ Secret token support ✅ Long polling support

Getting started

Installation

npm install nubitel-telegram-api

Install dependencies

In order to reduce the node_modules size dotenv (for environment variables) and express (for local development / deployment) packages are defined as devDependencies.

You don't have to use these packages if you don't want to, and you can use them only for local development if you choose so. If you do choose to work with these packages, install them manually:

npm install express dotenv

Or for serverless deployments install express as a dev dependency (to use in your local development environment) instead:

npm install express --save-dev

Set webhook

In order to listen to updates from Telegram servers you have to set up a webhook. To use the npx set-webhook command you should provide the webhook parameter and api token. You can do that by:

  1. Setting the WEBHOOK and API_TOKEN environment variables (SECRET_TOKEN is optional).
  2. Storing them in .env file (SECRET_TOKEN is optional).
  3. Use the --apiToken and --webhook command arguments (--secretToken is optional).

You also can provide the secret token parameter if you choose to.

Then you can execute the following command:

npx set-webhook

Long polling

If you prefer to use long polling method over creating a server with webhook you can use the startLongPolling method instead of createServer. The method accepts pollingDelay - a number that represents milliseconds (must be at least 50ms).

Note that long polling is usually not recommended and webhook is preferred for most use cases.

Usage

const NubitelTelegram = require('nubitel-telegram-api');
require('dotenv').config();

const bot = new NubitelTelegram({
	apiToken: process.env.API_TOKEN,
});

bot.createServer(); // spins up an express server

bot.onTextMessage('hello', async (messageBody) => {
	console.log(messageBody);
	await bot.sendTextMessage('hello back', messageBody.chat.id);
});

In this example the bot will listen only to 'hello' text messages and will respond to the user 'hello back'. Any other message will be ignored.

  • Note that bot.createServer() method requires express, and we are using dotenev as well which both are not installed automatically with NubitelTelegram.

Webhook security with secret token

You can secure your webhook with a secret token via the setWebhook method. You can do that by creating a SECRET_TOKEN variable in the .env file of your project (or environment variable) and run the npx set-webhook command. The command will tell Telegram servers to send the secret token in each request to your webhook as x-telegram-bot-api-secret-token header.

In order for the bot to use the secret token you need to pass to the NubitelTelegram class you instanciate the secretToken parameter.

You will have to pass a secretToken parameter to the telegramHandler method as well.

You can pass a third parameter called unauthorizedCallback - a callback that will fire in case the request wasn't authorized.


Run feature examples:

After you have set your webhook you can play and test the NubitelTelegram features.

Each feature of NubitelTelegram is demonstrated in an example file inside the examples folder (inside node_modules if you installed NubitelTelegram). You can run an example from the nubitel-telegram-api directory inside node_modules by using the command:

npm run dev --file=<example>

You might need nodemon and dotenv installed as dev dependencies to run the examples with the command above.


Deployment:

Since these days it is common to use serverless backend services, you can choose how the bot will work - or with express or with the HTTP engine of the serverless provider.

In order to spin up an express server you should use the command bot.createServer() - this is useful for deployments on VMs / containers / on-premise.

You can pass an object as options for createServer. Currently, it supports port and unauthorizedCallback (if you use secret token) - e.g:

bot.createServer({ port: 4000 }) // the default is 3000

In the other hand, if you want to deploy on serverless backend you need to use bot.telegramHandler method and pass to it the request object. You will probably have something like this:

functions.https.onCall((req, res) => {
    const secretToken = req.headers['x-telegram-bot-api-secret-token'];
    bot.telegramHandler(req.body, secretToken, unauthorizedHandler);
    res.end();
});

Note that on serverless you should extract by your own the secretToken since every serverless service might process the req object differently.