PHP code example of protobrick / mtproto-client

1. Go to this page and download the library: Download protobrick/mtproto-client library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

protobrick / mtproto-client example snippets


 //auth.php
MTProtoClient\Client;
use ProtoBrick\MTProtoClient\Settings;

// Get your api_id and api_hash from https://my.telegram.org
$settings = new Settings(
    api_id: 12345,
    api_hash: 'your_api_hash'
);

// Session files will be stored in 'session_name' folder
$client = Client::create($settings, __DIR__ . '/session_name');
$auth = $client->login();
$client->logger->info("Logged in as {$auth->user->firstName}\n");

$auth = $client->login(
    phoneNumber: '+1234567890',
    codeProvider: fn() => readline("Code: "),      // Or fetch from DB/API
    passwordProvider: fn() => readline("2FA: "),   // Or fetch from DB/API
    signupProvider: fn() => [readline("Name: "), readline("Last Name: ")]
);


ProtoBrick\MTProtoClient\Client;
use ProtoBrick\MTProtoClient\Settings;

$settings = new Settings(api_id: 12345, api_hash: 'hash');
$client = Client::create($settings, __DIR__. '/session_name');

$client->channels->joinChannel(channel: "@ProtoBrickChat");
$client->messages->sendMessage(
    peer: "@ProtoBrickChat", //auto-resolve peer
    message: 'Hello from ProtoBrick!'
);


ProtoBrick\MTProtoClient\Client;
use ProtoBrick\MTProtoClient\Settings;
use ProtoBrick\MTProtoClient\Event\MessageContext;
use ProtoBrick\MTProtoClient\Event\ServiceMessageContext;
// Import specific TL types if you need raw checks
use ProtoBrick\MTProtoClient\Generated\Types\Base\MessageActionChatCreate;
use ProtoBrick\MTProtoClient\Generated\Types\Base\MessageMediaPhoto;
use ProtoBrick\MTProtoClient\Generated\Types\Base\UpdateUserTyping;
use ProtoBrick\MTProtoClient\TL\TlObject;

$settings = new Settings(api_id: 12345, api_hash: 'hash');
$client = Client::create($settings, __DIR__. '/session_name');

// Handle New Messages
$client->onMessage(function (MessageContext $ctx) {
    // Ignore own messages
    if ($ctx->isOutgoing()) return;

    // High-level helpers
    // (See src/Event/MessageContext.php & AbstractMessageContext.php)
    if ($ctx->getText() === '/ping') {
        $ctx->reply("Pong! 🏓");
        $ctx->react('👍');
        return;
    }

    // Low-level access
    // Check for media types, via_bot_id, reply_markup, etc. directly
    if ($ctx->message->media instanceof MessageMediaPhoto) {
    
        echo "Received a photo with caption: " . $ctx->getText();
    }
});

// Handle Edited Messages
$client->onMessageEdit(function (MessageContext $ctx) {
    echo "EDIT in chat {$ctx->getChatId()}: {$ctx->getText()}\n";
});

// Handle Service Messages (Joins, Leaves, Title Changes)
$client->onServiceMessage(function (ServiceMessageContext $ctx) {
    // High-level helpers
    // (See src/Event/ServiceMessageContext.php & AbstractMessageContext.php)
    if ($ctx->isTitleChanged()) {
        echo "Chat {$ctx->getChatId()} renamed to: {$ctx->getNewTitle()}\n";
    }
    
    // Low-level access
    // Handle specific actions that don't have wrappers yet
    if ($ctx->message->action instanceof MessageActionChatCreate) {
        echo "Group created with title: " . $ctx->message->action->title;
    }
});

// Handle Raw Updates (Typing, Status, Read Receipts)
$client->onUpdate(function (TlObject $update) {
    // Catches ALL updates flowing from the server
    if ($update instanceof UpdateUserTyping) {
        echo "User {$update->userId} is typing...\n";
    }
});

// Start the Event Loop (Blocks execution)
$client->start();

use function Amp\Future\await;

// 🐢 Synchronous (Blocking)
// Execution stops here until the channel is joined.
$client->channels->joinChannel('@ProtoBrickChat');

// 🚀 Concurrent (Parallel)
// Send multiple requests at once. Total time = time of the slowest request.
$futures = [];
foreach (['@Chat1', '@Chat2', '@Chat3'] as $chat) {
    // Returns Amp\Future immediately without waiting
    $futures[] = $client->channels->joinChannelAsync($chat);
}

// Wait for ALL requests to complete
await($futures);
echo "Joined all chats!";

// The code continues immediately, the request is sent in the background
$client->messages->sendMessageAsync(
    peer: 'me', message: 'Background log entry', 
)->ignore();

use ProtoBrick\MTProtoClient\Transport\TransportProtocol;

$settings = new Settings(
    api_id: ...,
    api_hash: ...,
    server_address: '149.154.167.50', // Custom DC IP
    transport: TransportProtocol::PaddedIntermediate, // Obfuscation
    connect_timeout_seconds: 10
);
bash
   php bin/build.php
   
bash
php bin/build.php schema/TL_old_v199.json