Both request method to obtain messages are implemented. To use standard polling, set polling: true
+on options. Notice that webHook will need a SSL certificate.
+Emits message when a message arrives.
Bot Token
+StaticerrorsThe different errors the library uses.
+StaticmessageThe types of message updates the library handles.
+Optional[captureThe Symbol.for('nodejs.rejection') method is called in case a
+promise rejection happens when emitting an event and
+captureRejections is enabled on the emitter.
+It is possible to use events.captureRejectionSymbol in
+place of Symbol.for('nodejs.rejection').
import { EventEmitter, captureRejectionSymbol } from 'node:events';
class MyClass extends EventEmitter {
constructor() {
super({ captureRejections: true });
}
[captureRejectionSymbol](err, event, ...args) {
console.log('rejection happened for', event, 'with', err, ...args);
this.destroy(err);
}
destroy(err) {
// Tear the resource down here.
}
}
+
+
+Use this method to send answers to callback queries
+Unique identifier for the query to be answered
+Additional Telegram query options
+Removes all replies that have been prev. registered for a message response.
+deletedListeners An array of removed listeners.
+Remove all listeners registered with onText().
Close webhook. Multiple WebHooks are not supported.
+Promise
+Use this method to delete a message
+Unique identifier for the target chat
+Identifier of the message to delete
+Additional Telegram query options
+Use this method to remove webhook integration if you decide to +switch back to getUpdates.
+Additional Telegram query options
+Promise
+Edit live location messages
+Latitude of new location
+Longitude of new location
+Additional Telegram query options
+Use this method to edit message reply markup
+A JSON-serialized object for an inline keyboard
+Additional Telegram query options
+Use this method to edit text messages
+New text of the message
+Additional Telegram query options
+Synchronously calls each of the listeners registered for the event named
+eventName, in the order they were registered, passing the supplied arguments
+to each.
Returns true if the event had listeners, false otherwise.
import { EventEmitter } from 'node:events';
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
+
+
+Returns an array listing the events for which the emitter has registered +listeners.
+import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+
+Get information about a chat
+Get basic info about a file
+File identifier
+Additional Telegram query options
+Returns basic information about the bot
+Use this method to receive incoming updates using long polling.
+Options for the getUpdates call
+Promise of updates
+Use this method to get current webhook status.
+Additional Telegram query options
+Promise
+Return true if WebHook is active, false otherwise.
+Boolean
+Return true if polling is active, false otherwise.
+Boolean
+Returns the number of listeners listening for the event named eventName.
+If listener is provided, it will return how many times the listener is found
+in the list of the listeners of the event.
The name of the event being listened for
+Optionallistener: (...args: any[]) => voidThe event handler function
+Returns a copy of the array of listeners for the event named eventName.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+
+
+Add listener for the specified event.
+This is the usual emitter.on() method.
Adds a one-time listener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The
+emitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+
+The name of the event.
+The callback function
+Register a reply to wait for a message response.
+The chat id where the message cames from.
+The message id to be replied.
+Callback will be called with the reply message.
+id The ID of the inserted reply listener.
+Register a RegExp to test against an incomming text message.
+RegExp executed with exec.
Callback will be called with 2 parameters,
+the msg and the result of executing regexp.exec on message text.
Open webhook. +Multiple WebHooks are not supported. +Uses webhook options from TelegramBotOptions.webHook configuration.
+Promise that resolves when webhook is open
+Adds the listener function to the beginning of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventName
+and listener will result in the listener being added, and called, multiple
+times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+Adds a one-time listener function for the event named eventName to the
+beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+Process an update; emitting the proper events and executing regexp +callbacks. This method is useful should you be using a different +way to fetch updates, other than those provided by TelegramBot.
+Update object obtained from Telegram API
+Returns a copy of the array of listeners for the event named eventName,
+including any wrappers (such as those created by .once()).
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();
// Logs "log once" to the console and removes the listener
logFnWrapper();
emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');
+
+
+Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code,
+particularly when the EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
OptionaleventName: string | symbolRemoves the specified listener from the listener array for the event named
+eventName.
const callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
+
+
+removeListener() will remove, at most, one instance of a listener from the
+listener array. If any single listener has been added multiple times to the
+listener array for the specified eventName, then removeListener() must be
+called multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that any
+removeListener() or removeAllListeners() calls after emitting and
+before the last listener finishes execution will not remove them from
+emit() in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+
+Because listeners are managed using an internal array, calling this will
+change the position indexes of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners() method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener() will remove the most
+recently added instance. In the example the once('ping')
+listener is removed:
import { EventEmitter } from 'node:events';
const ee = new EventEmitter();
function pong() {
console.log('pong');
}
ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);
ee.emit('ping');
ee.emit('ping');
+
+
+Returns a reference to the EventEmitter, so that calls can be chained.
Removes a reply that has been prev. registered for a message response.
+The ID of the reply listener.
+deletedListener The removed reply listener if
+found. This object has id, chatId, messageId and callback
+properties. If not found, returns null.
Remove a listener registered with onText().
RegExp used previously in onText()
deletedListener The removed reply listener if
+found. This object has regexp and callback
+properties. If not found, returns null.
Send animation files (GIF or H.264/MPEG-4 AVC video without sound)
+Unique identifier for the target chat
+Animation to send
+Additional Telegram query options
+Optional file related meta-data
+Send audio files (MP3 or M4A format)
+Unique identifier for the target chat
+Audio file to send
+Additional Telegram query options
+Optional file related meta-data
+Send chat action (typing, uploading, etc.)
+Unique identifier for the target chat
+Type of action to broadcast
+Additional Telegram query options
+Send phone contacts
+Unique identifier for the target chat
+Contact's phone number
+Contact's first name
+Additional Telegram query options
+Send an animated emoji (dice, dart, basketball, etc.)
+Unique identifier for the target chat
+Additional Telegram query options
+Send general files
+Unique identifier for the target chat
+Document to send
+Additional Telegram query options
+Optional file related meta-data
+Send a game
+Unique identifier for the target chat
+Short name of the game
+Additional Telegram query options
+Send location on the map
+Unique identifier for the target chat
+Latitude of location
+Longitude of location
+Additional Telegram query options
+Send media group (album of photos and videos)
+Unique identifier for the target chat
+Array of InputMedia to be sent
+Additional Telegram query options
+Send a photo
+Unique identifier for the target chat
+Photo to send (file path, Stream, Buffer, or file_id)
+Additional Telegram query options
+Optional file related meta-data
+Send a native poll
+Unique identifier for the target chat
+Poll question
+Array of answer options
+Additional Telegram query options
+Send stickers (.WEBP, .TGS, or .WEBM format)
+Unique identifier for the target chat
+Sticker to send
+Additional Telegram query options
+Optional file related meta-data
+Send venue information
+Unique identifier for the target chat
+Latitude of location
+Longitude of location
+Name of the venue
+Address of the venue
+Additional Telegram query options
+Send video files (mp4 format)
+Unique identifier for the target chat
+Video to send
+Additional Telegram query options
+Optional file related meta-data
+Send video messages (rounded square MPEG4 videos up to 1 minute long)
+Unique identifier for the target chat
+Video note to send
+Additional Telegram query options
+Optional file related meta-data
+Send voice messages (OGG format with OPUS encoding, or MP3/M4A)
+Unique identifier for the target chat
+Voice file to send
+Additional Telegram query options
+Optional file related meta-data
+By default EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set to
+Infinity (or 0) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter, so that calls can be chained.
Specify a url to receive incoming updates via an outgoing webhook.
+URL where Telegram will make HTTP Post. Leave empty to delete webhook.
+Additional Telegram query options
+Optional file related meta-data
+Promise
+Start polling. +Rejects returned promise if a WebHook is being used by this instance.
+Promise
+Stop updating live location
+Additional Telegram query options
+Stops polling
+Promise
+npm i node-telegram-bot-api
+
+
+++โ๏ธ Note: If you use Typescript you can install this package that contains type definitions for this library
++ +npm install --save-dev @types/node-telegram-bot-api +
const TelegramBot = require('node-telegram-bot-api');
// replace the value below with the Telegram token you receive from @BotFather
const token = 'YOUR_TELEGRAM_BOT_TOKEN';
// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot(token, {polling: true});
// Matches "/echo [whatever]"
bot.onText(/\/echo (.+)/, (msg, match) => {
// 'msg' is the received Message from Telegram
// 'match' is the result of executing the regexp above on the text content
// of the message
const chatId = msg.chat.id;
const resp = match[1]; // the captured "whatever"
// send back the matched "whatever" to the chat
bot.sendMessage(chatId, resp);
});
// Listen for any kind of message. There are different kinds of
// messages.
bot.on('message', (msg) => {
const chatId = msg.chat.id;
// send a message to the chat acknowledging receipt of their message
bot.sendMessage(chatId, 'Received your message');
});
+
+
+Note: Development is done against the development branch. +Code for the latest release resides on the master branch. +Experimental features reside on the experimental branch.
+We thank all the developers in the Open-Source community who continuously +take their time and effort in advancing this project. +See our list of contributors.
+We have a Telegram channel where we post updates on +the Project. Head over and subscribe!
+We also have a Telegram group to discuss issues related to this library.
+Some things built using this library that might interest you:
+
+
+
+
+
The MIT License (MIT)
+Copyright ยฉ 2019 Yago
+ConstCollection of all error classes used by the Telegram Bot API library. +Provides convenient access to all error types for error handling and type checking.
+
TelegramBot allows you to interact with the Telegram Bot API. +Main class for creating and managing a Telegram bot. Supports both polling and webhook +modes for receiving updates, and provides methods for all Telegram Bot API endpoints.
+See
Bot API Documentation
+Example
+ +