Create an Eventbrite App that Notifies You of Local Events with Twilio SMS and Laravel PHP

August 30, 2019
Written by
Michael Jaroya
Contributor
Opinions expressed by Twilio contributors are their own

Create an Eventbrite App that Notifies You of Local Events with Twilio SMS and Laravel PHP.png

Networking is a skill that everyone needs, especially if you are an entrepreneur or plan on being one. A strong professional connection can help take your business to the next level. Those connections can provide solutions to the complex problems you’re facing, expand your customer base, and much more. Even if you’re not an entrepreneur, networking is a proven method to career and economic advancement.

The easiest way to create this connection is by attending local events in your city and interacting with people physically. I can’t count the number of times I have googled the keywords “events near me” only to see a lot of irrelevant results, not to mention the noise of ads. The events that are relevant are either in a faraway city or in another country altogether.

In this tutorial, we are going to implement a simple app that sends daily SMS notifications of events happening near you using Twilio SMS and the Eventbrite API.

Getting Started

To complete this tutorial, you will need the following:

Create a New Laravel Project

Create a new Laravel project by running the following command in your terminal:

$ composer create-project laravel/laravel event-app
$ cd event-app

Set up the Twilio SDK

First, we need to install the Twilio PHP SDK using Composer. This will allow our application to easily connect to the Twilio API and programmatically generate SMS. In your terminal, run the command below:

$ composer require twilio/sdk

Creating an Eventbrite Personal OAuth Token

Our application will be pulling its data from the popular event management platform, Eventbrite. In order to request data from the service and use the Eventbrite API, you must have a personal OAuth token. If you don't have a token, create one by following this guide.

After you have completed your token setup, install Guzzle to execute the HTTP API requests. Guzzle is a great alternative to writing your server-side requests in cURL. Run the command below to install the latest version:

$ composer require guzzlehttp/guzzle

Once these steps are complete, update the .env file with the credentials from your Twilio and Eventbrite dashboards as shown below:

TWILIO_SID="Your Twilio SID"
TWILIO_AUTH_TOKEN="Your Twilio Auth Token"
TWILIO_PHONE_NUMBER="Your Twilio SMS enable phone number"
EVENTBRITE_AUTH_TOKEN="Your Eventbrite Auth Public Token"

Create the Event App

We will create a model and extend it with custom methods to fetch events from Eventbrite based on location and time filters. Once filtered, the events will be sent to a list of subscribers using Twilio SMS.

Create the Event Model

Run the command below to create the Event model:

$ php artisan make:model Event 

Create Logic to Fetch and Send Events

We will use a function to fetch events from Eventribe and pass location and time filters. Let's make the API to return events happening this week within the locality of the subscriber.

You can always change these filters to fit your needs. More information on event filters can be found in the Eventribe docs. Open the app/Event.php file generated by the previous command and add the following method.

<?php
   use GuzzleHttp\Client as GuzClient;
       /**
   * Fetch events from Eventbrite
   * @param $location
   * @param $date
   * @param $within_radius
   * @param $limit
   * @param $sort_by
   */
  public function fetchEvents($location,$date,$limit=3,$sort_by="best",$within_radius="10km"){
      $client = new GuzClient();
      $events="";
      $base_url         = "https://www.eventbriteapi.com/v3/events/search?";
      $location         = "location.address=".$location."&location.within=".$within_radius."&expand=venue";
      $eventbrite_token = "&token=".getenv('EVENTBRITE_AUTH_TOKEN');
      $date             = "&start_date.keyword=".$date;
      $sort_by          = "&sort_by=".$sort_by;
      $url              = $base_url.$location.$eventbrite_token.$date.$sort_by;
      $client           = new GuzClient();
      $res              = $client->get($url);
      $data             = json_decode($res->getBody()->getContents());
      // transform response into a format that can easily be consumed through SMS.
      $count=1;
      foreach ($data->events as $datum){
         $title=$datum->name->text;
         $start_time=explode("T",$datum->start->local);
         $start_date=$start_time[0];
         $start_time=isset($start_time[1]) ? date('h:i a', strtotime($start_time[1])):"";
         $end_time=explode("T",$datum->end->local);
         $end_date=$end_time[0];
         $end_time=isset($end_time[1]) ? date('h:i a', strtotime($end_time[1])):"";
         $price=($datum->is_free==true)?"Free":"Paid";
         $url=$datum->url;
         $venue=$datum->venue->address->address_1;
         $sub_venue=isset($datum->venue->address->address_2)?"(".$datum->venue->address->address_2.")":"";
         $main_body="Event Name:".$title." \n Starts :".$start_date." ".$start_time." \n Ends :".$end_date." ".$end_time." \n Price :".$price." \n Venue :".$venue.$sub_venue." \n Ticket Link :".$url." \n \n ";
         $events.=$main_body;
         if($count==$limit){
            break;
         }
         $count++;
      }
      return $events;
  }

The fetchEvents() function accepts five parameters:

  1. $location - the location of the subscriber e.g Nairobi
  2. $date - the start date keyword
  3.  $within_radius - the radius covered from the location specified
  4. $limit - the maximum number of events to be returned
  5. $sort_by - how to sort the events

The start $date keyword returns events with start dates within the given keyword date range. Keyword options are "this_week", "next_week", "this_weekend", "next_month", "this_month", "tomorrow", "today".

The $sort_by parameter supports three options; "date", "distance", and "best". Prefix with a hyphen to reverse the order, e.g. "-date".

By default, the app will return events within a 10 Kilometres radius and sort by “best”.

Once we receive the response from Eventbrite with the list of events, we transform it into a format that can easily be consumed through SMS and remove unnecessary details.

Next, we need to create a function to send the fetched events to subscribers via Twilio SMS. Add the code below to the Event model:

<?php
use Twilio\Rest\Client;
   /**
   * send Twilio SMS
   *
   * @param $to
   * @param $sms_body
   */
   function sendSMS( $to, $events ) {
   // Your Account SID and Auth Token from twilio.com/console
     $sid    = getenv( 'TWILIO_SID' );
     $token  = getenv( 'TWILIO_AUTH_TOKEN' );
     $client = new Client( $sid, $token );
     $client->messages->create(
        $to,
        [
           // A Twilio phone number you purchased at twilio.com/console
           'from' => getenv( 'TWILIO_PHONE_NUMBER' ),
           // the body of the text message you'd like to send
           'body' => $events
        ]
     );
   }

The sendSMS() function accepts two parameters; $to the number of the recipient and the $events which forms the SMS body.

Consolidating the App

Having all of the components required to build the app, let’s put everything together. Reopen the Event model in app/Event.php and add this final method:

  /**
   * The Event App
   */
   public function eventApp(){
     // replace this your subscribers data
     $subscribers=
     [
         [
         'to' => '+2547XXXXXXXX',
         'location' => 'Nairobi',
         ],
         [
           'to' => '+2547XXXXXXXX',
           'location' => 'Kisumu'
        ]
     ];
     foreach($subscribers as $subscriber){
        $events=$this->fetchEvents($subscriber['location'],"this_week");
         // send sms
        if($events!=""){
           $this->sendSMS($subscriber['to'],$events);
        }
     }
 }

The Event Artisan Command

Lets create an artisan command that we will call from Laravel Scheduler to automate the process of sending events to the subscribers.

Run the artisan command below to generate the artisan command:

$ php artisan make:command sendEvents

Open the file app/Console/Commands/sendEvents.php and update the handle method as shown below:

<?php
use App\Event;
class sendQuotes extends Command
{
   protected $signature = 'send:event';
     /**
    * Execute the console command.
    *
    * @return mixed
    */
   public function handle()
   {
       $event = new Event();
       $event->eventApp();
       $this->info('Success :)');
   }
}

Laravel's command scheduler allows you to fluently and expressively define your command schedule within Laravel itself. When using the scheduler, only a single Cron entry is needed on your server. Your task schedule is defined in the app/Console/Kernel.php file's schedule method.

Next, update schedule method with this single line of code.

   protected function schedule(Schedule $schedule)
   {
       $schedule->command('send:event')->cron('30 6 * * 1,5');
   }

The command will be executed every Monday and Friday at 6:30 AM.

If you need help, you can use http://corntab.com/ to create cron rules.

Finally, add the following Cron entry to your server.

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

This Cron will call the Laravel command scheduler every minute. When the schedule:run command is executed, Laravel will evaluate your scheduled tasks and runs the tasks that are due.

Testing

To test the app, navigate to your project directory and run the artisan command below:

$ php artisan send:event

You should get an SMS as shown below:

Eventbrite Events sent via SMS

Wrap Up

To build upon this app, you can tailor the events received by each subscriber to be based on their interests and biases and also give them the liberty to choose the frequency in which they want to get notified. You can achieve this by providing your subscribers with a platform where they can set their preferences. The code is available on Github.

Have some ideas to better improve the app? Let me know. I can’t wait to see what you build.

Feel free to reach out to me: