telegraf-hardened
v5.0.0
Published
Hardened version of Telegraf with community fixes
Downloads
702
Maintainers
Readme
❤️ Special Thanks
This fork exists and improves thanks to the amazing contributors:
- @BataevDaniil — Architect of the
custom-fetchfeature. - @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-fetchandabort-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
undiciandsocks. 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_idandinline_message_idsimultaneously (even asundefined). 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
- Full Telegram Bot API 7.8 support
- Excellent TypeScript typings
- Lightweight
- AWS λ / Firebase / Glitch / Fly.io / Whatever ready
http/https/fastify/Connect.js/express.jscompatible webhooks- Extensible
📖 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-hardenedTelegraf 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);- AWS Lambda example integration
- Google Cloud Functions example integration
expressexample integrationfastifyexample integrationkoaexample integration- NestJS framework integration module
- Cloudflare Workers integration module
- Use
bot.handleUpdateto write new integrations
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_idFile pathUrlBufferReadStream
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:
- extract information from updates and then
await next()to avoid disrupting other middleware, - like
ComposerandRouter,await next()for updates you don't wish to handle, - like
sessionandScenes, extend the context by mutatingctxbeforeawait next(), - reuse other people's code,
- do whatever you come up with!
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()
})
// ...