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 - npm Package Compare versions

Comparing version 0.7.0 to 0.8.0

lib/constants.js

4

lib/memory-session.js
var debug = require('debug')('telegraf:session-memory')
var db = {}
module.exports = function (opts) {
var db = {}
module.exports = function (opts) {
opts = Object.assign({

@@ -7,0 +7,0 @@ getSessionKey: function (event) {

@@ -5,24 +5,26 @@ var debug = require('debug')('telegraf:core')

var fs = require('fs')
var http = require('http')
var https = require('https')
var ware = require('co-ware')
var https = require('https')
var http = require('http')
var memorySession = require('./memory-session')
var constants = require('./constants')
/**
* Telegraf prototype.
*/
var telegraf = Telegraf.prototype
/**
* Represents a Telegraf app.
* @constructor
* @param {string} token - Telegram token.
* @param {object} options - Additional options.
*/
function Telegraf (token) {
this.token = token
this.handlers = []
function Telegraf (token, options) {
this.options = Object.assign({
token: token,
webHookAnswer: true,
apiRoot: 'https://api.telegram.org'
}, options)
this.middleware = []
this.offset = 0
this.started = false
this.options = {}
this.polling = {
offset: 0,
started: false
}
this.context = {}

@@ -32,2 +34,80 @@ }

/**
* Expose `Telegraf`.
*/
module.exports = Telegraf
/**
* Telegraf prototype.
*/
var telegraf = Telegraf.prototype
/**
* Expose `memorySession`.
*/
Telegraf.memorySession = memorySession
/**
* Compose `middleware` returning
* a fully valid middleware comprised
* of all those which are passed.
*
* @param {GeneratorFumction[]} middleware
* @return {GeneratorFumction}
* @api public
*/
Telegraf.compose = function (middleware) {
return function * (next) {
if (!next) {
next = noop()
}
var i = middleware.length
while (i--) {
next = middleware[i].call(this, next)
}
return yield * next
}
}
/**
* Generates filter `middleware`
*
* @param {string|string[]} eventTypes
* @param {(GeneratorFunction|GeneratorFunction[])} fn - middleware
* @api public
*/
Telegraf.optional = function (eventTypes) {
if (typeof eventTypes === 'string') {
eventTypes = [eventTypes]
}
var fns = [].slice.call(arguments, 1)
return function * (next) {
if (eventTypes.indexOf(this.eventType) !== -1 || eventTypes.indexOf(this.eventSubType) !== -1) {
yield Telegraf.compose(fns)
}
yield next
}
}
/**
* O(1)
*
* @api private
*/
function * noop () {}
/**
* Default error handler.
*
* @param {Error} err
* @api private
*/
telegraf.onError = function (err) {
var msg = err.stack || err.toString()
console.error()
console.error(msg.replace(/^/gm, ' '))
console.error()
throw err
}
/**
* Start polling loop.

@@ -41,5 +121,5 @@ *

telegraf.startPolling = function (timeout, limit) {
this.started = true
this.options.timeout = timeout || 0
this.options.limit = limit || 100
this.polling.started = true
this.polling.timeout = timeout || 0
this.polling.limit = limit || 100
this.pollingLoop()

@@ -106,7 +186,8 @@ return this

telegraf.startWebHook = function (webHookPath, tlsOptions, port, host) {
this.started = true
this.polling.started = true
var callback = this.webHookCallback(webHookPath)
if (tlsOptions) {
this.webhookServer = https.createServer(tlsOptions, this.webHookCallback(webHookPath)).listen(port, host)
this.webhookServer = https.createServer(tlsOptions, callback).listen(port, host)
} else {
this.webhookServer = http.createServer(this.webHookCallback(webHookPath)).listen(port, host)
this.webhookServer = http.createServer(callback).listen(port, host)
}

@@ -123,3 +204,3 @@ return this

telegraf.stop = function () {
this.started = false
this.polling.started = false
if (this.webhookServer) {

@@ -152,10 +233,4 @@ this.webhookServer.close()

telegraf.on = function (eventTypes) {
if (typeof eventTypes === 'string') {
eventTypes = [eventTypes]
}
var fns = [].slice.call(arguments, 1)
this.handlers.push({
eventTypes: eventTypes,
middleware: Telegraf.compose(fns)
})
this.use(Telegraf.optional(eventTypes, Telegraf.compose(fns)))
return this

@@ -179,16 +254,15 @@ }

: new RegExp(trigger.replace(matchOperatorsRe, '\\$&'))
var handler = Telegraf.compose([].slice.call(arguments, 1))
this.handlers.push({
eventTypes: ['text'],
middleware: function * (next) {
var result = regex.exec(this.message.text)
if (result) {
this.__defineGetter__('match', function () {
return result || []
})
yield handler
}
yield next
var fns = [].slice.call(arguments, 1)
var middleware = Telegraf.optional('text', function * (next) {
var result = regex.exec(this.message.text)
if (result) {
this.__defineGetter__('match', function () {
return result || []
})
yield Telegraf.compose(fns)
}
yield next
})
this.use(middleware)
return this

@@ -226,3 +300,3 @@ }

telegraf.getFileLink = function (fileId) {
return this.getFile(fileId).then((response) => `https://api.telegram.org/file/bot${this.token}/${response.file_path}`)
return this.getFile(fileId).then((response) => `${this.options.apiRoot}/file/bot${this.options.token}/${response.file_path}`)
}

@@ -346,2 +420,44 @@

/**
* Sends venue.
*
* @param {(string|number)} chatId
* @param {number} latitude
* @param {number} longitude
* @param {string} title
* @param {string} address
* @param {Object} extra
* @return {Promise}
* @api public
*/
telegraf.sendVenue = function (chatId, latitude, longitude, title, address, extra) {
var options = {
chat_id: chatId,
latitude: latitude,
longitude: longitude,
title: title,
address: address
}
return this.sendRequest('sendVenue', Object.assign(options, extra))
}
/**
* Sends contact.
*
* @param {(string|number)} chatId
* @param {number} phoneNumber
* @param {number} firstName
* @param {Object} extra
* @return {Promise}
* @api public
*/
telegraf.sendContact = function (chatId, phoneNumber, firstName, extra) {
var options = {
chat_id: chatId,
phone_number: phoneNumber,
first_name: firstName
}
return this.sendRequest('sendContact', Object.assign(options, extra))
}
/**
* Use this method to send answers to an inline query.

@@ -589,11 +705,28 @@ *

* @param {Object} options - request options
* @param {Object} [response] - http.ServerResponse
* @return {Promise} Promise with result
* @api private
*/
telegraf.sendRequest = function (method, options) {
if (!this.token) {
telegraf.sendRequest = function (method, options, response) {
options = Object.assign({}, options)
var isFileRequest = Object.keys(options).filter((x) => options[x] && options[x].source).length > 0
if (response && !response.finished && !isFileRequest) {
debug('▷ webhook', method)
options.method = method
response.setHeader('Content-Type', 'application/json')
response.end(JSON.stringify(options))
return Promise.resolve()
}
if (!this.options.token) {
throw new Error('Telegram Bot Token is required')
}
var payload = options ? {method: 'POST', body: this.buildForm(options)} : { method: 'GET' }
return fetch(`https://api.telegram.org/bot${this.token}/${method}`, payload)
debug('▶︎ http', method)
var payload = {
method: 'POST',
headers: isFileRequest ? {} : {'Content-Type': 'application/json'},
body: isFileRequest ? this.buildFormData(options) : JSON.stringify(options)
}
return fetch(`${this.options.apiRoot}/bot${this.options.token}/${method}`, payload)
.then((res) => res.json())

@@ -610,3 +743,3 @@ .then((data) => {

/**
* Build Form-Data from oprions
* Build Form-Data from options
*

@@ -617,3 +750,3 @@ * @param {Object} options - Payload object

*/
telegraf.buildForm = function (options) {
telegraf.buildFormData = function (options) {
if (options.reply_markup && typeof options.reply_markup !== 'string') {

@@ -658,8 +791,8 @@ options.reply_markup = JSON.stringify(options.reply_markup)

telegraf.pollingLoop = function () {
if (!this.started) {
if (!this.polling.started) {
return
}
this.getUpdates(this.options.timeout, this.options.limit, this.offset)
this.getUpdates(this.polling.timeout, this.polling.limit, this.polling.offset)
.catch((err) => {
console.log('Telegraf: network error', err)
console.error('Telegraf: network error', err)
return new Promise((resolve) => {

@@ -674,4 +807,4 @@ setTimeout(() => resolve([]), 1000)

.catch((err) => {
console.log('Telegraf: polling error', err)
this.started = false
console.error('Telegraf: polling error', err)
this.polling.started = false
})

@@ -689,3 +822,3 @@ }

var result = {}
telegramUpdateTypes.forEach((key) => {
constants.updateTypes.forEach((key) => {
if (update[key]) {

@@ -697,3 +830,3 @@ result.payload = update[key]

if (update.message) {
messageSubTypes.forEach((messageType) => {
constants.messageSubTypes.forEach((messageType) => {
if (update.message[messageType]) {

@@ -720,3 +853,3 @@ result.subType = messageType

}
debug('update', update.type, update.subType || '--')
debug('⚡ update', update.type, update.subType || '--')
var state = {}

@@ -730,21 +863,19 @@ var context = Object.assign({

var self = this
var telegrafProxy = {
sendRequest: function (method, options) {
if (webHookResponse && !webHookResponse.finished && Object.keys(options).filter((x) => options[x].source).length === 0) {
debug('webhook reply', method)
options.method = method
webHookResponse.setHeader('Content-Type', 'application/json')
webHookResponse.end(JSON.stringify(options))
return Promise.resolve()
var proxy = this
if (this.options.webHookAnswer && webHookResponse) {
var self = this
proxy = {
sendRequest: function (method, options) {
return self.sendRequest(method, options, webHookResponse)
}
debug('http reply', method)
return self.sendRequest(method, options)
}
}
var chatId = (update.payload.chat && update.payload.chat.id) || (update.payload.message && update.payload.message.chat && update.payload.message.chat.id)
var payload = update.payload
var chatId = (payload.chat && payload.chat.id) || (payload.message && payload.message.chat && payload.message.chat.id)
if (chatId) {
chatMethods.forEach((command) => context[command.name] = this[command.target].bind(telegrafProxy, chatId))
constants.chatMethods.forEach((command) => {
context[command.name] = this[command.target].bind(proxy, chatId)
})
}

@@ -758,114 +889,20 @@

context.__defineGetter__(payloadContextName, function () {
return update.payload
return payload
})
if (update.type === 'callback_query') {
context.answerCallbackQuery = this.answerCallbackQuery.bind(telegrafProxy, update.payload.id)
context.answerCallbackQuery = this.answerCallbackQuery.bind(proxy, payload.id)
}
if (update.type === 'inline_query') {
context.answerInlineQuery = this.answerInlineQuery.bind(telegrafProxy, update.payload.id)
context.answerInlineQuery = this.answerInlineQuery.bind(proxy, payload.id)
}
var handlers = this.handlers
.filter((handler) => {
return handler.eventTypes.filter((n) => {
return update.type === n || update.subType === n
}).length > 0
})
.map((handler) => handler.middleware)
var ctx = ware()
ctx.context = context
ctx.use(Telegraf.compose(this.middleware))
ctx.use(Telegraf.compose(handlers))
ctx.on('error', this.onError)
return ctx.run().then(() => {
this.offset = rawUpdate.update_id + 1
this.polling.offset = rawUpdate.update_id + 1
})
}
/**
* Default error handler.
*
* @param {Error} err
* @api private
*/
telegraf.onError = function (err) {
var msg = err.stack || err.toString()
console.error()
console.error(msg.replace(/^/gm, ' '))
console.error()
throw err
}
var telegramUpdateTypes = [
'message',
'callback_query',
'inline_query',
'chosen_inline_result'
]
var messageSubTypes = [
'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'
]
var chatMethods = [
{ name: 'reply', target: 'sendMessage' },
{ name: 'replyWithPhoto', target: 'sendPhoto' },
{ name: 'replyWithAudio', target: 'sendAudio' },
{ name: 'replyWithDocument', target: 'sendDocument' },
{ name: 'replyWithSticker', target: 'sendSticker' },
{ name: 'replyWithVideo', target: 'sendVideo' },
{ name: 'replyWithVoice', target: 'sendVoice' },
{ name: 'replyWithChatAction', target: 'sendChatAction' },
{ name: 'replyWithLocation', target: 'sendLocation' }
]
/**
* Expose `memorySession`.
*/
Telegraf.memorySession = memorySession
/**
* Expose `compose`.
*/
Telegraf.compose = function (middleware) {
return function * (next) {
if (!next) {
next = noop()
}
var i = middleware.length
while (i--) {
next = middleware[i].call(this, next)
}
return yield *next
}
}
function * noop () {}
/**
* Expose `Telegraf`.
*/
module.exports = Telegraf
{
"name": "telegraf",
"version": "0.7.0",
"version": "0.8.0",
"description": "📢 Modern Telegram bot framework",

@@ -32,2 +32,3 @@ "main": "lib/telegraf.js",

"lib/telegraf.js",
"lib/constants.js",
"lib/memory-session.js"

@@ -45,2 +46,4 @@ ],

"devDependencies": {
"eslint": "^2.10.2",
"eslint-plugin-mocha": "^2.2.0",
"mocha": "^2.4.5",

@@ -47,0 +50,0 @@ "should": "^8.3.1",

@@ -5,5 +5,6 @@ [![npm](https://img.shields.io/npm/l/telegraf.svg?style=flat-square)](https://www.npmjs.com/package/telegraf)

[![David](https://img.shields.io/david/telegraf/telegraf.svg?style=flat-square)](https://www.npmjs.com/package/telegraf)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](http://standardjs.com/)
[![Build Status](https://img.shields.io/travis/telegraf/telegraf.svg?branch=master&style=flat-square)](https://travis-ci.org/telegraf/telegraf)
📢 Modern Telegram bot framework for node.js
📢 Modern Telegram bot framework for node.js.

@@ -20,3 +21,2 @@ ## Installation

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

@@ -29,2 +29,11 @@

telegraf.startPolling()
```
### One more example
```js
var Telegraf = require('telegraf');
var telegraf = new Telegraf(process.env.BOT_TOKEN);
// Look ma, middleware!

@@ -58,3 +67,2 @@ var sayYoMiddleware = function * (next) {

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

@@ -235,33 +243,30 @@

Telegraf context have many handy shortcuts.
Telegraf context shortcuts:
**Available shortcuts for `message` event:**
**Available shortcuts**
* `reply() -> telegraf.sendMessage()`
* `replyWithPhoto() -> telegraf.sendPhoto()`
* `replyWithAudio() -> telegraf.sendAudio()`
* `replyWithDocument() -> telegraf.sendDocument()`
* `replyWithSticker() -> telegraf.sendSticker()`
* `replyWithVideo() -> telegraf.sendVideo()`
* `replyWithVoice() -> telegraf.sendVoice()`
* `replyWithChatAction() -> telegraf.sendChatAction()`
* `replyWithLocation() -> telegraf.sendLocation()`
- `message` event
- `reply() -> telegraf.sendMessage()`
- `replyWithPhoto() -> telegraf.sendPhoto()`
- `replyWithAudio() -> telegraf.sendAudio()`
- `replyWithDocument() -> telegraf.sendDocument()`
- `replyWithSticker() -> telegraf.sendSticker()`
- `replyWithVideo() -> telegraf.sendVideo()`
- `replyWithVoice() -> telegraf.sendVoice()`
- `replyWithChatAction() -> telegraf.sendChatAction()`
- `replyWithLocation() -> telegraf.sendLocation()`
- `callback_query` event
- `answerCallbackQuery() -> telegraf.answerCallbackQuery()`
- `reply() -> telegraf.sendMessage()`
- `replyWithPhoto() -> telegraf.sendPhoto()`
- `replyWithAudio() -> telegraf.sendAudio()`
- `replyWithDocument() -> telegraf.sendDocument()`
- `replyWithSticker() -> telegraf.sendSticker()`
- `replyWithVideo() -> telegraf.sendVideo()`
- `replyWithVoice() -> telegraf.sendVoice()`
- `replyWithChatAction() -> telegraf.sendChatAction()`
- `replyWithLocation() -> telegraf.sendLocation()`
- `inline_query` event
- `answerInlineQuery() -> telegraf.answerInlineQuery()`
**Shortcuts for `callback_query` event:**
* `answerCallbackQuery() -> telegraf.answerCallbackQuery()`
* `reply() -> telegraf.sendMessage()`
* `replyWithPhoto() -> telegraf.sendPhoto()`
* `replyWithAudio() -> telegraf.sendAudio()`
* `replyWithDocument() -> telegraf.sendDocument()`
* `replyWithSticker() -> telegraf.sendSticker()`
* `replyWithVideo() -> telegraf.sendVideo()`
* `replyWithVoice() -> telegraf.sendVoice()`
* `replyWithChatAction() -> telegraf.sendChatAction()`
* `replyWithLocation() -> telegraf.sendLocation()`
**Shortcuts for `inline_query` event:**
* `answerInlineQuery() -> telegraf.answerInlineQuery()`
#### Examples

@@ -303,223 +308,271 @@

* `Telegraf`
* [`new Telegraf(token)`](#new)
* [`.webHookCallback(webHookPath)`](#webhookcallback)
* [`.setWebHook(url, cert)`](#setwebhook)
* [`.startWebHook(webHookPath, tlsOptions, port, [host])`](#startwebhook)
* [`.startPolling(timeout, limit)`](#startPolling)
* [`.stop()`](#stop)
* [`.handleUpdate(rawUpdate, response)`](#handleupdate)
* [`.use(function)`](#use)
* [`.on(messageType, function)`](#on)
* [`.hears(string|ReGex, function)`](#hears)
* [`.sendMessage(chatId, text, extra)`](#sendmessage)
* [`.forwardMessage(chatId, fromChatId, messageId, extra)`](#forwardmessage)
* [`.sendLocation(chatId, latitude, longitude, extra)`](#sendlocation)
* [`.sendPhoto(chatId, photo, extra)`](#sendphoto)
* [`.sendDocument(chatId, doc, extra)`](#senddocument)
* [`.sendAudio(chatId, audio, extra)`](#sendaudio)
* [`.sendSticker(chatId, sticker, extra)`](#sendsticker)
* [`.sendVideo(chatId, video, extra)`](#sendvideo)
* [`.sendVoice(chatId, voice, extra)`](#sendvoice)
* [`.sendChatAction(chatId, action)`](#sendchataction)
* [`.getMe()`](#getme)
* [`.getUserProfilePhotos(userId, offset, limit)`](#getuserprofilephotos)
* [`.getFile(fileId)`](#getfile)
* [`.getFileLink(fileId)`](#getFileLink)
* [`.removeWebHook()`](#removewebhook)
* [`.kickChatMember(chatId, userId)`](#kickchatmember)
* [`.unbanChatMember(chatId, userId)`](#unbanchatmember)
* [`.answerInlineQuery(inlineQueryId, results, extra)`](#answerinlinequery)
* [`.answerCallbackQuery(callbackQueryId, text, showAlert)`](#answercallbackquery)
* [`.editMessageText(chatId, messageId, text, extra)`](#editmessagetext)
* [`.editMessageCaption(chatId, messageId, caption, extra)`](#editmessagecaption)
* [`.editMessageReplyMarkup(chatId, messageId, markup, extra)`](#editmessagereplymarkup)
- [`Telegraf.optional(messageType, handler, [handler...])`](#optional)
- [`Telegraf.compose(middleware)`](#compose)
- [`new Telegraf(token)`](#new)
- [`.answerCallbackQuery(callbackQueryId, text, showAlert)`](#answercallbackquery)
- [`.answerInlineQuery(inlineQueryId, results, extra)`](#answerinlinequery)
- [`.editMessageCaption(chatId, messageId, caption, extra)`](#editmessagecaption)
- [`.editMessageReplyMarkup(chatId, messageId, markup, extra)`](#editmessagereplymarkup)
- [`.editMessageText(chatId, messageId, text, extra)`](#editmessagetext)
- [`.forwardMessage(chatId, fromChatId, messageId, extra)`](#forwardmessage)
- [`.getFile(fileId)`](#getfile)
- [`.getFileLink(fileId)`](#getFileLink)
- [`.getMe()`](#getme)
- [`.getUserProfilePhotos(userId, offset, limit)`](#getuserprofilephotos)
- [`.handleUpdate(rawUpdate, response)`](#handleupdate)
- [`.hears(string|ReGex, handler, [handler...])`](#hears)
- [`.kickChatMember(chatId, userId)`](#kickchatmember)
- [`.on(messageType, handler, [handler...])`](#on)
- [`.removeWebHook()`](#removewebhook)
- [`.sendAudio(chatId, audio, extra)`](#sendaudio)
- [`.sendChatAction(chatId, action)`](#sendchataction)
- [`.sendContact(chatId, phoneNumber, firstName, extra)`](#sendcontact)
- [`.sendDocument(chatId, doc, extra)`](#senddocument)
- [`.sendLocation(chatId, latitude, longitude, extra)`](#sendlocation)
- [`.sendMessage(chatId, text, extra)`](#sendmessage)
- [`.sendPhoto(chatId, photo, extra)`](#sendphoto)
- [`.sendSticker(chatId, sticker, extra)`](#sendsticker)
- [`.sendVenue(chatId, latitude, longitude, title, address, extra)`](#sendvenue)
- [`.sendVideo(chatId, video, extra)`](#sendvideo)
- [`.sendVoice(chatId, voice, extra)`](#sendvoice)
- [`.setWebHook(url, cert)`](#setwebhook)
- [`.startPolling(timeout, limit)`](#startPolling)
- [`.startWebHook(webHookPath, tlsOptions, port, [host])`](#startwebhook)
- [`.stop()`](#stop)
- [`.unbanChatMember(chatId, userId)`](#unbanchatmember)
- [`.use(function)`](#use)
- [`.webHookCallback(webHookPath)`](#webhookcallback)
<a name="new"></a>
##### `Telegraf.new(token)`
***
Initialize new Telegraf app.
<a name="optional"></a>
##### `Telegraf.optional(eventType, handler, [handler...])`
Generates middleware for handling provided [event type](#events).
| Param | Type | Description |
| --- | --- | --- |
| token | `String` | [Bot Token](https://core.telegram.org/bots#3-how-do-i-create-a-bot) |
| eventType | `string`\|`string[]` | [Event type](#events) |
| handler | `GeneratorFunction` | Handler |
* * *
<a name="webhookcallback"></a>
##### `Telegraf.webHookCallback(webHookPath) => Function`
<a name="compose"></a>
##### `Telegraf.compose(middleware)`
Return a callback function suitable for the http[s].createServer() method to handle a request.
You may also use this callback function to mount your telegraf app in a Koa/Connect/Express app.
Compose `middleware` returning a fully valid middleware comprised of all those which are passed.
| Param | Type | Description |
| --- | --- | --- |
| webHookPath | `String` | Webhook url path (see Telegraf.setWebHook) |
| --- | --- | --- |
| handler | `GeneratorFunction[]` | middleware |
* * *
<a name="setwebhook"></a>
##### `Telegraf.setWebHook(url, [cert]) => Promise`
Specifies an url to receive incoming updates via an outgoing webhook.
<a name="new"></a>
##### `new Telegraf(token)`
Initialize new Telegraf app.
| Param | Type | Description |
| --- | --- | --- |
| url | `String` | Public url for webhook |
| cert | [`File`](#file) | SSL public certificate |
| --- | --- | --- |
| token | `string` | [Bot Token](https://core.telegram.org/bots#3-how-do-i-create-a-bot) |
[Related Telegram api docs](https://core.telegram.org/bots/api#setwebhook)
* * *
<a name="answercallbackquery"></a>
##### `.answerCallbackQuery(callbackQueryId, text, showAlert) => Promise`
Use this method to send answers to callback queries.
| Param | Type | Description |
| --- | --- | --- |
| callbackQueryId | `string` | Query id |
| [text] | `string` | Notification text |
| [showAlert] | `bool` | Show alert instead of notification |
<sub>[Related Telegram api docs](https://core.telegram.org/bots/api#answercallbackquery)</sub>
* * *
<a name="startwebhook"></a>
##### `Telegraf.startWebHook(webHookPath, tlsOptions, port, [host])`
<a name="answerinlinequery"></a>
##### `.answerInlineQuery(inlineQueryId, results, extra) => Promise`
Start listening @ `https://host:port/webHookPath` for Telegram calls.
Use this method to send answers to an inline query.
| Param | Type | Description |
| --- | --- | --- |
| webHookPath | `String` | Webhook url path (see Telegraf.setWebHook) |
| tlsOptions | [TLS server options](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener) | (Optional) Pass null to use http |
| port | `Int` | Port number |
| host | `String` | (Optional) Hostname |
| --- | --- | --- |
| inlineQueryId | `string` | Query id |
| results | `object[]` | Results |
| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#answerinlinequery)|
* * *
<a name="startPolling"></a>
##### `Telegraf.startPolling(timeout, limit)`
<a name="editmessagecaption"></a>
##### `.editMessageCaption(chatId, messageId, caption, extra) => Promise`
Start poll updates.
Use this method to edit captions of messages sent by the bot or via the bot
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| timeout | `Int` | 0 | Poll timeout |
| limit | `Int` | 100 | Limits the number of updates to be retrieved |
| Param | Type | Description |
| --- | --- | --- |
| chatId | `number`\|`string` | Chat id |
| messageId | `string` | Message id |
| caption | `string` | Caption |
| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagecaption)|
* * *
<a name="stop"></a>
##### `Telegraf.stop()`
<a name="editmessagereplymarkup"></a>
##### `.editMessageReplyMarkup(chatId, messageId, markup, extra) => Promise`
Stop WebHook and polling
Use this method to edit only the reply markup of messages sent by the bot or via the bot.
| Param | Type | Description |
| --- | --- | --- |
| chatId | `number`\|`string` | Chat id |
| messageId | `string` | Message id |
| markup | `object` | Keyboard markup |
| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagereplymarkup)|
* * *
<a name="handleupdate"></a>
##### `Telegraf.handleUpdate(rawUpdate, [webHookResponse])`
<a name="editmessagetext"></a>
##### `.editMessageText(chatId, messageId, text, extra) => Promise`
Handle raw Telegram update.
In case you use centralized webhook server, queue, etc.
Use this method to edit text messages sent by the bot or via the bot.
| Param | Type | Description |
| --- | --- | --- |
| rawUpdate | `Object` | Telegram update payload |
| webHookResponse | `Object` | (Optional) [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse) |
| chatId | `number`\|`string` | Chat id |
| messageId | `string` | Message id |
| text | `string` | Message |
| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#editmessagetext)|
* * *
<a name="use"></a>
##### `Telegraf.use(middleware)`
<a name="forwardmessage"></a>
##### `.forwardMessage(chatId, fromChatId, messageId, extra) => Promise`
Registers a middleware.
Forwards message.
| Param | Type | Description |
| --- | --- | --- |
| middleware | `Function` | Middleware function |
| chatId | `number`\|`string` | Source Chat id |
| fromChatId | `number`\|`string` | Target Chat id |
| messageId | `number` | Message id |
| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#forwardmessage)|
* * *
<a name="on"></a>
##### `Telegraf.on(eventType, handler)`
<a name="getfile"></a>
##### `.getFile(fileId) => Promise`
Registers handler for provided [event type](#events).
Returns basic info about a file and prepare it for downloading.
| Param | Type | Description |
| --- | --- | --- |
| eventType | `String` or `Array[String]` | [Event type](#events) |
| handler | `Function` | Handler |
| fileId | `string` | File id |
<sub>[Related Telegram api docs](https://core.telegram.org/bots/api#getfile)</sub>
* * *
<a name="hears"></a>
##### `Telegraf.hears(pattern, handler)`
<a name="getFileLink"></a>
##### `.getFileLink(fileId) => Promise`
Registers handler only for `text` events using string pattern or RegEx.
Returns link to file.
| Param | Type | Description |
| --- | --- | --- |
| pattern | `String`/`RegEx` | Pattern or RegEx |
| handler | `Function` | Handler |
| fileId | `string` | File id |
<sub>[Related Telegram api docs](https://core.telegram.org/bots/api#getFileLink)</sub>
* * *
<a name="sendmessage"></a>
##### `Telegraf.sendMessage(chatId, text, extra) => Promise`
<a name="getme"></a>
##### `.getMe() => Promise`
Sends text message.
Returns basic information about the bot.
<sub>[Related Telegram api docs](https://core.telegram.org/bots/api#getme)</sub>
* * *
<a name="getuserprofilephotos"></a>
##### `.getUserProfilePhotos(userId, offset, limit) => Promise`
Returns profiles photos for provided user.
| Param | Type | Description |
| --- | --- | --- |
| chatId | `Integer`/`String` | Chat id |
| text | `String` | Message |
| extra | `Object` | [Optional parameters](https://core.telegram.org/bots/api#sendmessage)|
| userId | `number` | Chat id |
| offset | `number` | Offset |
| limit | `number` | Limit |
<sub>[Related Telegram api docs](https://core.telegram.org/bots/api#getuserprofilephotos)</sub>
* * *
<a name="forwardmessage"></a>
##### `Telegraf.forwardMessage(chatId, fromChatId, messageId, extra) => Promise`
<a name="handleupdate"></a>
##### `.handleUpdate(rawUpdate, [webHookResponse])`
Forwards message.
Handle raw Telegram update.
In case you use centralized webhook server, queue, etc.
| Param | Type | Description |
| --- | --- | --- |
| chatId | `Integer`/`String` | Source Chat id |
| fromChatId | `Integer`/`String` | Target Chat id |
| messageId | `Integer` | Message id |
| extra | `Object` | [Optional parameters](https://core.telegram.org/bots/api#forwardmessage)|
| rawUpdate | `object` | Telegram update payload |
| [webHookResponse] | `object` | (Optional) [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse) |
* * *
<a name="sendlocation"></a>
##### `Telegraf.sendLocation(chatId, latitude, longitude, extra) => Promise`
<a name="hears"></a>
##### `.hears(pattern, handler, [handler...])`
Sends location.
Registers handler only for `text` events using string pattern or RegEx.
| Param | Type | Description |
| --- | --- | --- |
| chatId | `Integer`/`String` | Chat id |
| latitude | `Integer` | Latitude |
| longitude | `Integer` | Longitude |
| extra | `Object` | [Optional parameters](https://core.telegram.org/bots/api#sendlocation)|
| pattern | `string`\|`RegEx` | Pattern or RegEx |
| handler | `GeneratorFunction` | Handler |
* * *
<a name="sendphoto"></a>
##### `Telegraf.sendPhoto(chatId, photo, extra) => Promise`
<a name="kickchatmember"></a>
##### `.kickChatMember(chatId, userId) => Promise`
Sends photo.
Use this method to kick a user from a group or a supergroup.
| Param | Type | Description |
| --- | --- | --- |
| chatId | `Integer`/`String` | Chat id |
| photo | [`File`](#file) | Photo |
| extra | `Object` | [Optional parameters](https://core.telegram.org/bots/api#sendphoto)|
| chatId | `number`\|`string` | Chat id |
| userId | `number` | User id |
<sub>[Related Telegram api docs](https://core.telegram.org/bots/api#kickchatmember)</sub>
* * *
<a name="senddocument"></a>
##### `Telegraf.sendDocument(chatId, doc, extra) => Promise`
<a name="on"></a>
##### `.on(eventType, handler, [handler...])`
Sends document.
Registers handler for provided [event type](#events).
| Param | Type | Description |
| --- | --- | --- |
| chatId | `Integer`/`String` | Chat id |
| doc | [`File`](#file) | Document |
| extra | `Object` | [Optional parameters](https://core.telegram.org/bots/api#senddocument)|
| eventType | `string`\|`string[]` | [Event type](#events) |
| handler | `GeneratorFunction` | Handler |
* * *
<a name="removewebhook"></a>
##### `.removeWebHook() => Promise`
Removes webhook. Shortcut for `Telegraf.setWebHook('')`
<sub>[Related Telegram api docs](https://core.telegram.org/bots/api#removewebhook)</sub>
* * *
<a name="sendaudio"></a>
##### `Telegraf.sendAudio(chatId, audio, extra) => Promise`
##### `.sendAudio(chatId, audio, extra) => Promise`

@@ -530,214 +583,223 @@ Sends audio.

| --- | --- | --- |
| chatId | `Integer`/`String` | Chat id |
| chatId | `number`\|`string` | Chat id |
| audio | [`File`](#file) | Document |
| extra | `Object` | [Optional parameters](https://core.telegram.org/bots/api#sendaudio)|
| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendaudio)|
* * *
<a name="sendsticker"></a>
##### `Telegraf.sendSticker(chatId, sticker, extra) => Promise`
<a name="sendchataction"></a>
##### `.sendChatAction(chatId, action) => Promise`
Sends sticker.
Sends chat action.
| Param | Type | Description |
| --- | --- | --- |
| chatId | `Integer`/`String` | Chat id |
| sticker | [`File`](#file) | Document |
| extra | `Object` | [Optional parameters](https://core.telegram.org/bots/api#sendsticker)|
| chatId | `number`\|`string` | Chat id |
| action | `string` | [Chat action](https://core.telegram.org/bots/api#sendchataction) |
* * *
<a name="sendvideo"></a>
##### `Telegraf.sendVideo(chatId, video, extra) => Promise`
<a name="sendcontact"></a>
##### `.sendContact(chatId, phoneNumber, firstName, extra) => Promise`
Sends video.
Sends document.
| Param | Type | Description |
| --- | --- | --- |
| chatId | `Integer`/`String` | Chat id |
| video | [`File`](#file) | Document |
| extra | `Object` | [Optional parameters](https://core.telegram.org/bots/api#sendvideo)|
| chatId | `number`\|`string` | Chat id |
| phoneNumber | `string` | Contact phone number |
| firstName | `string` | Contact first name |
| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendcontact)|
* * *
<a name="sendvoice"></a>
##### `Telegraf.sendVoice(chatId, voice, extra) => Promise`
<a name="senddocument"></a>
##### `.sendDocument(chatId, doc, extra) => Promise`
Sends voice.
Sends document.
| Param | Type | Description |
| --- | --- | --- |
| chatId | `Integer`/`String` | Chat id |
| voice | [`File`](#file) | Document |
| extra | `Object` | [Optional parameters](https://core.telegram.org/bots/api#sendvoice)|
| chatId | `number`\|`string` | Chat id |
| doc | [`File`](#file) | Document |
| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#senddocument)|
* * *
<a name="sendchataction"></a>
##### `Telegraf.sendChatAction(chatId, action) => Promise`
<a name="sendlocation"></a>
##### `.sendLocation(chatId, latitude, longitude, extra) => Promise`
Sends chat action.
Sends location.
| Param | Type | Description |
| --- | --- | --- |
| chatId | `Integer`/`String` | Chat id |
| action | `String` | [Chat action](https://core.telegram.org/bots/api#sendchataction) |
| chatId | `number`\|`string` | Chat id |
| latitude | `number` | Latitude |
| longitude | `number` | Longitude |
| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendlocation)|
* * *
<a name="getme"></a>
##### `Telegraf.getMe() => Promise`
<a name="sendmessage"></a>
##### `.sendMessage(chatId, text, extra) => Promise`
Returns basic information about the bot.
Sends text message.
[Related Telegram api docs](https://core.telegram.org/bots/api#getme)
| Param | Type | Description |
| --- | --- | --- |
| chatId | `number`\|`string` | Chat id |
| text | `string` | Message |
| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendmessage)|
* * *
<a name="getuserprofilephotos"></a>
##### `Telegraf.getUserProfilePhotos(userId, offset, limit) => Promise`
<a name="sendphoto"></a>
##### `.sendPhoto(chatId, photo, extra) => Promise`
Returns profiles photos for provided user.
Sends photo.
| Param | Type | Description |
| --- | --- | --- |
| userId | `Integer` | Chat id |
| offset | `Integer` | Offset |
| userId | `limit` | Limit |
| chatId | `number`\|`string` | Chat id |
| photo | [`File`](#file) | Photo |
| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendphoto)|
[Related Telegram api docs](https://core.telegram.org/bots/api#getuserprofilephotos)
* * *
<a name="getfile"></a>
##### `Telegraf.getFile(fileId) => Promise`
<a name="sendsticker"></a>
##### `.sendSticker(chatId, sticker, extra) => Promise`
Returns basic info about a file and prepare it for downloading.
Sends sticker.
| Param | Type | Description |
| --- | --- | --- |
| fileId | `String` | File id |
| chatId | `number`\|`string` | Chat id |
| sticker | [`File`](#file) | Document |
| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendsticker)|
[Related Telegram api docs](https://core.telegram.org/bots/api#getfile)
* * *
<a name="getFileLink"></a>
##### `Telegraf.getFileLink(fileId) => Promise`
<a name="sendvenue"></a>
##### `.sendVenue(chatId, latitude, longitude, title, address, extra) => Promise`
Returns link to file.
Sends venue information.
| Param | Type | Description |
| --- | --- | --- |
| fileId | `String` | File id |
| chatId | `number`\|`string` | Chat id |
| latitude | `number` | Latitude |
| longitude | `number` | Longitude |
| title | `string` | Venue title |
| address | `string` | Venue address |
| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvenue)|
[Related Telegram api docs](https://core.telegram.org/bots/api#getFileLink)
* * *
<a name="removewebhook"></a>
##### `Telegraf.removeWebHook() => Promise`
<a name="sendvideo"></a>
##### `.sendVideo(chatId, video, extra) => Promise`
Removes webhook. Shortcut for `Telegraf.setWebHook('')`
Sends video.
[Related Telegram api docs](https://core.telegram.org/bots/api#removewebhook)
| Param | Type | Description |
| --- | --- | --- |
| chatId | `number`\|`string` | Chat id |
| video | [`File`](#file) | Document |
| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvideo)|
* * *
<a name="kickchatmember"></a>
##### `Telegraf.kickChatMember(chatId, userId) => Promise`
<a name="sendvoice"></a>
##### `.sendVoice(chatId, voice, extra) => Promise`
Use this method to kick a user from a group or a supergroup.
Sends voice.
| Param | Type | Description |
| --- | --- | --- |
| chatId | `Integer`/`String` | Chat id |
| userId | `Integer` | User id |
| chatId | `number`\|`string` | Chat id |
| voice | [`File`](#file) | Document |
| [extra] | `object` | [Extra parameters](https://core.telegram.org/bots/api#sendvoice)|
[Related Telegram api docs](https://core.telegram.org/bots/api#kickchatmember)
* * *
<a name="unbanchatmember"></a>
##### `Telegraf.unbanChatMember(chatId, userId) => Promise`
<a name="setwebhook"></a>
##### `.setWebHook(url, [cert]) => Promise`
Use this method to unban a previously kicked user in a supergroup.
Specifies an url to receive incoming updates via an outgoing webhook.
| Param | Type | Description |
| --- | --- | --- |
| chatId | `Integer`/`String` | Chat id |
| userId | `Integer` | User id |
| --- | --- | --- |
| url | `string` | Public url for webhook |
| [cert] | [`File`](#file) | SSL public certificate |
[Related Telegram api docs](https://core.telegram.org/bots/api#unbanchatmember)
<sub>[Related Telegram api docs](https://core.telegram.org/bots/api#setwebhook)</sub>
* * *
<a name="answerinlinequery"></a>
##### `Telegraf.answerInlineQuery(inlineQueryId, results, extra) => Promise`
<a name="startwebhook"></a>
##### `.startWebHook(webHookPath, tlsOptions, port, [host])`
Use this method to send answers to an inline query.
Start listening @ `https://host:port/webHookPath` for Telegram calls.
| Param | Type | Description |
| --- | --- | --- |
| inlineQueryId | `String` | Query id |
| results | `Array` | Results |
| extra | `Object` | [Optional parameters](https://core.telegram.org/bots/api#answerinlinequery)|
| --- | --- | --- |
| webHookPath | `string` | Webhook url path (see Telegraf.setWebHook) |
| tlsOptions | `object` | (Optional) [TLS server options](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener). Pass null to use http |
| port | `number` | Port number |
| [host] | `string` | (Optional) Hostname |
* * *
<a name="answercallbackquery"></a>
##### `Telegraf.answerCallbackQuery(callbackQueryId, text, showAlert) => Promise`
<a name="startPolling"></a>
##### `.startPolling(timeout, limit)`
Use this method to send answers to callback queries.
Start poll updates.
| Param | Type | Description |
| --- | --- | --- |
| callbackQueryId | `String` | Query id |
| text | `String` | Notification text |
| showAlert | `Bool` | Show alert instead of notification |
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| timeout | `number` | 0 | Poll timeout |
| limit | `number` | 100 | Limits the number of updates to be retrieved |
[Related Telegram api docs](https://core.telegram.org/bots/api#answercallbackquery)
* * *
<a name="stop"></a>
##### `.stop()`
Stop WebHook and polling
* * *
<a name="editmessagetext"></a>
##### `Telegraf.editMessageText(chatId, messageId, text, extra) => Promise`
<a name="unbanchatmember"></a>
##### `.unbanChatMember(chatId, userId) => Promise`
Use this method to edit text messages sent by the bot or via the bot.
Use this method to unban a previously kicked user in a supergroup.
| Param | Type | Description |
| --- | --- | --- |
| chatId | `Integer`/`String` | Chat id |
| messageId | `String` | Message id |
| text | `String` | Message |
| extra | `Object` | [Optional parameters](https://core.telegram.org/bots/api#editmessagetext)|
| chatId | `number`\|`string` | Chat id |
| userId | `number` | User id |
<sub>[Related Telegram api docs](https://core.telegram.org/bots/api#unbanchatmember)</sub>
* * *
<a name="editmessagecaption"></a>
##### `Telegraf.editMessageCaption(chatId, messageId, caption, extra) => Promise`
<a name="use"></a>
##### `.use(middleware)`
Use this method to edit captions of messages sent by the bot or via the bot
Registers a middleware.
| Param | Type | Description |
| --- | --- | --- |
| chatId | `Integer`/`String` | Chat id |
| messageId | `String` | Message id |
| caption | `String` | Caption |
| extra | `Object` | [Optional parameters](https://core.telegram.org/bots/api#editmessagecaption)|
| middleware | `function` | Middleware function |
* * *
<a name="editmessagereplymarkup"></a>
##### `Telegraf.editMessageReplyMarkup(chatId, messageId, markup, extra) => Promise`
<a name="webhookcallback"></a>
##### `.webHookCallback(webHookPath) => Function`
Use this method to edit only the reply markup of messages sent by the bot or via the bot.
Return a callback function suitable for the http[s].createServer() method to handle a request.
You may also use this callback function to mount your telegraf app in a Koa/Connect/Express app.
| Param | Type | Description |
| --- | --- | --- |
| chatId | `Integer`/`String` | Chat id |
| messageId | `String` | Message id |
| markup | `Object` | Keyboard markup |
| extra | `Object` | [Optional parameters](https://core.telegram.org/bots/api#editmessagereplymarkup)|
| --- | --- | --- |
| webHookPath | `string` | Webhook url path (see Telegraf.setWebHook) |

@@ -750,6 +812,6 @@ ### File

* `File path`
* `Buffer`
* `ReadStream`
* `Existing file_id`
- `File path`
- `Buffer`
- `ReadStream`
- `Existing file_id`

@@ -771,3 +833,3 @@ Example:

[Related Telegram api docs](https://core.telegram.org/bots/api#file)
<sub>[Related Telegram api docs](https://core.telegram.org/bots/api#file)</sub>

@@ -778,30 +840,30 @@ ### Events

* `message`
* `inline_query`
* `chosen_inline_result`
* `callback_query`
- `message`
- `inline_query`
- `chosen_inline_result`
- `callback_query`
Available virtual 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`
- `text`
- `audio`
- `document`
- `photo`
- `sticker`
- `video`
- `voice`
- `contact`
- `location`
- `venue`
- `new_chat_member`
- `left_chat_member`
- `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`

@@ -822,3 +884,3 @@ ```js

```
[Related Telegram api docs](https://core.telegram.org/bots/api#message)
<sub>[Related Telegram api docs](https://core.telegram.org/bots/api#message)</sub>

@@ -825,0 +887,0 @@ ## License

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