Skip to main content

EventHandler

The abstract EventHandler class is the foundation for building Telegram bots with MadelineProto. It provides a structured way to handle various types of updates from Telegram.

Overview

EventHandler allows you to:
  • Handle incoming messages, updates, and queries
  • Use filters to process specific update types
  • Schedule periodic tasks with cron attributes
  • Load plugins for modular functionality
  • Access all Telegram API namespaces

Basic Usage

use danog\MadelineProto\EventHandler;
use danog\MadelineProto\EventHandler\Message;

class MyEventHandler extends EventHandler
{
    public function onStart(): void
    {
        // Called when the event handler starts
        $this->logger("Bot started!");
    }

    public function onUpdateNewMessage(Message $message): void
    {
        // Handle new messages
        if ($message->message === '/start') {
            $message->reply("Hello! I'm a bot.");
        }
    }
}

Starting the Event Handler

startAndLoop

Start MadelineProto and the event handler with automatic error reporting.
session
string
required
Session name
settings
SettingsAbstract
Optional settings configuration
MyEventHandler::startAndLoop('session.madeline');

startAndLoopBot

Start as a bot with token authentication.
session
string
required
Session name
token
string
required
Bot token from @BotFather
settings
SettingsAbstract
Optional settings configuration
MyEventHandler::startAndLoopBot('bot.madeline', 'YOUR_BOT_TOKEN');

Lifecycle Methods

onStart

Called when the event handler starts. Use this for initialization.
public function onStart(): void
{
    $this->logger("Initializing bot...");
    // Your initialization code
}

onStop

Called when the event handler is being destroyed.
public function __destruct()
{
    // Cleanup code
}

Update Handlers

Handle specific update types by implementing methods with the pattern onUpdate{UpdateType}:
// Handle new messages
public function onUpdateNewMessage(Message $message): void { }

// Handle edited messages
public function onUpdateEditMessage(Message $message): void { }

// Handle channel posts
public function onUpdateNewChannelMessage(Message $message): void { }

// Handle any update type
public function onAny(\danog\MadelineProto\EventHandler\Update $update): void { }

Available Namespaces

EventHandler provides direct access to all Telegram API namespaces:
auth
\danog\MadelineProto\Namespace\Auth
Authentication methods
account
\danog\MadelineProto\Namespace\Account
Account management
users
\danog\MadelineProto\Namespace\Users
User-related methods
contacts
\danog\MadelineProto\Namespace\Contacts
Contact management
messages
\danog\MadelineProto\Namespace\Messages
Message operations
channels
\danog\MadelineProto\Namespace\Channels
Channel management
bots
\danog\MadelineProto\Namespace\Bots
Bot-specific methods
photos
\danog\MadelineProto\Namespace\Photos
Photo operations
upload
\danog\MadelineProto\Namespace\Upload
File upload methods

Plugin System

getPluginPaths

Specify paths to recursively search for plugins.
return
string|array<string>|null
Path(s) containing plugin files (ending with Plugin.php)
public static function getPluginPaths(): string|array|null
{
    return __DIR__ . '/plugins';
}

getPlugins

Return a list of plugin event handler classes.
return
array<class-string>
Array of plugin class names
public static function getPlugins(): array
{
    return [
        \MyBot\Plugins\AdminPlugin::class,
        \MyBot\Plugins\StatsPlugin::class,
    ];
}

Error Reporting

getReportPeers

Specify peers where error reports should be sent.
return
string|int|array<string|int>
Peer(s) to receive error reports
public function getReportPeers(): string|int|array
{
    return '@admin'; // Username, user ID, or array of peers
}

Periodic Tasks

getPeriodicLoop

Obtain a PeriodicLoop instance created by the Cron attribute.
name
string
required
Method name
return
PeriodicLoop|null
The periodic loop instance or null
$loop = $this->getPeriodicLoop('myTask');

getPeriodicLoops

Obtain all PeriodicLoop instances.
return
array<string, PeriodicLoop>
Array of periodic loops indexed by method name
$loops = $this->getPeriodicLoops();

Database Properties

internalSaveDbProperties

Save database properties.
$this->internalSaveDbProperties();

internalClearDbProperties

Clear all database properties.
$this->internalClearDbProperties();

Example: Complete Bot

use danog\MadelineProto\EventHandler;
use danog\MadelineProto\EventHandler\Message;
use danog\MadelineProto\EventHandler\SimpleFilter\Incoming;

class MyBot extends EventHandler
{
    public function onStart(): void
    {
        $this->logger("Bot is running!");
    }

    #[Incoming]
    public function handleIncoming(Message $message): void
    {
        $text = $message->message;
        
        match($text) {
            '/start' => $message->reply('Welcome!'),
            '/help' => $message->reply('Available commands: /start, /help'),
            default => null
        };
    }
    
    public function getReportPeers(): string
    {
        return '@admin_username';
    }
}

MyBot::startAndLoopBot('bot.madeline', 'YOUR_BOT_TOKEN');

See Also

Build docs developers (and LLMs) love