Vous êtes ici

Synchroniser une timeline Twitter sur un compte Mastodon

Face aux limites imposées aux clients non officiels du réseau social Twitter - pourtant généralement meilleurs que l'officiel - notamment la limite des 200 statut par requête et des 15 requêtes toutes les 15 minutes maximum ou encore la non conservation de la position dans la timeline, j'ai eu l'idée de synchroniser le contenu de la timeline sur celui d'un compte privé Mastodon par l'intermédiaire d'un script, puisqu'en général instances et clients Mastodon son nettement moins limités. Il suffirait ensuite d'appeler de façon régulière ce script sans interaction humaine (car on ne peut pas passer sa vie à récupérer des tweets !).

Voici donc un début de résultat.

Pour l'exploiter à votre tour, il vous faudra au minimum PHP et son extension CURL. Sans oublier de faire le nécessaire pour obtenir vos jetons d'accès développeurs sur votre instance Mastodon et Twitter...

Son utilisation dans crontab sera ensuite on ne peut plus simple :

*/1 * * * * sudo -u www-data php /chemin/twitter_to_mastodon_timeline.php

Le script PHP

<?php // simple-php-twitter-to-mastodon-timeline.php

chdir('/script/path');

    function buildBaseString($baseURI, $method, $params) {
        $r = array();
        ksort($params);
        foreach($params as $key=>$value){
            $r[] = "$key=" . rawurlencode($value);
        }
        return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
    }

    function buildAuthorizationHeader($oauth) {
        $r = 'Authorization: OAuth ';
        $values = array();
        foreach($oauth as $key=>$value)
            $values[] = "$key=\"" . rawurlencode($value) . "\"";
        $r .= implode(', ', $values);
        return $r;
    }


    $url = 'https://api.twitter.com/1.1/statuses/home_timeline.json'; // or home_timeline.json

    // Custom Twitter data

    $oauth_access_token = " ";
    $oauth_access_token_secret = " ";
    $consumer_key = " ";
    $consumer_secret = " ";

    // Custom Mastodon data

    $mastodon_token = ' ';
    $mastodon_instance_url = 'https://instance.url'; // example : https://framapiaf.org'

    $curl_opt_url = $mastodon_instance_url . "/api/v1/statuses";

    $oauth = array( 'oauth_consumer_key' => $consumer_key,
                    'oauth_nonce' => time(),
                    'oauth_signature_method' => 'HMAC-SHA1',
                    'oauth_token' => $oauth_access_token,
                    'oauth_timestamp' => time(),
                    'oauth_version' => '1.0');

    $base_info = buildBaseString($url, 'GET', $oauth);
    $composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
    $oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
    $oauth['oauth_signature'] = $oauth_signature;

    $header = array(buildAuthorizationHeader($oauth), 'Expect:');
    $options = array( CURLOPT_HTTPHEADER => $header,
                      CURLOPT_HEADER => false,
                      CURLOPT_URL => $url,
                      CURLOPT_RETURNTRANSFER => true,
                      CURLOPT_SSL_VERIFYPEER => false);

    $feed = curl_init();
    curl_setopt_array($feed, $options);
    $json = curl_exec($feed);
    curl_close($feed);

    $twitter_data = json_decode($json);

    $lastid='';

    $lastidfile = 'lastid.txt';
    $current = file_get_contents($lastidfile);
    $content = "";
    $i = 0;

    foreach ($twitter_data as $twt) {
        if ($i == 0) {$lastid = $twt->id_str;}
        if ($twt->id_str == $current OR !isset($twt->id_str)) { break;  } else {

        $headers = [
        'Authorization: Bearer ' . $mastodon_token
        ];

        // You can change twitter API fields here :
        $toots[] = $twt->created_at . " -  " . $twt->user->name . "\r\r " . $twt->text . "\r\r https://twitter.com/" . $twt->user->screen_name . "/stat$

        $i++;
        }

}

if (!isset($toots)) { } else { 

$toots = array_reverse($toots);

foreach ($toots as $toot) {

$status_data = array(
  "status" => $toot,
  "language" => "fre",
  "visibility" => "private"
);

$ch_status = curl_init();
curl_setopt($ch_status, CURLOPT_URL, $curl_opt_url);
curl_setopt($ch_status, CURLOPT_POST, 1);
curl_setopt($ch_status, CURLOPT_POSTFIELDS, $status_data);
curl_setopt($ch_status, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_status, CURLOPT_HTTPHEADER, $headers);

$output_status = json_decode(curl_exec($ch_status));

curl_close ($ch_status);

}

file_put_contents($lastidfile, $lastid);

}

?>