Building a custom WhatsApp bot might seem daunting at first, but with clear guidance, it’s a manageable and rewarding project for developers—especially those just beginning to explore API integrations. This tutorial provides a straightforward path to setting up a WhatsApp bot in PHP, covering everything from API token setup to tailored message responses.
Designed for beginners, this guide is the perfect foundation for developing more advanced bots in the future.
Features of This WhatsApp Bot
This introductory bot is programmed to respond to incoming messages with preset text and image replies, depending on the message content. It’s a practical starting point for developers wanting to learn about API-driven interactions and automated messaging.
One standout feature: this bot operates seamlessly within WhatsApp Groups and communities, enabling you to bring automation to your WhatsApp channels with ease.
Prerequisites
To get started, make sure you have the following setup:
1. Obtain Your API Token
- Register on .
- Get your API Token to work with your WhatsApp. How to get the token is very detailed covers where to find this link, recommended server options, and popular solutions available. If you’re testing locally, however, a live server isn’t necessary. You can set up a tunnel to allow requests to reach your local machine.
Testing Locally: For local testing, use Ngrok to expose your server online temporarily, allowing you to simulate bot functions without needing to deploy on a live server.
Download and unzip Ngrok, then run:
./ngrok http PORT_NUMBER
Replace PORT_NUMBER with the port where your server is running.
Set Webhook URL in Dashboard: Copy the Ngrok-generated link as your webhook URL in the Whapi.Cloud dashboard. This directs incoming messages to your bot’s local server, allowing real-time interaction with WhatsApp.
.
Understanding the Structure of Your WhatsApp Bot
This bot is structured with clarity and detailed comments, making it beginner-friendly and easy to navigate. Below is an overview of the primary components:
Core Modules
/src/channel.php
This module contains essential functions that manage communication between the bot and users:
- checkHealth(): Confirms that the bot’s channel is functioning properly.
- sendMessage(): Sends text messages to specified recipients.
- setWebHook(): Configures the webhook automatically (optional).
- getWebHooks(): Retrieves webhook details from the API.
- sendLocalJPG(): Converts images from the /images/ directory to base64 and sends them as media messages.
The code snippet demonstrating sendMessage() functionality. This feature displays the “Typing” status in your WhatsApp for 5 seconds and then sends a text message after that:
CODEpublic function sendMessage($to, $body): bool {
$ch = curl_init('https://gate.whapi.cloud/messages/text');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $this->token,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'typing_time' => 5,
'to' => $to,
'body' => $body
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);
curl_close($ch);
return $data['sent'] ?? false;
}
Primary Logic
/src/Whapi.php
The main logic for the bot resides here, controlling how it processes and responds to incoming messages:
- Message Filtering: Screens out outgoing messages, ensuring only external incoming messages are handled.
- Sender and Content Parsing: Extracts the sender’s phone number and the message text.
- Command-Based Responses: Uses a switch statement to define responses based on specific commands or keywords received.
This structure allows for easy customization and extension, providing a solid foundation to build upon as you add new features.
CODE// The main cycle of the bot is to check and react to the incoming message depending on the text
switch ($receivedText) {
case 'help':
$channel->sendMessage($senderPhone, 'Text1'); // If the bot receives the message 'help', it will send the message 'Text1'
break;
case 'command':
$channel->sendMessage($senderPhone, 'Text2');
break;
case 'image':
$channel->sendLocalJPG(__DIR__ . '/../public/images/example.jpeg', $senderPhone, 'Caption'); // We encode the picture in base64, so it's easier to send a media message.
break;
default:
$channel->sendMessage($senderPhone, 'Unknown command'); // On an unknown team, it's best to send navigation information to help your customer navigate
break;
}
Customizing and Expanding Your WhatsApp Bot
With the initial setup complete, you have a strong foundation to enhance your bot with , turning your bot into a powerful tool for group coordination:
- Automatically create, modify, or delete groups.
- Access group information, including member details and total counts.
- Manage membership by adding or removing users, assigning administrator roles, and blocking members.
- Customize group settings like name, avatar, and permissions.
- Generate and share group invitation links effortlessly.
For full implementation details and code examples, check out Whapi.Cloud’s detailed documentation. to simulate incoming requests and confirm that your bot’s webhook URL matches what the API expects.
- Server Response Verification: Ensure your server responds with a
200 OKstatus, indicating that the webhook is active and receiving requests.
You can also use , and our team will assist with any webhook or bot configuration issues to get you up and running.
Conclusion
This WhatsApp bot in PHP offers an ideal entry point for beginners exploring chatbot creation and API integration. By following this guide, you’ll develop foundational skills for building more advanced bots capable of responding to various commands with text, images, and more. This project lays the groundwork for creating versatile and interactive bots that can grow in complexity as you expand your API knowledge.
SOCIAL SHARE CARD GENERATOR