Bot class is the single most important class in grammY. It represents your bot and handles all communication with Telegram.
Creating a Bot
To create a bot, you need a bot token from @BotFather. Once you have your token, instantiate a newBot:
Configuration Options
TheBot constructor accepts optional configuration through the BotConfig interface:
Advanced options for the API client that connects to Telegram’s servers
Pre-initialize the bot with cached bot information to skip the initial
getMe call. Useful for serverless environments where you restart frequently.Pass a custom context class constructor to use instead of the default
Context classExample with Configuration
Bot API Access
The bot provides full access to the Telegram Bot API through theapi property:
Inside middleware, prefer using
ctx.api instead of bot.api. The context API has the same methods but may include additional features like webhook reply envelopes.Registering Middleware
TheBot class extends Composer, giving you access to all middleware registration methods:
Running Your Bot
grammY provides a simple built-in long polling method:start() method accepts options:
Number of updates to fetch per request (1-100)
Timeout in seconds for long polling
Array of update types to receive. If not specified, receives all updates except
chat_member, message_reaction, and message_reaction_count.Pass
true to drop all pending updates before startingCallback function executed after setup completes, before fetching updates. Receives
bot.botInfo as an argument.Example with Options
The built-in
bot.start() is designed for small to medium bots. For high-load production bots (>5K messages/hour), use the @grammyjs/runner package for better performance.Stopping the Bot
To gracefully stop long polling:- Cancel the current
getUpdatesrequest - Prevent further
getUpdatescalls - Confirm the last received update to Telegram
Bot Information
Access information about your bot through thebotInfo property:
Manual Initialization
If you’re not usingbot.start(), initialize the bot manually:
Error Handling
Set an error handler to catch errors in middleware:Update Processing
Handling Updates Manually
For webhooks or custom update sources, usehandleUpdate():
Update Flow
When an update arrives:- Bot creates a new
Apiinstance with the bot token - Bot constructs a
Contextobject with the update, API, and bot info - Bot runs the middleware stack with the context
- Any errors are caught and passed to the error handler
Lifecycle Methods
Check if Running
Check if Initialized
Default Update Types
By default, grammY requests these update types:Type Safety
TheBot class is generic, allowing custom context types:
Best Practices
Related
- Context - Learn about context objects
- Middleware - Understanding middleware
- Error Handling - Comprehensive error handling
- Filter Queries - Filtering updates efficiently