Security News
Supply Chain Attack Detected in Solana's web3.js Library
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
š¢ Modern Telegram bot framework for node.js.
$ npm install telegraf
const Telegraf = require('telegraf')
const app = new Telegraf(process.env.BOT_TOKEN)
// Message handling
app.on('message', (ctx) => {
return ctx.reply('*42*', { parse_mode: 'Markdown' })
})
app.startPolling()
const Telegraf = require('telegraf')
const app = new Telegraf(process.env.BOT_TOKEN)
// Look ma, middleware!
const sayYoMiddleware = (ctx, next) => {
return ctx.reply('yo').then(next)
}
// Command handling
app.command('/command', sayYoMiddleware, (ctx) => {
return ctx.reply('Sure')
})
// Wow! RegEx
app.hears(/reverse (.+)/, sayYoMiddleware, (ctx) => {
return ctx.reply(ctx.match[1].split('').reverse().join(''))
})
app.startPolling()
There are some other examples.
A Telegraf application is an object containing an array of middlewares which are composed and executed in a stack-like manner upon request. Is similar to many other middleware systems that you may have encountered such as Koa, Ruby's Rack, Connect.
const app = new Telegraf(process.env.BOT_TOKEN)
app.on('text', (ctx) => {
return ctx.reply('Hello World')
})
app.startPolling()
A Telegraf Context encapsulates telegram message. Context is created per request and contains following props:
app.use((ctx) => {
ctx.telegram // Telegram instance
ctx.updateType // Update type(message, inline_query, etc.)
[ctx.updateSubType] // Update subtype(text, sticker, audio, etc.)
[ctx.message] // Received message
[ctx.editedMessage] // Edited message
[ctx.inlineQuery] // Received inline query
[ctx.chosenInlineResult] // Received inline query result
[ctx.callbackQuery] // Received callback query
[ctx.chat] // Current chat info
[ctx.from] // Sender info
[ctx.match] // Regex match (available only for `hears` handler)
})
Middleware normally takes two parameters (ctx, next), ctx
is the context for one Telegram message,
next
is a function that is invoked to execute the downstream middleware.
It returns a Promise with a then function for running code after completion.
const app = new Telegraf(process.env.BOT_TOKEN)
// Logger middleware
app.use((ctx, next) => {
const start = new Date()
return next().then(() => {
const ms = new Date() - start
console.log('response time %sms', ms)
})
})
app.on('text', (ctx) => {
return ctx.reply('Hello World')
})
The recommended namespace to share information between middlewares.
const app = new Telegraf(process.env.BOT_TOKEN)
app.use((ctx, next) => {
ctx.state.role = getUserRole(ctx.message)
return next()
})
app.on('text', (ctx) => {
return ctx.reply(`Hello ${ctx.state.role}`)
})
const app = new Telegraf(process.env.BOT_TOKEN)
// Session state will be lost on app restart
app.use(Telegraf.memorySession())
app.on('text', () => {
ctx.session.counter = ctx.session.counter || 0
ctx.session.counter++
return ctx.reply(`Message counter:${ctx.session.counter}`)
})
Important: For production environment use any of telegraf-session-*
middleware.
const app = new Telegraf(process.env.BOT_TOKEN)
// TLS options
const tlsOptions = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem'),
ca: [
// This is necessary only if the client uses the self-signed certificate.
fs.readFileSync('client-cert.pem')
]
}
// Set telegram webhook
app.telegram.setWebHook('https://server.tld:8443/secret-path', {
content: 'server-cert.pem'
})
// Start https webhook
app.startWebHook('/secret-path', tlsOptions, 8443)
// Http webhook, for nginx/heroku users.
app.startWebHook('/secret-path', null, 5000)
// Use webHookCallback() if you want attach telegraf to existing http server
require('http')
.createServer(app.webHookCallback('/secret-path'))
.listen(3000)
require('https')
.createServer(tlsOptions, app.webHookCallback('/secret-path'))
.listen(8443)
// Connect/Express.js integration
const express = require('express')
const expressApp = express()
expressApp.use(app.webHookCallback('/secret-path'))
expressApp.get('/', (req, res) => {
res.send('Hello World!')
})
expressApp.listen(3000, () => {
console.log('Example app listening on port 3000!')
})
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 = (err) => {
log.error('server error', err)
throw err
}
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 54,917 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
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.