![Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility](https://cdn.sanity.io/images/cgdhsj6q/production/97774ea8c88cc8f4bed2766c31994ebc38116948-1664x1366.png?w=400&fit=max&auto=format)
Security News
Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Telegram bot framework for node.js
$ npm install telegraf
var Telegraf = require('telegraf');
var app = Telegraf(process.env.BOT_TOKEN);
// Look ma, middleware!
var sayYoMiddleware = function * (next) {
yield this.reply('yo')
yield next
}
// Text messages handling
app.hears('/answer', sayYoMiddleware, function * () {
this.reply('*12*', { parse_mode: 'Markdown' })
})
// Wow! RegEx
app.hears(/reverse (.+)/, function * () {
// Copy/Pasted from StackOverflow
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.
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()
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')
// 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')
})
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 = 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}`)
})
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}`)
})
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)
}
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 |
Telegraf.sendMessage(chatId, text, extra)
=> Promise
Sends text message.
Param | Type | Description |
---|---|---|
chatId | Integer /String | Chat id |
text | String | Message |
extra | Object | Optional parameters |
Related Telegram api docs |
Telegraf.forwardMessage(chatId, fromChatId, messageId, extra)
=> Promise
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 |
Telegraf.sendLocation(chatId, latitude, longitude, extra)
=> Promise
Sends location.
Param | Type | Description |
---|---|---|
chatId | Integer /String | Chat id |
latitude | Integer | Latitude |
longitude | Integer | Longitude |
extra | Object | Optional parameters |
Telegraf.sendPhoto(chatId, photo, extra)
=> Promise
Sends photo.
Param | Type | Description |
---|---|---|
chatId | Integer /String | Chat id |
photo | File | Photo |
extra | Object | Optional parameters |
Telegraf.sendDocument(chatId, doc, extra)
=> Promise
Sends document.
Param | Type | Description |
---|---|---|
chatId | Integer /String | Chat id |
doc | File | Document |
extra | Object | Optional parameters |
Telegraf.sendAudio(chatId, audio, extra)
=> Promise
Sends audio.
Param | Type | Description |
---|---|---|
chatId | Integer /String | Chat id |
audio | File | Document |
extra | Object | Optional parameters |
Telegraf.sendSticker(chatId, sticker, extra)
=> Promise
Sends sticker.
Param | Type | Description |
---|---|---|
chatId | Integer /String | Chat id |
sticker | File | Document |
extra | Object | Optional parameters |
Telegraf.sendVideo(chatId, video, extra)
=> Promise
Sends video.
Param | Type | Description |
---|---|---|
chatId | Integer /String | Chat id |
video | File | Document |
extra | Object | Optional parameters |
Telegraf.sendVoice(chatId, voice, extra)
=> Promise
Sends voice.
Param | Type | Description |
---|---|---|
chatId | Integer /String | Chat id |
voice | File | Document |
extra | Object | Optional parameters |
Telegraf.sendChatAction(chatId, action)
=> Promise
Sends chat action.
Param | Type | Description |
---|---|---|
chatId | Integer /String | Chat id |
action | String | Chat action |
Telegraf.getMe()
=> Promise
Returns basic information about the bot.
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 |
Telegraf.getFile(fileId)
=> Promise
Returns basic info about a file and prepare it for downloading.
Param | Type | Description |
---|---|---|
fileId | String | File id |
Telegraf.getFileLink(fileId)
=> Promise
Returns link to file.
Param | Type | Description |
---|---|---|
fileId | String | File id |
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 |
Telegraf.removeWebHook()
=> Promise
Removes webhook. Shortcut for Telegraf.setWebHook('')
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 |
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 |
Telegraf.answerInlineQuery(inlineQueryId, results, extra)
=> Promise
Use this method to send answers to an inline query.
Param | Type | Description |
---|---|---|
inlineQueryId | String | Query id |
results | Array | Results |
extra | Object | Optional parameters |
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 |
Telegraf.editMessageText(chatId, messageId, text, extra)
=> Promise
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 |
Telegraf.editMessageCaption(chatId, messageId, caption, extra)
=> Promise
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 |
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.
Param | Type | Description |
---|---|---|
chatId | Integer /String | Chat id |
messageId | String | Message id |
markup | Object | Keyboard markup |
extra | Object | Optional parameters |
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')
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 all messages
app.on('message', function * () {
this.reply('Hey there!')
})
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 * (){
// 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()
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.
FAQs
Modern Telegram Bot Framework
The npm package telegraf receives a total of 87,799 weekly downloads. As such, telegraf popularity was classified as popular.
We found that telegraf demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
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.
Security News
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Security News
React's CRA deprecation announcement sparked community criticism over framework recommendations, leading to quick updates acknowledging build tools like Vite as valid alternatives.
Security News
Ransomware payment rates hit an all-time low in 2024 as law enforcement crackdowns, stronger defenses, and shifting policies make attacks riskier and less profitable.