Server Guy

How to Send Messages to a WhatsApp Group Programmatically via API

Sending messages programmatically to a WhatsApp group can be helpful for quick action and automating communications. Whether it’s for pipeline notifications, alerts, or updates, this guide will help you use APIs to send messages directly into WhatsApp groups or chats. Among many providers, Whapi (whapi.cloud) stands out for its free sandbox plan and affordable pricing.

Why Whapi?

Whapi offers a powerful yet straightforward solution to integrate WhatsApp messaging.

Step 1: Setting Up Whapi

To get started, sign up for a Whapi account on whapi.cloud. Once you’re logged in:

Step 2: Fetch Group IDs

To send messages to a group, you need the Group’s ID. To get it, simply call the Whapi’s https://gate.whapi.cloud/groups API endpoint with credential or simply from the dashboard.

{
  "groups": [
    {
      "id": "1234567890@g.us",
      "name": "DevOps Team",
      "type": "group"
    },
    {
      "id": "9876543210@g.us",
      "name": "Project Updates",
      "type": "group"
    }
  ]
}

From this response, note down the id of the group you want to send a message to.

Step 3: Sending a Message to a Group
Here’s a Python script to send messages programmatically to a WhatsApp group using Whapi.

import requests

def send_whatsapp_group_message(api_url, api_token, group_id, message):
    # Prepare WhatsApp API request headers
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_token}"
    }
    
    # WhatsApp message body
    body = {
        "typing_time": 0,
        "to": group_id,
        "body": message
    }
    
    # Make the POST request
    response = requests.post(f"{api_url}/send", headers=headers, json=body)
    
    # Check the response
    if response.status_code == 200:
        print("Message sent successfully:", response.json())
    else:
        print("Failed to send message:", response.text)

API_URL = "https://gate.whapi.cloud/messages/text"
API_TOKEN = "your_api_token"
GROUP_ID = "9876543210@g.us"  # Replace with the group ID you retrieved
MESSAGE = "Hello, DevOps Team! This is a test message."

send_whatsapp_group_message(API_URL, API_TOKEN, GROUP_ID, MESSAGE)

Replace the placeholders (API_TOKEN, GROUP_ID, and MESSAGE) with your actual details.

Other WhatsApp API Providers

If you’re exploring additional options, here are a few other providers:

  1. Twilio: A trusted platform for SMS and WhatsApp messaging with robust API support.
  2. 360Dialog: Offers a WhatsApp Business API at competitive pricing.
  3. Vonage: Provides messaging APIs with a developer-friendly interface.

With this article, you can now send pipeline notifications or other alerts using API to WhatsApp group. If you’re facing any issue let me know in the comment.

Exit mobile version