### Custom Twitter Configuration Example (Laravel) Source: https://context7.com/atymic/twitter/llms.txt This is an example of the `config/twitter.php` file after being published. It shows how to configure various API settings, including debug mode, API URLs, and authentication credentials, often by referencing environment variables. ```php // config/twitter.php contents return [ 'debug' => env('APP_DEBUG', false), 'api_url' => 'api.twitter.com', 'upload_url' => 'upload.twitter.com', 'api_version' => env('TWITTER_API_VERSION', '1.1'), 'consumer_key' => env('TWITTER_CONSUMER_KEY'), 'consumer_secret' => env('TWITTER_CONSUMER_SECRET'), 'access_token' => env('TWITTER_ACCESS_TOKEN'), 'access_token_secret' => env('TWITTER_ACCESS_TOKEN_SECRET'), 'authenticate_url' => 'https://api.twitter.com/oauth/authenticate', 'access_token_url' => 'https://api.twitter.com/oauth/access_token', 'request_token_url' => 'https://api.twitter.com/oauth/request_token', ]; ``` -------------------------------- ### Install X (formerly Twitter) for PHP using Composer Source: https://context7.com/atymic/twitter/llms.txt This command installs the X (formerly Twitter) for PHP library version 3.0 or higher using Composer. The `-W` flag ensures compatible dependencies are installed. ```bash composer require atymic/twitter:^3.0 -W ``` -------------------------------- ### Post a New Tweet using Twitter API v1.1 Source: https://context7.com/atymic/twitter/llms.txt This PHP code demonstrates how to post a new tweet using the X (formerly Twitter) for PHP library. It shows examples for a simple tweet, a reply with location data, and a tweet that includes uploaded media. ```php use Atymic\Twitter\Facade\Twitter; // Simple tweet $tweet = Twitter::postTweet([ 'status' => 'Hello from Laravel!', 'response_format' => 'json' ]); // Reply to a tweet with location $reply = Twitter::postTweet([ 'status' => '@username Thanks for the follow!', 'in_reply_to_status_id' => '1234567890', 'lat' => 37.7749, 'long' => -122.4194, 'display_coordinates' => 1, 'response_format' => 'array' ]); // Tweet with media (upload media first) $uploadedMedia = Twitter::uploadMedia(['media' => file_get_contents('image.jpg')]); $tweetWithMedia = Twitter::postTweet([ 'status' => 'Check out this photo!', 'media_ids' => $uploadedMedia->media_id_string ]); ``` -------------------------------- ### Get Authenticated User's Home Timeline using Twitter API v1.1 Source: https://context7.com/atymic/twitter/llms.txt This PHP code fetches the home timeline for the authenticated user, including tweets and retweets from followed users. It shows examples for retrieving a specific number of tweets and for pagination using `since_id`. ```php use Atymic\Twitter\Facade\Twitter; $homeTimeline = Twitter::getHomeTimeline([ 'count' => 50, 'exclude_replies' => 1, 'include_entities' => 1, 'tweet_mode' => 'extended', 'response_format' => 'json' ]); // Pagination using since_id (get newer tweets) $newTweets = Twitter::getHomeTimeline([ 'count' => 100, 'since_id' => '1234567890', 'response_format' => 'array' ]); ``` -------------------------------- ### Get User Information (v2) - PHP Source: https://context7.com/atymic/twitter/llms.txt Fetches user information by ID or username using Twitter API v2. This method is available through the Atymic Twitter package. It supports retrieving single or multiple users and allows specifying user fields for the response. Outputs are user objects. ```php use Atymic\Twitter\Facade\Twitter; use Atymic\Twitter\Twitter as TwitterContract; $twitter = Twitter::forApiV2(); // Get user by ID $user = $twitter->getUser('2244994945', [ 'user.fields' => 'created_at,description,public_metrics,profile_image_url', TwitterContract::KEY_RESPONSE_FORMAT => TwitterContract::RESPONSE_FORMAT_JSON, ]); // Get user by username $user = $twitter->getUserByUsername('TwitterDev', [ 'user.fields' => 'created_at,description,public_metrics', TwitterContract::KEY_RESPONSE_FORMAT => TwitterContract::RESPONSE_FORMAT_JSON, ]); // Get multiple users by IDs $users = $twitter->getUsers(['2244994945', '783214'], [ 'user.fields' => 'name,username,public_metrics', TwitterContract::KEY_RESPONSE_FORMAT => TwitterContract::RESPONSE_FORMAT_JSON, ]); // Get multiple users by usernames $users = $twitter->getUsersByUsernames(['TwitterDev', 'Twitter'], [ 'user.fields' => 'name,description,public_metrics', TwitterContract::KEY_RESPONSE_FORMAT => TwitterContract::RESPONSE_FORMAT_JSON, ]); ``` -------------------------------- ### Get User Information using Twitter SDK Source: https://context7.com/atymic/twitter/llms.txt Retrieves information about a specified user by their user ID or screen name. Includes options for embedding entities and specifying the response format. Requires user identifier (ID or screen name). ```php use Atymic\Twitter\Facade\Twitter; // Get user by screen name $user = Twitter::getUsers([ 'screen_name' => 'twitter', 'include_entities' => 1, 'response_format' => 'object' ]); echo $user->name; echo $user->followers_count; echo $user->profile_image_url_https; // Get user by ID $user = Twitter::getUsers([ 'user_id' => '783214', 'response_format' => 'array' ]); ``` -------------------------------- ### Get Friends and Followers using Twitter SDK Source: https://context7.com/atymic/twitter/llms.txt Retrieves lists of users that a specified user is following (friends) or that are following the specified user (followers). Supports pagination with cursors, count limits, and options for skipping status updates and including user entities. Requires a screen name or user ID. ```php use Atymic\Twitter\Facade\Twitter; // Get users you follow $friends = Twitter::getFriends([ 'screen_name' => 'twitter', 'cursor' => -1, 'count' => 200, 'skip_status' => 1, 'include_user_entities' => 0, 'response_format' => 'array' ]); // Get your followers $followers = Twitter::getFollowers([ 'screen_name' => 'twitter', 'cursor' => -1, 'count' => 200, 'response_format' => 'json' ]); // Handle pagination $nextCursor = $followers['next_cursor']; ``` -------------------------------- ### Get X (Twitter) API v1.1 User Credentials Source: https://github.com/atymic/twitter/blob/main/README.md Fetches the credentials for the authenticated user. This is a common utility function for verifying user authentication and retrieving basic user information. ```php use Atymic\Twitter\Facade\Twitter; $credentials = Twitter::getCredentials(); ``` -------------------------------- ### GET /getStream Source: https://github.com/atymic/twitter/blob/main/README.md Streams tweets in real-time based on active filter rules. ```APIDOC ## GET /getStream ### Description Streams Tweets in real-time based on a specific set of filter rules. ### Method GET ### Endpoint /getStream ### Response #### Success Response (200) - **stream** (stream) - Real-time stream of tweet data. ``` -------------------------------- ### Call New Twitter API v2 Endpoint (PHP) Source: https://github.com/atymic/twitter/blob/main/README.md Demonstrates how to call a newly added or undocumented endpoint in the Twitter API v2 using the Atymic Twitter package. This example specifically calls the 'recent count' endpoint for tweets. It utilizes the `getQuerier` method and `withOAuth2Client` for authentication. ```php // ... $querier = \Atymic\Twitter\Facade\Twitter::forApiV2() ->getQuerier(); $result = $querier ->withOAuth2Client() ->get('tweets/counts/recent', ['query' => 'foo']); // ... ``` -------------------------------- ### Get User's Tweets using Twitter API v1.1 Source: https://context7.com/atymic/twitter/llms.txt This PHP code retrieves a user's most recent tweets using the X (formerly Twitter) for PHP library. It provides examples for fetching tweets by screen name or user ID, with options for pagination and filtering. ```php use Atymic\Twitter\Facade\Twitter; // Get tweets by screen name $timeline = Twitter::getUserTimeline([ 'screen_name' => 'tabordasilva', 'count' => 20, 'include_rts' => 1, 'exclude_replies' => 0, 'tweet_mode' => 'extended', // Returns full tweet text (not truncated) 'response_format' => 'json' ]); // Get tweets by user ID with pagination $timeline = Twitter::getUserTimeline([ 'user_id' => '12345678', 'count' => 100, 'max_id' => '1234567890', // For pagination, get tweets older than this ID 'include_entities' => 1, 'response_format' => 'array' ]); ``` -------------------------------- ### Call New/Undocumented Endpoints (v2) - PHP Source: https://context7.com/atymic/twitter/llms.txt Enables making direct API calls to new or undocumented endpoints in Twitter API v2. This is facilitated by the Atymic Twitter package's querier object. It supports both GET and POST requests, including authentication with OAuth2 client. Inputs are the endpoint path and request parameters. ```php use Atymic\Twitter\Facade\Twitter; $querier = Twitter::forApiV2()->getQuerier(); // GET request with OAuth2 $result = $querier ->withOAuth2Client() ->get('tweets/counts/recent', ['query' => 'Laravel']); // POST request $result = $querier ->withOAuth2Client() ->post('tweets', ['text' => 'Hello from API v2!']); ``` -------------------------------- ### GET /userTweets Source: https://github.com/atymic/twitter/blob/main/README.md Retrieves tweets composed by a specific user. ```APIDOC ## GET /userTweets ### Description Returns Tweets composed by a single user, specified by the requested user ID. ### Method GET ### Endpoint /userTweets ### Parameters #### Query Parameters - **user_id** (string) - Required - The ID of the user to retrieve tweets for. ### Response #### Success Response (200) - **tweets** (array) - A list of tweet objects. ``` -------------------------------- ### Debug Twitter API Responses (PHP) Source: https://github.com/atymic/twitter/blob/main/README.md Shows how to debug API requests made using the Twitter facade, particularly when encountering errors. It involves enabling debug mode in the configuration and then using the `logs()` method to retrieve detailed information about the request and response. This example also includes a `try-catch` block for error handling. ```php try { $response = Twitter::getUserTimeline(['count' => 20, 'response_format' => 'array']); } catch (Exception $e) { // dd(Twitter::error()); dd(Twitter::logs()); } dd($response); ``` -------------------------------- ### Get User Tweets and Mentions (v2) - PHP Source: https://context7.com/atymic/twitter/llms.txt Fetches tweets composed by or mentioning a specific user using API v2. Requires the Atymic Twitter package. Inputs include user ID and optional parameters like tweet fields, expansions, and max results. Outputs are tweet objects. ```php use Atymic\Twitter\Facade\Twitter; use Atymic\Twitter\Twitter as TwitterContract; $twitter = Twitter::forApiV2(); // Get user's tweets $tweets = $twitter->userTweets('2244994945', [ 'tweet.fields' => 'created_at,public_metrics,entities', 'expansions' => 'attachments.media_keys', 'max_results' => 100, TwitterContract::KEY_RESPONSE_FORMAT => TwitterContract::RESPONSE_FORMAT_JSON, ]); // Get user's mentions $mentions = $twitter->userMentions('2244994945', [ 'tweet.fields' => 'author_id,created_at,in_reply_to_user_id', 'expansions' => 'author_id', 'user.fields' => 'name,username', TwitterContract::KEY_RESPONSE_FORMAT => TwitterContract::RESPONSE_FORMAT_JSON, ]); ``` -------------------------------- ### GET /statuses/user_timeline Source: https://context7.com/atymic/twitter/llms.txt Retrieves a collection of the most recent tweets posted by a specified user. ```APIDOC ## GET /statuses/user_timeline ### Description Returns a collection of the most recent tweets posted by the specified user. Supports pagination and filtering options. ### Method GET ### Endpoint /statuses/user_timeline ### Parameters #### Query Parameters - **screen_name** (string) - Optional - The screen name of the user for whom to return results. - **user_id** (string) - Optional - The ID of the user for whom to return results. - **count** (integer) - Optional - Specifies the number of tweets to try and retrieve. - **tweet_mode** (string) - Optional - Set to 'extended' to return full tweet text. ### Request Example { "screen_name": "tabordasilva", "count": 20, "tweet_mode": "extended" } ### Response #### Success Response (200) - **data** (array) - A collection of tweet objects. #### Response Example [ { "id": 12345, "text": "Full tweet text here..." } ] ``` -------------------------------- ### Get Mentions Timeline using Twitter API v1.1 Source: https://context7.com/atymic/twitter/llms.txt This PHP code retrieves the 20 most recent mentions of the authenticating user. It allows for specifying the count and including entities, with options for different response formats. ```php use Atymic\Twitter\Facade\Twitter; $mentions = Twitter::getMentionsTimeline([ 'count' => 50, 'include_entities' => 1, 'tweet_mode' => 'extended', 'response_format' => 'json' ]); ``` -------------------------------- ### Get User Tweets using Twitter API v2 (PHP) Source: https://github.com/atymic/twitter/blob/main/README.md Fetches tweets for a specific user using the Twitter API v2. It allows specifying various tweet and user fields, as well as response format. This function requires the Atymic Twitter package and uses the Twitter facade. ```php // ... use Atymic\Twitter\Twitter as TwitterContract; use Illuminate\Http\JsonResponse; use Twitter; // ... public function userTweets(int $userId): JsonResponse { $params = [ 'place.fields' => 'country,name', 'tweet.fields' => 'author_id,geo', 'expansions' => 'author_id,in_reply_to_user_id', TwitterContract::KEY_RESPONSE_FORMAT => TwitterContract::RESPONSE_FORMAT_JSON, ]; return JsonResponse::fromJsonString(Twitter::userTweets($userId, $params)); } ``` -------------------------------- ### Count Tweets (v2) - PHP Source: https://context7.com/atymic/twitter/llms.txt Retrieves counts of tweets matching a given query using API v2. This function is part of the Atymic Twitter package. It accepts a query string and optional parameters like granularity, start time, and response format. Outputs are tweet count objects. ```php use Atymic\Twitter\Facade\Twitter; use Atymic\Twitter\Twitter as TwitterContract; $twitter = Twitter::forApiV2(); // Count tweets from last 7 days $counts = $twitter->countRecent('Laravel', [ 'granularity' => 'day', // day, hour, or minute TwitterContract::KEY_RESPONSE_FORMAT => TwitterContract::RESPONSE_FORMAT_JSON, ]); // Full archive counts (Academic Research only) $archiveCounts = $twitter->countAll('Laravel', [ 'start_time' => '2020-01-01T00:00:00Z', 'granularity' => 'day', TwitterContract::KEY_RESPONSE_FORMAT => TwitterContract::RESPONSE_FORMAT_JSON, ]); ``` -------------------------------- ### Filtered Stream (v2) - Real-time Tweet Streaming - PHP Source: https://context7.com/atymic/twitter/llms.txt Streams tweets in real-time based on defined filter rules using API v2. This feature is part of the Atymic Twitter package. It allows managing stream rules (get, add, delete) and connecting to the stream with options to stop after a certain count or duration. The stream callback processes each incoming tweet. ```php use Atymic\Twitter\Facade\Twitter; use Atymic\Twitter\Twitter as TwitterContract; $twitter = Twitter::forApiV2(); // Get current stream rules $rules = $twitter->getStreamRules([ TwitterContract::KEY_RESPONSE_FORMAT => TwitterContract::RESPONSE_FORMAT_JSON, ]); // Add stream rules $newRules = $twitter->postStreamRules([ 'add' => [ ['value' => 'Laravel lang:en', 'tag' => 'Laravel tweets'], ['value' => 'PHP -is:retweet', 'tag' => 'PHP original tweets'], ] ]); // Delete rules by IDs $deleteResult = $twitter->postStreamRules([ 'delete' => [ 'ids' => ['rule_id_1', 'rule_id_2'] ] ]); // Connect to stream $twitter->getStream(function ($tweet) { echo "New tweet: " . json_encode($tweet) . "\n"; // Return false to stop streaming // return false; }, [ 'tweet.fields' => 'author_id,created_at,entities', 'expansions' => 'author_id', TwitterContract::KEY_STREAM_STOP_AFTER_COUNT => 100, // Stop after 100 tweets TwitterContract::KEY_STREAM_STOP_AFTER_SECONDS => 60, // Or stop after 60 seconds ]); ``` -------------------------------- ### Configure Twitter API Credentials in .env Source: https://context7.com/atymic/twitter/llms.txt This snippet shows how to set up environment variables in your `.env` file for Twitter API credentials. These include consumer key, consumer secret, access token, and access token secret. You can also specify the API version to use. ```bash # .env file TWITTER_CONSUMER_KEY=your_consumer_key TWITTER_CONSUMER_SECRET=your_consumer_secret TWITTER_ACCESS_TOKEN=your_access_token TWITTER_ACCESS_TOKEN_SECRET=your_access_token_secret TWITTER_API_VERSION=1.1 # Use '2' for API v2 ``` -------------------------------- ### Switch Twitter API Credentials (PHP) Source: https://context7.com/atymic/twitter/llms.txt This code demonstrates how to switch between different user credentials for making API calls. It shows how to use stored access tokens to instantiate a Twitter client and then perform actions like posting a tweet or fetching a timeline. ```php use Atymic\Twitter\Facade\Twitter; // Use stored user tokens $userToken = session('access_token'); $twitter = Twitter::usingCredentials( $userToken['oauth_token'], $userToken['oauth_token_secret'] ); // Post tweet as that user $tweet = $twitter->postTweet(['status' => 'Posted on behalf of user!']); // Get the user's timeline $timeline = $twitter->getHomeTimeline(['count' => 20]); ``` -------------------------------- ### Enable Debug Mode and Logging Source: https://context7.com/atymic/twitter/llms.txt Configures the library to capture detailed API logs for troubleshooting purposes, accessible via the logs() method. ```php use Atymic\Twitter\Facade\Twitter; try { $response = Twitter::getUserTimeline([ 'count' => 20, 'response_format' => 'array' ]); } catch (\Exception $e) { dd(Twitter::logs()); } ``` -------------------------------- ### Publish Twitter Configuration File (Laravel) Source: https://context7.com/atymic/twitter/llms.txt This command publishes the configuration file for the X (formerly Twitter) for PHP library in a Laravel application. This allows for advanced customization of API settings. ```php // Run artisan command php artisan vendor:publish --provider="Atymic\Twitter\ServiceProvider\LaravelServiceProvider" ``` -------------------------------- ### Switch Twitter API Versions (PHP) Source: https://context7.com/atymic/twitter/llms.txt This snippet illustrates how to dynamically switch between Twitter's API v1.1 and v2 clients. It shows how to obtain a v2 client from a v1 client (or vice versa) and mentions the possibility of setting the default API version via environment variables. ```php use Atymic\Twitter\Facade\Twitter; use Atymic\Twitter\Twitter as TwitterContract; // Get v2 client from v1 (or if already v2, returns same instance) $twitterV2 = Twitter::forApiV2(); // Get v1 client from v2 $twitterV1 = Twitter::forApiV1(); // Or set default to v2 in .env // TWITTER_API_VERSION=2 ``` -------------------------------- ### Retrieve User Credentials with PHP Source: https://github.com/atymic/twitter/blob/main/README.md Fetches the authenticating user's profile information. Note: 'include_email' must be passed as a string 'true' to be processed correctly. ```php $credentials = Twitter::getCredentials([ 'include_email' => 'true', ]); ``` -------------------------------- ### Manage Account Activity Webhooks Source: https://context7.com/atymic/twitter/llms.txt Register, list, and delete webhooks for premium account activity. Includes CRC token validation logic for endpoint verification. ```php use Atymic\Twitter\Facade\Twitter; $webhook = Twitter::setWebhook('production', 'https://yourapp.com/webhooks/twitter'); $webhooks = Twitter::getWebhooks('production'); Twitter::updateWebhooks('production', 'webhook_id_here'); Twitter::destroyWebhook('production', 'webhook_id_here'); // CRC Validation if ($request->has('crc_token')) { return response()->json(['response_token' => Twitter::crcHash($request->crc_token)], 200); } ``` -------------------------------- ### Get X (Twitter) API v1.1 Account Settings Source: https://github.com/atymic/twitter/blob/main/README.md Retrieves the current settings for the authenticated user, including trend, geo, and sleep time information. This function is part of the Account management features available in API v1.1. ```php use Atymic\Twitter\Facade\Twitter; $settings = Twitter::getSettings(); ``` -------------------------------- ### Configure Laravel Environment Variables for X (Twitter) API Source: https://github.com/atymic/twitter/blob/main/README.md Sets up the necessary environment variables in your Laravel project's .env file for authenticating with the X (formerly Twitter) API. These include consumer keys, access tokens, and API version. ```dotenv TWITTER_CONSUMER_KEY= TWITTER_CONSUMER_SECRET= TWITTER_ACCESS_TOKEN= TWITTER_ACCESS_TOKEN_SECRET= TWITTER_API_VERSION= ``` -------------------------------- ### Manage Account Activity Subscriptions Source: https://context7.com/atymic/twitter/llms.txt Subscribe to real-time events for specific accounts and manage existing subscriptions. Allows checking subscription status and counts. ```php use Atymic\Twitter\Facade\Twitter; Twitter::setSubscriptions('production'); $isSubscribed = Twitter::getSubscriptions('production'); $count = Twitter::getSubscriptionsCount(); $list = Twitter::getSubscriptionsList('production'); Twitter::destroyUserSubscriptions('production', 'user_id_here'); ``` -------------------------------- ### Get Single Tweet using Twitter SDK Source: https://context7.com/atymic/twitter/llms.txt Fetches a single tweet by its ID, including embedded author information. Supports various options like including entities, retweet status, and tweet mode. Requires the tweet ID as input. ```php use Atymic\Twitter\Facade\Twitter; $tweet = Twitter::getTweet('1234567890123456789', [ 'include_entities' => 1, 'include_my_retweet' => 1, 'tweet_mode' => 'extended', 'response_format' => 'object' ]); echo $tweet->full_text; echo $tweet->user->screen_name; ``` -------------------------------- ### Implement Twitter OAuth Flow (PHP) Source: https://context7.com/atymic/twitter/llms.txt This snippet demonstrates the complete OAuth flow for Twitter authentication, including obtaining request tokens, redirecting users, handling callbacks, and retrieving access tokens. It utilizes Laravel's routing and session management. ```php use Atymic\Twitter\Facade\Twitter; use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\Redirect; // Step 1: Get request token and redirect to Twitter Route::get('twitter/login', function () { $token = Twitter::getRequestToken(route('twitter.callback')); if (isset($token['oauth_token_secret'])) { Session::put('oauth_state', 'start'); Session::put('oauth_request_token', $token['oauth_token']); Session::put('oauth_request_token_secret', $token['oauth_token_secret']); $url = Twitter::getAuthenticateUrl($token['oauth_token']); return Redirect::to($url); } return Redirect::route('twitter.error'); }); // Step 2: Handle callback and get access token Route::get('twitter/callback', function () { if (Session::has('oauth_request_token')) { $twitter = Twitter::usingCredentials( session('oauth_request_token'), session('oauth_request_token_secret') ); $token = $twitter->getAccessToken(request('oauth_verifier')); if (isset($token['oauth_token_secret'])) { // Use new tokens to get user info $twitter = Twitter::usingCredentials( $token['oauth_token'], $token['oauth_token_secret'] ); $credentials = $twitter->getCredentials(['include_email' => 'true']); if (is_object($credentials) && !isset($credentials->error)) { // Store user data: $credentials->id, $credentials->screen_name, $credentials->email Session::put('access_token', $token); return Redirect::to('/')->with('notice', 'Successfully signed in!'); } } } return Redirect::route('twitter.error')->with('error', 'Authentication failed!'); }); // Logout Route::get('twitter/logout', function () { Session::forget('access_token'); return Redirect::to('/')->with('notice', 'Logged out successfully!'); }); ``` -------------------------------- ### Handle API Exceptions Source: https://context7.com/atymic/twitter/llms.txt Implements structured error handling for common API issues such as rate limiting, unauthorized access, and missing resources using specific exception classes. ```php use Atymic\Twitter\Facade\Twitter; use Atymic\Twitter\Exception\ClientException; use Atymic\Twitter\Exception\Request\RateLimitedException; use Atymic\Twitter\Exception\Request\UnauthorizedRequestException; use Atymic\Twitter\Exception\Request\NotFoundException; try { $tweet = Twitter::postTweet(['status' => 'Hello!']); } catch (RateLimitedException $e) { Log::warning('Rate limited', ['message' => $e->getMessage()]); } catch (UnauthorizedRequestException $e) { Log::error('Unauthorized', ['message' => $e->getMessage()]); } catch (NotFoundException $e) { Log::info('Not found', ['message' => $e->getMessage()]); } catch (ClientException $e) { Log::error('Twitter API error', ['message' => $e->getMessage()]); } ``` -------------------------------- ### Generate Twitter Profile and Tweet URLs Source: https://context7.com/atymic/twitter/llms.txt Creates direct URLs for user profiles and specific tweets using screen names or objects. Simplifies linking to external Twitter resources. ```php use Atymic\Twitter\Facade\Twitter; $url = Twitter::linkUser('laabordasilva'); $user = Twitter::getUsers(['screen_name' => 'twitter']); $url = Twitter::linkUser($user); $tweet = Twitter::getTweet('1234567890123456789'); $url = Twitter::linkTweet($tweet); ``` -------------------------------- ### Implement Twitter OAuth Login Flow with PHP Source: https://github.com/atymic/twitter/blob/main/README.md Handles the full OAuth handshake including requesting tokens, redirecting to Twitter for authorization, and processing the callback to obtain access tokens. ```php use Atymic\Twitter\Facade\Twitter; Route::get('twitter/login', ['as' => 'twitter.login', static function () { $token = Twitter::getRequestToken(route('twitter.callback')); if (isset($token['oauth_token_secret'])) { $url = Twitter::getAuthenticateUrl($token['oauth_token']); Session::put('oauth_state', 'start'); Session::put('oauth_request_token', $token['oauth_token']); Session::put('oauth_request_token_secret', $token['oauth_token_secret']); return Redirect::to($url); } return Redirect::route('twitter.error'); }]); Route::get('twitter/callback', ['as' => 'twitter.callback', static function () { if (Session::has('oauth_request_token')) { $twitter = Twitter::usingCredentials(session('oauth_request_token'), session('oauth_request_token_secret')); $token = $twitter->getAccessToken(request('oauth_verifier')); if (!isset($token['oauth_token_secret'])) { return Redirect::route('twitter.error')->with('flash_error', 'We could not log you in on Twitter.'); } $twitter = Twitter::usingCredentials($token['oauth_token'], $token['oauth_token_secret']); $credentials = $twitter->getCredentials(); if (is_object($credentials) && !isset($credentials->error)) { Session::put('access_token', $token); return Redirect::to('/')->with('notice', 'Congrats! You\'ve successfully signed in!'); } } return Redirect::route('twitter.error') ->with('error', 'Crab! Something went wrong while signing you up!'); }]); ``` -------------------------------- ### Helper Functions Source: https://github.com/atymic/twitter/blob/main/README.md Utility functions for formatting tweet data and user links. ```APIDOC ## Helper Functions ### Linkify Transforms URLs, @usernames, and hashtags into HTML links. `Twitter::linkify($tweet);` ### Ago Converts a timestamp into a human-readable relative time string (e.g., '2 hours ago'). `Twitter::ago($timestamp);` ### LinkUser Generates a link to a specific user profile. `Twitter::linkUser($user);` ### LinkTweet Generates a link to a specific tweet. `Twitter::linkTweet($tweet);` ``` -------------------------------- ### Search Users using Twitter SDK Source: https://context7.com/atymic/twitter/llms.txt Performs a relevance-based search for public user accounts. Parameters include the search query, page number, count of results, entity inclusion, and response format. Requires a search query string. ```php use Atymic\Twitter\Facade\Twitter; $users = Twitter::getUsersSearch([ 'q' => 'Laravel developer', 'page' => 1, 'count' => 20, 'include_entities' => 0, 'response_format' => 'json' ]); ``` -------------------------------- ### Lookup Multiple Users using Twitter SDK Source: https://context7.com/atymic/twitter/llms.txt Retrieves fully-hydrated user objects for up to 100 users per request, either by screen names or user IDs. Supports options for including entities and specifying the response format. Requires a comma-separated list of screen names or user IDs. ```php use Atymic\Twitter\Facade\Twitter; // Lookup by screen names $users = Twitter::getUsersLookup([ 'screen_name' => 'twitter,twitterdev,twitterapi', 'include_entities' => 0, 'response_format' => 'array' ]); // Lookup by user IDs $users = Twitter::getUsersLookup([ 'user_id' => '783214,2244994945,6253282', 'response_format' => 'json' ]); ``` -------------------------------- ### Post Tweet with Media with PHP Source: https://github.com/atymic/twitter/blob/main/README.md Uploads a local file to Twitter and attaches it to a new status update. ```php Route::get('/tweetMedia', function() { $uploaded_media = Twitter::uploadMedia(['media' => File::get(public_path('filename.jpg'))]); return Twitter::postTweet(['status' => 'Laravel is beautiful', 'media_ids' => $uploaded_media->media_id_string]); }); ``` -------------------------------- ### Publish Laravel Configuration for X (Twitter) API Source: https://github.com/atymic/twitter/blob/main/README.md Publishes the X (formerly Twitter) API configuration file to your Laravel project's config directory. This allows for advanced customization of the API client settings. ```bash php artisan vendor:publish --provider="Atymic\Twitter\ServiceProvider\LaravelServiceProvider" ``` -------------------------------- ### Follow and Unfollow Users using Twitter SDK Source: https://context7.com/atymic/twitter/llms.txt Allows the authenticating user to follow or unfollow specified users. The `postFollow` method takes a screen name and a 'follow' flag, while `postUnfollow` uses a user ID. Options include enabling notifications and specifying response format. Requires user identifier. ```php use Atymic\Twitter\Facade\Twitter; // Follow a user $followed = Twitter::postFollow([ 'screen_name' => 'twitter', 'follow' => 1, // Enable notifications 'response_format' => 'json' ]); // Unfollow a user $unfollowed = Twitter::postUnfollow([ 'user_id' => '783214', 'response_format' => 'json' ]); ``` -------------------------------- ### Manage Account Activity Webhooks Source: https://github.com/atymic/twitter/blob/main/README.md Methods for registering, retrieving, updating, and deleting webhooks for premium account activity. These functions handle environment-specific configurations and CRC token verification. ```php $twitter->setWebhook($env, $url); $hash = $twitter->crcHash($crcToken); $webhooks = $twitter->getWebhooks($env); $twitter->updateWebhooks($env, $webhookId); $twitter->destroyWebhook($env, $webhookId); ``` -------------------------------- ### Switch Between X (Twitter) API Versions in Laravel Source: https://github.com/atymic/twitter/blob/main/README.md Shows how to explicitly use API v1.1 or v2 clients within your Laravel application. You can set the default API version via environment variables or switch instances dynamically using helper methods. ```php // Set API v2 as default via .env: TWITTER_API_VERSION=2 // Get v2 client instance $v2Client = Twitter::forApiV2(); // Get v1.1 client instance from a v2 client $v1Client = $v2Client->forApiV1(); // Get v1.1 client instance directly $v1ClientDirect = Twitter::forApiV1(); // Get v2 client instance from a v1 client $v2ClientFromV1 = $v1Client->forApiV2(); // It's safe to call forApiV1() on either client type. ``` -------------------------------- ### Upload Media using Twitter SDK Source: https://context7.com/atymic/twitter/llms.txt Uploads images or videos to Twitter for use in tweets, returning a media ID string. Supports uploading from file paths or base64 encoded data. Can be used to attach media to new tweets. Requires media file content or data. ```php use Atymic\Twitter\Facade\Twitter; use Illuminate\Support\Facades\File; // Upload image from file $media = Twitter::uploadMedia([ 'media' => File::get(public_path('images/photo.jpg')) ]); // Upload using base64 encoded data $media = Twitter::uploadMedia([ 'media_data' => base64_encode(file_get_contents('photo.png')) ]); // Post tweet with uploaded media $tweet = Twitter::postTweet([ 'status' => 'Amazing photo!', 'media_ids' => $media->media_id_string ]); // Upload multiple images $mediaIds = []; foreach (['img1.jpg', 'img2.jpg', 'img3.jpg'] as $file) { $uploaded = Twitter::uploadMedia(['media' => File::get($file)]); $mediaIds[] = $uploaded->media_id_string; } $tweet = Twitter::postTweet([ 'status' => 'Photo gallery!', 'media_ids' => implode(',', $mediaIds) ]); ``` -------------------------------- ### Manage User Subscriptions Source: https://github.com/atymic/twitter/blob/main/README.md Functions to manage subscriptions for account activity events. Includes methods to set, retrieve, count, and destroy user-specific subscriptions. ```php $twitter->setSubscriptions($env); $isActive = $twitter->getSubscriptions($env); $count = $twitter->getSubscriptionsCount(); $list = $twitter->getSubscriptionsList($env); $twitter->destroyUserSubscriptions($env, $userId); ``` -------------------------------- ### POST /statuses/update Source: https://context7.com/atymic/twitter/llms.txt Updates the authenticating user's current status by creating a new tweet. ```APIDOC ## POST /statuses/update ### Description Updates the authenticating user's current status (creates a tweet). Supports optional parameters for replies, location, and media attachments. ### Method POST ### Endpoint /statuses/update ### Parameters #### Request Body - **status** (string) - Required - The text of the status update. - **in_reply_to_status_id** (string) - Optional - The ID of an existing status that the update is in reply to. - **lat** (float) - Optional - The latitude of the location. - **long** (float) - Optional - The longitude of the location. - **media_ids** (string) - Optional - A comma-separated list of media_ids to associate with the tweet. ### Request Example { "status": "Hello from Laravel!", "response_format": "json" } ### Response #### Success Response (200) - **id_str** (string) - The unique identifier of the created tweet. #### Response Example { "id": 1234567890, "text": "Hello from Laravel!" } ``` -------------------------------- ### Search Tweets using Twitter API v2 (PHP) Source: https://context7.com/atymic/twitter/llms.txt This snippet demonstrates searching for tweets using Twitter's API v2. It covers searching recent tweets (last 7 days) and full archive tweets (requires Academic Research product track), specifying various query parameters and fields. ```php use Atymic\Twitter\Facade\Twitter; use Atymic\Twitter\Twitter as TwitterContract; $twitter = Twitter::forApiV2(); // Recent search (last 7 days) $results = $twitter->searchRecent('Laravel from:laabordasilva', [ 'tweet.fields' => 'author_id,created_at,public_metrics', 'expansions' => 'author_id', 'user.fields' => 'name,username', 'max_results' => 100, TwitterContract::KEY_RESPONSE_FORMAT => TwitterContract::RESPONSE_FORMAT_JSON, ]); // Full archive search (Academic Research product track only) $archiveResults = $twitter->searchAll('Laravel lang:en', [ 'start_time' => '2020-01-01T00:00:00Z', 'end_time' => '2023-12-31T23:59:59Z', 'tweet.fields' => 'author_id,created_at', TwitterContract::KEY_RESPONSE_FORMAT => TwitterContract::RESPONSE_FORMAT_JSON, ]); ``` -------------------------------- ### Retweet a Tweet using Twitter SDK Source: https://context7.com/atymic/twitter/llms.txt Retweets a specified tweet, returning the original tweet with retweet details. Options include trimming user information and specifying response format. Requires the tweet ID as input. ```php use Atymic\Twitter\Facade\Twitter; $retweet = Twitter::postRt('1234567890123456789', [ 'trim_user' => 0, 'response_format' => 'json' ]); ``` -------------------------------- ### Search Tweets using Twitter SDK Source: https://context7.com/atymic/twitter/llms.txt Searches for tweets matching a query string. Supports basic search with parameters like query, count, and result type, as well as advanced search with filters for language, location, date, and entities. Requires a query string and optional filters. ```php use Atymic\Twitter\Facade\Twitter; // Basic search $results = Twitter::getSearch([ 'q' => 'Laravel PHP', 'count' => 100, 'result_type' => 'recent', // mixed, recent, or popular 'response_format' => 'json' ]); // Advanced search with filters $results = Twitter::getSearch([ 'q' => '#laravel -filter:retweets', 'lang' => 'en', 'geocode' => '37.781157,-122.398720,25mi', 'until' => '2024-01-15', 'since_id' => '1234567890123456789', 'include_entities' => 1, 'response_format' => 'array' ]); ``` -------------------------------- ### Manage Favorites Source: https://github.com/atymic/twitter/blob/main/README.md Methods to retrieve, create, and destroy favorites for specific tweets. These actions are performed on behalf of the authenticating user. ```php $favorites = $twitter->getFavorites(); $twitter->postFavorite($tweetId); $twitter->destroyFavorite($tweetId); ``` -------------------------------- ### Media API Source: https://github.com/atymic/twitter/blob/main/README.md Endpoint for uploading media (images) to Twitter. ```APIDOC ## POST /media/upload ### Description Upload media (images) to Twitter, to use in a Tweet or Twitter-hosted Card. ### Method POST ### Endpoint /media/upload ### Parameters #### Request Body - **media** (file) - Required - The media file to upload. ### Response #### Success Response (200) - **media_id_string** (string) - The ID of the uploaded media. #### Response Example { "media_id_string": "1234567890" } ``` -------------------------------- ### Manage User Blocks Source: https://github.com/atymic/twitter/blob/main/README.md Methods to retrieve blocked users or IDs, and to perform block/unblock actions on specific users. These actions modify the authenticating user's relationship with others. ```php $blocks = $twitter->getBlocks(); $ids = $twitter->getBlocksIds(); $twitter->postBlock($userId); $twitter->destroyBlock($userId); ``` -------------------------------- ### Handle Direct Messages Source: https://github.com/atymic/twitter/blob/main/README.md Operations for interacting with Direct Messages, including retrieving single or multiple messages, sending new messages, and deleting existing ones. ```php $dm = $twitter->getDm($id); $dms = $twitter->getDms(); $twitter->postDm($userId, $text); $twitter->destroyDm($id); ``` -------------------------------- ### Convert Tweet Content to HTML Links Source: https://context7.com/atymic/twitter/llms.txt Transforms raw tweet text into clickable HTML by identifying URLs, @mentions, and hashtags. Supports input as strings or tweet objects and allows selective configuration of linkification features. ```php use Atymic\Twitter\Facade\Twitter; $text = "Check out https://laravel.com and follow @laabordasilva #Laravel"; $html = Twitter::linkify($text); $tweet = Twitter::getTweet('1234567890123456789'); $html = Twitter::linkify($tweet); $html = Twitter::linkify($text, linkifyHashTags: true, linkifyUsers: true, linkifyEmails: false ); ``` -------------------------------- ### Generate User Link Source: https://github.com/atymic/twitter/blob/main/README.md Generates a link to a specific user's profile using their user object, ID, or username string. ```php Twitter::linkUser($user); ```