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

telegraf-hardened

v5.0.0

Published

Hardened version of Telegraf with community fixes

Downloads

702

Readme

❤️ Special Thanks

This fork exists and improves thanks to the amazing contributors:

  • @BataevDaniil — Architect of the custom-fetch feature.
  • @clansty — Critical JSON serialization and thumbnail fixes.

🛠 Roadmap & Community Fixes

🎯 Current Status: v1 Strategic Roadmap Fully Closed ✅

Version: 🚀 v5.0.0 Stable | 🛡 Hardened

We have successfully integrated all planned critical improvements from the community that were abandoned by the official Telegraf upstream. Telegraf-hardened is now a feature-complete and stable alternative.

Check our Strategic Roadmap v1

Key Improvements in this Fork already done:

  • 🛠 Future: Even stricter type validation & community-requested features.
  • Native Telegram Stars Support (API 7.8):
    • Full support for digital goods, star transactions, and paid media.
    • sendPaidMedia() — Send exclusive content for stars.
    • getStarTransactions() — Built-in business logic for tracking star revenue.
    • refundStarPayment() — Native refund support for star-based transactions.
  • Zero-Dependency Network Layer: Completely dropped node-fetch and abort-controller. Now using native Node.js 18+ Fetch API for maximum performance and security.
  • Fail-Fast Security: Integrated token validation and strict error handling to prevent state leaks.
  • Community PRs: Already merged some critical fixes from the community.
  • New Features
    • bot.validateTokenAsync() Performs an actual network request to Telegram via getMe to verify the token and pre-populate botInfo. Throws a descriptive 401 Unauthorized error if the token is revoked or invalid. Automatically populates bot.botInfo on success.
  • Native SOCKS5/TOR Support: Built-in support for SOCKS4/5 and Tor proxies using undici and socks. No more external fetch-wrappers needed.

Are you a Telegraf contributor? If your PR is ignored upstream, resubmit it here!

⚠️ Breaking Changes

Class methods

Telegraf Constructor (Fail-Fast Validation)

  • Change: Added synchronous token validation directly in the constructor.
  • Impact: If you pass undefined, an empty string, or a malformed token (missing :), the constructor will now throw an Error immediately.
  • Reason: In original Telegraf, a bot could be instantiated with an invalid token and only fail much later during launch() or the first API call. We catch this at the earliest possible stage.

Telegram API Methods

setStickerSetThumbnail

Method signature updated to align with the latest Bot API requirements.

  • New parameter: format (mandatory) is now required as the third argument.
  • Before: telegram.setStickerSetThumbnail(name, userId, thumbnail)
  • After: telegram.setStickerSetThumbnail(name, userId, format, thumbnail)
  • Reason: Telegram Bot API now strictly distinguishes between sticker formats (static, animated, video) for thumbnails.

editMessageText (Strict Mode)

  • Change: The method now uses a Discriminated Union for parameters.
  • Impact: You can no longer pass both chat_id and inline_message_id simultaneously (even as undefined). TypeScript will now enforce either the "Chat" signature or the "Inline" signature, preventing 400 Bad Request errors at compile time.

Introduction

Bots are special Telegram accounts designed to handle messages automatically. Users can interact with bots by sending them command messages in private or group chats. These accounts serve as an interface for code running somewhere on your server.

Telegraf is a library that makes it simple for you to develop your own Telegram bots using JavaScript or TypeScript.

🔌 Proxy Support (SOCKS/HTTP)

Telegraf-hardened supports SOCKS4, SOCKS5 (including Tor), and HTTP proxies out of the box.

const { Telegraf } = require('telegraf-hardened')

const bot = new Telegraf(process.env.BOT_TOKEN, {
    telegram: {
        proxy: 'socks5://127.0.0.1:9050', // Tor default port
    },
})

// For authenticated proxies:
// proxy: '[http://user:[email protected]:8080](http://user:[email protected]:8080)'

Features

📖 Documentation

The complete documentation for telegraf-hardened is available at: 👉 telegraf-hardened/telegraf-docs > Note: We are currently updating the docs to include all the new Hardened features like Native Fetch and Telegram Stars.

Example

const { Telegraf } = require('telegraf-hardened')
const { message } = require('telegraf-hardened/filters')

const bot = new Telegraf(process.env.BOT_TOKEN)

;(async () => {
    await bot.validateTokenAsync()
    bot.start((ctx) => ctx.reply('Welcome'))
    bot.help((ctx) => ctx.reply('Send me a sticker'))
    bot.on(message('sticker'), (ctx) => ctx.reply('👍'))
    bot.hears('hi', (ctx) => ctx.reply('Hey there'))
    // Example: Sending paid media (Bot API 7.8)
    bot.command('vip', (ctx) => {
        return ctx.telegram.sendPaidMedia(ctx.chat.id, 50, [
            {
                type: 'photo',
                media: Input.fromLocalFile('./premium_content.jpg'),
            },
        ])
    })
    bot.launch()
})()

// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'))
process.once('SIGTERM', () => bot.stop('SIGTERM'))
const { Telegraf } = require('telegraf-hardened')

const bot = new Telegraf(process.env.BOT_TOKEN)(async () => {
    await bot.validateTokenAsync()
    bot.command('oldschool', (ctx) => ctx.reply('Hello'))
    bot.command('hipster', Telegraf.reply('λ'))
    bot.launch()
})()

// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'))
process.once('SIGTERM', () => bot.stop('SIGTERM'))

Getting started

Telegram token

To use the Telegram Bot API, you first have to get a bot account by chatting with BotFather.

BotFather will give you a token, something like 123456789:AbCdefGhIJKlmNoPQRsTUVwxyZ.

Installation

$ npm install telegraf-hardened

Telegraf class

Telegraf instance represents your bot. It's responsible for obtaining updates and passing them to your handlers.

Start by listening to commands and launching your bot.

Context class

ctx you can see in every example is a Context instance. Telegraf creates one for each incoming update and passes it to your middleware. It contains the update, botInfo, and telegram for making arbitrary Bot API requests, as well as shorthand methods and getters.

This is probably the class you'll be using the most.

Shorthand methods

import { Telegraf } from 'telegraf-hardened'
import { message } from 'telegraf-hardened/filters'

const bot = new Telegraf(process.env.BOT_TOKEN)

bot.command('quit', async (ctx) => {
    // Explicit usage
    await ctx.telegram.leaveChat(ctx.message.chat.id)

    // Using context shortcut
    await ctx.leaveChat()
})

bot.on(message('text'), async (ctx) => {
    // Explicit usage
    await ctx.telegram.sendMessage(
        ctx.message.chat.id,
        `Hello ${ctx.state.role}`
    )

    // Using context shortcut
    await ctx.reply(`Hello ${ctx.state.role}`)
})

bot.on('callback_query', async (ctx) => {
    // Explicit usage
    await ctx.telegram.answerCbQuery(ctx.callbackQuery.id)

    // Using context shortcut
    await ctx.answerCbQuery()
})

bot.on('inline_query', async (ctx) => {
    const result = []
    // Explicit usage
    await ctx.telegram.answerInlineQuery(ctx.inlineQuery.id, result)

    // Using context shortcut
    await ctx.answerInlineQuery(result)
})

bot.launch()

// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'))
process.once('SIGTERM', () => bot.stop('SIGTERM'))

Production

Webhooks

import { Telegraf } from "telegraf-hardened";
import { message } from 'telegraf-hardened/filters';

const bot = new Telegraf(token);

bot.on(message("text"), ctx => ctx.reply("Hello"));

// Start webhook via launch method (preferred)
bot.launch({
  webhook: {
    // Public domain for webhook; e.g.: example.com
    domain: webhookDomain,

    // Port to listen on; e.g.: 8080
    port: port,

    // Optional path to listen for.
    // `bot.secretPathComponent()` will be used by default
    path: webhookPath,

    // Optional secret to be sent back in a header for security.
    // e.g.: `crypto.randomBytes(64).toString("hex")`
    secretToken: randomAlphaNumericString,
  },
});

Use createWebhook() if you want to attach Telegraf to an existing http server.

import { createServer } from "http";

createServer(await bot.createWebhook({ domain: "example.com" })).listen(3000);
import { createServer } from "https";

createServer(tlsOptions, await bot.createWebhook({ domain: "example.com" })).listen(8443);

Error handling

If middleware throws an error or times out, Telegraf calls bot.handleError. If it rethrows, update source closes, and then the error is printed to console and process terminates. If it does not rethrow, the error is swallowed.

Default bot.handleError always rethrows. You can overwrite it using bot.catch if you need to.

⚠️ Swallowing unknown errors might leave the process in invalid state!

ℹ️ In production, systemd or pm2 can restart your bot if it exits for any reason.

Advanced topics

Working with files

Supported file sources:

  • Existing file_id
  • File path
  • Url
  • Buffer
  • ReadStream

Also, you can provide an optional name of a file as filename when you send the file.

bot.on('message', async (ctx) => {
    // resend existing file by file_id
    await ctx.replyWithSticker('123123jkbhj6b')

    // send file
    await ctx.replyWithVideo(Input.fromLocalFile('/path/to/video.mp4'))

    // send stream
    await ctx.replyWithVideo(
        Input.fromReadableStream(fs.createReadStream('/path/to/video.mp4'))
    )

    // send buffer
    await ctx.replyWithVoice(Input.fromBuffer(Buffer.alloc()))

    // send url via Telegram server
    await ctx.replyWithPhoto(Input.fromURL('https://picsum.photos/200/300/'))

    // pipe url content
    await ctx.replyWithPhoto(
        Input.fromURLStream(
            'https://picsum.photos/200/300/?random',
            'kitten.jpg'
        )
    )
})

Middleware

In addition to ctx: Context, each middleware receives next: () => Promise<void>.

As in Koa and some other middleware-based libraries, await next() will call next middleware and wait for it to finish:

import { Telegraf } from 'telegraf-hardened';
import { message } from 'telegraf-hardened/filters';

const bot = new Telegraf(process.env.BOT_TOKEN);

bot.use(async (ctx, next) => {
  console.time(`Processing update ${ctx.update.update_id}`);
  await next() // runs next middleware
  // runs after next middleware finishes
  console.timeEnd(`Processing update ${ctx.update.update_id}`);
})

bot.on(message('text'), (ctx) => ctx.reply('Hello World'));
bot.launch();

// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));

With this simple ability, you can:

Usage with TypeScript

Telegraf is written in TypeScript and therefore ships with declaration files for the entire library. Moreover, it includes types for the complete Telegram API via the typegram package. While most types of Telegraf's API surface are self-explanatory, there's some notable things to keep in mind.

Extending Context

The exact shape of ctx can vary based on the installed middleware. Some custom middleware might register properties on the context object that Telegraf is not aware of. Consequently, you can change the type of ctx to fit your needs in order for you to have proper TypeScript types for your data. This is done through Generics:

import { Context, Telegraf } from 'telegraf-hardened'

// Define your own context type
interface MyContext extends Context {
    myProp?: string
    myOtherProp?: number
}

// Create your bot and tell it about your context type
const bot = new Telegraf<MyContext>('SECRET TOKEN')

// Register middleware and launch your bot as usual
bot.use((ctx, next) => {
    // Yay, `myProp` is now available here as `string | undefined`!
    ctx.myProp = ctx.chat?.first_name?.toUpperCase()
    return next()
})
// ...