Telegraf
Telegram bot framework for node.js
Installation
$ npm install telegraf
Example
var Telegraf = require('telegraf');
var app = Telegraf(process.env.BOT_TOKEN);
var sayYoMiddleware = function * (next) {
yield this.reply('yo')
yield next
}
app.hears('/answer', sayYoMiddleware, function * () {
this.reply('*12*', { parse_mode: 'Markdown' })
})
app.hears(/reverse (.+)/, function * () {
function reverse (s) {
for (var i = s.length - 1, o = ''; i >= 0; o += s[i--]) { }
return o
}
this.reply(reverse(this.match[1]))
})
app.startPolling()
There are some other examples on 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 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 = Telegraf('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 = Telegraf('BOT TOKEN')
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
this.message
this.inlineQuery
this.chosenInlineResult
this.callbackQuery
});
The recommended way to extend application context.
var app = Telegraf('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 = Telegraf('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 outputs all errors to stderr.
To perform custom error-handling logic such as centralized logging you can set onerror
handler:
app.onerror = function(err){
log.error('server error', err)
}
API reference
Telegraf
new Telegraf(token)
.startPolling(timeout, limit)
.startWebHook(token, tlsOptions, port, [host])
.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)
.setWebHook(url, cert)
.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 app.
Param | Type | Description |
---|
token | String | Bot Token |
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.startWebHook(token, tlsOptions, port, [host])
Start listening @ https://host:port/token
for Telegram calls.
Param | Type | Description |
---|
token | String | Token |
tlsOptions | Object | tls server options |
port | Int | Port number |
host | String | Hostname |
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 | 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.setWebHook(url, [cert])
=> Promise
Specifies an url to receive incoming updates via an outgoing webHook.
Param | Type | Description |
---|
url | String | File id |
cert | File | SSL 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.
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
.
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 = Telegraf('BOT TOKEN')
app.on('text', function * (){
app.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()
-> 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.