PHP code example of gimucco / bluesky-php

1. Go to this page and download the library: Download gimucco/bluesky-php 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/ */

    

gimucco / bluesky-php example snippets


use Gimucco\Bluesky\Client;
use Gimucco\Bluesky\EmbeddedImage;

$client = new Client($session);   // session restored from atproto-php OAuth flow

$client->post('Hello world');
$client->post('With image', images: [new EmbeddedImage($blob, alt: 'A sunset')]);
$client->postVideo('Watch this', $videoBytes, alt: 'A clip');   // upload + await + post
$client->thread('First', 'Second', 'Third');
$client->reply($parentUri, $parentCid, 'Great post!');
$client->like($postUri, $postCid);
$client->follow('alice.bsky.social');           // handle auto-resolved to DID
$client->block('did:plc:troll');
$me = $client->myProfile();
$post = $client->getPost($uri);

use Gimucco\Bluesky\Client;

$client = new Client($session);   // see "OAuth setup" below for how to get $session
$client->post('Hello from bluesky-php!');

use Gimucco\Atproto\ClientConfig;
use Gimucco\Atproto\OAuthClient;
use Gimucco\Atproto\Storage\FileSessionStore;
use Gimucco\Atproto\Storage\FileStateStore;
use Gimucco\Bluesky\Client;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Psr7\HttpFactory;

$factory = new HttpFactory();
$oauth = new OAuthClient(
    config: new ClientConfig(
        clientId: 'https://your-app.com/atproto/client-metadata.json',
        redirectUri: 'https://your-app.com/atproto/callback',
        scope: 'atproto transition:generic',
        clientName: 'My Bluesky App',
        jwksUri: 'https://your-app.com/atproto/jwks.json',
        privateKey: file_get_contents('/secure/private.pem'),
        encryptionPassphrase: getenv('ATPROTO_PASSPHRASE'),
    ),
    sessionStore: new FileSessionStore('/var/app/sessions', getenv('ATPROTO_PASSPHRASE')),
    stateStore: new FileStateStore('/var/app/states', getenv('ATPROTO_PASSPHRASE')),
    httpClient: new GuzzleClient(['timeout' => 30]),
    requestFactory: $factory,
    streamFactory: $factory,
);

$session = $oauth->restoreSession('did:plc:abc123');
if ($session === null) {
    throw new RuntimeException('No stored session — user must complete OAuth flow first');
}

$client = new Client($session);

$ref = $client->post('Hello world');
echo $ref->uri;

$ref = $client->reply(
    parentUri: $parentUri,
    parentCid: $parentCid,
    text: 'Great take!',
);

$refs = $client->thread(
    'First post in the thread ๐Ÿงต',
    'Second post (auto-replies to the first)',
    'Third post (auto-replies to the second, root remains the first)',
);

$client->setDefaultThreadDelay(2)->thread('First', 'Second', ...);

use Gimucco\Bluesky\{
    EmbeddedImage, EmbeddedVideo, EmbeddedExternal,
    EmbeddedRecord, EmbeddedRecordWithMedia,
};

// Images (up to 4 — alt text strongly recommended for accessibility)
$client->post('caption', images: [
    new EmbeddedImage($blob, alt: 'A sunset over the ocean'),
]);

// Video (after upload + awaitVideo)
$client->post('Watch this', video: new EmbeddedVideo($videoBlob, alt: '...'));

// Link card (with optional thumbnail blob)
$client->post('Worth a read:', external: new EmbeddedExternal(
    uri: 'https://example.com/article',
    title: 'Article title',
    description: 'Card description',
    thumb: $thumbnailBlob,    // optional
));

// Quote post
$client->post('Look at this ๐Ÿ‘‡', quoting: new EmbeddedRecord($postUri, $postCid));

// Quote with media (images OR video)
$client->post('My take, with proof:', quoting: new EmbeddedRecordWithMedia(
    record: new EmbeddedRecord($postUri, $postCid),
    images: [new EmbeddedImage($blob, alt: 'screenshot')],
));

$blob = $client->uploadImage(file_get_contents('photo.jpg'));   // MIME auto-detected
$blob = $client->uploadImage($bytes, 'image/webp');             // explicit MIME

// One-shot: upload + await + post.
$ref = $client->postVideo('Watch this', $bytes, alt: 'A clip');

// Returns a BlobRef — for reuse (same video on multiple posts, retries, recordWithMedia, etc.)
$blob = $client->uploadVideo($bytes);
$client->post('Watch this', video: new EmbeddedVideo($blob, alt: '...'));
$client->reply($parent, $cid, 'see this', video: new EmbeddedVideo($blob));

// Lowest level: drive the upload + poll loop yourself.
$job = $client->video->uploadVideo($bytes);
$blob = $client->awaitVideo($job->jobStatus->jobId, timeoutSeconds: 60);

$client->like($postUri, $postCid);          // returns LikeRef
$client->unlike($likeRef);                  // accepts string|AtUri|LikeRef (Stringable)

$client->repost($postUri, $postCid);
$client->unrepost($repostRef);

$client->follow('alice.bsky.social');       // resolves handle → DID, then follows
$client->follow('did:plc:abc');             // direct, no resolution call
$client->follow(new Did('did:plc:abc'));    // typed
$client->unfollow($followRef);

$client->block('did:plc:troll');            // returns BlockRef
$client->unblock($blockRef);

$client->mute('spammer.bsky.social');
$client->unmute('spammer.bsky.social');

$me = $client->myProfile();                          // ProfileViewDetailed
$them = $client->actor->getProfile('alice.bsky.social');

$post = $client->getPost('at://did:plc:.../app.bsky.feed.post/abc');  // throws NotFoundException if missing

// Iterate the timeline (auto-pages)
foreach ($client->feed->paginateTimeline(limit: 50, maxItems: 200) as $item) {
    echo $item->post->author->handle.': '.$item->post->record['text']."\n";
}

foreach ($client->feed->paginateTimeline() as $item) { /* ... */ }
foreach ($client->graph->paginateFollowers('alice.bsky.social') as $follower) { /* ... */ }
foreach ($client->notification->paginateNotifications() as $notif) { /* ... */ }

use Gimucco\Bluesky\Pager;

$items = Pager::iterate(
    fetch: fn(?string $cursor) => [
        ($r = $client->feed->getTimeline(cursor: $cursor))->feed,
        $r->cursor,
    ],
    maxItems: 500,
);

use Gimucco\Bluesky\{Did, Handle, AtUri};

$did = new Did('did:plc:abc123');
$client->follow($did);

$uri = new AtUri('at://did:plc:alice/app.bsky.feed.post/abc');
echo $uri->authority;    // did:plc:alice
echo $uri->collection;   // app.bsky.feed.post
echo $uri->rkey;         // abc

$h = new Handle('@alice.bsky.social');   // strips leading @
echo $h->value;                           // alice.bsky.social

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$logger = new Logger('bluesky');
$logger->pushHandler(new StreamHandler('php://stderr'));

$client = new Client($session, $logger);

use Gimucco\Bluesky\Exception\{
    BlueskyException,            // base class
    ApiException,                // catch-all for HTTP errors
    NotFoundException,           // 404
    RateLimitException,          // 429 — exposes ->retryAfter (DateTimeImmutable|null)
    ValidationException,         // 400 from API
    AuthException,               // 401, 403
    ServerException,             // 5xx
    LexiconException,            // malformed response from server
    InvalidArgumentException,    // bad input to this library (distinct from API 400)
};

try {
    $client->getPost($uri);
} catch (NotFoundException $e) {
    // handle "not found"
} catch (RateLimitException $e) {
    sleep((int) ($e->retryAfter?->getTimestamp() - time() ?? 60));
    // retry...
} catch (ApiException $e) {
    // any other HTTP error
    error_log("Bluesky {$e->status}: {$e->error} — {$e->getMessage()}");
}