switchon@lavalamp.biz
+27(0) 83 419 4851 / +27(0) 21 036 1165
Application & software development
Get A Quote

    • Home
    • Services
      • Application & software development
      • Outsourced software development
      • Project based resourcing
      • Digital marketing & consulting
      • Graphic design & consulting
      • UI / UX design & consulting
      • Recruitment services
      • Lease an expert
    • About
      • How we work
      • NBConsult Group
      • Partners
      • Lightbox Digital
    • Blog
    • Join us
    • Contact

    • Home
    • Services
      • Application & software development
      • Outsourced software development
      • Project based resourcing
      • Digital marketing & consulting
      • Graphic design & consulting
      • UI / UX design & consulting
      • Recruitment services
      • Lease an expert
    • About
      • How we work
      • NBConsult Group
      • Partners
      • Lightbox Digital
    • Blog
    • Join us
    • Contact

    • Home
    • Services
      • Application & software development
      • Outsourced software development
      • Project based resourcing
      • Digital marketing & consulting
      • Graphic design & consulting
      • UI / UX design & consulting
      • Recruitment services
      • Lease an expert
    • About
      • How we work
      • NBConsult Group
      • Partners
      • Lightbox Digital
    • Blog
    • Join us
    • Contact

    • Home
    • Services
      • Application & software development
      • Outsourced software development
      • Project based resourcing
      • Digital marketing & consulting
      • Graphic design & consulting
      • UI / UX design & consulting
      • Recruitment services
      • Lease an expert
    • About
      • How we work
      • NBConsult Group
      • Partners
      • Lightbox Digital
    • Blog
    • Join us
    • Contact
    misconceptions about software development
    Misconceptions About Software Development
    Sep 26, 2022
    laragon
    Laragon: Fast Website Development Environment For Windows
    Oct 24, 2022

    Building A Chat Bot With The WhatsApp Service From Twilio In Laravel

    twilio
    twilio

    In this blog I’ll be going through the steps to making a chat bot in Laravel using Twilio’s Whatapp service and how to setup your sandbox environment for testing your chat bot using Postman.



    Initial Setup:


    Step 1:

    You have to have an account made with Twilio in order for this to work. If you don’t have one please register here.


    Step 2:

    We will need to make use of some packages to assist us in the process of building the chat bot. The following are the composer packages that you will need to run on the Laravel application that you are working with.

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

    Step 3:

    We need to setup our .env file. So that it can make use of your account specific “ACCOUNT SID” and “AUTH TOKEN” which will be used to authenticate the requests using the Twilio SDK composer package we installed in the previous step.

      twilio account dashboard You need to add the following to you .env file:
    TWILIO_SID="YOUR_ACCOUNT_SID"
    TWILIO_AUTH_TOKEN="YOUR_AUTH_TOKEN"


    Now lets set up your sandbox:

    We are going to setup our sand box so that we can use the mobile number they provide to test with.  In your regular production environment you will need a Twilio Approved Number in order to make use of their WhatsApp service. Thanks to Twilio's API we are able to prototype our code before even having an Approved Twilio Number.


    Step 1:

    In order to setup your sandbox you must navigate to your accounts Twilio console dashboard in order to start the process.


    Step 2:

    There you will see a menu on the left hand side of the screen. Expand the tab that says "Messaging", Then expand the tab that says "Try it out". There you should see a tab that says "Send a WhatsApp message".

    setup twilio sandbox

    To sum it all up for you.  On this screen you learn a bit about the Twilio API and how it handles requests. Besides that we get provided with a number that is Twilio Approved and ready for you to start prototyping with.  To get setup you will need to send WhatsApp a message to the number they provide like in the above example (I.e +1 415 523 8886) your message must contain the word " join <key-phrase>". Once you have done that you should receive an automated reply saying that it was successfully setup.

    Important note! If you setup your sandbox. After 3 days you must reinitiate the sandbox setup. From my experience the key phrase doesn't change so all you would need to do is resend the message (" join <key-phrase>").

    That's all! You have setup your sandbox correctly then.


    Step 3:

    All that's left for us to do is to add our Twilio approved number to the .env file.

    TWILIO_SID="YOUR_ACCOUNT_SID" 
    TWILIO_AUTH_TOKEN="YOUR_AUTH_TOKEN"
    TWILIO_WHATSAPP_NUMBER="+14155238886"

    Now lets write the code for the chatbot so that it can take a message and send back a reply:


    Step 1:

    In-order for us to process the message, we need some where to process the incoming message and for us to send back a response. So we will need to create a controller to handle all the processing of the message.

    $ php artisan make:controller MyFirstWhatsAppTwilioChatBotController

    Step 2:

    Now that we have a controller lets setup the two functions we will need:

    <?php
    
    namespace App\Http\Controllers;
    
    use GuzzleHttp\Exception\RequestException;
    use Illuminate\Http\Request;
    use Twilio\Rest\Client;
    
    class MyFirstWhatsAppTwilioChatBotController extends Controller
    {
        // This function is used to listen for incoming messages
        public function listenToReplies(Request $request) {
            $from = $request->input('from'); // This is the number that sending your bot a message.
            $body = $request->input('body'); // This is the message you get from the number sending the message to the bot.
            try {
                if($body == "hello"){
                   $message = "Hello\n";
                   $message .= "This is a custom message that you can set\n";
                   $this->sendWhatsAppMessage($message, $from);
                }
            } catch (RequestException $th) {
                $response = json_decode($th->getResponse()->getBody());
                $this->sendWhatsAppMessage($response->message, $from);
            }
            return;
        }
    
        // This function is used to send the message we complied in the
        public function sendWhatsAppMessage(string $message, string $recipient)
        {
            $twilio_whatsapp_number = getenv('TWILIO_WHATSAPP_NUMBER');
            $account_sid = getenv("TWILIO_SID");
            $auth_token = getenv("TWILIO_AUTH_TOKEN");
            $client = new Client($account_sid, $auth_token);
            return $client->messages->create("whatsapp:$recipient", 
                array(
                    'from' => "whatsapp:$twilio_whatsapp_number", 
                    'body' => $message
                ));
        }
    }
    

    Next thing for us to do is for us to setup a Webhook for chat bot:


    Step 1:

    Navigate to your "routes/api.php", Then add your controller to the routes within that file.

    Route::post('/chat-bot', 'MyFirstWhatsAppTwilioChatBotController@listenToReplies');

    Note that we set the request type to post. When Twilio gets a message from a number it will post to this route with the phone number that sent the message as well as the message they sent.


    Now that we have it all setup lets serve our project and start testing the whole setup using postman:


    Lets get our application served.  You can do so by running the below command in your applications root directory.

    $ php artisan serve

    Now that we have our application served to our local environment we can test to see if it works. For that we will need to have post man install on our machine. Here is how I set it up:

    postman setup for whatsapp twilio chatbot testing

    When you click "send" you should receive a message from the number you started your sandbox with on WhatsApp and it should contain the message you set within your listenToReplies() function.

    The reply you should get back

    So in a nutshell this is how you test your WhatsApp chat bot.

     

    Conclusion

    In this blog post you learned the following:

    • You learned how to setup your applications with the correct packages to make use of the WhatsApp API from Twilio.
    • You learned how to setup your Twilio sandbox and how to refresh it after the three days have past.
    • You learned how to setup your code so that you can send a custom reply back.
    • You learned how to test your WebHook using postman.

    Twilio does a really good job at keeping their documentation up to date. I would recommend checking it out if you want to know something about the API.

    I hope you found this blog useful.

    Contact us


      Related posts:

      rules for ux designersRules For UX Designers dynamic doughnut graph using laravel vue componentDynamic Doughnut Graph Using Laravel Vue Component angularUpdating A Primitive Type Variable From A Service In Angular 7 design principles for web design7 Design Principles For Web Design
      Share
      0
      Collin Yarrington
      Collin Yarrington
      Collin is a software developer for Lava Lamp Lab. For him there is no obstacle too big. Learning to improve and overcome those obstacles is what drives him forward.

      Leave a Reply Cancel reply

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

      Lava Lamp Lab


      Like technology, a lava lamp constantly changes form, producing new conditions with every passing moment



      lava lamp lab facebook   lava lamp lab twitter   lava lamp lab linkedin   lava lamp lab instgram

      Services


      Application & software development

      Outsourced software development

      Project based resourcing

      Digital marketing & consulting

      Graphic design & consulting

      UI / UX design & consulting

      Contact Us


      +27(0) 83 419 4851

      +27(0) 21 036 1165

      +61(0) 42 420 8911


      switchon@lavalamp.biz


      Unit 1 Monaco Square,
      14 Church Street,
      Durbanville,
      Cape Town, 7550

      NBConsult Group


      nbconsult
      designer needed
      © 2023 Lava Lamp Lab (Pty) Ltd | All Rights Reserved | Privacy Policy
      Contact us now

        Application & software development

          Outsourced software development

            Project based resourcing

              Digital marketing & consulting

                Graphic design & consulting

                  UI/UX design & consulting

                    Lease an expert

                      Recruitment services

                        We are using cookies to give you the best experience on our website.

                        You can find out more about which cookies we are using or switch them off in settings.

                        Lava Lamp Lab
                        Powered by  GDPR Cookie Compliance
                        Privacy Overview

                        This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

                        Strictly Necessary Cookies

                        Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

                        If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.

                        3rd Party Cookies

                        This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

                        Keeping this cookie enabled helps us to improve our website.

                        Please enable Strictly Necessary Cookies first so that we can save your preferences!

                        Cookie Policy

                        More information about our Cookie Policy