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 🙏

© 2026 – Pkg Stats / Ryan Hefner

telegram-polling-bot

v1.0.0

Published

Lightweight, type-safe Telegram bot library using long polling

Readme

telegram-polling-bot

A lightweight, type-safe Telegram bot library using long polling.

Installation

npm install telegram-polling-bot

Quick Start

import { TelegramBot } from 'telegram-polling-bot';

const bot = new TelegramBot({
  token: 'YOUR_BOT_TOKEN',
  chatId: 'YOUR_CHAT_ID', // Optional: filter messages from specific chat
});

// Handle commands
bot.onCommand('start', async (ctx) => {
  await ctx.reply('Hello! I am your bot.');
});

// Handle text patterns
bot.onText(/^\d{4}$/, async (ctx, match) => {
  await ctx.reply(`You sent a 4-digit code: ${match[0]}`);
});

// Handle all messages
bot.onMessage(async (ctx) => {
  console.log('Received:', ctx.message.text);
});

// Start polling
bot.start();

API Reference

Constructor

const bot = new TelegramBot(options);

Options:

  • token (string, required): Telegram bot token from @BotFather
  • chatId (string | number, optional): Filter messages from specific chat
  • pollingInterval (number, optional): Polling interval in ms (default: 3000)
  • onError (function, optional): Global error handler

Methods

bot.onCommand(command, handler)

Handle slash commands like /start, /help

bot.onCommand('start', async (ctx) => {
  await ctx.reply('Welcome!');
});

bot.onText(pattern, handler)

Handle messages matching regex pattern

bot.onText(/hello/i, async (ctx) => {
  await ctx.reply('Hi there!');
});

bot.onMessage(handler)

Handle all incoming messages

bot.onMessage(async (ctx) => {
  console.log('Message:', ctx.message.text);
});

bot.use(middleware)

Add middleware for message processing

bot.use(async (ctx, next) => {
  console.log('Before:', ctx.message.text);
  await next();
  console.log('After processing');
});

bot.start()

Start polling for messages

await bot.start();

bot.stop()

Stop polling

bot.stop();

Context API (ctx)

The context object passed to handlers contains:

interface Context {
  message: TelegramMessage;      // Original message
  bot: TelegramBot;              // Bot instance

  // Send text message
  reply(text: string): Promise<void>;

  // Send photo
  sendPhoto(photo: string | Buffer, caption?: string): Promise<void>;

  // Send document
  sendDocument(document: string | Buffer, caption?: string): Promise<void>;

  // Get update data
  update: TelegramUpdate;
}

Advanced Usage

Multiple Handlers

// Login command
bot.onCommand('login', async (ctx) => {
  await ctx.reply('Logging you in...');
  // Perform login logic
});

// Status command
bot.onCommand('status', async (ctx) => {
  await ctx.sendPhoto(screenshot, 'Current status');
});

// Captcha code (4 digits)
bot.onText(/^\d{4}$/, async (ctx, match) => {
  const code = match[0];
  await ctx.reply(`Processing captcha code: ${code}`);
});

Middleware Chain

// Logging middleware
bot.use(async (ctx, next) => {
  console.log(`[${new Date().toISOString()}] ${ctx.message.text}`);
  await next();
});

// Authentication middleware
bot.use(async (ctx, next) => {
  if (ctx.message.chat.id !== AUTHORIZED_CHAT_ID) {
    await ctx.reply('Unauthorized');
    return;
  }
  await next();
});

// Commands will only run after middleware passes
bot.onCommand('admin', async (ctx) => {
  await ctx.reply('Admin command executed');
});

Error Handling

const bot = new TelegramBot({
  token: TOKEN,
  onError: (error) => {
    console.error('Bot error:', error);
    // Send to monitoring service
  },
});

// Per-handler error handling
bot.onCommand('start', async (ctx) => {
  try {
    await riskyOperation();
  } catch (error) {
    await ctx.reply('Something went wrong!');
  }
});

Custom Message Sending

// Direct API access
await bot.sendMessage(chatId, 'Hello!');
await bot.sendPhoto(chatId, photoBuffer, 'Caption here');
await bot.sendDocument(chatId, fileBuffer, 'document.pdf');

Examples

Captcha Solver Bot

import { TelegramBot } from 'telegram-polling-bot';

const bot = new TelegramBot({
  token: process.env.BOT_TOKEN!,
  chatId: process.env.CHAT_ID!,
});

// Handle 1-4 digit captcha codes
bot.onText(/^\d{1,4}$/, async (ctx, match) => {
  const code = match[0];
  console.log('Solving captcha with code:', code);

  // Solve captcha logic here
  const solved = await solveCaptcha(code);

  if (solved) {
    await ctx.reply('✅ Captcha solved successfully!');
  } else {
    await ctx.reply('❌ Failed to solve captcha');
  }
});

bot.start();

Multi-Command Bot

import { TelegramBot } from 'telegram-polling-bot';

const bot = new TelegramBot({
  token: process.env.BOT_TOKEN!,
});

bot.onCommand('start', async (ctx) => {
  await ctx.reply('Welcome! Available commands:\n/status - Get status\n/login - Login');
});

bot.onCommand('status', async (ctx) => {
  const screenshot = await captureScreen();
  await ctx.sendPhoto(screenshot, 'Current status');
});

bot.onCommand('login', async (ctx) => {
  await performLogin();
  await ctx.reply('Logged in successfully!');
});

bot.onCommand('help', async (ctx) => {
  await ctx.reply('Commands:\n/start\n/status\n/login\n/help');
});

bot.start();

TypeScript Support

Full TypeScript support out of the box:

import { TelegramBot, Context, TelegramMessage } from 'telegram-polling-bot';

const bot = new TelegramBot({
  token: process.env.BOT_TOKEN!,
});

bot.onCommand('test', async (ctx: Context) => {
  const message: TelegramMessage = ctx.message;
  await ctx.reply('Type-safe!');
});

License

MIT