duane blake

Published on November 14, 2015 | Posted in Laravel

Sending out automated tweets in Laravel

Sending out automated tweets is really easy for a Laravel using the CodeBird package. I’ve wrote a quick guide how to do this which you may find useful for you site.

Automated tweet

For the following guide all you need is a fresh version of Laravel 5.1 and a Twitter account where you want to send the tweets from.

  • Setting up the Database and seeding the data

  • We will be using sqlite for the database, so this is the first thing we need to create.

    touch storage/database.sqlite
  • Open up /config/database.php and change the site to use sqlite rather than mysql

    'default' => env('DB_CONNECTION', 'sqlite'),
  • Now we need to create our migration. We are going to just have table for our quote.

    php artisan make:migration create_quotes_table --create=quotes
  • Now open up our the migration in the database/migrations folder

    <?php
    
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;
    
    class CreateQuotesTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('quotes', function (Blueprint $table) {
                $table->increments('id');
                $table->text('body');
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::drop('quotes');
        }
    }
    
    
  • Back to the command now we will migrate the tables

      php artisan migrate  
  • We going to need add some dummy data using the fzaninotto/faker package. From the command line enter the following

      composer require fzaninotto/faker  
  • Next step is to create Quote model. Again from the command line enter the following

     php artisan make:model Quote  
  • Time to create the seed file

    php artisan make:seed QuotesTableSeeder 
  • Open up the seeder file database/seed QuotesTableSeeder.php. We are now going to create 50 random records to do so add the following below to the file

    <?php
    
    use Illuminate\Database\Seeder;
    use App\Quote;
    
    class QuotesTableSeeder extends Seeder
    {
        /**
         * Run the database seeds.
         *
         * @return void
         */
        public function run()
        {
            $faker = Faker\Factory::create();
            
            foreach(range(1,50) as $index) {
                Quote::create([
                    'body' => $faker->sentence()
                ]);
            }
                
        }
    } 
  • We now to add the seeder classes to the following file database/seeds/DatabaseSeeder.php

    <?php
    
    use Illuminate\Database\Seeder;
    use Illuminate\Database\Eloquent\Model;
    
    class DatabaseSeeder extends Seeder
    {
        /**
         * Run the database seeds.
         *
         * @return void
         */
        public function run()
        {
            Model::unguard();
    
            $this->call(QuotesTableSeeder::class);
    
            Model::reguard();
        }
  • In the Quote Model file – app/Quote.php we need to state that the body field will be fillable.

    protected $fillable = ['body'];
  • Now time to seed the database with our dummy data.

    php artisan migrate --seed
  • Creating our Twitter credentials

  • We now need to get our Twitter credentials go to the following URL https://apps.twitter.com/. You need sign into the twitter account which you want to send the tweets from, Once signed in click on Create New App

    Fill in the fields for website just use your development enviroment URL. If you haven’t got a production url. Then agree to the terms.

  • Click on – “Manage keys and access tokens”. To generate your keys and tokens. On the the next page click on “Create my Access Token”.

  • Make a note of the Consumer Key (API Key), Consumer Secret (API Secret), Access Token, Access Token Secret.

  • Creating the Twitter Command

    Time to create a Command to send a random quote to Twitter. Again from the command line enter the following

     php artisan make:console SendTweets --command=tweets:send  
  • We need to pull in a composer package called jublonet/codebird-php. From the command line enter the following

     composer require jublonet/codebird-php  
  • Open up the file we just created app/Console/Commands/SendTweets.php. Now we need to add in CodeBird and our Quote model.

    use Illuminate\Console\Command;
    use App\Quote;
    use Codebird\Codebird; 
  • Update the description of the command

     protected $description = 'Send a random quote tweet.'; 
  • Now in the handle function we are going to create a new codebird instance and register our Twitter Consumer and Token Keys.

    $cb = new Codebird;
    $cb->setConsumerKey('TWITTER_CONSUMERKEY', 'TWITTER_CONSUMERSECRET');
    $cb->setToken('TWITTER_TOKENKEY', 'TWITTER_TOKENSECRET'); 
  • I’ve been having difficulties maybe because the setup of my vagrant box. So this command is optional. I added a connection timeout for the script. Again this goes in the handle function.

    $cb->setConnectionTimeout(10000);
    $cb->setTimeout(20000); 
  • We just going to fetch a random quote from the table and send it to Twitter.

    $quote = Quote::all()->random(1);
    $cb->statuses_update([
    	'status' => $quote->body
    ]); 
  • Now open up the app/Console/Kernel.php in this file we are going to add our twitter command to artisan.

    protected $commands = [
    	\App\Console\Commands\Inspire::class,
            \App\Console\Commands\SendTweets::class
    ]; 
  • Our Twitter command is now built if you go back to the command line enter the following below to see our artisan command. We will now see our command in the artisan list

    php artisan list 
  • With the command built we can send out a random tweet again from the command line enter the following below

    php tweets:send 
  • Automating our Twitter Command

    The final stage left is to schedule our tweet. I recommend reading this link from the Laravel documention http://laravel.com/docs/5.1/scheduling. Now go back to the app/Console/Kernel.php file. We going to send a tweet every hour at 3am.

    protected function schedule(Schedule $schedule)
        {
            $schedule->command('tweets:send')
                     ->weekly()->sundays()->at('3:00');
        } 
  • You need to add the following to your Cron file.

    * * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1 
  • This is end of the tutorial the code above can be refactored down loads but I wanted to keep as simple and precise to the follow through. Hopefully you can find use for this code in your application.

View the code on BitBucket.

2 comments

  1. Michael says:

    “We need to pull in a composer package called jublonet/codebird-php. From the command line enter the following

    composer require fzaninotto/faker ”

    This seems to be a mistake.

Leave a comment

Your email address will not be published. Required fields are marked *