Telegraf
Modern Telegram bot framework for node.js
Installation
$ npm install telegraf
Example
var Telegraf = require('telegraf');
var telegraf = new Telegraf(process.env.BOT_TOKEN);
telegraf.hears('/answer', function * () {
this.reply('*42*', { parse_mode: 'Markdown' })
})
var sayYoMiddleware = function * (next) {
yield this.reply('yo')
yield next
}
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 = require('telegraf')
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.message
this.inlineQuery
this.chosenInlineResult
this.callbackQuery
});
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 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
For development you can use Telegraf.memorySession()
, but session will be lost on app restart.
For production environment use any telegraf-session-*
middleware.
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}`)
})
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
}
API reference
Telegraf
new Telegraf(token)
.setWebHook(url, cert)
.startWebHook(path, tlsOptions, port, [host])
.startPolling(timeout, limit)
.stop()
.use(function)
.on(messageType, function)
.hear(string|ReGex, function)
.sendMessage(chatId, text, extra)
.forwardMessage(chatId, fromChatId, messageId, extra)
.sendLocation(chatId, latitude, longitude, extra)
.sendPhoto(chatId, photo, extra)
.sendDocument(chatId, doc, extra)
.sendAudio(chatId, audio, extra)
.sendSticker(chatId, sticker, extra)
.sendVideo(chatId, video, extra)
.sendVoice(chatId, voice, extra)
.sendChatAction(chatId, action)
.getMe()
.getUserProfilePhotos(userId, offset, limit)
.getFile(fileId)
.getFileLink(fileId)
.removeWebHook()
.kickChatMember(chatId, userId)
.unbanChatMember(chatId, userId)
.answerInlineQuery(inlineQueryId, results, extra)
.answerCallbackQuery(callbackQueryId, text, showAlert)
.editMessageText(chatId, messageId, text, extra)
.editMessageCaption(chatId, messageId, caption, extra)
.editMessageReplyMarkup(chatId, messageId, markup, extra)
Telegraf.new(token)
Initialize new Telegraf app.
Telegraf.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
Telegraf.startWebHook(token, tlsOptions, port, [host])
Start listening @ https://host:port/token
for Telegram calls.
Param | Type | Description |
---|
path | String | Url path (see Telegraf.setWebHook) |
tlsOptions | Object | tls server options |
port | Int | Port number |
host | String | Hostname |
Telegraf.startPolling(timeout, limit)
Start poll updates.
Param | Type | Default | Description |
---|
timeout | Int | 0 | Poll timeout |
limit | Int | 100 | Limits the number of updates to be retrieved |
Telegraf.stop()
Stop WebHook and polling
Telegraf.use(middleware)
Registers a middleware.
Param | Type | Description |
---|
middleware | Function | Middleware function |
Telegraf.on(eventType, handler)
Registers handler for provided event type.
Param | Type | Description |
---|
eventType | String or Array[String] | Event type |
handler | Function | Handler |
Telegraf.hear(pattern, handler)
Registers handler only for text
events using string pattern or RegEx.
Param | Type | Description |
---|
pattern | String /RegEx | Pattern or RegEx |
handler | Function | Handler |
Sends text message.
Forwards message.
Param | Type | Description |
---|
chatId | Integer /String | Source Chat id |
fromChatId | Integer /String | Target Chat id |
messageId | Integer | Message id |
extra | Object | Optional parameters |
Related Telegram api docs
Sends location.
Param | Type | Description |
---|
chatId | Integer /String | Chat id |
latitude | Integer | Latitude |
longitude | Integer | Longitude |
extra | Object | Optional parameters |
Related Telegram api docs
Sends photo.
Related Telegram api docs
Sends document.
Related Telegram api docs
Sends audio.
Related Telegram api docs
Sends sticker.
Related Telegram api docs
Sends video.
Related Telegram api docs
Sends voice.
Related Telegram api docs
Telegraf.sendChatAction(chatId, action)
=> Promise
Sends chat action.
Param | Type | Description |
---|
chatId | Integer /String | Chat id |
action | String | Chat 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.
Param | Type | Description |
---|
userId | Integer | Chat id |
offset | Integer | Offset |
userId | limit | Limit |
Related Telegram api docs
Telegraf.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
Telegraf.getFileLink(fileId)
=> Promise
Returns link to file.
Param | Type | Description |
---|
fileId | String | File id |
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.
Param | Type | Description |
---|
chatId | Integer /String | Chat id |
userId | Integer | User id |
Related Telegram api docs
Telegraf.unbanChatMember(chatId, userId)
=> Promise
Use this method to unban a previously kicked user in a supergroup.
Param | Type | Description |
---|
chatId | Integer /String | Chat id |
userId | Integer | User id |
Related Telegram api docs
Use this method to send answers to an inline query.
Param | Type | Description |
---|
inlineQueryId | String | Query id |
results | Array | Results |
extra | Object | Optional parameters |
Related Telegram api docs
Telegraf.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 edit text messages sent by the bot or via the bot.
Param | Type | Description |
---|
chatId | Integer /String | Chat id |
messageId | String | Message id |
text | String | Message |
extra | Object | Optional parameters |
Related Telegram api docs
Use this method to edit captions of messages sent by the bot or via the bot
Param | Type | Description |
---|
chatId | Integer /String | Chat id |
messageId | String | Message id |
caption | String | Caption |
extra | Object | Optional parameters |
Related Telegram api docs
Use this method to edit only the reply markup of messages sent by the bot or via the bot.
Param | Type | Description |
---|
chatId | Integer /String | Chat id |
messageId | String | Message id |
markup | Object | Keyboard markup |
extra | Object | Optional 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:
app.sendVideo('chatId', {source: '/path/to/video.mp4'}})
app.sendVoice('chatId', {source: new Buffer(...)})
app.sendAudio('chatId', {source: fs.createReadStream('/path/to/video.mp4')})
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
.
telegraf.on(['sticker', 'photo'], function * () {
console.log(this.message)
this.reply('Cool!')
})
telegraf.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 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 })
})
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()
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.