Skip to content

Instantly share code, notes, and snippets.

@kasparsd
Created April 22, 2025 14:02
Show Gist options
  • Select an option

  • Save kasparsd/bc8a4d495d582c3a93f785643ee5fc0d to your computer and use it in GitHub Desktop.

Select an option

Save kasparsd/bc8a4d495d582c3a93f785643ee5fc0d to your computer and use it in GitHub Desktop.

Revisions

  1. kasparsd created this gist Apr 22, 2025.
    71 changes: 71 additions & 0 deletions x.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,71 @@
    <?php

    class Twitter {
    private string $bearer;

    public function __construct( string $bearer ) {
    $this->bearer = $bearer;
    }

    public function get_rate_limits() {
    $response = $this->get_from_api_url( 'https://api.x.com/1.1/application/rate_limit_status.json' );

    return $response->resources;
    }

    public function get( string $path, ?array $params = [] ) {
    $api_url = sprintf( 'https://api.x.com/2/%s', trim( $path, '/\\' ) );

    if ( ! empty( $params ) ) {
    $api_url .= '?' . http_build_query( $params );
    }

    $response = $this->get_from_api_url( $api_url );

    return $response->data;
    }

    private function get_from_api_url( string $api_url ) {
    $context = stream_context_create(
    [
    'http' => [
    'method' => 'GET',
    'header' => implode(
    "\r\n",
    [
    'Authorization: Bearer ' . $this->bearer,
    'Content-Type: application/json',
    ]
    ),
    ],
    ]
    );

    return json_decode( file_get_contents( $api_url, false, $context ) );
    }
    }

    $bearer = getenv( 'TWITTER_BEARER' );
    $twitter = new Twitter( $bearer );

    // Get the author ID.
    // $users = $twitter->get( 'users/by', [ 'usernames' => 'YOUR_USERNAME', 'tweet.fields' => 'author_id' ] );
    $user_id = 123456789; // Replace with the actual user ID.

    $limits = $twitter->get_rate_limits();
    file_put_contents( 'limits.json', json_encode( $limits, JSON_PRETTY_PRINT ) );

    $tweets = $twitter->get(
    sprintf( 'users/%d/tweets', $user_id ),
    [
    'tweet.fields' => 'created_at,attachments,in_reply_to_user_id,public_metrics,referenced_tweets,text',
    'media.fields' => 'preview_image_url,url',
    'max_results' => 100,
    ]
    );

    if ( is_array( $tweets ) ) {
    file_put_contents( 'tweets.json', json_encode( $tweets, JSON_PRETTY_PRINT ) );
    } else {
    die( 'Error: ' . json_encode( $tweets ) );
    }