Build modular event handlers with MadelineProto’s plugin architecture
MadelineProto provides a powerful plugin system that allows you to create modular, reusable event handlers. Plugins extend the PluginEventHandler class and are automatically loaded from specified directories.
Plugins extend the PluginEventHandler class and must have filenames ending with Plugin.php.
namespace MadelinePlugin\YourNamespace;use danog\MadelineProto\EventHandler\Filter\FilterCommand;use danog\MadelineProto\EventHandler\Message;use danog\MadelineProto\EventHandler\SimpleFilter\Incoming;use danog\MadelineProto\EventHandler\SimpleFilter\FromAdmin;use danog\MadelineProto\PluginEventHandler;class PingPlugin extends PluginEventHandler{ private int $pingCount = 0; private string $pongText = 'pong'; /** * Properties returned by __sleep are automatically stored in the database. */ public function __sleep(): array { return ['pingCount', 'pongText']; } /** * Initialization logic. */ public function onStart(): void { $this->logger("Plugin started!"); $this->sendMessageToAdmins("The ping plugin is online!"); } /** * Control whether the plugin is enabled. */ public function isPluginEnabled(): bool { return true; } #[FilterCommand('ping')] public function pingCommand(Incoming&Message $message): void { $message->reply($this->pongText); $this->pingCount++; }}
Specify plugin directories in your base event handler:
use danog\MadelineProto\SimpleEventHandler;class BaseHandler extends SimpleEventHandler{ /** * Return a path or array of paths to plugin directories. */ public static function getPluginPaths(): array|string|null { return 'plugins/'; // Or return an array for multiple directories: // return ['plugins/', 'vendor/yourname/plugins/']; }}// Start your bot with the base handlerBaseHandler::startAndLoop('bot.madeline', $settings);
Plugins support periodic tasks using the #[Cron] attribute:
use danog\MadelineProto\EventHandler\Attributes\Cron;class MonitorPlugin extends PluginEventHandler{ #[Cron(period: 60.0)] public function everyMinute(): void { $this->sendMessageToAdmins("Status check: All systems operational"); } #[Cron(period: 3600.0)] public function everyHour(): void { // Cleanup, stats, etc. }}
Control plugin activation based on runtime conditions:
class OnlinePlugin extends PluginEventHandler{ public function isPluginEnabled(): bool { // Only enable for user accounts (not bots) return $this->getSelf()['bot'] === false; }}
use danog\MadelineProto\EventHandler\Plugin\RestartPlugin;class MyHandler extends SimpleEventHandler{ public static function getPlugins(): array { return [RestartPlugin::class]; }}
This provides a /restart command for admins to restart the bot and apply changes.