Bots are special Telegram accounts designed to handle messages automatically. Users can interact with bots by sending them command messages in private or group chats. These accounts serve as an interface for code running somewhere on your server.
Telegraf is a library that makes it simple for you to develop your own Telegram bots using JavaScript or TypeScript.
- Full Telegram Bot API 4.9 support
- Telegram Payment Platform
- HTML5 Games
- Inline mode
- Incredibly fast
- Firebase/Glitch/Heroku/AWS λ/Whatever ready
http/https/fastify/Connect.js/express.js
compatible webhooks- Easy to extend
TypeScript
typings
npm install telegraf --save
or using yarn
yarn add telegraf
const { Telegraf } = require('telegraf')
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.start((ctx) => ctx.reply('Welcome'))
bot.help((ctx) => ctx.reply('Send me a sticker'))
bot.on('sticker', (ctx) => ctx.reply('👍'))
bot.hears('hi', (ctx) => ctx.reply('Hey there'))
bot.launch()
const { Telegraf } = require('telegraf')
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.command('oldschool', (ctx) => ctx.reply('Hello'))
bot.command('modern', ({ reply }) => reply('Yo'))
bot.command('hipster', Telegraf.reply('λ'))
bot.launch()
For additional bot examples see examples
folder.
Resources:
Community bots:
Name | Description |
---|---|
BibleBot | Bot to get bible verses |
BibleQuizzleBot | Bible quiz game - group fun similar to Quizzarium |
BitcoinDogBot | Bitcoin prices, Technical analysis and Alerts! |
BooksAndBot | An inline bot that allows you to search for books and share them in a conversation. Powered by Goodreads |
CaptchaOnlyBot | Configurable question \w set of buttons on a new group user |
ChannelHashBot | Keep track of hashtags that are sent in your group by forwarding them to a channel |
ChatAdmin | Helps to administer the chats |
ChatLinkerBot | The bridge between jabber and telegram |
ChessBot | Inline chess game in a message |
CounterBot | Keep track of multiple counters and increment, decrement, set and reset them to your hearts content |
DefendTheCastle | Telegram Bot Game - Defend The Castle |
DiscordTelegramBridge | A simple, small and fast discord to telegram bridge written in node.js |
EveMoviesBot | Track movie torrent releases and get notifications when it's there |
GNU/LinuxIndonesiaBot | BGLI Bot a.k.a Miranda Salma |
GoogleItBot | Instant inline search |
GroupsAdminBot | Telegram groups administrator bot |
KitchenTimerBot | Bot for setting up multiple timers for cooking |
LyricsGramBot | Song Lyrics |
MangadexBot | Read manga from Mangadex |
Memcoin | Memcoin for the Memconomy |
MetalArchivesBot | Unofficial metal-archives.com bot |
MidnaBot | Midnabot for telegram |
MineTelegram | Minecraft - Telegram bridge |
NodeRSSBot | Bot to subscribe RSS feed which allows many configurations |
Nyaa.si Bot | Nyaa.si torrents |
OCRToolBot | Tesseract text from image recognition |
OneQRBot | Scan and generate QR |
OrdisPrime | A telegram bot helper for warframe |
PodSearchBot | TypeScript |
RandomPassBot | Generate a password |
Randy | Randy Marsh raffle Telegram bot |
ReferalSystem | Channels promoter |
ScrobblerBot | An unofficial Last.fm Scrobbler |
Shieldy | Telegram bot repository |
SimpleRegBot | Simple bot for registration users to any event |
SpyfallGameBot | Simple telegram bot for an interesting board game |
StickersPlayBot | Search series covers stickers via inline |
StoreOfBot | Search, explore & discover the bests bots, channel or groups |
SyntaxHighlighterBot | A code highlighting tool for telegram chats |
TelegrafRutrackerTransmission | Bot for searching torrents at Rutracker and add them to your Transmission web service |
TelegramTelegrafBot | Telegram bot example using Telegraf with easy configuration steps |
Temply | |
TereGramBot | Simple telegram node bot with a few funny commands |
TheGuardBot | Manage a network of related groups |
ThemerBot | Create themes for Telegram based on colors chosen from a picture |
TTgram | Receive and send Twitters used a Telegram Bot |
Voicy | |
Watchy | |
YtSearchBot | Bot to share YouTube fetched videos from any channel |
YTubevideoBot | Bot created to help you find and share any video from youtube |
Send PR to add link to your bot |
To use the Telegram Bot API, you first have to get a bot account by chatting with BotFather.
BotFather will give you a token, something like 123456789:AbCdfGhIJKlmNoQQRsTUVwxyZ
.
A Telegraf bot 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 Express, Koa, Ruby's Rack, Connect.
Middleware is an essential part of any modern framework. It allows you to modify requests and responses as they pass between the Telegram and your bot.
You can imagine middleware as a chain of logic connection your bot to the Telegram request.
Middleware normally takes the two parameters: ctx
and next
.
ctx
is the context for one Telegram update. It contains mainly two things:
- the update object, it contains for example the incoming message and the respective the chat, and
- a number of useful methods for reacting to the update, such as replying to the message or answering a callback query.
See the context section below for a detailed overview.
next
is a function that is invoked to execute the downstream middleware.
It returns a Promise
with a function then
for running code after completion.
Here is a simple example for how to use middleware to track the response time, using async
and await
to deal with the Promise
.
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.use(async (ctx, next) => {
const start = new Date()
await next()
const ms = new Date() - start
console.log('Response time: %sms', ms)
})
bot.on('text', (ctx) => ctx.reply('Hello World'))
bot.launch()
Note how the function next
is used to invoke the subsequent layers of the middleware stack, performing the actual processing of the update (in this case, replying with “Hello World”).
Middleware is an extremely flexible concept that can be used for a myriad of things, including these:
- storing data per chat, per user, you name it
- allowing access to old messages (by storing them)
- making internationalization available
- rate limiting
- tracking response times (see above)
- much more
All important kinds of middleware have already been implemented, and the community keeps on adding more.
Just install a package via npm
, add it to your bot and you're ready to go.
Here is a list of
- Internationalization—simplifies selecting the right translation to use when responding to a user.
- Redis powered session—store session data using Redis.
- Local powered session (via lowdb)—store session data in a local file.
- Rate-limiting—apply rate limitting to chats or users.
- Bottleneck powered throttling—apply throttling to both incoming updates and outgoing API calls.
- Menus via inline keyboards—simplify creating interfaces based on menus.
- Stateless Questions—create stateless questions to Telegram users working in privacy mode.
- Natural language processing via wit.ai
- Natural language processing via recast.ai
- Multivariate and A/B testing—add experiments to see how different versions of a feature are used.
- Powerfull bot stats via Mixpanel
- statsd integration
- and more...
By default Telegraf will print all errors to stderr
and rethrow error.
To perform custom error-handling logic, use following snippet:
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.catch((err, ctx) => {
console.log(`Ooops, encountered an error for ${ctx.updateType}`, err)
})
bot.start((ctx) => {
throw new Error('Example error')
})
bot.launch()
A Telegraf Context encapsulates telegram update. Context is created per request and contains following props:
Property | Description |
---|---|
ctx.telegram |
Telegram client instance |
ctx.updateType |
Update type (message, inline_query, etc.) |
[ctx.updateSubTypes] |
Update subtypes (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.shippingQuery] |
Shipping query |
[ctx.preCheckoutQuery] |
Precheckout query |
[ctx.channelPost] |
New incoming channel post of any kind — text, photo, sticker, etc. |
[ctx.editedChannelPost] |
New version of a channel post that is known to the bot and was edited |
[ctx.poll] |
New version of a anonymous poll that is known to the bot and was changed |
[ctx.pollAnswer] |
This object represents an answer of a user in a non-anonymous poll. |
[ctx.chat] |
Current chat info |
[ctx.from] |
Sender info |
[ctx.match] |
Regex match (available only for hears , command , action , inlineQuery handlers) |
ctx.webhookReply |
Shortcut to ctx.telegram.webhookReply |
bot.use((ctx) => {
console.log(ctx.message)
})
The recommended way to extend bot context:
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.context.db = {
getScores: () => { return 42 }
}
bot.on('text', (ctx) => {
const scores = ctx.db.getScores(ctx.message.from.username)
return ctx.reply(`${ctx.message.from.username}: ${scores}`)
})
bot.launch()
If you're using TypeScript, have a look at the section below about usage with TypeScript. (You need to extend the type of the context.)
Context shortcuts for message update:
Context shortcuts for callback_query update:
Context shortcuts for inline_query update:
Shortcut | Bound to |
---|---|
answerInlineQuery |
telegram.answerInlineQuery |
Context shortcuts for shipping_query update:
Shortcut | Bound to |
---|---|
answerShippingQuery |
telegram.answerShippingQuery |
Context shortcuts for pre_checkout_query update:
Shortcut | Bound to |
---|---|
answerPreCheckoutQuery |
telegram.answerPreCheckoutQuery |
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.command('quit', (ctx) => {
// Explicit usage
ctx.telegram.leaveChat(ctx.message.chat.id)
// Using context shortcut
ctx.leaveChat()
})
bot.on('text', (ctx) => {
// Explicit usage
ctx.telegram.sendMessage(ctx.message.chat.id, `Hello ${ctx.state.role}`)
// Using context shortcut
ctx.reply(`Hello ${ctx.state.role}`)
})
bot.on('callback_query', (ctx) => {
// Explicit usage
ctx.telegram.answerCbQuery(ctx.callbackQuery.id)
// Using context shortcut
ctx.answerCbQuery()
})
bot.on('inline_query', (ctx) => {
const result = []
// Explicit usage
ctx.telegram.answerInlineQuery(ctx.inlineQuery.id, result)
// Using context shortcut
ctx.answerInlineQuery(result)
})
bot.launch()
The recommended namespace to share information between middlewares.
const bot = new Telegraf(process.env.BOT_TOKEN)
// Naive authorization middleware
bot.use((ctx, next) => {
ctx.state.role = getUserRole(ctx.message)
return next()
})
bot.on('text', (ctx) => {
return ctx.reply(`Hello ${ctx.state.role}`)
})
bot.launch()
Sessions are used to store data per user or per chat (or per whatever if you want, this is the session key).
Think of a session as an object that can hold any kind of information you provide. This could be the ID of the last message of the bot, or simply a counter about how many photos a user already sent to the bot.
You can use session middleware to add sessions support to your bot. This will do the heavy lifting for you. Using session middleware will result in a sequence like this:
- A new update comes in.
- The session middleware loads the current session data for the respective chat/user/whatever.
- The session middleware makes that session data available on the context object
ctx
. - Your middleware stack is run, all of your code can do its work.
- The session middleware takes back control and checks how you altered the session data on the
ctx
object. - The session middleware write the session back to your storage, i.e. a file, a database, an in-memory storage, or even a cloud storage solution.
Here is a simple example of how the built-in session middleware of Telegraf can be used to count photos.
const session = require('telegraf/session')
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.use(session())
bot.on('text', (ctx) => {
ctx.session.counter = ctx.session.counter || 0
ctx.session.counter++
return ctx.reply(`Message counter:${ctx.session.counter}`)
})
bot.launch()
In this example, the session middleware just stores the counters in-memory. This means that all counters will be lost when you stop your bot. If you want to store data even across restarts, you need to use persistent sessions.
Note: For persistent sessions you can use any of telegraf-session-*
middleware.
Tip: To use same session in private chat with bot and in inline mode, use following session key resolver:
{
getSessionKey: (ctx) => {
if (ctx.from && ctx.chat) {
return `${ctx.from.id}:${ctx.chat.id}`
} else if (ctx.from && ctx.inlineQuery) {
return `${ctx.from.id}:${ctx.from.id}`
}
return null
}
}
You can react to several different types of updates (and even sub-types of them), see the example below.
Supported update types:
message
edited_message
callback_query
inline_query
shipping_query
pre_checkout_query
chosen_inline_result
channel_post
edited_channel_post
Available update sub-types:
text
audio
dice
document
photo
sticker
video
voice
contact
location
venue
forward
new_chat_members
left_chat_member
new_chat_title
new_chat_photo
delete_chat_photo
group_chat_created
migrate_to_chat_id
supergroup_chat_created
channel_chat_created
migrate_from_chat_id
pinned_message
game
video_note
invoice
successful_payment
connected_website
passport_data
poll
// Handle message update
bot.on('message', (ctx) => {
return ctx.reply('Hello')
})
// Handle sticker or photo update
bot.on(['sticker', 'photo'], (ctx) => {
console.log(ctx.message)
return ctx.reply('Cool!')
})
require('dotenv')
const bot = 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 a self-signed certificate.
fs.readFileSync('client-cert.pem')
]
}
// Set telegram webhook
// The second argument is necessary only if the client uses a self-signed
// certificate. Including it for a verified certificate may cause things to break.
bot.telegram.setWebhook('https://server.tld:8443/secret-path', {
source: 'server-cert.pem'
})
// Start https webhook
bot.startWebhook('/secret-path', tlsOptions, 8443)
// Http webhook, for nginx/heroku users.
bot.startWebhook('/secret-path', null, 5000)
Use webhookCallback()
if you want to attach Telegraf to an existing http server.
require('http')
.createServer(bot.webhookCallback('/secret-path'))
.listen(3000)
require('https')
.createServer(tlsOptions, bot.webhookCallback('/secret-path'))
.listen(8443)
Express.js example integration
const { Telegraf } = require('telegraf')
const express = require('express')
const expressApp = express()
const bot = new Telegraf(process.env.BOT_TOKEN)
expressApp.use(bot.webhookCallback('/secret-path'))
bot.telegram.setWebhook('https://server.tld:8443/secret-path')
expressApp.get('/', (req, res) => {
res.send('Hello World!')
})
expressApp.listen(3000, () => {
console.log('Example app listening on port 3000!')
})
Fastify example integration
const { Telegraf } = require('telegraf')
const fastifyApp = require('fastify')()
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.on('text', ({ reply }) => reply('Hello'))
fastifyApp.use(bot.webhookCallback('/secret-path'))
// Set telegram webhook
// npm install -g localtunnel && lt --port 3000
bot.telegram.setWebhook('https://------.localtunnel.me/secret-path')
fastifyApp.listen(3000, () => {
console.log('Example app listening on port 3000!')
})
Koa.js example integration
const { Telegraf } = require('telegraf')
const Koa = require('koa')
const koaBody = require('koa-body')
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.telegram.setWebhook('https://server.tld:8443/secret-path')
const app = new Koa()
app.use(koaBody())
app.use(async (ctx, next) => {
if (ctx.method !== 'POST' || ctx.url !== '/secret-path') {
return next()
}
await bot.handleUpdate(ctx.request.body, ctx.response)
ctx.status = 200
})
app.use(async (ctx) => {
ctx.body = 'Hello World'
})
app.listen(3000)
Supported file sources:
Existing file_id
File path
Url
Buffer
ReadStream
Also, you can provide an optional name of a file as filename
when you send the file.
bot.on('message', (ctx) => {
// resend existing file by file_id
ctx.replyWithSticker('123123jkbhj6b')
// send file
ctx.replyWithVideo({ source: '/path/to/video.mp4' })
// send stream
ctx.replyWithVideo({
source: fs.createReadStream('/path/to/video.mp4')
})
// send buffer
ctx.replyWithVoice({
source: Buffer.alloc()
})
// send url via Telegram server
ctx.replyWithPhoto('https://picsum.photos/200/300/')
// pipe url content
ctx.replyWithPhoto({
url: 'https://picsum.photos/200/300/?random',
filename: 'kitten.jpg'
})
})
To enable Telegram Passport support you can use telegram-passport
package:
const { Telegraf } = require('telegraf')
const TelegramPassport = require('telegram-passport')
const bot = new Telegraf(process.env.BOT_TOKEN)
const passport = new TelegramPassport("PRIVATE_KEY_IN_PEM_FORMAT")
bot.on('passport_data', (ctx) => {
const decryptedPasswordData = passport.decrypt(ctx.passportData)
console.log(decryptedPasswordData)
return ctx.setPassportDataErrors([
{ source: 'selfie', type: 'driver_license', file_hash: 'file-hash', message: 'Selfie photo is too low quality'}
])
})
Telegraf Modules is higher level abstraction for writing modular Telegram bots.
A module is simply a .js file that exports Telegraf middleware:
module.exports = (ctx) => ctx.reply('Hello from Telegraf Module!')
const Composer = require('telegraf/composer')
module.exports = Composer.mount(
'sticker',
(ctx) => ctx.reply('Wow, sticker')
)
To run modules, you can use telegraf
module runner, it allows you to start Telegraf module easily from the command line.
npm install telegraf -g
telegraf [opts] <bot-file>
-t Bot token [$BOT_TOKEN]
-d Webhook domain
-H Webhook host [0.0.0.0]
-p Webhook port [$PORT or 3000]
-s Stop on error
-l Enable logs
-h Show this help message
Create module with name bot.js
and following content:
const Composer = require('telegraf/composer')
const PhotoURL = 'https://picsum.photos/200/300/?random'
const bot = new Composer()
bot.start((ctx) => ctx.reply('Hello there!'))
bot.help((ctx) => ctx.reply('Help message'))
bot.command('photo', (ctx) => ctx.replyWithPhoto({ url: PhotoURL }))
module.exports = bot
then run it:
telegraf -t "bot token" bot.js
Telegraf is written in TypeScript and therefore ships with declaration files for the entire library.
Moreover, it includes types for the complete Telegram API via the typegram
package.
While most types of Telegraf's API surface are self-explanatory, there's some notable things to keep in mind.
Recap from the above section about Middleware that ctx
is the context object that holds information about the incoming update, as well as a number of convenience functions such as ctx.reply
.
The exact shape of ctx
can vary based on the installed middleware.
Some custom middleware might register properties on the context object that Telegraf is not aware of.
Consequently, you can change the type of ctx
to fit your needs in order for you to have proper TypeScript types for your data.
This is done through Generics:
import { Context, Telegraf } from "telegraf";
// Define your own context type
interface MyContext extends Context {
myProp?: string
myOtherProp?: number
}
// Create your bot and tell it about your context type
const bot = new Telegraf<MyContext>('SECRET TOKEN')
// Register middleware and launch your bot as usual
bot.use((ctx, next) => {
// Yay, `myProp` is now available here as `string | undefined`!
ctx.myProp = ctx.chat?.first_name?.toUpperCase()
return next()
})
// ...
If you are using session middleware, you need to define your session property on your custom context object. This could look like this:
import { Context, Telegraf } from 'telegraf'
import session from 'telegraf/session'
interface SessionData {
lastMessageId?: number
photoCount?: number
// ... more session data go here
}
// Define your own context type
interface MyContext extends Context {
session: SessionData
// ... more props go here
}
// Create your bot and tell it about your context type
const bot = new Telegraf<MyContext>('SECRET TOKEN')
// Make session data available
bot.use(session())
// Register middleware and launch your bot as usual
bot.use((ctx, next) => {
// Yay, `session` is now available here as `SessionData`!
if (ctx.message !== undefined)
ctx.session.lastMessageId = ctx.message.message_id
return next()
})
bot.on('photo', (ctx, next) => {
ctx.session.photoCount = 1 + (ctx.session.photoCount ?? 0)
return next()
})
// ...
Telegraf API reference
const { Telegraf } = require('telegraf')
Initialize new Telegraf bot.
const telegraf = new Telegraf(token, [options])
Param | Type | Description |
---|---|---|
token | string |
Bot Token |
[options] | object |
Telegraf options |
Telegraf options:
{
telegram: { // Telegram options
agent: null, // https.Agent instance, allows custom proxy, certificate, keep alive, etc.
webhookReply: true // Reply via webhook
},
username: '' // Bot username (optional)
channelMode: false // Handle `channel_post` updates as messages (optional)
}
Use this property to get/set bot token.
telegraf.token = [string]
Use this property to control reply via webhook
feature.
telegraf.webhookReply = [bool]
Registers a middleware.
telegraf.use(...middleware)
Param | Type | Description |
---|---|---|
middleware | function |
Middleware function |
Registers middleware for provided update type.
telegraf.on(updateTypes, ...middleware)
Param | Type | Description |
---|---|---|
updateTypes | string/string[] |
Update type |
middleware | function |
Middleware |
Registers middleware for handling text
messages.
telegraf.hears(triggers, ...middleware)
Param | Type | Description |
---|---|---|
triggers | string/string[]/RegEx/RegEx[]/Function |
Triggers |
middleware | function |
Middleware |
Command handling.
telegraf.command(commands, ...middleware)
Param | Type | Description |
---|---|---|
commands | string/string[] |
Commands |
middleware | function |
Middleware |
Handler for /start command.
telegraf.start(...middleware)
Param | Type | Description |
---|---|---|
middleware | function |
Middleware |
Handler for /help command.
telegraf.help(...middleware)
Param | Type | Description |
---|---|---|
middleware | function |
Middleware |
Handler for /settings command.
telegraf.settings(...middleware)
Param | Type | Description |
---|---|---|
middleware | function |
Middleware |
Entity handling.
telegraf.entity(entity, ...middleware)
Param | Type | Description |
---|---|---|
entity | string/string[]/RegEx/RegEx[]/Function |
Entity name |
middleware | function |
Middleware |
Mention handling.
telegraf.mention(username, ...middleware)
Param | Type | Description |
---|---|---|
username | string/string[] |
Username |
middleware | function |
Middleware |
Phone number handling.
telegraf.phone(number, ...middleware)
Param | Type | Description |
---|---|---|
number | string/string[] |
Phone number |
middleware | function |
Middleware |
Hashtag handling.
telegraf.hashtag(hashtag, ...middleware)
Param | Type | Description |
---|---|---|
hashtag | string/string[] |
Hashtag |
middleware | function |
Middleware |
Cashtag handling.
telegraf.cashtag(cashtag, ...middleware)
Param | Type | Description |
---|---|---|
cashtag | string/string[] |
Cashtag |
middleware | function |
Middleware |
Registers middleware for handling callback_data
actions with regular expressions.
telegraf.action(triggers, ...middleware)
Param | Type | Description |
---|---|---|
triggers | string/string[]/RegEx/RegEx[] |
Triggers |
middleware | function |
Middleware |
Registers middleware for handling inline_query
actions with regular expressions.
telegraf.inlineQuery(triggers, ...middleware)
Param | Type | Description |
---|---|---|
triggers | string/string[]/RegEx/RegEx[] |
Triggers |
middleware | function |
Middleware |
Registers middleware for handling callback_data
actions with game query.
telegraf.gameQuery(...middleware)
Param | Type | Description |
---|---|---|
middleware | function |
Middleware |
Launch bot in long-polling or webhook mode.
telegraf.launch(options) => Promise
Param | Type | Default | Description |
---|---|---|---|
[options] | object |
Launch options |
Launch options:
{
// Start bot in polling mode (Default)
// See startPolling reference
polling: { timeout, limit, allowedUpdates, stopCallback },
// Start bot in webhook mode
// See startWebhook reference
webhook: { domain, hookPath, port, host, tlsOptions, cb }
}
Start poll updates.
telegraf.startPolling([timeout], [limit], [allowedUpdates], [stopCallback])
Param | Type | Default | Description |
---|---|---|---|
[timeout] | number |
30 | Poll timeout in seconds |
[limit] | number |
100 | Limits the number of updates to be retrieved |
[allowedUpdates] | string[]/string/null |
null | List the types of updates you want your bot to receive |
[stopCallback] | function |
null | Polling stop callback |
Start listening @ https://host:port/webhookPath
for Telegram calls.
telegraf.startWebhook(hookPath, [tlsOptions], port, [host])
Param | Type | Description |
---|---|---|
hookPath | string |
Webhook url path (see Telegraf.setWebhook) |
[tlsOptions] | object |
TLS server options. Pass null to use http |
port | number |
Port number |
[host] | string |
Hostname |
Stop Webhook and polling
telegraf.stop([callback]) => Promise
Param | Type |
---|---|
[callback] | 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 Connect/Express app.
telegraf.webhookCallback(webhookPath) => Function
Param | Type | Description |
---|---|---|
webhookPath | string |
Webhook url path (see Telegraf.setWebhook) |
Handle raw Telegram update. In case you use centralized webhook server, queue, etc.
telegraf.handleUpdate(rawUpdate, [webhookResponse])
Param | Type | Description |
---|---|---|
rawUpdate | object |
Telegram update payload |
[webhookResponse] | object |
http.ServerResponse |
Compose middlewares
returning a fully valid middleware comprised of all those which are passed.
Telegraf.compose(middlewares) => function
Param | Type | Description |
---|---|---|
middlewares | function[] |
Array of middlewares |
Generates middleware for handling provided update types.
Telegraf.mount(updateTypes, ...middleware) => function
Param | Type | Description |
---|---|---|
updateTypes | string/string[] |
Update type |
middleware | function |
middleware |
Generates middleware for handling text
messages with regular expressions.
Telegraf.hears(triggers, ...middleware) => function
Param | Type | Description |
---|---|---|
triggers | string/string[]/RegEx/RegEx[]/Function/Function[] |
Triggers |
handler | function |
Handler |
Generates middleware for handling callbackQuery
data with regular expressions.
Telegraf.action(triggers, ...middleware) => function
Param | Type | Description |
---|---|---|
triggers | string/string[]/RegEx/RegEx[]/Function/Function[] |
Triggers |
handler | function |
Handler |
Generates middleware for handling inlineQuery
data with regular expressions.
Telegraf.inlineQuery(triggers, ...middleware) => function
Param | Type | Description |
---|---|---|
triggers | string/string[]/RegEx/RegEx[]/Function/Function[] |
Triggers |
handler | function |
Handler |
Generates pass thru middleware.
Telegraf.passThru() => function
Generates optional middleware.
Telegraf.optional(test, ...middleware) => function
Param | Type | Description |
---|---|---|
test | truthy/function |
Value or predicate (ctx) => bool |
middleware | function |
middleware |
Generates middleware for provided users only.
Telegraf.acl(userId, ...middleware) => function
Param | Type | Description |
---|---|---|
userId | string/string[] |
User id |
middleware | function |
middleware |
Generates drop middleware.
Telegraf.drop(test) => function
Param | Type | Description |
---|---|---|
test | truthy/function |
Value or predicate (ctx) => bool |
Generates filter middleware.
Telegraf.filter(test) => function
Param | Type | Description |
---|---|---|
test | truthy/function |
Value or predicate (ctx) => bool |
Generates branch middleware.
Telegraf.branch(test, trueMiddleware, falseMiddleware) => function
Param | Type | Description |
---|---|---|
test | truthy/function |
Value or predicate (ctx) => bool |
trueMiddleware | function |
true action middleware |
falseMiddleware | function |
false action middleware |
Generates middleware for handling messages with email
entity.
Telegraf.email(triggers, ...middleware) => function
Param | Type | Description |
---|---|---|
triggers | string/string[]/RegEx/RegEx[]/Function/Function[] |
Triggers |
handler | function |
Handler |
Generates middleware for handling messages with hashtag
entity.
Telegraf.hashtag(triggers, ...middleware) => function
Param | Type | Description |
---|---|---|
triggers | string/string[]/RegEx/RegEx[]/Function/Function[] |
Triggers |
handler | function |
Handler |
Generates middleware for handling messages with cashtag
entity.
Telegraf.cashtag(triggers, ...middleware) => function
Param | Type | Description |
---|---|---|
triggers | string/string[]/RegEx/RegEx[]/Function/Function[] |
Triggers |
handler | function |
Handler |
Generates middleware for handling messages with url
entity.
Telegraf.url(triggers, ...middleware) => function
Param | Type | Description |
---|---|---|
triggers | string/string[]/RegEx/RegEx[]/Function/Function[] |
Triggers |
handler | function |
Handler |
Generates middleware for handling messages with phone
entity.
Telegraf.phone(triggers, ...middleware) => function
Param | Type | Description |
---|---|---|
triggers | string/string[]/RegEx/RegEx[]/Function/Function[] |
Triggers |
handler | function |
Handler |
Generates middleware for handling messages with text_link
entity.
Telegraf.textLink(triggers, ...middleware) => function
Param | Type | Description |
---|---|---|
triggers | string/string[]/RegEx/RegEx[]/Function/Function[] |
Triggers |
handler | function |
Handler |
Generates middleware for handling messages with text_mention
entity.
Telegraf.textMention(triggers, ...middleware) => function
Param | Type | Description |
---|---|---|
triggers | string/string[]/RegEx/RegEx[]/Function/Function[] |
Triggers |
handler | function |
Handler |
Telegram client API reference.
const Telegram = require('telegraf/telegram')
Initialize new Telegram client.
const telegram = new Telegram(token, [options])
Param | Type | Description |
---|---|---|
token | string |
Bot Token |
[options] | object |
Telegram options |
Telegram options:
{
agent: null, // https.Agent instance, allows custom proxy, certificate, keep alive, etc.
webhookReply: true // Reply via webhook
}
Use this property to control reply via webhook
feature.
telegram.webhookReply = [bool]
Use this method to add a new sticker to a set created by the bot.
telegram.addStickerToSet(ownerId, name, stickerData) => Promise
Official documentation
Param | Type | Description |
---|---|---|
ownerId | string |
User identifier of sticker set owner |
name | string |
Sticker set name |
stickerData | Object |
Sticker data({png_sticker: 'stiker file', emojis: '😉', mask__position: '' }) |
Use this method to send answers to callback queries.
telegram.answerCbQuery(callbackQueryId, text, [showAlert], [extra]) => Promise
Official documentation
Param | Type | Description |
---|---|---|
callbackQueryId | string |
Query id |
[text] | string |
Notification text |
[showAlert] | bool |
Show alert instead of notification |
[extra] | object |
Extra parameters |
Use this method to send answers to game query.
telegram.answerGameQuery(callbackQueryId, url) => Promise
Param | Type | Description |
---|---|---|
callbackQueryId | string |
Query id |
url | string |
Notification text |
Use this method to send answers to shipping query.
telegram.answerShippingQuery(shippingQueryId, ok, shippingOptions, [errorMessage]) => Promise
Param | Type | Description |
---|---|---|
shippingQueryId | string |
Shipping Query id |
ok | bool |
Specify True if delivery to the specified address is possible |
shippingOptions | object |
Shipping Options |
[errorMessage] | string |
Error message in human readable form |
Use this method to send answers to shipping query.
telegram.answerPreCheckoutQuery(preCheckoutQueryId, ok, [errorMessage]) => Promise
Param | Type | Description |
---|---|---|
preCheckoutQueryId | string |
Shipping Query id |
ok | bool |
Specify True if everything is alright (goods are available, etc.) |
[errorMessage] | string |
Error message in human readable form |
Use this method to send answers to an inline query.
telegram.answerInlineQuery(inlineQueryId, results, [extra]) => Promise
Param | Type | Description |
---|---|---|
inlineQueryId | string |
Query id |
results | object[] |
Results |
[extra] | object |
Extra parameters |
Use this method to create new sticker set owned by a user.
telegram.createNewStickerSet(ownerId, name, title, stickerData, [isMasks]) => Promise
Official documentation
Param | Type | Description |
---|---|---|
ownerId | string |
User identifier of sticker set owner |
name | string |
Sticker set name |
title | string |
Sticker set title |
stickerData | object |
Sticker data({png_sticker: 'stiker file', emojis: '😉', mask__position: '' }) |
[isMasks] | bool |
Pass True, if a set of mask stickers should be created |
Use this method to delete a group sticker set from a supergroup.
telegram.deleteChatStickerSet(chatId) => Promise
Official documentation
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
Use this method to delete bot messages.
telegram.deleteMessage(chatId, messageId) => Promise
Official documentation
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
messageId | string |
Message id |
Use this method to set the thumbnail of a sticker set.
telegram.setStickerSetThumb(name, userId, [thumb]) => Promise
Official documentation
Param | Type | Description |
---|---|---|
name | string |
Sticker set name |
userId | string |
User identifier of the sticker set owner |
thumb | File |
A PNG image with the thumbnail, must be up to 128 kilobytes in size and have width and height exactly 100px, or a TGS animation with the thumbnail up to 32 kilobytes in size |
Use this method to delete a sticker from a set created by the bot.
telegram.deleteStickerFromSet(stickerId) => Promise
Official documentation
Param | Type | Description |
---|---|---|
stickerId | string |
File identifier of the sticker |
Use this method to edit captions of messages sent by the bot or via the bot.
telegram.editMessageCaption(chatId, messageId, inlineMessageId, caption, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
messageId | string |
Message id |
inlineMessageId | string |
Inline message id |
caption | string |
Caption |
[extra] | object |
Extra parameters |
Use this method to edit media of messages sent by the bot or via the bot.
telegram.editMessageMedia(chatId, messageId, inlineMessageId, media, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
messageId | string |
Message id |
inlineMessageId | string |
Inline message id |
media | InputMedia |
InputMedia |
[extra] | object |
Extra parameters |
Use this method to edit live location messages sent by the bot or via the bot.
telegram.editMessageLiveLocation(latitude, longitude, chatId, messageId, inlineMessageId, [markup]) => Promise
Official documentation
Param | Type | Description |
---|---|---|
latitude | string |
Latitude of new location |
longitude | string |
Longitude of new location |
chatId | number/string |
Chat id |
messageId | string |
Message id |
inlineMessageId | string |
Inline message id |
[markup] | object |
Keyboard markup |
Use this method to edit only the reply markup of messages sent by the bot or via the bot.
telegram.editMessageReplyMarkup(chatId, messageId, inlineMessageId, markup, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
messageId | string |
Message id |
inlineMessageId | string |
Inline 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.
telegram.editMessageText(chatId, messageId, inlineMessageId, text, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
messageId | string |
Message id |
inlineMessageId | string |
Inline message id |
text | string |
Message |
[extra] | object |
Extra parameters |
Forwards message.
telegram.forwardMessage(chatId, fromChatId, messageId, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Target Chat id |
fromChatId | number/string |
Source Chat id |
messageId | number |
Message id |
[extra] | object |
Extra parameters |
Sends message copy.
telegram.sendCopy(chatId, message, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Target Chat id |
message | object |
Message |
[extra] | object |
Extra parameters |
Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.
telegram.getWebhookInfo() => Promise
Use this method to get up to date information about the chat (current name of the user for one-on-one conversatio ns, current username of a user, group or channel, etc.).
telegram.getChat(chatId) => Promise
Official documentation
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
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.
telegram.getChatAdministrators(chatId) => Promise
Official documentation
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat.
telegram.setGameScore(userId, score, inlineMessageId, chatId, messageId, [editMessage], [force]) => Promise
Official documentation
Param | Type | Description |
---|---|---|
userId | number |
Target User id |
score | number |
Target User id |
inlineMessageId | string |
Inline message id |
chatId | number/string |
Target Chat id |
messageId | number/string |
Message id |
[editMessage] | boolean |
edit target message, default value is True |
[force] | boolean |
Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters |
Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects.
telegram.getGameHighScores(userId, inlineMessageId, chatId, messageId) => Promise
Official documentation
Param | Type | Description |
---|---|---|
userId | number \ |
Target User id |
inlineMessageId | string |
Inline message id |
chatId | number/string |
Target Chat id |
messageId | number/string |
Message id |
Use this method to get information about a member of a chat.
telegram.getChatMember(chatId, userId) => Promise
Official documentation
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
userId | number |
User identifier |
Use this method to get the number of members in a chat.
telegram.getChatMembersCount(chatId) => Promise
Official documentation
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
Returns basic info about a file and prepare it for downloading.
telegram.getFile(fileId) => Promise
Official documentation
Param | Type | Description |
---|---|---|
fileId | string |
File id |
Returns link to file.
telegram.getFileLink(fileId) => Promise
Param | Type | Description |
---|---|---|
fileId | string/object |
File id or file object |
Returns basic information about the bot.
telegram.getMe() => Promise
Official documentation
Use this method to get the current list of the bot's commands. Requires no parameters. Returns Array of BotCommand on success.
telegram.getMyCommands() => Promise
Official documentation
Use this method to get a sticker set.
telegram.getStickerSet(name) => Promise
Param | Type | Description |
---|---|---|
name | string |
Short name of the sticker set |
Official documentation |
Returns profiles photos for provided user.
telegram.getUserProfilePhotos(userId, [offset], [limit]) => Promise
Official documentation
Param | Type | Description |
---|---|---|
userId | number |
Chat id |
[offset] | number |
Offset |
[limit] | number |
Limit |
Use this method to set default chat permissions for all members.
telegram.setChatPermissions(chatId, permissions) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
permissions | object |
New default chat permissions |
Use this method to kick a user from a group or a supergroup.
telegram.kickChatMember(chatId, userId, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
userId | number |
User id |
[extra] | object |
Extra parameters |
Use this method to restrict a user in a supergroup.
telegram.restrictChatMember(chatId, userId, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
userId | number |
User id |
[extra] | object |
Extra parameters |
Use this method to promote or demote a user in a supergroup or a channel.
telegram.promoteChatMember(chatId, userId, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
userId | number |
User id |
[extra] | object |
Extra parameters |
New custom title for the administrator; 0-16 characters, emoji are not allowed
telegram.setChatAdministratorCustomTitle(chatId, userId, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
userId | number |
User id |
title | string |
Custom title |
Use this method to export an invite link to a supergroup or a channel.
telegram.exportChatInviteLink(chatId) => Promise
Official documentation
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
Use this method to set a new profile photo for the chat.
telegram.setChatPhoto(chatId, photo) => Promise
Official documentation
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
photo | File |
New chat photo |
Use this method to delete a chat photo.
telegram.deleteChatPhoto(chatId) => Promise
Official documentation
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
Use this method to change the title of a chat.
telegram.setChatTitle(chatId, title) => Promise
Official documentation
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
title | string |
New chat title, 1-255 characters |
Use this method to change the description of a supergroup or a channel.
telegram.setChatDescription(chatId, description) => Promise
Official documentation
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
description | string |
New chat description, 0-255 characters |
Use this method to set a new group sticker set for a supergroup.
telegram.setChatStickerSet(chatId, stickerSetName) => Promise
Official documentation
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
stickerSetName | string |
Name of the sticker set |
Use this method to pin a message in a supergroup.
telegram.pinChatMessage(chatId, messageId, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
messageId | number |
Message id |
[extra] | object |
Extra parameters |
Use this method to unpin a message in a supergroup chat.
telegram.unpinChatMessage(chatId) => Promise
Official documentation
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
Use this method for your bot to leave a group, supergroup or channel.
telegram.leaveChat(chatId) => Promise
Official documentation
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
Removes webhook integration.
telegram.deleteWebhook() => Promise
Official documentation
Sends audio.
telegram.sendAudio(chatId, audio, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
audio | File |
Document |
[extra] | object |
Extra parameters |
Sends game.
telegram.sendGame(chatId, gameName, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
gameName | String |
Game short name |
[extra] | object |
Extra parameters |
Sends chat action.
telegram.sendChatAction(chatId, action) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
action | string |
Chat action |
Sends document.
telegram.sendContact(chatId, phoneNumber, firstName, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
phoneNumber | string |
Contact phone number |
firstName | string |
Contact first name |
[extra] | object |
Extra parameters |
Sends dice.
telegram.sendDice(chatId, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
[extra] | object |
Extra parameters |
Sends document.
telegram.sendDocument(chatId, doc, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
doc | File |
Document |
[extra] | object |
Extra parameters |
Sends location.
telegram.sendLocation(chatId, latitude, longitude, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
latitude | number |
Latitude |
longitude | number |
Longitude |
[extra] | object |
Extra parameters |
Sends text message.
telegram.sendMessage(chatId, text, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
text | string |
Message |
[extra] | object |
Extra parameters |
Sends photo.
telegram.sendPhoto(chatId, photo, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
photo | File |
Photo |
[extra] | object |
Extra parameters |
Sends media album.
telegram.sendMediaGroup(chatId, media, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
media | InputMedia[] |
Media array |
[extra] | object |
Extra parameters |
Sends sticker.
telegram.sendSticker(chatId, sticker, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
sticker | File |
Document |
[extra] | object |
Extra parameters |
Use this method to move a sticker in a set created by the bot to a specific position.
telegram.setStickerPositionInSet(sticker, position) => Promise
Param | Type | Description |
---|---|---|
sticker | string |
File identifier of the sticker |
position | number |
New sticker position in the set, zero-based |
Sends venue information.
telegram.sendVenue(chatId, latitude, longitude, title, address, [extra]) => Promise
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 invoice.
telegram.sendInvoice(chatId, invoice) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
invoice | object |
Invoice object |
Sends video.
telegram.sendVideo(chatId, video, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
video | File |
Document |
[extra] | object |
Extra parameters |
Sends video.
telegram.sendAnimation(chatId, animation, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
animation | File |
Document |
[extra] | object |
Extra parameters |
Sends round video.
telegram.sendVideoNote(chatId, video, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
video | File |
Video note file |
[extra] | object |
Extra parameters |
Sends voice.
telegram.sendVoice(chatId, voice, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
voice | File/string |
File, file id or HTTP URL |
[extra] | object |
Extra parameters |
Sends anonymous poll.
telegram.sendPoll(chatId, question, options, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
question | string |
Poll question |
options | string[] |
Answer options |
[extra] | object |
Extra parameters |
Use this method to change the list of the bot's commands
telegram.setMyCommands(commands) => Promise
Param | Type | Description |
---|---|---|
commands | object[] |
List of bot commands |
Sends quiz.
telegram.sendQuiz(chatId, question, options, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
question | string |
Poll question |
options | string[] |
Answer options |
[extra] | object |
Extra parameters |
Stops anonymous poll.
telegram.stopPoll(chatId, messageId, [extra]) => Promise
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
messageId | string |
Poll message id |
options | string[] |
Answer options |
[extra] | object |
Extra parameters |
Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires.
telegram.stopMessageLiveLocation(chatId, messageId, inlineMessageId, [markup]) => Promise
Official documentation
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
messageId | string |
Message id |
inlineMessageId | string |
Inline message id |
[markup] | object |
Keyboard markup |
Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods.
telegram.uploadStickerFile(ownerId, stickerFile) => Promise
Official documentation
Param | Type | Description |
---|---|---|
ownerId | string |
User identifier of sticker file owner |
stickerFile | File |
Png image with the sticker |
Specifies an url to receive incoming updates via an outgoing webhook.
telegram.setWebhook(url, [cert], [maxConnections], [allowedUpdates]) => Promise
Official documentation
Param | Type | Description |
---|---|---|
url | string |
Public url for webhook |
[cert] | File |
SSL public certificate |
[maxConnections] | number |
Maximum allowed number of simultaneous HTTPS connections to the webhook |
[allowedUpdates] | string[] |
List the types of updates you want your bot to receive |
Use this method to unban a previously kicked user in a supergroup.
telegram.unbanChatMember(chatId, userId) => Promise
Official documentation
Param | Type | Description |
---|---|---|
chatId | number/string |
Chat id |
userId | number |
User id |
Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change).
telegram.setPassportDataErrors(errors) => Promise
Official documentation
Param | Type | Description |
---|---|---|
[errors] | PassportElementError[] |
An array describing the errors |
Telegram message options helper, see examples.
Telegram markup helper, see examples.
Simple scene-based control flow middleware.
const { Telegraf } = require('telegraf')
const session = require('telegraf/session')
const Stage = require('telegraf/stage')
const Scene = require('telegraf/scenes/base')
const { leave } = Stage
// Greeter scene
const greeter = new Scene('greeter')
greeter.enter((ctx) => ctx.reply('Hi'))
greeter.leave((ctx) => ctx.reply('Bye'))
greeter.hears(/hi/gi, leave())
greeter.on('message', (ctx) => ctx.reply('Send `hi`'))
// Create scene manager
const stage = new Stage()
stage.command('cancel', leave())
// Scene registration
stage.register(greeter)
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.use(session())
bot.use(stage.middleware())
bot.command('greeter', (ctx) => ctx.scene.enter('greeter'))
bot.startPolling()
Scenes related context props and functions:
bot.on('message', (ctx) => {
ctx.scene.state // Current scene state (persistent)
ctx.scene.enter(sceneId, [defaultState, silent]) // Enter scene
ctx.scene.reenter() // Reenter current scene
ctx.scene.leave() // Leave scene
})