How to Build a Simple WhatsApp Bot

This tutorial will show you how to create a simple Bot that gets the current exchange rate (Dollar to Naira). This bot uses PHP and our Whatsapp API.

Our bot will be able to display a simple greeting and will request a user input before it displays the exchange rate.

To send and receive messages with the bot, please ensure that the phone for your WhatsApp account is connected to the internet and your WhatsApp channel is Live.

Lets Get Started

You will need to setup a webhook URL on your Whatsapp channel so that our server can send new messages when they arrive.

You can use a direct link to your script for your webhook e.g. https://domain.com/mybot.php. See how to set up your webhook URL here.

So, we will create the mybot.php file.

Below is the script;


//receive messages pushed to our webhook

if(isset($_POST['phone']) && isset($_POST['message'])){
$phone=$_POST['phone'];
$message=$_POST['message'];

if(strtolower($message)=='hello' || strtolower($message)=='hi'){
//send welcome message
$reply="Hello. I am here to help you with the exchange rate of Dollar to Naira.\nShould I get the exchange rate now?";
$send=sendMessage($phone,$reply);
}
elseif(strtolower($message)=='yes'){
$reply="Hello. Current exchange rate is 360 Naira to 1 dollar";
$send=sendMessage($phone,$reply);
}
elseif(strtolower($message)=='no'){
$reply="Alright no problem. Just say Hi anytime you are ready.";
$send=sendMessage($phone,$reply);
}
else{
//unknown message
$reply="Oops! I don't seem to get that. Just say yes or no.";
$send=sendMessage($phone,$reply);

}
}

//function to send message

function sendMessage($phone,$reply){
$username='';
$apikey='';

$postdata = http_build_query(
array(
'username' => $username,
'apikey' => $apikey,
'phone' => $phone,
'type' => '1',
'message' => $reply
) );

$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $postdata ) );

$context = stream_context_create($opts);

@$result = file_get_contents ('https://wasapng.com/client/live-send', false, $context);
}

 

The first part of the script is to receive the phone number and message sent to our webhook via our Whatsapp account. The second part is just the function to send message via the API.

However, if you do not have a developer we can offer Whatsapp chat bot creation for your business. Click here