fastify-telegram
Create and manage a Telegram bot, easily.
This plugin is a good wrapper around Telegraf build by a Fastify maintainer.
Why you should use this plugin compared to what you can find on google?
- All the blog posts and tutorials I found are outdated and use old versions of Telegraf
- The mentioned tutorials start 2 HTTP servers, one for Fastify and one Node.js HTTP server because the Telgram wrapper starts its own HTTP server. This is just a waste of resources.
This plugin instead:
- Integrates the Telegram bot into the Fastify HTTP server
- You can use all the Fastify features like hooks and decorators
- It has good utilities to manage errors and the telegram features (such as polling mode)
Install
npm install fastify-telegram
Compatibility
Plugin version | Fastify version | Telegraf version |
---|
^1.0.0 | ^4.0.0 | ^4.0.0 |
Usage
When you register the plugin, it will add a decorator to the Fastify instance.
You can use it to access the Telegraf instance and configure your bot:
const fastify = require('fastify')
const fastifyTelegram = require('fastify-telegram')
async function run () {
const app = fastify({
pluginTimeout: 10_000
})
await app.register(fastifyTelegram, {
botToken: '123-abc',
baseUrl: 'https://example.come',
decoratorBotName: 'telegramBot',
webhookSecret: 'secret',
waitForHealthPolling: 3_000,
onUnhandledError: (err, ctx) => {
console.log(`Ooops, encountered an error for ${ctx.updateType}`, err)
}
})
app.telegramBot.on('text', (ctx) => ctx.reply('Hello World'))
await app.listen({ port: 3001 })
}
run()
Webhook mode
In this mode, the Telegram bot will send the updates to your server, so the plugin must know the public base url of your server.
Then, it will register a POST route at the url /telegraf/<secretPath>
where <secretPath>
is a random string generated by Telegraf.
You can read the Webhook secret path from the app.telegramWebhook
decorator.
Long polling mode
In this mode, the plugin will start a long polling process that will fetch the updates from the Telegram server by calling the method getUpdates
.
The timeout
is set to 50
seconds by default, and you can't change it: it's a Telegraf limitation.
Options
You can pass the following options to the plugin:
botToken
: [required] it must be a valid bot tokenbaseUrl
: [required] in webhook mode: the base url of your webhook; in long polling mode: undefineddecoratorBotName
: [optional] customize the decorator namewebhookSecret
: [optional] this string is used to validate the incoming requestonUnhandledError
: [optional] this function is called when an error is not handled by default it logs the error using fastify.log.error
Decorators
The plugin adds the following decorators to the Fastify instance:
app.telegramBot
: the Telegraf instanceapp.telegramWebhook
: the webhook secret path (only in webhook mode)
License
Copyright Manuel Spigolon, Licensed under MIT.