Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
T

telegram-node-bot

> 编程语言
Open source

Node module for creating Telegram bots.

724 stars0 likes2 views
WebsiteGitHub

About

Node module for creating Telegram bots.

telegram-node-bot

Very powerful module for creating Telegram bots. Full API reference

help chat

Installation

To install the stable version:

bash
npm install --save telegram-node-bot

This assumes you are using npm as your package manager. If you don’t, you can access these files on unpkg, download them, or point your package manager to them.

Whats new in 4.0?

  • Bug fixes
  • Clustering
  • New router
  • Web admin

Get started

First of all you need to create your bot and get Token, you can do it right in telegram, just write to @BotFather.

Now let's write simple bot!

javascript
'use strict'

const Telegram = require('telegram-node-bot')
const TelegramBaseController = Telegram.TelegramBaseController
const TextCommand = Telegram.TextCommand
const tg = new Telegram.Telegram('YOUR_TOKEN')

class PingController extends TelegramBaseController {
    /**
     * @param {Scope} $
     */
    pingHandler($) {
        $.sendMessage('pong')
    }

    get routes() {
        return {
            'pingCommand': 'pingHandler'
        }
    }
}

tg.router
    .when(
        new TextCommand('ping', 'pingCommand'),
        new PingController()
    )

That's it!

Introduction

I'm using something like MVC, so we have router and controllers. First you need to declare your commands and which controller will handle it. Then you need to write controllers and handle specific commands in it.

Router

Lets say our bot has three commands: /start, /stop and /restart And we want that commands to be handled by different controllers.

Router declaration code will be like this:

javascript
tg.router
    .when(new TextCommand('/start', 'startCommand'), new StartController())
    .when(new TextCommand('/stop', 'stopCommand'), new StopController())
    .when(new TextCommand('/restart', 'restartCommand'), new RestartController())

Probably we will have a case when user send us command we didn't know, for that case router have otherwise function:

javascript
tg.router
    .when(new TextCommand('/start', 'startCommand'), new StartController())
    .when(new TextCommand('/stop', 'stopCommand'), new StopController())
    .when(new TextCommand('/restart', 'restartCommand'), new RestartController())
    .otherwise(new OtherwiseController())

Now all unknown commands will be handled by OtherwiseController:

javascript
class OtherwiseController extends TelegramBaseController {
    handle() {
        console.log('otherwise')
    }
}

In this cases for all controllers will be called handle method to handle request. But you can pass your custom handler name as second parameter to any command:

javascript
tg.router
    .when(
        new TextCommand('/start', 'startHandler'),
        new StartController()
    )

Then you must add routes property to your controller like this:

javascript
class StartConstoller extends TelegramBaseController {
    /**
     * @param {Scope} $
     */
    start($) {
        $.sendMessage('Hello!')
    }

    get routes() {
        return {
            'startHandler': 'start'
        }
    }
}

You can define controller for inline queries using inlineQuery method:

javascript
tg.router
    .inlineQuery(new InlineModeController())

And controllers for callback queries using callbackQuery:

javascript
tg.router
    .callbackQuery(new CallbackQueryController())

List of all commands

  • TextCommand - just text command like /start
javascript
tg.router
    .when(
        new TextCommand('/start', 'startHandler'),
        new StartController()
    )
  • RegextCommand - any regexp command
javascript
tg.router
    .when(
        new RegexpCommand(/test/g, 'testHandler'),
        new TestController()
    )
  • CustomFilterCommand - custom command
javascript
tg.router
    .when(
        new CustomFilterCommand($ => {
            return $.message.text == 'some text'
        }, 'customFilterHandler'),
        new CustomFilterHandlerController()
    )

You can also create your own command, just extend BaseCommand

Controllers

There are three types of controllers:

  • Controller for messages - TelegramBaseController
  • Controller for CallbackQueries - TelegramBaseCallbackQueryController
  • Controller for InlineQueries - TelegramBaseInlineQueryController

TelegramBaseController

To create controller for message updates you must extend TelegramBaseController.

If you want specific methods of your controller be called for specific commands, you should return a plain object in routes property where key is a route and value is name of your method. In that case handle method will not be called and scope will be passed to your method. Example:

javascript
class TestController extends TelegramBaseController {
    get routes() {
        return {
            'test': 'testHandler'
        }
    }
}

If there are no routes defined then handle method of your controller will be called.

There is also before method, this method will be called after all updates and you should return the scope, you can modify scope if you want:

javascript
class TestController extends TelegramBaseController {
    before(scope) {
        scope.someData = true

        return scope
    }
}

Remember: if you want to handle command in controller you need to declare it in router.

All instances of TelegramBaseController also have private _api property which is a reference to TelegramApi and private _localization property which is a reference to Ivan

TelegramBaseCallbackQueryController

To create such controller you must extend TelegramBaseCallbackQueryController.

This controllers are very simple, they have only one method - handle, this method will be called for all queries and instance of CallbackQuery will be passed.

TelegramBaseInlineQueryController

To create such controller you must extend TelegramBaseInlineQueryController.

These controllers also have handle method which will be called for all queries and an instance of InlineScope will be passed. Also they its have chosenResult method which will be called when user select some result, an instance of ChosenInlineResult

Also as the TelegramBaseController it has _api and _localization properties.

Getting updates

You can use long-pooling or webhooks to get updates. Long-pooling used by default. To use webhooks you need to init library like this:

javascript
const tg = new Telegram.Telegram('YOUR_TOKEN', {
    webhook: {
        url: 'https://61f66256.ngrok.io',
        port: 3000,
        host: 'localhost'
    }
})

You can also create any other custom update fetcher: just extend Telegram.BaseUpdateFetcher and pass it to library:

javascript
const tg = new Telegram.Telegram('YOUR_TOKEN', {
    updateFetcher: new MyUpdateFetcher()
})

Clustering

By default library will create one worker per cpu. You can change it like this:

javascript
const tg = new Telegram.Telegram('YOUR_TOKEN', {
    workers: 1
})

If you want run some code on main process use tg.onMaster method:

javascript
const tg = new Telegram.Telegram('YOUR_TOKEN', {
    workers: 1
})

tg.sendMessage(123, 'test message') //will be sent 2 times (one time on master and one time on worker)

tg.onMaster(() => {
    tg.sendMessage(123, 'test message') //will be sent one time
})

Web admin

By default library will start web admin at localhost:7777, to change that use webAdmin properpty:

javascript
const tg = new Telegram.Telegram('YOUR_TOKEN', {
    webAdmin: {
        port: 1234,
        host: 'localhost'
    }
})

API

You can call api methods two ways:

Directly from tg:

javascript
tg.api.sendMessage(chatId, 'Hi')

Or if you using controllers controller will pass you context $ that already knows current chat id, so it's more easy to use:

javascript
$.sendMessage('Hi')

All methods have required parameters and optional parameters, you can find them in api documentation If you want to pass optional parameters you should pass them as an object:

javascript
$.sendMessage('Hi', { disable_notification: true })

Scope

There is two types of scope:

  • scope for message controllers - Scope
  • scope for inline mode controller - InlineScope

Message controllers scope:

scope will be passed to handle method or to your methods defined in routes

Main feature of scope is that scope already knows current chat id, so there is no need to pass that parameter. Scope have all api methods that have chatId as their first parameter already filled.

Scope also contains some information about update.

Inline controllers scope also has all api methods filled with userId.

Forms

In message controllers scope has runForm method.

With $.runForm method you can create forms:

…

Bot will send the 'q' message to user, wait for message, validate it with your validator function and save the answer, if validation fails bot will ask again that question. You can also do some filtering in your validator, so you can pass the result as second parameter to callback. You can also pass keyboard to keyboard field.

Menu

You can create menu with $.runMenu function:

javascript
$.runMenu({
    message: 'Select:',
    options: {
        parse_mode: 'Markdown' // in options field you can pass some additional data, like parse_mode
    },
    'Exit': {
	    message: 'Do you realy want to exit?',
	    resizeKeyboard: true,
	    'yes': () => {

	    },
	    'no': () => {

	    }
    },
    'anyMatch': () => { //will be executed at any other message

    }
})

Bot will create keyboard and send it with your message, when user tap button bot will call its callback, if it's submenu bot will send submenu.

Layouting menu:

You can pass the maximum number of buttons in line like this:

javascript
$.runMenu({
    message: 'Select:',
    layout: 2,
    'test1': () => {}, //will be on first line
    'test2': () => {}, //will be on first line
    'test3': () => {}, //will be on second line
    'test4': () => {}, //will be on second line
    'test5': () => {}, //will be on third line
})

Or you can pass an array of number of buttons for each line:

javascript
$.runMenu({
    message: 'Select:',
    layout: [1, 2, 1, 1],
    'test1': () => {}, //will be on first line
    'test2': () => {}, //will be on second line
    'test3': () => {}, //will be on second line
    'test4': () => {}, //will be on third line
    'test5': () => {}, //will be on fourth line
})

Inline Menu

You can create inline menu using $.runInlineMenu:

…

waitForRequest

Messages controller scope has waitForRequest method after calling that the next update from current user will be passed to promise.

waitForCallbackQuery

If you send some inline keyboard after that you can call this method, pass to it string or array of string with callback data or your InlineKeyboardMarkup and then when user press button CallbackQuery will be passed to Promise

javascript
$.sendMessage('Send me your name')
$.waitForRequest
    .then($ => {
        $.sendMessage(`Hi ${$.message.text}!`)
    })

Sessions

For user:

javascript
$.setUserSession('someKey', 'some data')
    .then(() => {
        return $.getUserSession('someKey')
    })
    .then(data => {
        console.log(data)
    })

For chat:

javascript
$.setChatSession('someKey', 'some data')
    .then(() => {
        return $.getChatSession('someKey')
    })
    .then(data => {
        console.log(data)
    })

By default sessions are stored in memory, but you can store them anywhere, you need to extend BaseStorage and pass instance of your storage to Telegram:

javascript
const tg = new Telegram.Telegram('YOUR_TOKEN',{
    storage: new MyStorage()
})

Logging

Module makes some logs during work, by default logs are written to console, but you can create your own logger if you want, you must extend BaseLogger and pass instance of your logger to Telegram:

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

JavaScript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言