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

Telegram bot framework

  • 0.4.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
79K
increased by9.27%
Maintainers
1
Weekly downloads
 
Created
Source

Telegraf

Build Status NPM Version

Telegram bot framework for node.js

Installation

$ npm install telegraf

Example

var Telegraf = require('telegraf');

var app = new Telegraf(process.env.BOT_TOKEN);

// Text messages handling
app.hears('/answer', function * () {
  this.reply('*42*', { parse_mode: 'Markdown' })
})

// Look ma, middleware!
var sayYoMiddleware = function * (next) {
  yield this.reply('yo')
  yield next
}

// Wow! RegEx
app.hears(/reverse (.+)/, sayYoMiddleware, function * () {
  this.reply(this.match[1].split('').reverse().join(''))
})

app.startPolling()

There are some other examples.

API

Application

A Telegraf application is an object containing an array of middleware generator functions which are composed and executed in a stack-like manner upon request. Telegraf is similar to many other middleware systems that you may have encountered such as Koa, Ruby's Rack, Connect, and so on - however a key design decision was made to provide high level "sugar" at the otherwise low-level middleware layer. This improves interoperability, robustness, and makes writing middleware much more enjoyable.

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

app.on('text', function * (){
  this.reply('Hello World')
})

app.startPolling()

Cascading

Telegraf middleware cascade in a more traditional way as you may be used to with similar tools - this was previously difficult to make user friendly with node's use of callbacks. However with generators we can achieve "true" middleware. Contrasting Connect's implementation which simply passes control through series of functions until one returns, Telegraf yields "downstream", then control flows back "upstream".

The following example bot will reply with "Hello World", however first the message flows through the logger middleware to mark when the message has been received. When a middleware invokes yield next the function suspends and passes control to the next middleware defined. After there are no more middleware to execute downstream, the stack will unwind and each middleware is resumed to perform its upstream behaviour.

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

// Logger middleware
app.use(function * (next){
  var start = new Date
  this.state.started = start
  yield next
  var ms = new Date - start
  debug('response time %sms', ms)
})

app.on('text', function * (){
  this.reply('Hello World')
})

Context

A Telegraf Context encapsulates telegram message. Context is created per request, and is referenced in middleware as the receiver, or the this identifier, as shown in the following snippet:

app.use(function * (){
  this.eventType          // Event type
  this.message            // Received message
  this.inlineQuery        // Received inline query
  this.chosenInlineResult // Received inline query result
  this.callbackQuery      // Received callback query
});

The recommended way to extend application context.

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

app.context.db = {
  getScores: function () { return 42 }
}

app.on('text', function * (){
  var scores = this.db.getScores(this.message.from.username)
  this.reply(`${this.message.from.username}: ${score}`)
})

State

The recommended namespace to share information between middlewares.

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

app.use(function * (next) {
  this.state.role = getUserRole(this.message) 
  yield next
})

app.on('text', function * (){
  this.reply(`Hello ${this.state.role}`)
})

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:

app.onError = function(err){
  log.error('server error', err)
  
  // If user messages is important for us, we will exit from update loop
  throw err
}

API reference

Telegraf.new(token)

Initialize new app.

ParamTypeDescription
tokenStringBot Token

Telegraf.startPolling(timeout, limit)

Start poll updates.

ParamTypeDefaultDescription
timeoutInt0Poll timeout
limitInt100Limits the number of updates to be retrieved

Telegraf.startWebHook(token, tlsOptions, port, [host])

Start listening @ https://host:port/token for Telegram calls.

ParamTypeDescription
tokenStringToken
tlsOptionsObjecttls server options
portIntPort number
hostStringHostname

Telegraf.stop()

Stop WebHook and polling


Telegraf.use(middleware)

Registers a middleware.

ParamTypeDescription
middlewareFunctionMiddleware function

Telegraf.on(eventType, handler)

Registers handler for provided event type.

ParamTypeDescription
eventTypeString or Array[String]Event type
handlerFunctionHandler

Telegraf.hear(pattern, handler)

Registers handler only for text events using string pattern or RegEx.

ParamTypeDescription
patternString/RegExPattern or RegEx
handlerFunctionHandler

Telegraf.sendMessage(chatId, text, extra) => Promise

Sends text message.

ParamTypeDescription
chatIdInteger/StringChat id
textStringMessage
extraObjectOptional parameters
Related Telegram api docs

Telegraf.forwardMessage(chatId, fromChatId, messageId, extra) => Promise

Forwards message.

ParamTypeDescription
chatIdInteger/StringSource Chat id
fromChatIdInteger/StringTarget Chat id
messageIdIntegerMessage id
extraObjectOptional parameters

Related Telegram api docs


Telegraf.sendLocation(chatId, latitude, longitude, extra) => Promise

Sends location.

ParamTypeDescription
chatIdInteger/StringChat id
latitudeIntegerLatitude
longitudeIntegerLongitude
extraObjectOptional parameters

Related Telegram api docs


Telegraf.sendPhoto(chatId, photo, extra) => Promise

Sends photo.

ParamTypeDescription
chatIdInteger/StringChat id
photoFilePhoto
extraObjectOptional parameters

Related Telegram api docs


Telegraf.sendDocument(chatId, doc, extra) => Promise

Sends document.

ParamTypeDescription
chatIdInteger/StringChat id
docFileDocument
extraObjectOptional parameters

Related Telegram api docs


Telegraf.sendAudio(chatId, audio, extra) => Promise

Sends audio.

ParamTypeDescription
chatIdInteger/StringChat id
audioFileDocument
extraObjectOptional parameters

Related Telegram api docs


Telegraf.sendSticker(chatId, sticker, extra) => Promise

Sends sticker.

ParamTypeDescription
chatIdInteger/StringChat id
stickerFileDocument
extraObjectOptional parameters

Related Telegram api docs


Telegraf.sendVideo(chatId, video, extra) => Promise

Sends video.

ParamTypeDescription
chatIdInteger/StringChat id
videoFileDocument
extraObjectOptional parameters

Related Telegram api docs


Telegraf.sendVoice(chatId, voice, extra) => Promise

Sends voice.

ParamTypeDescription
chatIdInteger/StringChat id
voiceFileDocument
extraObjectOptional parameters

Related Telegram api docs


Telegraf.sendChatAction(chatId, action) => Promise

Sends chat action.

ParamTypeDescription
chatIdInteger/StringChat id
actionStringChat action

Related Telegram api docs


Telegraf.getMe() => Promise

Returns basic information about the bot.

Related Telegram api docs


Telegraf.getUserProfilePhotos(userId, offset, limit) => Promise

Returns profiles photos for provided user.

ParamTypeDescription
userIdIntegerChat id
offsetIntegerOffset
userIdlimitLimit

Related Telegram api docs


Telegraf.getFile(fileId) => Promise

Returns basic info about a file and prepare it for downloading.

ParamTypeDescription
fileIdStringFile id

Related Telegram api docs


Telegraf.getFileLink(fileId) => Promise

Returns link to file.

ParamTypeDescription
fileIdStringFile id

Related Telegram api docs


Telegraf.setWebHook(url, [cert]) => Promise

Specifies an url to receive incoming updates via an outgoing webHook.

ParamTypeDescription
urlStringFile id
certFileSSL public certificate

Related Telegram api docs


Telegraf.removeWebHook() => Promise

Removes webhook. Shortcut for Telegraf.setWebHook('')

Related Telegram api docs


Telegraf.kickChatMember(chatId, userId) => Promise

Use this method to kick a user from a group or a supergroup.

ParamTypeDescription
chatIdInteger/StringChat id
userIdIntegerUser id

Related Telegram api docs


Telegraf.unbanChatMember(chatId, userId) => Promise

Use this method to unban a previously kicked user in a supergroup.

ParamTypeDescription
chatIdInteger/StringChat id
userIdIntegerUser id

Related Telegram api docs


Telegraf.answerInlineQuery(inlineQueryId, results, extra) => Promise

Use this method to send answers to an inline query.

ParamTypeDescription
inlineQueryIdStringQuery id
resultsArrayResults
extraObjectOptional parameters

Related Telegram api docs


Telegraf.answerCallbackQuery(callbackQueryId, text, showAlert) => Promise

Use this method to send answers to callback queries.

ParamTypeDescription
callbackQueryIdStringQuery id
textStringNotification text
showAlertBoolShow alert instead of notification

Related Telegram api docs


Telegraf.editMessageText(chatId, messageId, text, extra) => Promise

Use this method to edit text messages sent by the bot or via the bot.

ParamTypeDescription
chatIdInteger/StringChat id
messageIdStringMessage id
textStringMessage
extraObjectOptional parameters

Related Telegram api docs


Telegraf.editMessageCaption(chatId, messageId, caption, extra) => Promise

Use this method to edit captions of messages sent by the bot or via the bot

ParamTypeDescription
chatIdInteger/StringChat id
messageIdStringMessage id
captionStringCaption
extraObjectOptional parameters

Related Telegram api docs


Telegraf.editMessageReplyMarkup(chatId, messageId, markup, extra) => Promise

Use this method to edit only the reply markup of messages sent by the bot or via the bot.

ParamTypeDescription
chatIdInteger/StringChat id
messageIdStringMessage id
markupObjectKeyboard markup
extraObjectOptional parameters

Related Telegram api docs

File

This object represents the contents of a file to be uploaded.

Supported file sources:

  • File path
  • Buffer
  • ReadStream
  • Existing file_id

Example:

  // send file
  app.sendVideo('chatId', {source: '/path/to/video.mp4'}})
  
  // send buffer
  app.sendVoice('chatId', {source: new Buffer(...)})

  // send stream
  app.sendAudio('chatId', {source: fs.createReadStream('/path/to/video.mp4')})

  // resend existing file
  app.sendSticker('chatId', '123123jkbhj6b')

Related Telegram api docs

Events

Supported events:

  • text
  • audio
  • document
  • photo
  • sticker
  • video
  • voice
  • contact
  • location
  • venue
  • new_chat_participant
  • left_chat_participant
  • new_chat_title
  • new_chat_photo
  • delete_chat_photo
  • group_chat_created
  • supergroup_chat_created
  • channel_chat_created
  • migrate_to_chat_id
  • migrate_from_chat_id
  • pinned_message
  • inline_query
  • chosen_inline_result
  • callback_query

Also, Telegraf will emit message event for for all messages except inline_query, chosen_inline_result and callback_query.


// Handle stickers and photos
app.on(['sticker', 'photo'], function * () {
  console.log(this.message)
  this.reply('Cool!')
})

// Handle all messages except `inline_query`, `chosen_inline_result` and `callback_query`
app.on('message', function * () {
  this.reply('Hey there!')
})

Related Telegram api docs

Shortcuts

Telegraf context have many handy shortcuts.

Note: shortcuts are not available for `inline_query` and `chosen_inline_result` events.
var app = new Telegraf(process.env.BOT_TOKEN)

app.on('text', function * (){
  // Simple usage 
  app.sendMessage(this.message.chat.id, `Hello ${this.state.role}`)
  
  // Using shortcut
  this.reply(`Hello ${this.state.role}`)

  // If you want to mark message as reply to source message
  this.reply(`Hello ${this.state.role}`, { reply_to_message_id: this.message.id })
})
  • reply() -> app.sendMessage()
  • replyWithPhoto() -> app.sendPhoto()
  • replyWithAudio() -> app.sendAudio()
  • replyWithDocument() -> app.sendDocument()
  • replyWithSticker() -> app.sendSticker()
  • replyWithVideo() -> app.sendVideo()
  • replyWithVoice() -> app.sendVoice()
  • replyWithChatAction() -> app.sendChatAction()
  • replyWithLocation() -> app.sendLocation()

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 29 Apr 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