PHP code example of scottybo / twitter

1. Go to this page and download the library: Download scottybo/twitter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

scottybo / twitter example snippets


'providers' => [
	Scottybo\Twitter\TwitterServiceProvider::class,
]

'aliases' => [
	'Twitter' => Scottybo\Twitter\Facades\Twitter::class,
]

Twitter::linkify($tweet);

Twitter::ago($timestamp);

Twitter::linkUser($user);

Twitter::linkTweet($tweet);

Route::get('/userTimeline', function()
{
	return Twitter::getUserTimeline(['screen_name' => 'scottybo', 'count' => 20, 'format' => 'json']);
});

Route::get('/homeTimeline', function()
{
	return Twitter::getHomeTimeline(['count' => 20, 'format' => 'json']);
});

Route::get('/mentionsTimeline', function()
{
	return Twitter::getMentionsTimeline(['count' => 20, 'format' => 'json']);
});

Route::get('/tweet', function()
{
	return Twitter::postTweet(['status' => 'Laravel is beautiful', 'format' => 'json']);
});

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]);
});

Route::get('twitter/login', ['as' => 'twitter.login', function(){
	// your SIGN IN WITH TWITTER  button should point to this route
	$sign_in_twitter = true;
	$force_login = false;

	// Make sure we make this request w/o tokens, overwrite the default values in case of login.
	Twitter::reconfig(['token' => '', 'secret' => '']);
	$token = Twitter::getRequestToken(route('twitter.callback'));

	if (isset($token['oauth_token_secret']))
	{
		$url = Twitter::getAuthorizeURL($token, $sign_in_twitter, $force_login);

		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', function() {
	// You should set this route on your Twitter Application settings as the callback
	// https://apps.twitter.com/app/YOUR-APP-ID/settings
	if (Session::has('oauth_request_token'))
	{
		$request_token = [
			'token'  => Session::get('oauth_request_token'),
			'secret' => Session::get('oauth_request_token_secret'),
		];

		Twitter::reconfig($request_token);

		$oauth_verifier = false;

		if (Input::has('oauth_verifier'))
		{
			$oauth_verifier = Input::get('oauth_verifier');
			// getAccessToken() will reset the token for you
			$token = Twitter::getAccessToken($oauth_verifier);
		}

		if (!isset($token['oauth_token_secret']))
		{
			return Redirect::route('twitter.error')->with('flash_error', 'We could not log you in on Twitter.');
		}

		$credentials = Twitter::getCredentials();

		if (is_object($credentials) && !isset($credentials->error))
		{
			// $credentials contains the Twitter user object with all the info about the user.
			// Add here your own user logic, store profiles, create new users on your tables...you name it!
			// Typically you'll want to store at least, user id, name and access tokens
			// if you want to be able to call the API on behalf of your users.

			// This is also the moment to log in your users if you're using Laravel's Auth class
			// Auth::login($user) should do the trick.

			Session::put('access_token', $token);

			return Redirect::to('/')->with('flash_notice', 'Congrats! You\'ve successfully signed in!');
		}

		return Redirect::route('twitter.error')->with('flash_error', 'Crab! Something went wrong while signing you up!');
	}
}]);

Route::get('twitter/error', ['as' => 'twitter.error', function(){
	// Something went wrong, add your own error handling here
}]);

Route::get('twitter/logout', ['as' => 'twitter.logout', function(){
	Session::forget('access_token');
	return Redirect::to('/')->with('flash_notice', 'You\'ve successfully logged out!');
}]);


$file_size = 'FILE_SIZE_IN_BYTES';

// Initialize the media upload - no files are sent at this point
// https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload-init#parameters
$init_media = Twitter::uploadMedia([
    'command' => 'INIT',
    'media_type' => 'video/mp4',
    'media_category' => 'tweet_video',
    'total_bytes' => $file_size,
    'additional_owners' => null
]);

// Upload the first (or only) chunk
// https://developer.twitter.com/en/docs/media/upload-media/uploading-media/chunked-media-upload
$uploaded_media = Twitter::uploadMedia([
    'media' => $file,
    'command' => 'APPEND',
    'segment_index' => '0',
    'media_id' => $init_media->media_id_string
]);


// Finalize the video upload
$final_media = Twitter::uploadMedia([
    'command' => 'FINALIZE',
    'media_id' => $init_media->media_id_string,
]);

// After a video has been uploaded it can take Twitter some time to process it before 
// it can be used in a Tweet. A better approach than the one below would be to use a
// queue (e.g. Redis), but this demonstrates the logic.
$waits = 0;

while($waits <= 3) {

    // Check the status
    $status_media = Twitter::uploadStatus([
        'command' => 'STATUS',
        'media_id' => $init_media->media_id,
    ]);

	// Check that the STATUS command is returning a valid state
    if(isset($status_media->processing_info->state)) {

        switch($status_media->processing_info->state) {
            case 'succeeded':
                $waits = 4; // break out of the while loop
                break;
            case 'failed':
                throw new Exception('Video processing failed: '.$status_media->processing_info->error->message);
            default:
            	// Check how long Twitter tells us to wait for before checking the status again
                $status_media->processing_info->check_after_secs;
                
                // Sleep for that amount of time
                sleep($status_media->processing_info->check_after_secs);

                // Increment the wait count (in this example, we'll wait 3 times before leaving the loop just in case Twitter breaks)
                $waits++;
        }

    } else {
        throw new Exception('There was an unknown error uploading your video');
    }
}

// Now that Twitter has processed the video upload, let's send the Tweet
$post_response = Twitter::postTweet([
    'status' => $text,
    'media_ids' => $final_media->media_id_string
]);

            

try
{
	$response = Twitter::getUserTimeline(['count' => 20, 'format' => 'array']);
}
catch (Exception $e)
{
	// dd(Twitter::error());
	dd(Twitter::logs());
}

dd($response);

/app/config/packages/scottybo/twitter/config.php

/config/ttwitter.php