Search by

pushinbr / pam-telegram-web

DavidWilliamBalbino

Persistent Telegram Web client for PHP on PAM: QR login, chats, history, messages and events from a real Telegram account, without Node.js or Puppeteer.

v0.3.1 2026-12-02 19:23 UTC

This package is auto-updated.

Last update: 2026-12-02 19:24:42 UTC


README

PAM Telegram Web

Your Telegram account, in persistent PHP.

PHP 8.5+ PAM Runtime Packagist CI License

Terminal QR · two-step password · chats · history · text, photos, videos and files · edit, delete, react, forward · groups · live events · full MTProto API

Documentation · Start here · Features · Architecture · Safety

A PHP client for a real Telegram user account (not a bot). PAM keeps the process alive, pam-browser drives Chrome/Chromium through the DevTools Protocol, and this library logs into Telegram Web and gives you typed chats, messages and events, plus every method of the Telegram API through the web client's own connection. No Node.js, no Puppeteer and no api_id needed.

Terminal: logged in as Alex Doe, recent chats with unread counts and live messages, one answered with pong

Building a bot instead? Use pushinbr/pam-telegram.

Start here

1. Install PAM

curl --proto '=https' --proto-redir '=https' --tlsv1.2 \
    --connect-timeout 15 --max-time 60 --max-filesize 1048576 -fsSL \
    https://pamphp.com/install | sh

pam doctor

2. Create your project and install the library

mkdir my-telegram && cd my-telegram
pam composer init --no-interaction
pam composer require pushinbr/pam-telegram-web:^0.3

Chrome or Chromium must be installed on the host.

3. Create listen.php

<?php

declare(strict_types=1);

require __DIR__.'/vendor/autoload.php';

use Pam\TelegramWeb\Client;
use Pam\TelegramWeb\Event\MessageReceived;
use Pam\TelegramWeb\Event\QrCodeReceived;
use Pam\TelegramWeb\Event\Ready;

$client = new Client();

$client->onQrCode(static function (QrCodeReceived $event): void {
    echo "\033[2J\033[H"; // a new QR replaces the old one every ~30 s
    echo "Open Telegram on your phone > Settings > Devices > Link Desktop Device\n\n";
    echo $event->terminal(), "\n";
});

$client->onPasswordRequired(static function () use ($client): void {
    echo "\nTwo-step verification password: ";
    system('stty -echo');
    $password = fgets(STDIN);
    system('stty echo');
    echo "\n";
    if ($password !== false) {
        $client->submitPassword(rtrim($password, "\r\n"));
    }
});

$client->onReady(static function (Ready $event) use ($client): void {
    echo "✓ Telegram connected as {$event->me?->name()}\n\nRecent chats:\n";
    foreach ($client->getChats(10) as $chat) {
        printf("  %-8s %3d unread  %s\n", $chat->type->value, $chat->unreadCount, $chat->title);
    }
    echo "\nWaiting for messages… (Ctrl+C to stop)\n";
});

$client->onMessage(static function (MessageReceived $event): void {
    $message = $event->message;
    echo "[{$message->chatTitle}] {$message->fromName}: {$message->text}\n";

    if (!$message->outgoing && strtolower($message->text) === 'ping') {
        $message->reply('pong');
    }
});

$client->onLoggedOut(static function () use ($client): void {
    echo "Telegram ended this session. Run again to log in.\n";
    $client->stop();
});

try {
    $client->run();
} finally {
    $client->close();
}

4. Run it

pam listen.php

Terminal: login QR code with the steps scan, type your password, done

Scan the QR with your phone and type your two-step password if you have one. The login is saved in .pam-telegram-web/, so the next run connects directly. Ctrl+C stops the client and closes the browser.

What's included

Chats and history

foreach ($client->getChats(50) as $chat) {          // most recent first
    $chat->id;          // users > 0, groups and channels < 0
    $chat->type;        // ChatType::Private, Bot, Group, Channel
    $chat->title; $chat->username; $chat->unreadCount; $chat->pinned;
    $chat->lastMessage?->text;
}

$messages = $client->getMessages($chatId, 20);      // newest first
$messages[0]->text; $messages[0]->fromName; $messages[0]->outgoing; $messages[0]->hasMedia;

Send

$sent = $client->sendMessage($chatId, 'Hello!');          // returns the sent Message
$client->sendMessage($chatId, 'Quiet one', ['silent' => true, 'noWebpage' => true]);
$chat->sendMessage('Hello!');
$message->reply('Got it');

Messages are sent by Telegram Web itself, so they appear on all your devices.

Photos, videos and files

$client->sendFile($chatId, __DIR__.'/invoice.pdf', 'Your invoice');
$client->sendFile($chatId, 'photo.jpg', 'Look!');                      // sent as a photo
$client->sendFile($chatId, 'photo.jpg', '', ['asDocument' => true]);   // sent as a file
$client->sendFileContents($chatId, $pngBytes, 'chart.png');
$message->replyWithFile('report.csv');

if ($message->hasMedia) {
    $message->mediaType;                 // MediaType::Photo, Video, Voice, Document, Sticker…
    $message->fileName; $message->mimeType; $message->fileSize;
    $message->download()->saveTo(__DIR__.'/downloads');
}

JPEG, PNG and WebP go as photos and MP4/WebM as videos (Telegram shows a video without an audio track as a GIF). Files cross to the browser in 6 MB chunks; ClientOptions sets the time limit (fileTimeoutSeconds, 300 s) and the largest download (maxDownloadBytes, 100 MB).

Manage messages

$message->edit('Fixed typo');
$message->react('👍');            // null removes your reaction
$message->forwardTo($otherChatId);
$message->delete();               // for everyone, when Telegram allows it

$client->deleteMessages($chatId, [101, 102], forEveryone: false);
$client->forwardMessages($fromChatId, [101, 102], $toChatId, ['dropAuthor' => true]);
$client->markAsRead($chatId);
$client->sendChatAction($chatId, ChatAction::Typing);   // "typing…" for a few seconds

Groups and channels

$groupId = $client->createGroup('Release team', 'Deploy talk', [$aliceId]);  // a supergroup; users optional
$channelId = $client->createChannel('PAM News');
$link = $client->inviteLink($groupId);           // https://t.me/+…

$chatId = $client->join('@pam_news');           // or https://t.me/name or an invite link t.me/+AbC…
$members = $client->getMembers($chatId, 50);    // list<User>
$peerId = $client->resolveUsername('@someone');  // users > 0, groups and channels < 0
$client->leave($chatId);
$client->deleteChat($groupId);                   // a group or channel you own, for everyone

Events

Listener Fires when
onQrCode(fn (QrCodeReceived $e)) a new login QR is shown ($e->link, $e->terminal())
onPasswordRequired(fn (PasswordRequired $e)) the account has two-step verification; call submitPassword()
onReady(fn (Ready $e)) the account is logged in ($e->me)
onMessage(fn (MessageReceived $e)) a new message arrives in any chat, or you send one elsewhere
onMessageEdited(fn (MessageEdited $e)) a message is edited ($e->message)
onMessagesDeleted(fn (MessagesDeleted $e)) messages are deleted ($e->chatId, $e->messageIds)
onLoggedOut(fn (LoggedOut $e)) the session was ended (by you, another device or Telegram)
onError(fn (ErrorOccurred $e)) a listener threw; with this registered, run() keeps going

Drive the loop with run(), or with initialize() + pump($seconds) inside your own loop. waitUntilReady() blocks until the login is done.

The whole Telegram API

invoke() calls any Telegram API method with your account, through the web client's connection:

$client->invoke('contacts.getContacts', ['hash' => 0]);
$client->invoke('messages.search', [
    'peer' => $client->inputPeer($chatId),
    'q' => 'invoice',
    'filter' => ['_' => 'inputMessagesFilterEmpty'],
    'min_date' => 0, 'max_date' => 0, 'offset_id' => 0, 'add_offset' => 0,
    'limit' => 20, 'max_id' => 0, 'min_id' => 0, 'hash' => 0,
]);

Results are Telegram's own objects as arrays. Pass bytes as ['$bytes' => base64] and 64-bit integers as ['$long' => '123'].

Several accounts

Each account is one session directory. Drive them from one loop with pump():

$accounts = [
    'sales' => new Client(new ClientOptions(sessionDirectory: __DIR__.'/.sessions/sales')),
    'support' => new Client(new ClientOptions(sessionDirectory: __DIR__.'/.sessions/support')),
];
foreach ($accounts as $name => $client) {
    $client->onMessage(fn (MessageReceived $e) => print "[{$name}] {$e->message->text}\n");
}
while (true) {
    foreach ($accounts as $client) {
        $client->pump(0.2);
    }
}

Each account runs its own headless Chrome.

Options

new Client(new ClientOptions(
    sessionDirectory: __DIR__.'/.sessions/main', // one directory per account
    headless: true,
    browserExecutable: null,                     // auto-detected
    requestTimeoutSeconds: 30,
    fileTimeoutSeconds: 300,
    maxDownloadBytes: 100 * 1024 * 1024,
));

Testing

Unit tests replace the browser with a fake Session (tests/Support/FakeSession.php); do the same in your application.

pam composer verify            # PHPStan level 9 + PHPUnit
pam tests/integration/qr.php   # opens Telegram Web and decodes a login QR
pam tests/integration/enroll.php  # interactive login, then lists chats
PAM_TGW_SESSION=.pam-telegram-web/session pam tests/integration/live.php
                               # every operation, in your Saved Messages only; deletes what it sent
PAM_TGW_SESSION=.pam-telegram-web/session pam tests/integration/group.php
                               # creates a group with only you and tests media, edits, invite link, leave/join

Architecture

your PHP code
      │
      ▼
PAM Telegram Web ── typed chats, messages and events
      │
      ▼
PAM Browser ─────── Chrome DevTools Protocol
      │
      ▼
Chrome / Chromium ─ Telegram Web (web.telegram.org/k) ── MTProto ── Telegram

The bridge reads the login QR from the page and decodes it in PHP, follows the web client's events, and calls its API layer. Telegram Web does the protocol, encryption and storage.

Responsible use

  • The session directory is your account. Anyone who copies it can read and send your messages. It is created with 0700 permissions; keep it out of Git and backups you do not control, and log out ($client->logout()) when done.
  • This is an unofficial library and is not affiliated with Telegram. Telegram may change Telegram Web at any time, and limits or bans accounts that send spam or bulk messages. Only message people who expect it.
  • For bots and official automation, use the Bot API (pushinbr/pam-telegram).

License

Open source under the Apache License 2.0. You may use, modify, and distribute it, including commercially. See NOTICE.