Skip to content

Instantly share code, notes, and snippets.

@adactio
Created November 24, 2024 14:02
Show Gist options
  • Save adactio/ac776509693d7470828d0e3b51f6dc84 to your computer and use it in GitHub Desktop.
Save adactio/ac776509693d7470828d0e3b51f6dc84 to your computer and use it in GitHub Desktop.

Revisions

  1. adactio created this gist Nov 24, 2024.
    91 changes: 91 additions & 0 deletions postToBluesky.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,91 @@
    <?php

    /*
    Pass in an array of data that includes the text of the post and an access token e.g.
    postToBluesky(array(
    'text' => 'Hello World',
    'accessToken' => getBlueskyToken()
    ));
    Here's the gist for getting getBlueskyToken():
    https://gist.github.com/adactio/1a850920a0554a49f36daf79d776a440
    */

    function postToBluesky($data=array()) {

    $url = 'https://bsky.social/xrpc/com.atproto.repo.createRecord';

    $fields = array(
    'collection' => 'app.bsky.feed.post',
    'repo' => 'adactio.com',
    'record' => array(
    '$type' => 'app.bsky.feed.post',
    'text' => $data['text'],
    'createdAt' => date(DATE_ATOM)
    )
    );

    if (isset($data['embed'])) {
    $fields['record']['embed'] = $data['embed'];
    }

    $regex = '/(https?:\/\/[^\s]+)/';
    preg_match_all($regex, $data['text'], $matches, PREG_OFFSET_CAPTURE);

    $links = array();

    foreach ($matches[0] as $match) {
    $urlstring = $match[0];
    $start = $match[1];
    $end = $start + strlen($urlstring);

    $links[] = array(
    'start' => $start,
    'end' => $end,
    'url' => $urlstring
    );
    }

    if (!empty($links)) {
    $facets = array();
    foreach ($links as $link) {
    $facets[] = array(
    'index' => array(
    'byteStart' => $link['start'],
    'byteEnd' => $link['end'],
    ),
    'features' => array(
    array(
    '$type' => 'app.bsky.richtext.facet#link',
    'uri' => $link['url'],
    ),
    )
    );
    }
    $fields['record']['facets'] = $facets;
    }

    $headers = array(
    "Authorization: Bearer ".$data['accessToken'],
    "Content-Type: application/json",
    "Accept: application/json",
    "Accept-Charset: utf-8"
    );

    $options = array(
    CURLOPT_URL => $url,
    CURLOPT_USERAGENT => "adactio.com",
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_POST => TRUE,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_POSTFIELDS => json_encode($fields, JSON_UNESCAPED_SLASHES),
    CURLOPT_TIMEOUT => 5
    );

    $curl = curl_init();
    curl_setopt_array($curl, $options);
    $response = curl_exec($curl);
    curl_close($curl);

    return json_decode($response, true);

    }