How to develop a What’s App BOT in C#
To design and develop a WhatsApp bot using C#, you need to understand how to interact with the WhatsApp Business API, as WhatsApp doesn’t provide direct access for bot development through a regular WhatsApp account. Here’s a step-by-step guide on building a WhatsApp bot using C#, including setting up your environment and coding an example.
Steps Overview:
- Setup WhatsApp Business API: Set up and configure the WhatsApp Business API.
- Setup Webhook Receiver: Configure a webhook to receive messages from WhatsApp.
- Send & Receive Messages: Implement message-sending and handling in C#.
Prerequisites
- WhatsApp Business Account: You’ll need a WhatsApp Business account to access the API.
- Facebook Developer Account: Create a Facebook Developer account if you don’t have one.
- WhatsApp Cloud API Access: Sign up for WhatsApp's Cloud API or use WhatsApp's Business API on-premises. This example assumes you are using the Cloud API, which is easier for testing and development.
Setting Up the WhatsApp Cloud API
- Go to the Meta for Developers website and create an app.
- Add "WhatsApp" as a product and create a test WhatsApp number.
- Get your API key/token from the "WhatsApp" section under the app settings.
- Note your API_TOKEN, PHONE_NUMBER_ID, and BUSINESS_ACCOUNT_ID as they will be required to send and receive messages.
Step 1: Create a C# Project
Create a new C# console or web application (e.g., ASP.NET Core Web API) to serve as your bot backend.
Step 2: Setup Webhook to Receive Messages
WhatsApp Cloud API sends incoming messages to a webhook. Here’s how to set up a simple webhook in ASP.NET Core.
?
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;
?
[ApiController]
[Route("api/whatsapp")]
public class WhatsAppWebhookController : ControllerBase
{
??? [HttpPost("webhook")]
??? public IActionResult ReceiveMessage([FromBody] JsonDocument incomingMessage)
??? {
??????? // Log incoming message for debugging
??????? Console.WriteLine("Received Message: " + incomingMessage);
?
??????? // Process the message
??????? var message = incomingMessage.RootElement.GetProperty("entry")[0]
???????????????????????? .GetProperty("changes")[0]
???????????????????????? .GetProperty("value")
????????????????????? ???.GetProperty("messages")[0];
??????? var from = message.GetProperty("from").GetString();
??????? var text = message.GetProperty("text").GetProperty("body").GetString();
?
??????? Console.WriteLine($"Message from {from}: {text}");
?
??????? // Respond with a success status
??????? return Ok();
??? }
}
?
?
Step 3: Sending Messages from the Bot
You can send messages using WhatsApp’s API endpoint. Use HttpClient to call the API.
- Install the System.Net.Http.Json package if needed.
- Create a method to send messages.
Example Code to Send a Message
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text;
using System.Threading.Tasks;
?
public class WhatsAppBotService
{
??? private readonly HttpClient _httpClient;
??? private readonly string apiUrl = "https://graph.facebook.com/v16.0/PHONENUMBER_ID/messages";? // Replace PHONE_NUMBER_ID
??? private readonly string apiToken = "YOURAPI_TOKEN"; // Replace YOUR_API_TOKEN
?
??? public WhatsAppBotService()
??? {
??????? _httpClient = new HttpClient();
??????? httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken);
??? }
?
??? public async Task SendMessageAsync(string recipientPhoneNumber, string messageText)
??? {
??????? var messageData = new
领英推è
??????? {
??????????? messaging_product = "whatsapp",
??????????? to = recipientPhoneNumber,
??????????? text = new { body = messageText },
??????????? type = "text"
??????? };
?
??????? var content = new StringContent(JsonSerializer.Serialize(messageData), Encoding.UTF8, "application/json");
?
??????? var response = await httpClient.PostAsync(apiUrl, content);
??????? response.EnsureSuccessStatusCode();
?
??????? var responseContent = await response.Content.ReadAsStringAsync();
??????? Console.WriteLine("Message sent. Response: " + responseContent);
??? }
}
Step 4: Calling the Send Method in Response to an Incoming Message
Modify the ReceiveMessage method to send a reply message.
?[HttpPost("webhook")]
public async Task<IActionResult> ReceiveMessage([FromBody] JsonDocument incomingMessage)
{
??? var message = incomingMessage.RootElement.GetProperty("entry")[0]
???????????????????? .GetProperty("changes")[0]
???????????????????? .GetProperty("value")
???????????????????? .GetProperty("messages")[0];
??? var from = message.GetProperty("from").GetString();
??? var text = message.GetProperty("text").GetProperty("body").GetString();
?
??? Console.WriteLine($"Message from {from}: {text}");
?
??? // Process received message and send response
??? var botService = new WhatsAppBotService();
??? await botService.SendMessageAsync(from, "Hello! This is an automated reply from our bot.");
?
??? return Ok();
}
Step 5: Run the Bot
bash
Copy code
ngrok http 5000
- Copy the public URL from ngrok and paste it as the webhook URL in your WhatsApp Cloud API settings. Example webhook URL: https://your-ngrok-url/api/whatsapp/webhook
- Verify the Webhook: WhatsApp will send a verification request to your webhook. Handle this by modifying the webhook endpoint to accept and respond to the verification challenge.
Optional: Webhook Verification Example
Add the following code to handle webhook verification requests from WhatsApp.
?[HttpGet("webhook")]
public IActionResult VerifyWebhook([FromQuery] string hub_mode, [FromQuery] string hub_challenge, [FromQuery] string hub_verify_token)
{
??? var verifyToken = "YOUR_VERIFY_TOKEN"; // Set this token in WhatsApp API settings
?
??? if (hub_mode == "subscribe" && hub_verify_token == verifyToken)
??? {
??????? return Ok(hub_challenge);
??? }
??? return Unauthorized();
}
Replace "YOUR_VERIFY_TOKEN" with a token you set in WhatsApp’s API settings.
Full Example Structure
- WhatsAppWebhookController.cs: Receives incoming messages and triggers response.
- WhatsAppBotService.cs: Contains logic to send messages through WhatsApp API.
- Program.cs: Sets up and runs the application.
Running and Testing
- Run the application and ensure it’s connected to ngrok.
- Send a test message to your WhatsApp number, and the bot should respond with the configured message.
Notes
- This bot only supports simple text responses. To add more capabilities like sending images or templates, modify the messageData object in SendMessageAsync.
- Make sure to follow Meta’s policies and guidelines for WhatsApp bots to avoid restrictions on your account.
With this setup, you now have a working WhatsApp bot in C#.