Build an English to Shakespearean Translator using SMS and PHP

January 28, 2020
Written by
Ladapo Samuel
Contributor
Opinions expressed by Twilio contributors are their own

Build an English to Shakespearean Translator using SMS and PHP

Technical Requirements

To complete this tutorial, you will need the following dependencies globally installed on your computer:

Set Up Our Development Environment

To kick start our project we will need to create a project directory for it. You may use Shakespeare as this is what I will be using too. In the folder create the following files:

  • .env
  • webhook.php
  • functions.php

Next, we need to set up our .env file.

NOTE: The .env file is a hidden file we create on our servers to store secret and private keys. It is not accessible by the browser, so we can store our API keys or credentials in it and access it from anywhere within our app on the server-side.

To allow the support of .env configs in our app, we need to install a package using Composer. Run this command in your terminal in the project directory:

$ composer require vlucas/phpdotenv

We also need to install one more package from Twilio. There are many libraries that enable us to access the Twilio API more efficiently than traditional cURL requests. For this project, we need to install the Twilio PHP SDK. Run the following command in your terminal in the project directory.

$ composer require twilio/sdk

Setup Twilio Credentials & Phone Number

If you have not already done so, take a few minutes and head to your Twilio account to create a new number. We need to get the following information from the Twilio console to allow us to send and receive SMS from our project:

  • Twilio Account SID
  • Twilio Auth Token
  • A Phone Number

Once we have these items, we can add them to our .env file.

# TWILIO CREDENTIALS
TWILIO_ACCOUNT_SID=""
TWILIO_AUTH_TOKEN=""
TWILIO_PHONE_NUMBER="+1999999999"

Create a Function to Translate our English SMS into Shakespeare

To translate our English language SMS into Shakespeare, we are going to leverage the FunTranslations API service by creating a function for it.

API Explorer

Update you .env file with FunTranslation’s API URL like so:

# API TRANSLATION URL
TRANSLATION_API_URL=http://api.funtranslations.com/translate/shakespeare.json

The functions.php file we created earlier will contain the function that will take the user’s SMS, process it, and send it to FunTranslation’s API. Add the following code to the functions.php file.


<?php

function clean_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}


function convertToShakespeare($englishTexts)
{
    //clean user data
  
    if ($englishTexts) {
       $englishTexts =  clean_input($englishTexts);
         try {
            $data = [
          'text' => $englishTexts
        ];
            $url = getenv("TRANSLATION_API_URL");
            $query_url = sprintf("%s?%s", $url, http_build_query($data));
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $query_url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_TIMEOUT, 10);
            curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($curl, CURLOPT_HEADER, 0);
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
            $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            $result = curl_exec($curl);
            header('Content-type: application/json');
            $response = json_decode($result, true);
            if($response['success']['total'] === 1) {
              return $response['contents']['translated'];
            }
            curl_close($curl);
        } catch (exception $e) {
            print_r($e);
        }
    }
}

Create a Twilio Webhook

To receive SMS translation requests from users, we will need to create a Twilio webhook. Twilio has a webhook feature that sends a response to an endpoint whenever your phone number receives a message.

We will need to create our own webhook to receive translation requests from users. In the webhook.php file, copy and paste the following code into it.

  
<?php
require 'vendor/autoload.php';

use Twilio\Rest\Client;

// Load our `.env` variables
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

require_once('functions.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $message = $_REQUEST['Body'] ?? '';
    $from = $_REQUEST['From'] ?? '';
  if ($message !== '') {
      $account_sid = getenv("TWILIO_ACCOUNT_SID");
      $auth_token = getenv("TWILIO_AUTH_TOKEN");
      $twilio_number = getenv("TWILIO_PHONE_NUMBER");
      $translatedEnglish = convertToShakespeare($message);
      $client = new Client($account_sid, $auth_token);
      $client->messages->create($from,
      array(
        'from' => $twilio_number,
        'body' =>  $translatedEnglish
      )
    );
  }
}

We will now use Ngrok in order to make this webhook accessible through a public URL from our localhost.

From the terminal, run the command:

$ php -S localhost:3000

On a new terminal window, run the command:

./ngrok http 3000

Your terminal window should look like this:

ngrok session

In our Twilio project, we will provide the webhook URL above, followed by the path to our webhook file. For example, mine is:

https://7c7e6e32.ngrok.io/webhook.php

The final step is hooking our Twilio number to the webhook we created. Navigate to the active numbers on your dashboard and click on the number you would like to use. In the messaging section, there is an input box labeled “A MESSAGE COMES IN”. Replace the URL with our webhook URL and click “Save”!

Twilio phone number edit screen

Testing Our App

Send I want to drink water for example to your Twilio number to get its translation to Shakespeare.

SMS response

Conclusion

Good job! Now we can translate the English language to Shakespeare using SMS. You can implement other fun translations like translating to minions language.

Bonus

The Github Repo is available for a quick start: https://github.com/ladaposamuel/english-shakespeare

Additional Reading

If you would like to learn more about any of the technologies mentioned within this tutorial, check out the links below:

 

Ladapo Samuel

Email: ladaposamuel@gmail.com

Twitter: @samuel2dotun

Github: ladaposamuel