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.
Create an event handler by extending SimpleEventHandler:
use danog\MadelineProto\SimpleEventHandler;use danog\MadelineProto\EventHandler\Attributes\Handler;use danog\MadelineProto\EventHandler\Message;use danog\MadelineProto\EventHandler\SimpleFilter\Incoming;class MyBot extends SimpleEventHandler{ #[Handler] public function handleMessage(Incoming&Message $message): void { $message->reply('Hello! You said: ' . $message->message); }}// Start the botMyBot::startAndLoop('bot.madeline');
From SimpleEventHandler.php:26, this class provides access to filters and the simplified API.
use danog\MadelineProto\EventHandler\Filter\FilterCommand;#[FilterCommand('start')]public function startCommand(Message $message): void{ $message->reply('Welcome!');}#[FilterCommand('help')]public function helpCommand(Message $message): void{ $message->reply('Here is the help text...');}
use danog\MadelineProto\EventHandler\Message;use danog\MadelineProto\EventHandler\Message\PrivateMessage;use danog\MadelineProto\EventHandler\Message\GroupMessage;use danog\MadelineProto\EventHandler\Message\ChannelMessage;#[Handler]public function handlePrivate(PrivateMessage $message): void{ // Only private messages}#[Handler]public function handleGroup(GroupMessage $message): void{ // Only group messages}#[Handler]public function handleChannel(ChannelMessage $message): void{ // Only channel posts}
use danog\MadelineProto\EventHandler\Message\ServiceMessage;use danog\MadelineProto\EventHandler\Message\Service\DialogPhotoChanged;#[Handler]public function photoChanged(DialogPhotoChanged $message): void{ if ($message->photo) { $message->reply('New photo set!'); }}
Schedule periodic tasks using the #[Cron] attribute:
use danog\MadelineProto\EventHandler\Attributes\Cron;#[Cron(period: 60.0)]public function everyMinute(): void{ $this->sendMessageToAdmins('Minute passed!');}#[Cron(period: 3600.0)]public function hourlyTask(): void{ // Cleanup or maintenance tasks}
From EventHandler/Attributes/Cron.php:25, the period is in seconds.
// Get a specific periodic loop$loop = $this->getPeriodicLoop('everyMinute');if ($loop) { $loop->stop(); $loop->start();}// Get all periodic loops$loops = $this->getPeriodicLoops();
From EventHandler.php:371, these methods manage cron jobs created by the #[Cron] attribute.