Last weekend I decided to make one of my Twitter accounts a little more active by posting a random article from the website at a random interval of time.
Here’s a step-by-step process on how I accomplished this process.
What is Posted?
I decided to post a random song from the website musiccafenepal.com every 2 hours on the Twitter account MusicCafeNepal
1. Sign up for Twitter developer account
Sign up to https://developer.twitter.com/en/portal/dashboard and create a new App and get the credentials.
For this, we are using API Key, API Secret Key, Access Token and Access Token Secret.
2. Add Package atymic/twitter on Laravel
For this task, we are using a composer package atymic/twitter.
Install the package on Laravel by using the following command.
composer require atymic/twitter
Add the above keys and credentials to the .env file in Laravel
TWITTER_CONSUMER_KEY=XXXX TWITTER_CONSUMER_SECRET=XXXX TWITTER_ACCESS_TOKEN=XXXX TWITTER_ACCESS_TOKEN_SECRET=XXXX
3. Create a Tweet command in Laravel console
To send tweets to the Twitter API, I decided to create a console command on Laravel.
Create a new console command in Laravel:
php artisan make:command Twitter
And add the code inside the handle() function in app/console/Commands/Twitter.php file
Also, change the value of $signature property in the above file to look like this,
protected $signature = ‘twitter:tweet’;
4. Fetch a random song from the database in Laravel
Now when someone hits the console command, we will fetch a random song from the database and Tweet that song.
To Fetch a random song
inRandomOrder(): will fetch a random row from the database
Compose a tweet with the song details
$tweetContent = sprintf(“%s Chords, Lyrics and Video by %s on MusicCafeNepal %s”, $song->getTitle(), $song->getArtistNames(), $song->getUrl());
And with Tweet Facade, tweet the above content
Twitter::postTweet([‘status’ => $tweetContent, ‘response_format’ => ‘json’]);
5. Add a cron Job
Now that we have created the console command, we will put the command on the cron Job to run it on interval of every 2 hours.
For that we log in to our server and do the following.
and Add the cron command to run it every 2 hours. You can use this tool to design your own cron command based on your need.
0 */2 * * * php PATH_TO_LARAVEL_FOLDER/artisan twitter:tweet
This will run the above command every two hours and the tweet will be posted on your Twitter account every two hours.
Now you know how to automatically tweet random articles from your website. You can also implement this to tweet trending articles, new articles or other kind of contents from your website.