Wasend

Remove Group Participants

Remove participants from a WhatsApp group

Remove Group Participants

Remove one or more participants from a specific WhatsApp group.

Endpoint

DELETE /{sessionId}/groups/{groupId}/participants

Headers

NameTypeRequiredDescription
AuthorizationstringYesBearer token for authentication
Content-TypestringYesapplication/json

Path Parameters

ParameterTypeRequiredDescription
sessionIdstringYesThe session ID
groupIdstringYesThe group ID

Request Body

Refer to ParticipantsRequest in API.md.

FieldTypeRequiredDescription
participantsstring[]YesAn array of participant IDs (phone numbers) to remove. Example: ["1234567890@s.whatsapp.net", "0987654321@s.whatsapp.net"]

Response

Returns a RemoveParticipantsResponse object. Refer to API.md.

{
  "success": true,
  "removed": [
    {
      "id": "1234567890@s.whatsapp.net"
    },
    {
      "id": "0987654321@s.whatsapp.net"
    }
  ],
  "message": "Selected participants were successfully removed."
}

Examples

curl -X DELETE "https://api.wasend.dev/YOUR_SESSION_ID/groups/YOUR_GROUP_ID/participants" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "participants": ["1234567890@s.whatsapp.net", "0987654321@s.whatsapp.net"]
  }'
import { WasendClient, WasendConfig, ParticipantsRequest, RemoveParticipantsResponse } from '@wasend/core'; // Adjust imports

const config = new WasendConfig({ apiKey: 'YOUR_API_KEY' });
const client = new WasendClient(config);

const sessionId = 'YOUR_SESSION_ID';
const groupId = 'YOUR_GROUP_ID';

async function removeParticipantsExample() {
  const requestBody: ParticipantsRequest = {
    participants: ["1234567890@s.whatsapp.net", "0987654321@s.whatsapp.net"]
  };

  try {
    const response: RemoveParticipantsResponse = await client.removeGroupParticipants(sessionId, groupId, requestBody);
    if (response.success) {
      console.log('Successfully removed participants:', response.removed);
      console.log(response.message);
    } else {
      console.error('Failed to remove participants:', response.error);
    }
  } catch (error) {
    console.error('Error removing participants:', error);
  }
}

removeParticipantsExample();
const { WasendClient, WasendConfig } = require('@wasend/core'); // Adjust imports

const config = new WasendConfig({ apiKey: 'YOUR_API_KEY' });
const client = new WasendClient(config);

const sessionId = 'YOUR_SESSION_ID';
const groupId = 'YOUR_GROUP_ID';

async function removeParticipantsExample() {
  const requestBody = {
    participants: ["1234567890@s.whatsapp.net", "0987654321@s.whatsapp.net"]
  };

  try {
    const response = await client.removeGroupParticipants(sessionId, groupId, requestBody);
    if (response.success) {
      console.log('Successfully removed participants:', response.removed);
      console.log(response.message);
    } else {
      console.error('Failed to remove participants:', response.error);
    }
  } catch (error) {
    console.error('Error removing participants:', error);
  }
}

removeParticipantsExample();
from wasend_sdk import WasendClient, WasendConfig # Adjust imports

config = WasendConfig(api_key='YOUR_API_KEY')
client = WasendClient(config)

session_id = 'YOUR_SESSION_ID'
group_id = 'YOUR_GROUP_ID'

request_body = {
    'participants': ["1234567890@s.whatsapp.net", "0987654321@s.whatsapp.net"]
}

try:
    # Assuming remove_group_participants takes a dictionary or a specific request object
    response = client.remove_group_participants(session_id=session_id, group_id=group_id, request=request_body)
    if response.success:
        print(f"Successfully removed participants: {response.removed}")
        print(response.message)
    else:
        print(f"Failed to remove participants: {response.error}")
except Exception as e:
    print(f"Error removing participants: {e}")
package main

import (
	"fmt"
	"log"

	"github.com/wasenddev/wasend-sdk-go/wasendcore" // Correct import path
)

func main() {
	config := &wasendcore.WasendConfig{
		ApiKey: "YOUR_API_KEY",
	}
	client := wasendcore.NewWasendClient(config)

	sessionId := "YOUR_SESSION_ID"
	groupId := "YOUR_GROUP_ID"

	requestBody := &wasendcore.ParticipantsRequest{
		Participants: []string{"1234567890@s.whatsapp.net", "0987654321@s.whatsapp.net"},
	}

	response, err := client.RemoveGroupParticipants(sessionId, groupId, requestBody) // Assumes method exists
	if err != nil {
		log.Fatalf("Error removing participants: %v", err)
	}

	if response.Success {
		fmt.Printf("Successfully removed participants: %+v\\n", response.Removed)
		fmt.Println(response.Message)
	} else {
		fmt.Printf("Failed to remove participants: %s\\n", response.Error)
	}
}
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Wasend.Core; // Adjust imports for WasendConfig, ParticipantsRequest, RemoveParticipantsResponse

public class RemoveParticipantsExample
{
    public static void Main(string[] args) // Can be async Task Main if other async ops are needed
    {
        var config = new WasendConfig { ApiKey = "YOUR_API_KEY" };
        var client = new WasendClient(config);

        var sessionId = "YOUR_SESSION_ID";
        var groupId = "YOUR_GROUP_ID";

        var requestBody = new ParticipantsRequest
        {
            Participants = new List<string> { "1234567890@s.whatsapp.net", "0987654321@s.whatsapp.net" }
        };

        try
        {
            // Assumes RemoveGroupParticipants is a synchronous method in the .NET SDK
            var response = client.RemoveGroupParticipants(sessionId, groupId, requestBody);
            if (response.Success)
            {
                Console.WriteLine("Successfully removed participants:");
                if (response.Removed != null)
                {
                    foreach (var p in response.Removed)
                    {
                        Console.WriteLine($"  ID: {p.Id}"); // Assuming RemovedParticipant type has Id
                    }
                }
                Console.WriteLine(response.Message);
            }
            else
            {
                Console.WriteLine($"Failed to remove participants: {response.Error}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error removing participants: {ex.Message}");
        }
    }
}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;
// Add imports for JSON processing (e.g., org.json.JSONObject, com.google.gson.Gson)

public class RemoveParticipantsHttp {
    public static void main(String[] args) {
        String sessionId = "YOUR_SESSION_ID";
        String groupId = "YOUR_GROUP_ID";
        String apiKey = "YOUR_API_KEY";
        String baseUrl = "https://api.wasend.dev";

        String requestPayload = "{\"participants\": [\"1234567890@s.whatsapp.net\", \"0987654321@s.whatsapp.net\"]}";

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(baseUrl + "/" + sessionId + "/groups/" + groupId + "/participants"))
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .method("DELETE", BodyPublishers.ofString(requestPayload)) // Standard way to send DELETE with body
                .build();

        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println("Response status: " + response.statusCode());
            System.out.println("Response body: " + response.body());
            // Parse JSON to check success and removed participants
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
<?php
$sessionId = 'YOUR_SESSION_ID';
$groupId = 'YOUR_GROUP_ID';
$apiKey = 'YOUR_API_KEY';
$baseUrl = 'https://api.wasend.dev';

$payload = json_encode([
    'participants' => ["1234567890@s.whatsapp.net", "0987654321@s.whatsapp.net"]
]);

$ch = curl_init($baseUrl . '/' . $sessionId . '/groups/' . $groupId . '/participants');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); // Set method to DELETE
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $apiKey,
    'Content-Type: application/json'
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo "HTTP status: " . $httpCode . "\\n";
echo "Response: " . $response . "\\n";
// Parse JSON response to check success and removed participants
?>
require 'net/http'
require 'uri'
require 'json'

session_id = 'YOUR_SESSION_ID'
group_id = 'YOUR_GROUP_ID'
api_key = 'YOUR_API_KEY'
base_url = 'https://api.wasend.dev'

uri = URI("#{base_url}/#{session_id}/groups/#{group_id}/participants")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = (uri.scheme == 'https')

request = Net::HTTP::Delete.new(uri.path, {
  'Authorization' => "Bearer #{api_key}",
  'Content-Type' => 'application/json'
})
request.body = {
  participants: ["1234567890@s.whatsapp.net", "0987654321@s.whatsapp.net"]
}.to_json

response_data = http.request(request)

puts "Response status: #{response_data.code}"
puts "Response body: #{response_data.body}"
# Parse JSON to check success and removed participants
import Foundation

#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

let sessionId = "YOUR_SESSION_ID"
let groupId = "YOUR_GROUP_ID"
let apiKey = "YOUR_API_KEY"
let baseUrl = "https://api.wasend.dev"

guard let url = URL(string: "\(baseUrl)/\(sessionId)/groups/\(groupId)/participants") else {
    print("Invalid URL")
    exit(1)
}

var request = URLRequest(url: url)
request.httpMethod = "DELETE"
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let payload: [String: Any] = [
    "participants": ["1234567890@s.whatsapp.net", "0987654321@s.whatsapp.net"]
]

do {
    request.httpBody = try JSONSerialization.data(withJSONObject: payload, options: [])
} catch {
    print("Error serializing JSON: \(error)")
    exit(1)
}

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print("Error: \(error)")
        return
    }
    guard let httpResponse = response as? HTTPURLResponse else {
        print("Invalid response")
        return
    }
    print("Response status code: \(httpResponse.statusCode)")
    if let data = data, let responseBody = String(data: data, encoding: .utf8) {
        print("Response body: \(responseBody)")
        // Parse JSON to check success and removed participants
    }
    #if os(macOS) || os(Linux)
    CFRunLoopStop(CFRunLoopGetCurrent())
    #endif
}

task.resume()

#if os(macOS) || os(Linux)
CFRunLoopRun()
#endif
use reqwest::Client;
use serde_json::json;
use tokio;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let session_id = "YOUR_SESSION_ID";
    let group_id = "YOUR_GROUP_ID";
    let api_key = "YOUR_API_KEY";
    let base_url = "https://api.wasend.dev";
    let client = Client::new();

    let payload = json!({
        "participants": ["1234567890@s.whatsapp.net", "0987654321@s.whatsapp.net"]
    });

    let response = client.delete(format!("{}/{}/groups/{}/participants", base_url, session_id, group_id))
        .bearer_auth(api_key)
        .json(&payload)
        .send()
        .await?;

    println!("Status: {}", response.status());
    let body = response.text().await?;
    println!("Body: {}", body);
    // Parse JSON to check success and removed participants

    Ok(())
}

Response Fields

Refer to RemoveParticipantsResponse in API.md.

FieldTypeDescription
successbooleanWhether the operation was successful.
removedarray of RemovedParticipant objectList of participants who were successfully removed. Each object typically contains just the id.
messagestringA message confirming the action or detailing partial success/failure.
errorstringOptional. Error message if the entire request fails.

RemovedParticipant Object Fields

FieldTypeDescription
idstringThe JID of the participant.

Error Codes

CodeDescription
400Bad Request - Invalid parameters (e.g., missing participants, invalid ID format).
401Unauthorized - Invalid or missing API key.
403Forbidden - Authenticated user is not an admin of the group.
404Not Found - Session, group, or one or more specified participants not found.
422Unprocessable Entity - Attempting to remove a non-member or the group owner.
429Too Many Requests - Rate limit exceeded.
500Internal Server Error.

Notes

  • Only existing group administrators can remove other participants.
  • You cannot remove the group owner.
  • Ensure participant IDs are in the correct JID format (e.g., xxxxxxxxxx@s.whatsapp.net).
  • You can remove multiple participants in a single API call by including them in the participants array.
  • The response indicates which participants were successfully removed.
  • If some participants cannot be removed (e.g., not found, not a member), the API might still succeed for others and detail this in the message or removed array.
  • Removed participants will be notified that they have been removed from the group.