TaCode Tuesdays:  Optimize Chat Support Through Bot Messaging

Posted by Pedram Mohammadi on December 28, 2016

Welcome back to TaCode Tuesdays! This is the only place you can find snippets of code for use in your very own text/voice apps, along with a weekly dose of taco puns. I’m a developer here at Zang and not only am I a big fan of tacos (if that wasn’t already apparent), I’m also a fan of open source. My goal is to share a new app idea each week that you're free to use “as is” or modify and use as the basis for your next app.

In the last few weeks, I detailed how you can detect and minimize the threat of fraud in your voice and SMS apps—you can get the free code here, and as always, if you’d like to learn how to get started on Zang, take a look at our very first post

Let's Taco 'bout Bots

Chatterbot, also known as chatbot, uses machine learning algorithms to simulate human conversation. The earliest bots, named Eliza and Parry, were created in the 60s and were the first ones to pass the Turing Test- a test used to determine if a computer can think like humans. Eliza (from MIT AI Lab) could mimic human conversations through a flawless script simulated by a psychotherapist. Parry on the other hand was a paranoid chatbot. He was created to consistently misinterpret motives and carry a complex system of assumptions, attributions, and emotional responses triggered by the individuals he talked to. Parry was actually the first one to pass the Turing Test when interrogators weren’t able to distinguish him from a real paranoid individual.

The AI tech behind chatbots have come a long way since the 60s. Early this year, Microsoft launched Tay, a millennial bot turned racist. Facebook also released its own, called the Messenger Platform (beta), allowing developers to create their own bot to enhance connection and interaction with its users. And, as smart phones and chat applications have grown in popularity, so has the market for this tech. To date, more than 2.5 billion people have at least one messaging app, with Facebook Messenger and WhatsApp claiming the top two spots, according to a study done by Economist.

Using Bot Messaging for Chat Support

Using bots to enhance customer service is a revolutionary idea. Being one of the most resource intensive departments, customer support requires people to be on the phone, chat, and email 24/7. This part of the operation is directly linked to a ROI – as more than 50 percent of customers expect businesses to always be responsive; and when they’re not, people become dissatisfied. About 64 percent of users also think that businesses should be easily reached through messaging applications.

Creating Your Own Chatbot

To create a chatbot, we need to understand its capabilities. Basically, chatbots belong to the Weak Artificial Intelligence field. Weak AI is a non-sentient artificial intelligence that is focused on one narrow task. Contrasting this to "Strong AI," whose primary goal is to create software that are as smart as humans.

Basic chatbots have a wide variety of uses, like web, smartphone, and interactive voice response (IVR) systems based customer service. They are mainly used for initial customer interaction in the absence of human support.

There are four basic steps in creating a chatbot:

  1. Create an array of strings that will store the bot’s predefined responses;
  2. Build a random number function to create a set of pre-defined responses that can be sent to the user interacting with the chatbot;
  3. Create a function that handles the user’s inputs; and
  4. Build a function that processes the user’s inputs and provide a response coming from the hard-coded array of response strings.

From these four steps, we can see that the program isn’t really trying to understand what the user is saying, rather it is just responding from a set of canned statements.

Before we start coding, here are just a few pre-requisites:

  • Intermediate knowledge of Objective C, C, and C++
  • Intermediate knowledge of string manipulation and arrays
  • Apple XCode IDE installed
  • Intermediate knowledge of JQuery, PHP and MySQL

Chatbot Code in Objective C

For developers and hobbyists, these technology stacks are good starting points in building a chatbot widget following a basic algorithm such as our POC.

  • JavaScript Chatterbot Workshop - This open source program provides the essentials to program your chatbot with Bootstrap AI. The basic functions built in a chatbot framework typically are:  
    • Handling a user statement or question;
    • Cycling through the list of predefined input patterns until the code finds a match; and
    • Generating a reply based on the response pattern you provided.
  • Chatbot UI -  This is a stripped-down version of a JavaScript user interface created using JQuery that you can readily use as your user interface.

Now, were ready to start!

Steps 1 and 2: Create an array of strings that will store the bot’s all predefined responses; and build a random number function to create a set of pre-defined responses that can be sent to the user interacting with the chatbot.

//  main.m

//  chatbot (Objective C implementation)

#import <Foundation/Foundation.h>

// declaration of  function prototypes

NSMutableArray *find_match (NSString *str_input);

void copy(char  *array[], NSMutableArray *s);

typedef unsigned char s;

//mininum number of response

const int MAX_RESP = 3;

//structure definition in handling the IO response

typedef struct


   char *input;

   char *responses[MAX_RESP];

} record;


//initialize an array 18 rows in each 6 columns

record KnowledgeBase[] =


   {"Hi. I want to report a problem regarding the item that I just purchased.",


        "Hi there. Thank you for contacting Customer Support.",

        "My name is Alex, I would be glad to assist you with that concern.",

        "Can I have your order number please?",




   {"My order no is: 3479573895734895743",


        "Kindly wait for a few seconds as I process your inquiry",

        "You ordered for: Bosse Bluetooth Speaker on 01-October-2016"

         “What seems to be the problem?”}



   {"I want to have a replacement because it is not charging",

       {"Im sorry to hear that the product is defective",

          "Let me process the return for you",

           "Can you hold on for a few minutes?"}



   {"Sure not a problem",

       {"I have already processed your product return form.",

           "Please wait for an email containing the request and detailed instructions how to   

           return the item.",

           "Just to confirm your email is: dan@gmail.com?"}



   {"Yes that is correct",

       {"Thanks. Hang-on as I send out the email.",

           "All done. Is there anything else I can help you with?}



   {"Yes. I want to ask a few details about this product: SKU#4324398472389",

       {"I see, glad that you’re still looking at our other items?",

           "I will transfer our conversation to Charles. He is in Sales and would better assist


           "Hold on a second."}



size_t nKnowledgeBaseSize = sizeof(KnowledgeBase)/sizeof(KnowledgeBase[0]);

int main(int argc, const char * argv[])




       srand((unsigned) time(NULL));

       while(1) {

           NSLog(@"type a text:");

           NSFileHandle *input = [NSFileHandle fileHandleWithStandardInput];

           NSData *inputData = [input availableData];


           NSString *strInput = [[NSString alloc] initWithData:inputData



           strInput = [strInput stringByTrimmingCharactersInSet:[NSCharacterSet


           NSLog(@"Text: %@", strInput);


           NSString *strExit = @"exit";

           NSMutableArray  *a = searchString(strInput);


           if ([strExit isEqualToString:strInput]) {

               NSLog(@"It was nice talking to you! bye");


           else if(sizeof(a) == 0) {

               NSLog(@"Please rephrase your query");


           else {

               int nSelection = rand()  % MAX_RESP;

               NSString *sResponse = a[nSelection];

               NSLog(@"response: %@",sResponse);




   return 0;



Steps 3 and 4: Create a function that handles the inputs of the user, and build a function that processes their inputs and provide a reply coming from the hard-coded array of response string. This function takes the user input and tries to find a match from the struct record. Then, it pushes the response items into an array.


NSMutableArray *searchString(NSString *str_input)


   NSMutableArray *result = [[NSMutableArray alloc]init];

   for(int i = 0; i < nKnowledgeBaseSize;  ++i) //6


       NSLog(@"--> [%d]:%s:%s",i,KnowledgeBase[i].input,str_input.UTF8String);

       NSString *mm = [NSString stringWithUTF8String: KnowledgeBase[i].input];

       NSString *xm = [NSString stringWithUTF8String: KnowledgeBase[i].input];

       NSInteger b = [xm integerValue];

       if ( [mm isEqualToString:str_input])


           NSLog(@"FOUND MATCH %@ : %@ : %d",mm,str_input,i);

           for(int y = 0;  y < MAX_RESP; ++y)


               NSString *g = [[NSString alloc]


                           length:30 encoding:NSUTF8StringEncoding];

               NSArray *ss = [[NSArray alloc] initWithObjects:g,nil];

               [result addObject:ss];

               NSLog(@"--> %@ ",g);


           NSLog(@"%i", i);



   return result;



This roughly shows how a basic algorithm for "exact sentence matching" is implemented. First, we create a struct called record with two data types "input" and "response." Then, we instantiate the struct record using the name "KnowledgeBase."

This struct record can hold 18 rows and six columns for your chatbot’s pre-defined messages. If your user says something like: "Hi. I want to report a problem regarding the item that I just purchased," the program will call the function "searchString" and return back an array of three statement matches coming from the struct "record KnowledgeBase."

It will loop through all the possible matches until the user exits. From there, the code will terminate our Cocoa command line program. For those coming from a web development background, you can "pattern match" by creating a MySQL table and looping through record sets via foreign keys between two tables. The following PHP code snippet does that:


$response_queue = Array(); //create an array for chatbot "responses" to be presented to the user.

$sql = 'SELECT * FROM tbl_input WHERE tbl_input.question="Hi. I want to report a problem regarding the item that I just purchased"';

//implementing a nested mysql queries

$rs = mysql_query($sql,$connection);

if (mysql_num_rows($rs)>0) {}

   while($row = mysql_fetch_object($rs)) {

       //accessing the second table to get the desired output

       $sql_response= 'SELECT * FROM tbl_responses WHERE tbl_responses.id='.$row->response_idFK;

       $result = mysql_query($sql_response,$connection);

       while($rows = mysql_fetch_object$(result)) {





Save Time and Money with Chatbots

Chatbot uses machine learning algorithms to simulate a “chatter” or human conversation. When implemented correctly, bot messaging can save you (and your customers) millions in customer service support. There are a lot of open source AI chatbots in the market today; however, as a quick win, you can create your own chat bot that can be embedded on your existing website in four easy steps. When implemented correctly, your simple web AI can help cut down customer service costs, increase productivity, and improve overall customer satisfaction.

You can use this code to begin building on Zang Cloud today

Topics: Ideas, TaCode Tuesday, bots