Overview
Event handlers are the core of MadelineProto bots. They allow you to react to updates (messages, button clicks, etc.) in an object-oriented, type-safe way.Basic Event Handler
Create an event handler by extendingSimpleEventHandler:
SimpleEventHandler.php:26, this class provides access to filters and the simplified API.
Handler Attributes
#[Handler]
Mark methods that should handle updates:EventHandler/Attributes/Handler.php:23, this attribute marks a method as an update handler.
Filter Attributes
Use filter attributes for specific update types:Event Handler Lifecycle
onStart
Called once when the event handler initializes:EventHandler.php:230, this method:
- Runs during initialization
- Cannot use
yield(must not be a generator) - Useful for setup tasks
onStop
Called when the event handler shuts down:Update Types
MadelineProto provides typed update classes:Message Updates
Service Messages
Other Update Types
Property Persistence
Properties are automatically persisted across restarts:examples/bot.php:88, properties returned by __sleep() are saved to the database.
Error Reporting
Configure where error reports are sent:examples/bot.php:98, this method returns peer(s) where errors should be reported.
Cron Jobs
Schedule periodic tasks using the#[Cron] attribute:
EventHandler/Attributes/Cron.php:25, the period is in seconds.
Managing Cron Jobs
EventHandler.php:371, these methods manage cron jobs created by the #[Cron] attribute.
Plugins
Extend functionality with plugins:examples/bot.php:117, plugins are event handlers that extend PluginEventHandler.
Plugin Paths
Load plugins from directories:EventHandler.php:410, plugin files must:
- End with
Plugin.php - Extend
PluginEventHandler - Be in the
MadelinePluginnamespace
Multiple Event Handlers
Run multiple bot instances simultaneously:API.php:410, this starts multiple instances with their respective handlers.
Advanced Patterns
Handling Broadcasts
examples/bot.php:192, broadcast progress updates are handled separately.
Database Properties
Use ORM annotations for database-backed properties:EventHandler.php:219, use ORM annotations instead of the deprecated $dbProperties.
Complete Example
Here’s a complete event handler with multiple features:Next Steps
Filters
Learn about powerful filtering mechanisms
Updates
Explore all available update types