Created
November 24, 2024 14:02
-
-
Save adactio/ac776509693d7470828d0e3b51f6dc84 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment