What is a Context?
A context object does two main things:- Holds the update - Access the raw update via
ctx.update - Provides API shortcuts - Call Bot API methods with pre-filled parameters
Context Properties
Every context object has these core properties:Update
The complete update object from Telegram
Api
The Bot API instance for making API calls
UserFromGetMe
Information about your bot
string | RegExpMatchArray | undefined
Populated by methods like
hears(), command(), and callbackQuery() with matched contentUpdate Shortcuts
Instead of accessingctx.update.message, use convenient shortcuts:
Direct Update Properties
Aggregation Shortcuts
These shortcuts intelligently aggregate data from multiple possible sources:ctx.msg
Get the message from wherever it appears in the update:
ctx.chat
Get the chat from wherever possible:
ctx.from
Get the user who triggered the update:
Other Aggregations
Chat | undefined
The sender chat from
ctx.msg?.sender_chatnumber | undefined
Message ID from
ctx.msg, ctx.messageReaction, or ctx.messageReactionCountnumber | undefined
Chat ID from
ctx.chat?.id or ctx.businessConnection?.user_chat_idstring | undefined
Inline message ID from
ctx.callbackQuery or ctx.chosenInlineResultstring | undefined
Business connection ID from various business-related updates
API Shortcuts
Context provides convenient methods that are shortcuts toctx.api.* with pre-filled parameters.
Sending Messages
ctx.reply()
Reply to the current chat:
ctx.replyWithPhoto()
Other Reply Methods
ctx.replyWithAudio()- Send audio filesctx.replyWithDocument()- Send documentsctx.replyWithVideo()- Send videosctx.replyWithAnimation()- Send animations/GIFsctx.replyWithVoice()- Send voice messagesctx.replyWithVideoNote()- Send video notesctx.replyWithSticker()- Send stickersctx.replyWithDice()- Send dicectx.replyWithPoll()- Send pollsctx.replyWithLocation()- Send locationsctx.replyWithVenue()- Send venuesctx.replyWithContact()- Send contactsctx.replyWithInvoice()- Send invoicesctx.replyWithGame()- Send games
Forwarding and Copying
ctx.forwardMessage()
ctx.copyMessage()
Message Editing
Callback Query Handling
User and Chat Actions
Helper Methods
ctx.entities()
Extract entities from messages:
ctx.reactions()
Analyze reaction updates:
Context Predicates
Test if a context matches certain conditions:ctx.has()
Check if context matches a filter query:
Specialized Predicates
Static Predicates
Generate reusable predicate functions:Custom Context
Extend the context with your own properties:Custom Context Constructor
Create a custom context class:Type Narrowing
Filter queries automatically narrow context types:Context in Action
Here’s a complete example showing various context features:Best Practices
Related
- Middleware - How context flows through middleware
- Filter Queries - Filtering context objects
- Bot - The Bot class that creates contexts