Last active
December 22, 2022 16:27
-
-
Save adactio/c3652f2241c29bdc5af116bb02594d61 to your computer and use it in GitHub Desktop.
A PHP function that posts an update to Mastodon
This file contains 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 with keys for `status` | |
e.g. | |
postToMastodon(array( | |
'status' => 'Hello, world!' | |
)); | |
Include `reply_url` if you're responding to a post | |
e.g. | |
postToMastodon(array( | |
'status' => 'Hello, Jeremy!', | |
'reply_url' => 'https://mastodon.social/@adactio/109343712638768951' | |
)); | |
*/ | |
function postToMastodon($data=array()) { | |
// Get your access token from /settings/applications in your Mastodon instance. | |
$accessToken = 'XXXXXXXXXXXX'; | |
// Swap out mastodon.social for your Mastodon instance | |
$url = 'https://mastodon.social/api/v1/statuses'; | |
$fields['status'] = $data['status']; | |
if (isset($data['reply_url'])) { | |
if (stristr($data['reply_url'], '/@')) { | |
$urlparts = parse_url($data['reply_url']); | |
$pathparts = explode('/', $urlparts['path']); | |
$toot_id = $pathparts[2]; | |
$fields['in_reply_to_id'] = $toot_id; | |
$username = $pathparts[1]; | |
$fields['status'] = $username.' '.$fields['status']; | |
} | |
} | |
$headers = array( | |
"Authorization: Bearer ".$accessToken, | |
"Content-Type: application/json", | |
"Accept: application/json", | |
"Accept-Charset: utf-8" | |
); | |
$options = array( | |
CURLOPT_URL => $url, | |
CURLOPT_RETURNTRANSFER => TRUE, | |
CURLOPT_POST => TRUE, | |
CURLOPT_HTTPHEADER => $headers, | |
CURLOPT_POSTFIELDS => json_encode($fields), | |
CURLOPT_TIMEOUT => 20 | |
); | |
$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
Referenced in this blog post: Syndicating to Mastodon.