For any queries you can reach us at infovistarindia@gmail.com / WhatsApp us: +919158876092

Build a WhatsApp Chatbot with Twilio WhatsApp API using Codeigniter

Overview

Build a WhatsApp Chatbot with Twilio WhatsApp API using Codeigniter

In this tutorial, we will create a simple WhatsApp Chatbot that enables you to get details about a developer's GitHub profile using their username.

Prerequisites

$ composer require twilio/sdk
$ composer require guzzlehttp/guzzle

Next, Go to your Twilio dashboard and copy your ACCOUNT SID and AUTH TOKEN which will be used for authenticating your requests with the Twilio SDK:

Proceed to update your constant variables with these credentials. Open up your config/constants.php file and add the following variables:

define('TWILIO_SID', "TWILIO_SID");
define('TWILIO_AUTH_TOKEN', "TWILIO_AUTH_TOKEN");
define('TWILIO_WHATSAPP_NUMBER', "+14XXXXXXXX6");
Build a WhatsApp Chatbot with Twilio WhatsApp API using Codeigniter

controllers/Chatbot.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

use GuzzleHttp\Exception\RequestException;
use Twilio\Rest\Client;
// Load Composer's autoloader
require 'vendor/autoload.php';

class Chatbot extends CI_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function index() {
    }

    public function listenToReplies() {
        $from       = $this->input->post('From');
        $body       = $this->input->post('Body');
        $client     = new \GuzzleHttp\Client();
        try {
            $response = $client->request('GET', "https://api.github.com/users/junaidsshaikh");
            $githubResponse = json_decode($response->getBody());
            if ($response->getStatusCode() == 200) {
                $message = "*Name:* $githubResponse->name\n";
                $message .= "*Bio:* $githubResponse->bio\n";
                $message .= "*Lives in:* $githubResponse->location\n";
                $message .= "*Followers:* $githubResponse->followers devs\n";
                $message .= "*Following:* $githubResponse->following devs\n";
                $message .= "*Number of Repos:* $githubResponse->public_repos\n";
                $message .= "*URL:* $githubResponse->html_url\n";
                $message .= "*Repos URL:* $githubResponse->repos_url\n";
                $this->sendWhatsAppMessage($message, $from);
            } else {
                $this->sendWhatsAppMessage($githubResponse->message, $from);
            }
        } catch (RequestException $th) {
            $response = json_decode($th->getResponse()->getBody());
            $this->sendWhatsAppMessage($response->message, $from);
        }
    }

    public function sendWhatsAppMessage($message, $recipient) {
        $twilio_whatsapp_number = TWILIO_WHATSAPP_NUMBER;
        $account_sid = TWILIO_SID;
        $auth_token = TWILIO_AUTH_TOKEN;
        $client = new Client($account_sid, $auth_token);
        return $client->messages->create($recipient, array('from' => "whatsapp:$twilio_whatsapp_number", 'body' => $message));
    }
}

listenToReplies()

The listenToReplies() method is where messages sent to your WhatsApp number will be executed. The response sent will rely on the body of the received message.

public function listenToReplies() {
    $from       = $this->input->post('From');
    $body       = $this->input->post('Body');
    $client     = new \GuzzleHttp\Client();
    try {
        $response = $client->request('GET', "https://api.github.com/users/junaidsshaikh");
        $githubResponse = json_decode($response->getBody());
        if ($response->getStatusCode() == 200) {
            $message = "*Name:* $githubResponse->name\n";
            $message .= "*Bio:* $githubResponse->bio\n";
            $message .= "*Lives in:* $githubResponse->location\n";
            $message .= "*Followers:* $githubResponse->followers devs\n";
            $message .= "*Following:* $githubResponse->following devs\n";
            $message .= "*Number of Repos:* $githubResponse->public_repos\n";
            $message .= "*URL:* $githubResponse->html_url\n";
            $message .= "*Repos URL:* $githubResponse->repos_url\n";
            $this->sendWhatsAppMessage($message, $from);
        } else {
            $this->sendWhatsAppMessage($githubResponse->message, $from);
        }
    } catch (RequestException $th) {
        $response = json_decode($th->getResponse()->getBody());
        $this->sendWhatsAppMessage($response->message, $from);
    }
}

sendWhatsAppMessage()

The sendWhatsAppMessage() method uses the Twilio SDK for sending the WhatsApp messages:

public function sendWhatsAppMessage($message, $recipient) {
    $twilio_whatsapp_number = TWILIO_WHATSAPP_NUMBER;
    $account_sid = TWILIO_SID;
    $auth_token = TWILIO_AUTH_TOKEN;
    $client = new Client($account_sid, $auth_token);
    return $client->messages->create($recipient, array('from' => "whatsapp:$twilio_whatsapp_number", 'body' => $message));
}

Setup the Webhook - config/routes.php

$route['api/chat-bot'] = 'Chatbot/listenToReplies';

Update the Sandbox Webhook

Go to the WhatsApp sandbox settings in your Twilio dashboard and update the input field labeled as "WHEN A MESSAGE COMES IN" with the complete URL to your chatbot.

Your webhook URL must be in following format:

https://<hostname>/api/chat-bot

Output

Build a WhatsApp Chatbot with Twilio WhatsApp API using Codeigniter