š¢ Modern Telegram bot framework for node.js.
Features
Installation
$ npm install telegraf
Example
var Telegraf = require('telegraf');
var telegraf = new Telegraf(process.env.BOT_TOKEN);
telegraf.on('message', function * () {
this.reply('*42*', { parse_mode: 'Markdown' })
})
telegraf.startPolling()
One more example
var Telegraf = require('telegraf');
var telegraf = new Telegraf(process.env.BOT_TOKEN);
var sayYoMiddleware = function * (next) {
yield this.reply('yo')
yield next
}
telegraf.hears('/command', sayYoMiddleware, function * () {
this.reply('Sure')
})
telegraf.hears(/reverse (.+)/, sayYoMiddleware, function * () {
this.reply(this.match[1].split('').reverse().join(''))
})
telegraf.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 = new Telegraf(process.env.BOT_TOKEN)
telegraf.on('text', function * (){
this.reply('Hello World')
})
telegraf.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 telegraf = new Telegraf(process.env.BOT_TOKEN)
telegraf.use(function * (next){
var start = new Date
this.state.started = start
yield next
var ms = new Date - start
debug('response time %sms', ms)
})
telegraf.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:
telegraf.use(function * (){
this.telegraf
this.eventType
this.eventSubType
this.message
this.editedMessage
this.inlineQuery
this.chosenInlineResult
this.callbackQuery
this.match
});
The recommended way to extend application context.
var telegraf = new Telegraf(process.env.BOT_TOKEN)
telegraf.context.db = {
getScores: function () { return 42 }
}
telegraf.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 telegraf = new Telegraf(process.env.BOT_TOKEN)
telegraf.use(function * (next) {
this.state.role = getUserRole(this.message)
yield next
})
telegraf.on('text', function * (){
this.reply(`Hello ${this.state.role}`)
})
Session
var telegraf = new Telegraf(process.env.BOT_TOKEN)
telegraf.use(Telegraf.memorySession())
telegraf.on('text', function * (){
this.session.counter = this.session.counter || 0
this.session.counter++
this.reply(`Message counter:${this.session.counter}`)
})
Important: For production environment use any of telegraf-session-*
middleware.
Telegram WebHook
var telegraf = new Telegraf(process.env.BOT_TOKEN)
var tlsOptions = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem'),
ca: [ fs.readFileSync('client-cert.pem') ]
}
telegraf.setWebHook('https://server.tld:8443/secret-path', {
content: 'server-cert.pem'
})
telegraf.startWebHook('/secret-path', tlsOptions, 8443)
telegraf.startWebHook('/secret-path', null, 5000)
require('http')
.createServer(telegraf.webHookCallback('/secret-path'))
.listen(3000)
require('https')
.createServer(tlsOptions, telegraf.webHookCallback('/secret-path'))
.listen(8443)
var express = require('express')
var app = express()
app.use(telegraf.webHookCallback('/secret-path'))
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000, function () {
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 = function(err){
log.error('server error', err)
throw err
}
Shortcuts
Telegraf context shortcuts:
Available shortcuts:
message event:
callback_query event:
inline_query event:
Examples
var telegraf = new Telegraf(process.env.BOT_TOKEN)
telegraf.on('text', function * (){
telegraf.sendMessage(this.message.chat.id, `Hello ${this.state.role}`)
this.reply(`Hello ${this.state.role}`)
this.reply(`Hello ${this.state.role}`, { reply_to_message_id: this.message.id })
})
telegraf.on('/quit', function * (){
telegraf.leaveChat(this.message.chat.id)
this.leaveChat()
})
telegraf.on('callback_query', function * (){
telegraf.answerCallbackQuery(this.callbackQuery.id)
this.answerCallbackQuery()
})
telegraf.on('inline_query', function * (){
var result = []
telegraf.answerInlineQuery(this.inlineQuery.id, result)
this.answerInlineQuery(result)
})
API reference
Telegraf.handler(messageType, handler, [handler...])
Telegraf.compose(handlers)
new Telegraf(token)
.answerCallbackQuery(callbackQueryId, text, showAlert)
.answerInlineQuery(inlineQueryId, results, extra)
.editMessageCaption(chatId, messageId, caption, extra)
.editMessageReplyMarkup(chatId, messageId, markup, extra)
.editMessageText(chatId, messageId, text, extra)
.forwardMessage(chatId, fromChatId, messageId, extra)
.getChat(chatId)
.getChatAdministrators(chatId)
.getChatMember(chatId, userId)
.getChatMembersCount(chatId)
.getFile(fileId)
.getFileLink(fileId)
.getMe()
.getUserProfilePhotos(userId, offset, limit)
.handleUpdate(rawUpdate, response)
.hears(string|ReGex, handler, [handler...])
.kickChatMember(chatId, userId)
.leaveChat(chatId)
.on(messageType, handler, [handler...])
.removeWebHook()
.sendAudio(chatId, audio, extra)
.sendChatAction(chatId, action)
.sendContact(chatId, phoneNumber, firstName, extra)
.sendDocument(chatId, doc, extra)
.sendLocation(chatId, latitude, longitude, extra)
.sendMessage(chatId, text, extra)
.sendPhoto(chatId, photo, extra)
.sendSticker(chatId, sticker, extra)
.sendVenue(chatId, latitude, longitude, title, address, extra)
.sendVideo(chatId, video, extra)
.sendVoice(chatId, voice, extra)
.setWebHook(url, cert)
.startPolling(timeout, limit)
.startWebHook(webHookPath, tlsOptions, port, [host])
.stop()
.unbanChatMember(chatId, userId)
.use(function)
.webHookCallback(webHookPath)
Telegraf.handler(eventType, handler, [handler...]) => GeneratorFunction
Generates middleware for handling provided event type.
Param | Type | Description |
---|
eventType | string |string[] | Event type |
handler | GeneratorFunction | Handler |
Telegraf.compose(handlers) => GeneratorFunction
Compose middleware
returning a fully valid middleware comprised of all those which are passed.
Param | Type | Description |
---|
handlers | GeneratorFunction[] | Array of handlers |
new Telegraf(token)
Initialize new Telegraf app.
.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 |
Related Telegram api docs
Use this method to send answers to an inline query.
Param | Type | Description |
---|
inlineQueryId | string | Query id |
results | object[] | Results |
[extra] | object | Extra parameters |
Use this method to edit captions of messages sent by the bot or via the bot
Param | Type | Description |
---|
chatId | number |string | Chat id |
messageId | string | Message id |
caption | string | Caption |
[extra] | object | Extra parameters |
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 |
Use this method to edit text messages sent by the bot or via the bot.
Param | Type | Description |
---|
chatId | number |string | Chat id |
messageId | string | Message id |
text | string | Message |
[extra] | object | Extra parameters |
Forwards message.
Param | Type | Description |
---|
chatId | number |string | Source Chat id |
fromChatId | number |string | Target Chat id |
messageId | number | Message id |
[extra] | object | Extra parameters |
.getChat(chatId) => Promise
Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.).
Param | Type | Description |
---|
chatId | number |string | Chat id |
Related Telegram api docs
.getChatAdministrators(chatId) => Promise
Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
Param | Type | Description |
---|
chatId | number |string | Chat id |
Related Telegram api docs
.getChatMember(chatId) => Promise
Use this method to get information about a member of a chat.
Param | Type | Description |
---|
chatId | number |string | Chat id |
Related Telegram api docs
.getChatMembersCount(chatId) => Promise
Use this method to get the number of members in a chat.
Param | Type | Description |
---|
chatId | number |string | Chat id |
Related Telegram api docs
.getFile(fileId) => Promise
Returns basic info about a file and prepare it for downloading.
Param | Type | Description |
---|
fileId | string | File id |
Related Telegram api docs
.getFileLink(fileId) => Promise
Returns link to file.
Param | Type | Description |
---|
fileId | string | File id |
Related Telegram api docs
.getMe() => Promise
Returns basic information about the bot.
Related Telegram api docs
.getUserProfilePhotos(userId, offset, limit) => Promise
Returns profiles photos for provided user.
Param | Type | Description |
---|
userId | number | Chat id |
offset | number | Offset |
limit | number | Limit |
Related Telegram api docs
.handleUpdate(rawUpdate, [webHookResponse])
Handle raw Telegram update.
In case you use centralized webhook server, queue, etc.
Param | Type | Description |
---|
rawUpdate | object | Telegram update payload |
[webHookResponse] | object | (Optional) http.ServerResponse |
.hears(pattern, handler, [handler...])
Registers handler only for text
events using string pattern or RegEx.
Param | Type | Description |
---|
pattern | string |RegEx | Pattern or RegEx |
handler | GeneratorFunction | Handler |
.kickChatMember(chatId, userId) => Promise
Use this method to kick a user from a group or a supergroup.
Param | Type | Description |
---|
chatId | number |string | Chat id |
userId | number | User id |
Related Telegram api docs
.leaveChat(chatId) => Promise
Use this method for your bot to leave a group, supergroup or channel.
Param | Type | Description |
---|
chatId | number |string | Chat id |
Related Telegram api docs
.on(eventType, handler, [handler...])
Registers handler for provided event type.
Param | Type | Description |
---|
eventType | string |string[] | Event type |
handler | GeneratorFunction | Handler |
.removeWebHook() => Promise
Removes webhook. Shortcut for Telegraf.setWebHook('')
Related Telegram api docs
Sends audio.
.sendChatAction(chatId, action) => Promise
Sends chat action.
Param | Type | Description |
---|
chatId | number |string | Chat id |
action | string | Chat action |
Sends document.
Param | Type | Description |
---|
chatId | number |string | Chat id |
phoneNumber | string | Contact phone number |
firstName | string | Contact first name |
[extra] | object | Extra parameters |
Sends document.
Sends location.
Param | Type | Description |
---|
chatId | number |string | Chat id |
latitude | number | Latitude |
longitude | number | Longitude |
[extra] | object | Extra parameters |
Sends text message.
Param | Type | Description |
---|
chatId | number |string | Chat id |
text | string | Message |
[extra] | object | Extra parameters |
Sends photo.
Sends sticker.
Sends venue information.
Param | Type | Description |
---|
chatId | number |string | Chat id |
latitude | number | Latitude |
longitude | number | Longitude |
title | string | Venue title |
address | string | Venue address |
[extra] | object | Extra parameters |
Sends video.
Sends voice.
.setWebHook(url, [cert]) => Promise
Specifies an url to receive incoming updates via an outgoing webhook.
Param | Type | Description |
---|
url | string | Public url for webhook |
[cert] | File | SSL public certificate |
Related Telegram api docs
.startWebHook(webHookPath, tlsOptions, port, [host])
Start listening @ https://host:port/webHookPath
for Telegram calls.
Param | Type | Description |
---|
webHookPath | string | Webhook url path (see Telegraf.setWebHook) |
tlsOptions | object | (Optional) TLS server options. Pass null to use http |
port | number | Port number |
[host] | string | (Optional) Hostname |
.startPolling(timeout, limit)
Start poll updates.
Param | Type | Default | Description |
---|
timeout | number | 0 | Poll timeout |
limit | number | 100 | Limits the number of updates to be retrieved |
.stop()
Stop WebHook and polling
.unbanChatMember(chatId, userId) => Promise
Use this method to unban a previously kicked user in a supergroup.
Param | Type | Description |
---|
chatId | number |string | Chat id |
userId | number | User id |
Related Telegram api docs
.use(middleware)
Registers a middleware.
Param | Type | Description |
---|
middleware | function | Middleware function |
.webHookCallback(webHookPath) => Function
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 |
---|
webHookPath | string | Webhook url path (see Telegraf.setWebHook) |
File
This object represents the contents of a file to be uploaded.
Supported file sources:
File path
Buffer
ReadStream
Existing file_id
Example:
telegraf.sendVideo('chatId', {source: '/path/to/video.mp4'}})
telegraf.sendVoice('chatId', {source: new Buffer(...)})
telegraf.sendAudio('chatId', {source: fs.createReadStream('/path/to/video.mp4')})
telegraf.sendSticker('chatId', '123123jkbhj6b')
Related Telegram api docs
Events
Supported event:
message
inline_query
chosen_inline_result
callback_query
Available virtual events:
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
telegraf.on('message', function * () {
this.reply('Hey there!')
})
telegraf.on(['sticker', 'photo'], function * () {
console.log(this.message)
this.reply('Cool!')
})
Related Telegram api docs
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.