CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-node-telegram-bot-api

Node.js wrapper for the official Telegram Bot API with polling and webhook support, comprehensive message handling, media operations, and bot management features.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

bot-setup.mddocs/

Bot Configuration and Connection

Core bot setup, connection management, and configuration options for initializing Telegram bots and managing polling or webhook connections.

Capabilities

TelegramBot Constructor

Creates a new Telegram bot instance with specified token and configuration options.

/**
 * Create a new TelegramBot instance
 * @param {string} token - Bot authentication token from @BotFather
 * @param {TelegramBotOptions} [options] - Configuration options
 */
class TelegramBot extends EventEmitter {
  constructor(token, options);
}

Usage Example:

const TelegramBot = require('node-telegram-bot-api');

// Basic bot with polling
const bot = new TelegramBot('YOUR_BOT_TOKEN', { polling: true });

// Bot with detailed polling configuration
const bot = new TelegramBot('YOUR_BOT_TOKEN', {
  polling: {
    interval: 1000,
    autoStart: true,
    params: {
      timeout: 10,
      limit: 100,
      allowed_updates: ['message', 'callback_query']
    }
  }
});

// Bot with webhook configuration
const bot = new TelegramBot('YOUR_BOT_TOKEN', {
  webHook: {
    port: 8443,
    host: '0.0.0.0',
    cert: './cert.pem',
    key: './private.key'
  }
});

Polling Methods

Methods for managing long polling connections to receive updates from Telegram servers.

/**
 * Start polling for updates
 * @param {object} [options] - Polling options
 * @param {boolean} [options.restart] - Whether to restart if already polling
 * @returns {Promise<void>}
 */
startPolling(options): Promise<void>;

/**
 * Stop polling for updates
 * @param {object} [options] - Stop options
 * @param {boolean} [options.cancel] - Cancel current request
 * @param {string} [options.reason] - Reason for stopping
 * @returns {Promise<void>}
 */
stopPolling(options): Promise<void>;

/**
 * Check if bot is currently polling
 * @returns {boolean} True if polling is active
 */
isPolling(): boolean;

Usage Example:

// Start polling with options
await bot.startPolling({
  restart: true
});

// Check polling status
if (bot.isPolling()) {
  console.log('Bot is currently polling');
}

// Stop polling
await bot.stopPolling({
  cancel: true,
  reason: 'Server shutdown'
});

Webhook Methods

Methods for managing webhook connections to receive updates via HTTP callbacks.

/**
 * Open webhook server to receive updates
 * @returns {Promise<void>}
 */
openWebHook(): Promise<void>;

/**
 * Close webhook server
 * @returns {Promise<void>}
 */
closeWebHook(): Promise<void>;

/**
 * Check if webhook is currently open
 * @returns {boolean} True if webhook is open
 */
hasOpenWebHook(): boolean;

Usage Example:

// Open webhook
await bot.openWebHook();

// Check webhook status
if (bot.hasOpenWebHook()) {
  console.log('Webhook is open and receiving updates');
}

// Close webhook
await bot.closeWebHook();

Webhook Configuration

Methods for configuring webhooks on Telegram's servers.

/**
 * Set webhook URL on Telegram servers
 * @param {string} url - HTTPS URL to send updates to
 * @param {object} [options] - Webhook options
 * @param {string[]} [options.allowed_updates] - List of update types to receive
 * @param {boolean} [options.drop_pending_updates] - Drop pending updates
 * @param {string} [options.secret_token] - Secret token for webhook security
 * @param {number} [options.max_connections] - Maximum allowed connections (1-100)
 * @param {object} [fileOptions] - File upload options
 * @returns {Promise<boolean>}
 */
setWebHook(url, options, fileOptions): Promise<boolean>;

/**
 * Delete webhook configuration
 * @param {object} [options] - Delete options
 * @param {boolean} [options.drop_pending_updates] - Drop pending updates
 * @returns {Promise<boolean>}
 */
deleteWebHook(options): Promise<boolean>;

/**
 * Get current webhook information
 * @param {object} [options] - Request options
 * @returns {Promise<WebhookInfo>}
 */
getWebHookInfo(options): Promise<WebhookInfo>;

Usage Example:

// Set webhook URL
await bot.setWebHook('https://mybot.example.com/webhook', {
  allowed_updates: ['message', 'callback_query'],
  max_connections: 40,
  secret_token: 'my-secret-token'
});

// Get webhook info
const webhookInfo = await bot.getWebHookInfo();
console.log('Webhook URL:', webhookInfo.url);
console.log('Pending updates:', webhookInfo.pending_update_count);

// Delete webhook
await bot.deleteWebHook({
  drop_pending_updates: true
});

Static Properties

Static properties available on the TelegramBot class.

/**
 * Error classes used by the library
 * @type {object}
 */
static errors: {
  BaseError: class,
  FatalError: class,
  ParseError: class,
  TelegramError: class
};

/**
 * Supported message types
 * @type {string[]}
 */
static messageTypes: string[];

Usage Example:

// Access error classes
const { TelegramError } = TelegramBot.errors;

try {
  await bot.sendMessage(chatId, message);
} catch (error) {
  if (error instanceof TelegramError) {
    console.error('Telegram API error:', error.code, error.message);
  }
}

// Check supported message types
console.log('Supported types:', TelegramBot.messageTypes);
// ['text', 'photo', 'video', 'audio', 'document', 'sticker', ...]

Types

interface TelegramBotOptions {
  polling?: boolean | {
    timeout?: number;           // Deprecated, use params.timeout
    interval?: number;          // Polling interval in milliseconds (default: 300)
    autoStart?: boolean;        // Start polling immediately (default: true)
    params?: {
      timeout?: number;         // Long polling timeout in seconds (default: 10)
      limit?: number;          // Max number of updates per request (1-100)
      offset?: number;         // Identifier of first update to return
      allowed_updates?: string[]; // Update types to receive
    };
  };
  webHook?: boolean | {
    host?: string;             // Host to bind to (default: "0.0.0.0")
    port?: number;            // Port to bind to (default: 8443)
    key?: string;             // Path to PEM private key file
    cert?: string;            // Path to PEM certificate file
    pfx?: string;             // Path to PFX certificate file
    autoOpen?: boolean;       // Open webhook immediately (default: true)
    https?: object;           // Additional HTTPS options
    healthEndpoint?: string;  // Health check endpoint (default: "/healthz")
  };
  onlyFirstMatch?: boolean;    // Stop after first text pattern match
  request?: object;           // Additional request options for all API calls
  baseApiUrl?: string;        // Custom API base URL (default: "https://api.telegram.org")
  filepath?: boolean;         // Allow file paths in media methods (default: true)
  badRejection?: boolean;     // Handle unhandled rejections (default: false)
  testEnvironment?: boolean;  // Use test environment API
}

interface WebhookInfo {
  url: string;
  has_custom_certificate: boolean;
  pending_update_count: number;
  ip_address?: string;
  last_error_date?: number;
  last_error_message?: string;
  last_synchronization_error_date?: number;
  max_connections?: number;
  allowed_updates?: string[];
  secret_token?: string;
}

docs

advanced-features.md

bot-settings.md

bot-setup.md

chat-management.md

index.md

interactive-features.md

media-files.md

message-handling.md

messaging.md

tile.json