Node.js wrapper for the official Telegram Bot API with polling and webhook support, comprehensive message handling, media operations, and bot management features.
npx @tessl/cli install tessl/npm-node-telegram-bot-api@0.66.0Node.js Telegram Bot API is a comprehensive wrapper for the official Telegram Bot API that enables developers to create sophisticated Telegram bots with JavaScript. It offers both polling and webhook mechanisms for receiving updates, supports regex-based message handlers for command processing, and provides full coverage of Telegram Bot API methods including media handling, inline keyboards, payments, games, and business features.
npm install node-telegram-bot-apiconst TelegramBot = require('node-telegram-bot-api');For ES modules:
import TelegramBot from 'node-telegram-bot-api';const TelegramBot = require('node-telegram-bot-api');
// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot('YOUR_BOT_TOKEN', { polling: true });
// Listen for any kind of message
bot.on('message', (msg) => {
const chatId = msg.chat.id;
bot.sendMessage(chatId, 'Received your message');
});
// Matches "/echo [whatever]"
bot.onText(/\/echo (.+)/, (msg, match) => {
const chatId = msg.chat.id;
const resp = match[1]; // the captured "whatever"
bot.sendMessage(chatId, resp);
});
// Handle callback queries from inline keyboards
bot.on('callback_query', (callbackQuery) => {
const message = callbackQuery.message;
const data = callbackQuery.data;
bot.answerCallbackQuery(callbackQuery.id, {
text: `You clicked: ${data}`
});
});Node.js Telegram Bot API is built around several key components:
Core bot setup, connection management, and configuration options. Essential for initializing bots and managing polling or webhook connections.
class TelegramBot extends EventEmitter {
constructor(token, options);
// Connection management
startPolling(options): Promise<void>;
stopPolling(options): Promise<void>;
isPolling(): boolean;
openWebHook(): Promise<void>;
closeWebHook(): Promise<void>;
hasOpenWebHook(): boolean;
}
// Static properties
TelegramBot.errors: Object;
TelegramBot.messageTypes: string[];Bot Configuration and Connection
Event-driven message processing with support for text pattern matching, reply handling, and custom event listeners for different message types.
// Event handling
on(event, listener): void;
onText(regexp, callback): void;
removeTextListener(regexp): Object;
clearTextListeners(): void;
onReplyToMessage(chatId, messageId, callback): number;
removeReplyListener(replyListenerId): Object;
clearReplyListeners(): void;
// Update processing
processUpdate(update): void;
getUpdates(options): Promise<Update[]>;Core messaging functionality for sending text messages, handling replies, forwarding, and copying messages between chats.
// Basic messaging
sendMessage(chatId, text, options): Promise<Message>;
forwardMessage(chatId, fromChatId, messageId, options): Promise<Message>;
forwardMessages(chatId, fromChatId, messageIds, options): Promise<MessageId[]>;
copyMessage(chatId, fromChatId, messageId, options): Promise<MessageId>;
copyMessages(chatId, fromChatId, messageIds, options): Promise<MessageId[]>;
// Message editing and deletion
editMessageText(text, options): Promise<Message|boolean>;
editMessageCaption(caption, options): Promise<Message|boolean>;
editMessageReplyMarkup(replyMarkup, options): Promise<Message|boolean>;
deleteMessage(chatId, messageId, options): Promise<boolean>;
deleteMessages(chatId, messageIds, options): Promise<boolean>;Comprehensive media handling including photos, videos, audio, documents, stickers, and voice messages with upload, download, and streaming capabilities.
// Media sending
sendPhoto(chatId, photo, options, fileOptions): Promise<Message>;
sendAudio(chatId, audio, options, fileOptions): Promise<Message>;
sendDocument(chatId, doc, options, fileOptions): Promise<Message>;
sendVideo(chatId, video, options, fileOptions): Promise<Message>;
sendAnimation(chatId, animation, options, fileOptions): Promise<Message>;
sendVoice(chatId, voice, options, fileOptions): Promise<Message>;
sendVideoNote(chatId, videoNote, options, fileOptions): Promise<Message>;
sendMediaGroup(chatId, media, options): Promise<Message[]>;
sendSticker(chatId, sticker, options, fileOptions): Promise<Message>;
// File operations
getFile(fileId, options): Promise<File>;
getFileLink(fileId, options): Promise<string>;
getFileStream(fileId, options): stream.Readable;
downloadFile(fileId, downloadDir, options): Promise<string>;Complete chat administration including member management, permissions, roles, and chat settings with support for groups, supergroups, and channels.
// Chat information
getChat(chatId, options): Promise<Chat>;
getChatAdministrators(chatId, options): Promise<ChatMember[]>;
getChatMemberCount(chatId, options): Promise<number>;
getChatMember(chatId, userId, options): Promise<ChatMember>;
// Member management
banChatMember(chatId, userId, options): Promise<boolean>;
unbanChatMember(chatId, userId, options): Promise<boolean>;
restrictChatMember(chatId, userId, options): Promise<boolean>;
promoteChatMember(chatId, userId, options): Promise<boolean>;
setChatAdministratorCustomTitle(chatId, userId, customTitle, options): Promise<boolean>;
// Chat settings
setChatTitle(chatId, title, options): Promise<boolean>;
setChatDescription(chatId, description, options): Promise<boolean>;
setChatPhoto(chatId, photo, options, fileOptions): Promise<boolean>;
deleteChatPhoto(chatId, options): Promise<boolean>;Interactive elements including polls, dice games, location sharing, contact sharing, and chat actions for enhanced user engagement.
// Interactive elements
sendPoll(chatId, question, pollOptions, options): Promise<Message>;
stopPoll(chatId, pollId, options): Promise<Poll>;
sendDice(chatId, options): Promise<Message>;
sendLocation(chatId, latitude, longitude, options): Promise<Message>;
sendVenue(chatId, latitude, longitude, title, address, options): Promise<Message>;
sendContact(chatId, phoneNumber, firstName, options): Promise<Message>;
sendChatAction(chatId, action, options): Promise<boolean>;
setMessageReaction(chatId, messageId, options): Promise<boolean>;
// Location updates
editMessageLiveLocation(latitude, longitude, options): Promise<Message|boolean>;
stopMessageLiveLocation(options): Promise<Message|boolean>;Advanced Telegram features including inline queries, payments, games, sticker management, forum topics, and business features for sophisticated bot implementations.
// Inline queries
answerInlineQuery(inlineQueryId, results, options): Promise<boolean>;
answerWebAppQuery(webAppQueryId, result, options): Promise<SentWebAppMessage>;
// Payments
sendInvoice(chatId, title, description, payload, providerToken, currency, prices, options): Promise<Message>;
createInvoiceLink(title, description, payload, providerToken, currency, prices, options): Promise<string>;
answerShippingQuery(shippingQueryId, ok, options): Promise<boolean>;
answerPreCheckoutQuery(preCheckoutQueryId, ok, options): Promise<boolean>;
// Games
sendGame(chatId, gameShortName, options): Promise<Message>;
setGameScore(userId, score, options): Promise<Message|boolean>;
getGameHighScores(userId, options): Promise<GameHighScore[]>;
// Business features
getUserChatBoosts(chatId, userId, options): Promise<UserChatBoosts>;
getBusinessConnection(businessConnectionId, options): Promise<BusinessConnection>;Bot configuration and information management including commands, descriptions, menu buttons, and administrator rights.
// Bot information
getMe(options): Promise<User>;
logOut(options): Promise<boolean>;
close(options): Promise<boolean>;
// Bot settings
setMyCommands(commands, options): Promise<boolean>;
deleteMyCommands(options): Promise<boolean>;
getMyCommands(options): Promise<BotCommand[]>;
setMyName(options): Promise<boolean>;
getMyName(options): Promise<BotName>;
setMyDescription(options): Promise<boolean>;
getMyDescription(options): Promise<BotDescription>;
setMyShortDescription(options): Promise<boolean>;
getMyShortDescription(options): Promise<BotShortDescription>;
setChatMenuButton(options): Promise<boolean>;
getChatMenuButton(options): Promise<MenuButton>;
setMyDefaultAdministratorRights(options): Promise<boolean>;
getMyDefaultAdministratorRights(options): Promise<ChatAdministratorRights>;// Error classes
class BaseError extends Error {
constructor(code, message);
code: string;
toJSON(): { code: string, message: string };
}
class FatalError extends BaseError {
constructor(data);
}
class ParseError extends BaseError {
constructor(message, response);
response: http.IncomingMessage;
}
class TelegramError extends BaseError {
constructor(message, response);
response: http.IncomingMessage;
}
// Constructor options
interface TelegramBotOptions {
polling?: boolean | {
timeout?: number;
interval?: number;
autoStart?: boolean;
params?: {
timeout?: number;
limit?: number;
allowed_updates?: string[];
};
};
webHook?: boolean | {
host?: string;
port?: number;
key?: string;
cert?: string;
pfx?: string;
autoOpen?: boolean;
https?: object;
healthEndpoint?: string;
};
onlyFirstMatch?: boolean;
request?: object;
baseApiUrl?: string;
filepath?: boolean;
badRejection?: boolean;
testEnvironment?: boolean;
}