Bot class is the single most important class in grammY. It represents your bot and provides methods for handling updates, registering middleware, and managing the bot’s lifecycle.
Constructor
Creates a new Bot instance with the given token.string
required
The bot’s token as acquired from @BotFather
BotConfig<C>
Optional configuration properties for the bot
Example
Properties
string
The bot’s authentication token (read-only)
Api
Full access to the Telegram Bot API. Use this to call any Bot API method.Note: Prefer using
ctx.api inside middleware when you have access to the context object.UserFromGetMe
Information about the bot itself as retrieved from
api.getMe(). Only available after the bot has been initialized via await bot.init(), or after a manual value has been set.Starting the bot will always perform initialization automatically unless a manual value is already set.ErrorHandler<C>
The bot’s error handler that is invoked whenever middleware throws an error. Set your own error handler via
bot.catch.Middleware Methods
use
Registers middleware that receives all updates.Middleware<C>
required
The middleware function(s) to register. Often used to install plugins like session middleware.
on
Registers middleware for specific update types using filter queries.FilterQuery | FilterQuery[]
required
The filter query (or array of queries) to match. Examples:
'message'- All message updates'message:text'- Only text messages'message:entities:url'- Messages with URL entities':text'- Text messages and channel posts['message:text', 'edited_message:text']- Multiple filters (OR)
Middleware<Filter<C, Q>>[]
required
Middleware function(s) to execute when the filter matches
command
Registers middleware for specific bot commands.string | string[]
required
The command(s) to match (without the leading
/)CommandMiddleware<C>[]
required
Middleware to execute when the command is found. The command arguments are available via
ctx.match.hears
Registers middleware for messages matching text or regular expressions.string | RegExp | Array<string | RegExp>
required
The text or regex pattern to match against message text or captions
HearsMiddleware<C>[]
required
Middleware to execute on match. For regex triggers,
ctx.match contains the RegExpMatchArray.reaction
Registers middleware for message reaction updates.ReactionTypeEmoji['emoji'] | ReactionType | Array
required
The reaction emoji or reaction type to match
message_reaction updates in allowed_updates for your bot to receive reaction updates.
Example:
callbackQuery
Registers middleware for callback queries (inline button presses).string | RegExp | Array<string | RegExp>
required
The callback data to match
chatType
Registers middleware for specific chat types.'private' | 'group' | 'supergroup' | 'channel' | Array
required
The chat type(s) to match
Running the Bot
start
Starts the bot using long polling.PollingOptions
Options for configuring long polling
- The returned Promise will never resolve except if your bot is stopped
- You don’t need to
awaitthe call tobot.start, but remember to catch potential errors viabot.catch - This uses simple long polling suitable for small to medium bots
- For high-load bots (>5K messages/hour) or bots with long-running operations, use
@grammyjs/runnerinstead
stop
Stops the bot from long polling.getUpdates calls will be performed. The current getUpdates request will be cancelled.
This method also confirms the last received update to the Telegram servers by calling getUpdates one last time with the latest offset value.
Example:
init
Initializes the bot by fetching bot information.AbortSignal
Optional
AbortSignal to cancel the initializationbot.botInfo before starting.
Example:
Utility Methods
catch
Sets the bot’s error handler for long polling.(error: BotError<C>) => unknown
required
Function that handles middleware errors. Receives a
BotError object containing both the error and the context.handleUpdate
Processes a single update object. This is an internal method used by grammY.Update
required
An update from the Telegram Bot API
WebhookReplyEnvelope
Optional webhook reply envelope for responding to webhook requests
- Writing a library on top of grammY
- Running the bot on webhooks
- Implementing custom update handling logic
isInited
Checks if the bot has been initialized.boolean
true if bot information is set, false otherwiseisRunning
Checks if the bot is currently running via built-in long polling.boolean
true if the bot is running, false otherwisebot.start(). It doesn’t reflect webhook server status or grammY runner status.
Advanced Methods
TheBot class inherits all methods from Composer, including:
filter()- Filter updates with custom predicatesdrop()- Inverse filteringfork()- Run middleware concurrentlylazy()- Generate middleware dynamicallyroute()- Branch between different middlewarebranch()- Conditional branchingerrorBoundary()- Install error boundaries
Complete Example
See Also
- Context - The context object passed to middleware
- Composer - Base class for composing middleware
- API Client - Making direct API calls
- Filter Queries - Documentation on filter query syntax