Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

telegraf

Package Overview
Dependencies
Maintainers
1
Versions
241
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

telegraf

📢 Modern Telegram bot framework

  • 2.0.1
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

npm NPM Version node David js-standard-style Build Status

📢 Modern Telegram bot framework for node.js.

Features

Installation

$ npm install telegraf

Example

const Telegraf = require('telegraf')
const app = new Telegraf(process.env.BOT_TOKEN)

// Message handling
app.on('message', (ctx) => {
  return ctx.reply('*42*', { parse_mode: 'Markdown' })
})

app.startPolling()

One more example

const Telegraf = require('telegraf')

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

// Look ma, middleware!
const sayYoMiddleware = (ctx, next) => {
  return ctx.reply('yo').then(next)
}

// Command handling
app.hears('/command', sayYoMiddleware, (ctx) => {
  return ctx.reply('Sure')
})

// Wow! RegEx
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.

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

app.on('text', (ctx) => {
  return ctx.reply('Hello World')
})

app.startPolling()

Context

A Telegraf Context encapsulates telegram message. Context is created per request and contains following props:

app.use((ctx) => {
  ctx.telegram             // Telegram instance
  ctx.updateType           // Update type(message, inline_query, etc.)
  [ctx.updateSubType]      // Update subtype(text, sticker, audio, etc.)
  [ctx.message]            // Received message
  [ctx.editedMessage]      // Edited message
  [ctx.inlineQuery]        // Received inline query
  [ctx.chosenInlineResult] // Received inline query result
  [ctx.callbackQuery]      // Received callback query
  [ctx.chat]               // Current chat info
  [ctx.from]               // Sender info
  [ctx.match]              // Regex match (available only for `hears` handler)
})

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)

// Logger middleware
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)

// Session state will be lost on app restart
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)

// TLS options
const tlsOptions = {
  key:  fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem'),
  ca: [ 
    // This is necessary only if the client uses the self-signed certificate.
    fs.readFileSync('client-cert.pem') 
  ]
}

// Set telegram webhook
app.telegram.setWebHook('https://server.tld:8443/secret-path', {
  content: 'server-cert.pem'
})

// Start https webhook
app.startWebHook('/secret-path', tlsOptions, 8443)


// Http webhook, for nginx/heroku users.
app.startWebHook('/secret-path', null, 5000)


// Use webHookCallback() if you want attach telegraf to existing http server
require('http')
  .createServer(app.webHookCallback('/secret-path'))
  .listen(3000)

require('https')
  .createServer(tlsOptions, app.webHookCallback('/secret-path'))
  .listen(8443)

// Connect/Express.js integration
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.

Keywords

FAQs

Package last updated on 15 Jun 2016

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc