noweh / twitter-api-v2-php
This library provides methods for sending messages to Twitter and receiving statuses.
Installs: 106 260
Dependents: 1
Suggesters: 0
Security: 0
Stars: 116
Watchers: 3
Forks: 31
Open Issues: 4
Requires
- php: >=7.4
- ext-curl: *
- ext-json: *
- guzzlehttp/guzzle: ^7.5.0
- guzzlehttp/oauth-subscriber: ^0.6.0
Requires (Dev)
- phpstan/phpstan: ^1.9.14
- phpunit/php-code-coverage: ^9.2.24
- phpunit/phpunit: ^9.6.3
- vlucas/phpdotenv: ^v5.5.0
README
Twitter API V2 is a PHP package which provides an easy and fast access to Twitter REST API for Version 2 endpoints.
Documentation
- Installation
- Github Actions
- Usage
- Tweets endpoints
- Users endpoints
- Contributing
Installation
To begin, you'll need to add the component to your composer.json
composer require noweh/twitter-api-v2-php
After adding the component, update your packages using composer update
or install them using composer install
.
Github Actions
This repository uses Github Actions for each push/pull request, employing PHPStan/PHPUnit.
Consequently, with each valid push, a new Tweet is posted from the Twitter test account.
Usage
Active your developer account
Before anything else, you must follow this tutorial.
- Request approval for a developer account;
- Once your developer account is approved, you will need to create a Project;
- Enable read/write access for your Twitter app;
- Generate Consumer Keys and Authentication Tokens;
- Retrieve your Keys and Tokens from the Twitter Developer portal.
Configuration setup
Expected settings are as follows:
use Noweh\TwitterApi\Client; $settings = [ 'account_id' => 'YOUR_ACCOUNT_ID', 'access_token' => 'YOUR_ACCESS_TOKEN', 'access_token_secret' => 'YOUR_TOKEN_SECRET', 'consumer_key' => 'YOUR_CONSUMER_KEY', 'consumer_secret' => 'YOUR_CONSUMER_SECRET', 'bearer_token' => 'YOUR_BEARER_TOKEN', 'free_mode' => false, // Optional 'api_base_uri' => 'https://api.twitter.com/2/', // Optional ]; $client = new Client($settings);
By changing the value of 'api_base_uri'
you can have the requests target a different server, for instance, a simulated one, thus making testing your application in isolation easier.
For a quick mock server setup you can use mockoon.
API Functionality
All API calls are triggered when the performRequest()
method is invoked.
Depending on the context, this method can either be empty or contain data that will be sent as PostData (refer to examples of each call below).
Include the HTTP headers provided by Twitter in the response
The performRequest()
method accepts a second parameter, $withHeaders
, which is a boolean value.
Setting this parameter to true
will include the headers information in the response.
Here are some examples of information included in headers:
x-rate-limit-limit
: the rate limit ceiling for that given endpointx-rate-limit-remaining
: the number of requests left for the 15-minute windowx-rate-limit-reset
: the remaining window before the rate limit resets, in UTC epoch seconds
Example:
$response = $this->client->tweet()->create() ->performRequest([ 'text' => 'Test Tweet... ' ], withHeaders: true) ; /* Output: object(stdClass)#399 (2) { ["data"]=> object(stdClass)#398 (3) { ["edit_history_tweet_ids"]=> array(1) { [0]=> string(19) "1690304934837637121" } ["id"]=> string(19) "1690304934837637121" ["text"]=> string(39) "Test Tweet..." } ["headers"]=> ... ["x-rate-limit-limit"]=> array(1) { [0]=> string(5) "40000" } ["x-rate-limit-reset"]=> array(1) { [0]=> string(10) "1691835953" } ["x-rate-limit-remaining"]=> array(1) { [0]=> string(5) "39998" } ... } } */
Free mode
This API can be used in free mode, which allows for a limited usage of the API.
In this mode, the Find me method is the only one that can be used.
You have to set the free_mode
parameter to true
when creating the client.
Example:
... $settings['free_mode'] = true; $client = new Client($settings);
Tweets endpoints
Timeline endpoints
Find Recent Mentioning for a User
Example:
$return = $client->timeline()->getRecentMentions($accountId)->performRequest();
Find Recent Tweets for a User
Example:
$return = $client->timeline()->getRecentTweets($accountId)->performRequest();
Reverse Chronological Timeline by user ID
Example:
$return = $client->timeline()->getReverseChronological()->performRequest();
Tweet/Likes endpoints
Tweets liked by a user
Example:
$return = $client->tweetLikes()->addMaxResults($pageSize)->getLikedTweets($accountId)->performRequest();
Users who liked a tweet
Example:
$return = $client->tweetLikes()->addMaxResults($pageSize)->getUsersWhoLiked($tweetId)->performRequest();
Tweet/Lookup endpoints
Search specific tweets
Example:
$return = $client->tweetLookup() ->showMetrics() ->onlyWithMedias() ->addFilterOnUsernamesFrom([ 'twitterdev', 'Noweh95' ], \Noweh\TwitterApi\TweetLookup::OPERATORS['OR']) ->addFilterOnKeywordOrPhrase([ 'Dune', 'DenisVilleneuve' ], \Noweh\TwitterApi\TweetLookup::OPERATORS['AND']) ->addFilterOnLocales(['fr', 'en']) ->showUserDetails() ->performRequest() ; $client->tweetLookup() ->addMaxResults($pageSize) ->addFilterOnKeywordOrPhrase($keywordFilter) ->addFilterOnLocales($localeFilter) ->showUserDetails() ->showMetrics() ->performRequest() ;
Find all replies from a Tweet
->addFilterOnConversationId($tweetId);
Tweet endpoints
Fetch a tweet by Id
Example:
$return = $client->tweet()->->fetch(1622477565565739010)->performRequest();
Create a new Tweet
Example:
$return = $client->tweet()->create()->performRequest(['text' => 'Test Tweet... ']);
Upload image to Twitter (and use in Tweets)
Example:
$file_data = base64_encode(file_get_contents($file)); $media_info = $client->uploadMedia()->upload($file_data); $return = $client->tweet()->create() ->performRequest([ 'text' => 'Test Tweet... ', "media" => [ "media_ids" => [ (string)$media_info["media_id"] ] ] ]) ;
Tweet/Quotes endpoints
Returns Quote Tweets for a Tweet specified by the requested Tweet ID
Example:
$return = $client->tweetQuotes()->getQuoteTweets($tweetId)->performRequest();
Retweet endpoints
Retweet a Tweet
Example:
$return = $client->retweet()->performRequest(['tweet_id' => $tweet_id]);
Tweet/Replies endpoints
Hide a reply to a Tweet
Example:
$return = $client->->tweetReplies()->hideReply($tweetId)->performRequest(['hidden' => true]);
Unhide a reply to a Tweet
Example:
$return = $client->->tweetReplies()->hideReply($tweetId)->performRequest(['hidden' => false]);
Tweet/Bookmarks endpoints
Lookup a user's Bookmarks
Example:
$return = $client->tweetBookmarks()->lookup()->performRequest();
Users endpoints
User/Blocks endpoints
Retrieve the users which you've blocked
Example:
$return = $client->userBlocks()->lookup()->performRequest();
User/Follows endpoints
Retrieve the users which are following you
Example:
$return = $client->userFollows()->getFollowers()->performRequest();
Retrieve the users which you are following
Example:
$return = $client->userFollows()->getFollowing()->performRequest();
Follow a user
Example:
$return = $client->userFollows()->follow()->performRequest(['target_user_id' => $userId]);
Unfollow a user
Example:
$return = $client->userFollows()->unfollow($userId)->performRequest(['target_user_id' => self::$userId]);
User/Lookup endpoints
Find Me
Example:
$return = $client->userMeLookup()->performRequest();
Find Twitter Users
findByIdOrUsername()
expects either an array, or a string.
You can specify the search mode as a second parameter (Client::MODES['USERNAME']
OR Client::MODES['ID']
)
Example:
$return = $client->userLookup() ->findByIdOrUsername('twitterdev', \Noweh\TwitterApi\UserLookup::MODES['USERNAME']) ->performRequest() ;
User/Mutes endpoints
Retrieve the users which you've muted
Example:
$return = $client->userMutes()->lookup()->performRequest();
Mute user by username or ID
Example:
$return = $client->userMutes()->mute()->performRequest(['target_user_id' => $userId]);
Unmute user by username or ID
Example:
$return = $client->userMutes()->unmute()->performRequest(['target_user_id' => $userId]);
Contributing
Fork/download the code and run
composer install
copy test/config/.env.example
to test/config/.env
and add your credentials for testing.
To run tests
./vendor/bin/phpunit
To run code analyzer
./vendor/bin/phpstan analyse .