store telegram profile picture in laravel - Gianguyen1234/app-doc GitHub Wiki

Storing Telegram Profile Pictures in Laravel 📸

How It Works:

  • Fetch user profile pictures from Telegram
  • Save them in Laravel storage
  • Display profile pictures in your web app

1️⃣ Step 1: Get User Profile Picture

Modify TelegramService.php:

public function getUserProfilePhoto($telegramUserId)
{
    $url = "https://api.telegram.org/bot" . env('TELEGRAM_BOT_TOKEN') . "/getUserProfilePhotos?user_id=" . $telegramUserId;

    $response = Http::get($url);
    $photos = $response->json();

    if (!empty($photos['result']['photos'])) {
        // Get the latest profile picture
        $fileId = $photos['result']['photos'][0][0]['file_id'];
        return $this->downloadTelegramFile($fileId);
    }

    return null;
}

Now we can fetch the user’s profile photo ID!


2️⃣ Step 2: Download the Image from Telegram

Modify TelegramService.php:

public function downloadTelegramFile($fileId)
{
    // Get File Path from Telegram API
    $filePathUrl = "https://api.telegram.org/bot" . env('TELEGRAM_BOT_TOKEN') . "/getFile?file_id=" . $fileId;
    $fileResponse = Http::get($filePathUrl);
    $fileData = $fileResponse->json();

    if (!isset($fileData['result']['file_path'])) {
        return null;
    }

    // Construct Download URL
    $downloadUrl = "https://api.telegram.org/file/bot" . env('TELEGRAM_BOT_TOKEN') . "/" . $fileData['result']['file_path'];

    // Download & Save File in Storage
    $fileContents = file_get_contents($downloadUrl);
    $fileName = "profile_pics/" . uniqid() . ".jpg";
    Storage::disk('public')->put($fileName, $fileContents);

    return Storage::url($fileName);
}

Now the bot downloads and saves the image in Laravel storage! 🎉


3️⃣ Step 3: Store Profile Picture in Database

Modify database/migrations/xxxx_create_telegram_users_table.php:

Schema::table('telegram_users', function (Blueprint $table) {
    $table->string('profile_pic')->nullable();
});

Run the migration:

php artisan migrate

Modify TelegramService.php:

public function updateUserProfilePhoto($telegramData)
{
    $photoUrl = $this->getUserProfilePhoto($telegramData['id']);

    if ($photoUrl) {
        TelegramUser::where('telegram_id', $telegramData['id'])
            ->update(['profile_pic' => $photoUrl]);
    }
}

Now, every user’s profile picture is saved! 🖼️


4️⃣ Step 4: Display Profile Picture in Blade

Modify profile.blade.php:

<img src="{{ $user->profile_pic ?? '/images/default-avatar.png' }}" class="rounded-circle" width="100" height="100">

Now, the user’s Telegram profile picture is shown in your app! 🎨


🔥 Final Test

User sends a message → Bot fetches their profile pic
Saves image in storage/app/public/profile_pics/
Displays the profile picture in Laravel Blade