Wasend

Promote Group Participants

Promote participants to admin in a WhatsApp group

Promote Group Participants

Promote one or more participants to become administrators in a specific WhatsApp group.

Endpoint

POST /{sessionId}/groups/{groupId}/participants/promote

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 promote. Example: ["1234567890@s.whatsapp.net", "0987654321@s.whatsapp.net"]

Response

Returns a PromoteParticipantsResponse object. Refer to API.md.

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

Examples

curl -X POST "https://api.wasend.dev/YOUR_SESSION_ID/groups/YOUR_GROUP_ID/participants/promote" \\
  -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, PromoteParticipantsResponse } 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 promoteParticipantsExample() {
  const requestBody: ParticipantsRequest = {
    participants: ["1234567890@s.whatsapp.net", "0987654321@s.whatsapp.net"]
  };

  try {
    const response: PromoteParticipantsResponse = await client.promoteGroupParticipants(sessionId, groupId, requestBody);
    if (response.success) {
      console.log('Successfully promoted participants:', response.promoted);
      console.log(response.message);
    } else {
      console.error('Failed to promote participants:', response.error);
    }
  } catch (error) {
    console.error('Error promoting participants:', error);
  }
}

promoteParticipantsExample();
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 promoteParticipantsExample() {
  const requestBody = {
    participants: ["1234567890@s.whatsapp.net", "0987654321@s.whatsapp.net"]
  };

  try {
    const response = await client.promoteGroupParticipants(sessionId, groupId, requestBody);
    if (response.success) {
      console.log('Successfully promoted participants:', response.promoted);
      console.log(response.message);
    } else {
      console.error('Failed to promote participants:', response.error);
    }
  } catch (error) {
    console.error('Error promoting participants:', error);
  }
}

promoteParticipantsExample();
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 promote_group_participants takes a dictionary or a specific request object
    response = client.promote_group_participants(session_id=session_id, group_id=group_id, request=request_body)
    if response.success:
        print(f"Successfully promoted participants: {response.promoted}")
        print(response.message)
    else:
        print(f"Failed to promote participants: {response.error}")
except Exception as e:
    print(f"Error promoting 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.PromoteGroupParticipants(sessionId, groupId, requestBody) // Assumes method exists
	if err != nil {
		log.Fatalf("Error promoting participants: %v", err)
	}

	if response.Success {
		fmt.Printf("Successfully promoted participants: %+v\\n", response.Promoted)
		fmt.Println(response.Message)
	} else {
		fmt.Printf("Failed to promote 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, PromoteParticipantsResponse

public class PromoteParticipantsExample
{
    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 PromoteGroupParticipants is a synchronous method in the .NET SDK
            var response = client.PromoteGroupParticipants(sessionId, groupId, requestBody);
            if (response.Success)
            {
                Console.WriteLine("Successfully promoted participants:");
                if (response.Promoted != null)
                {
                    foreach (var p in response.Promoted)
                    {
                        Console.WriteLine($"  ID: {p.Id}, IsAdmin: {p.IsAdmin}");
                    }
                }
                Console.WriteLine(response.Message);
            }
            else
            {
                Console.WriteLine($"Failed to promote participants: {response.Error}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error promoting 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 PromoteParticipantsHttp {
    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";

        // Ensure participant IDs are in the correct format (e.g., with @s.whatsapp.net)
        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/promote"))
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .POST(BodyPublishers.ofString(requestPayload))
                .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 promoted 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/promote');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
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 promoted 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/promote")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = (uri.scheme == 'https')

request = Net::HTTP::Post.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 promoted 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/promote") else {
    print("Invalid URL")
    exit(1)
}

var request = URLRequest(url: url)
request.httpMethod = "POST"
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 promoted 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.post(format!("{}/{}/groups/{}/participants/promote", 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 promoted participants

    Ok(())
}

Response Fields

Refer to PromoteParticipantsResponse in API.md.

FieldTypeDescription
successbooleanWhether the operation was successful.
promotedarray of GroupParticipantList of participants who were successfully promoted.
messagestringA message confirming the action or detailing partial success/failure.
errorstringOptional. Error message if the entire request fails.

GroupParticipant Object Fields (Simplified for this response)

FieldTypeDescription
idstringThe JID of the participant.
isAdminbooleanIndicates if the participant is now an admin. Generally true.
isSuperAdminbooleanIndicates if the participant is a super admin. Generally false.

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 promote an already admin or non-existent user.
429Too Many Requests - Rate limit exceeded.
500Internal Server Error.

Notes

  • Only existing group administrators can promote other participants.
  • You cannot promote the group owner or a participant who is already an admin.
  • Ensure participant IDs are in the correct JID format (e.g., xxxxxxxxxx@s.whatsapp.net).
  • You can promote multiple participants in a single API call by including them in the participants array.
  • The response indicates which participants were successfully promoted.
  • If some participants cannot be promoted (e.g., not found, already admin), the API might still succeed for others and detail this in the message or promoted array.