📢 Modern Telegram bot framework for node.js.
Features
Installation
$ npm install telegraf
Examples
const Telegraf = require('telegraf')
const app = new Telegraf(process.env.BOT_TOKEN)
app.on('message', (ctx) => ctx.replyWithMarkdown('*42*'))
app.startPolling()
const Telegraf = require('telegraf')
const app = new Telegraf(process.env.BOT_TOKEN)
const sayYoMiddleware = (ctx, next) => {
return ctx.reply('yo').then(next)
}
app.command('/command', sayYoMiddleware, (ctx) => {
return ctx.reply('Sure')
})
app.hears(/reverse (.+)/, sayYoMiddleware, (ctx) => {
return ctx.reply(ctx.match[1].split('').reverse().join(''))
})
app.startPolling()
There are some other examples.
API
Application
A Telegraf application is an object containing an array of middlewares which are composed
and executed in a stack-like manner upon request. Is similar to many other middleware systems
that you may have encountered such as Koa, Ruby's Rack, Connect.
Context
A Telegraf Context encapsulates telegram message.
Context is created per request and contains following props:
app.use((ctx) => {
ctx.telegram
ctx.updateType
[ctx.updateSubType]
[ctx.message]
[ctx.editedMessage]
[ctx.inlineQuery]
[ctx.chosenInlineResult]
[ctx.callbackQuery]
[ctx.chat]
[ctx.from]
[ctx.match]
})
Context api docs
Cascading
Middleware normally takes two parameters (ctx, next), ctx
is the context for one Telegram message,
next
is a function that is invoked to execute the downstream middleware.
It returns a Promise with a then function for running code after completion.
const app = new Telegraf(process.env.BOT_TOKEN)
app.use((ctx, next) => {
const start = new Date()
return next().then(() => {
const ms = new Date() - start
console.log('response time %sms', ms)
})
})
app.on('text', (ctx) => {
return ctx.reply('Hello World')
})
State
The recommended namespace to share information between middlewares.
const app = new Telegraf(process.env.BOT_TOKEN)
app.use((ctx, next) => {
ctx.state.role = getUserRole(ctx.message)
return next()
})
app.on('text', (ctx) => {
return ctx.reply(`Hello ${ctx.state.role}`)
})
Session
const app = new Telegraf(process.env.BOT_TOKEN)
app.use(Telegraf.memorySession())
app.on('text', () => {
ctx.session.counter = ctx.session.counter || 0
ctx.session.counter++
return ctx.reply(`Message counter:${ctx.session.counter}`)
})
Important: For production environment use any of telegraf-session-*
middleware.
Telegram WebHook
const app = new Telegraf(process.env.BOT_TOKEN)
const tlsOptions = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem'),
ca: [
fs.readFileSync('client-cert.pem')
]
}
app.telegram.setWebHook('https://server.tld:8443/secret-path', {
content: 'server-cert.pem'
})
app.startWebHook('/secret-path', tlsOptions, 8443)
app.startWebHook('/secret-path', null, 5000)
require('http')
.createServer(app.webHookCallback('/secret-path'))
.listen(3000)
require('https')
.createServer(tlsOptions, app.webHookCallback('/secret-path'))
.listen(8443)
const express = require('express')
const expressApp = express()
expressApp.use(app.webHookCallback('/secret-path'))
expressApp.get('/', (req, res) => {
res.send('Hello World!')
})
expressApp.listen(3000, () => {
console.log('Example app listening on port 3000!')
})
Error Handling
By default Telegraf will print all errors to stderr and rethrow error.
To perform custom error-handling logic you can set onError
handler:
telegraf.onError = (err) => {
log.error('server error', err)
throw err
}
API reference
Telegraf API reference
License
The MIT License (MIT)
Copyright (c) 2016 Telegraf
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.