Wasend

Set Group Settings

Update multiple group settings at once (e.g., admin-only for info and messages).

Set Group Settings

This endpoint allows administrators to update multiple group settings simultaneously. This typically includes configuring who can send messages and who can edit group information (subject, description, picture).

Endpoint

PUT /{sessionId}/groups/{groupId}/settings

Headers

NameTypeRequiredDescription
AuthorizationstringYesBearer token for authentication
Content-TypestringYesapplication/json

Path Parameters

ParameterTypeRequiredDescription
sessionIdstringYesThe session ID
groupIdstringYesThe group ID

Request Body

Refer to GroupSettingsRequest in API.md (or a similar encompassing settings object). It typically contains boolean fields for infoAdminOnly (restrict) and messagesAdminOnly (announce).

FieldTypeRequiredDescription
infoAdminOnlybooleanYestrue if only admins can edit group info, false otherwise (alias restrict).
messagesAdminOnlybooleanYestrue if only admins can send messages, false otherwise (alias announce).

Response

Returns a GroupSettingsResponse object reflecting the new settings. Refer to API.md (likely similar to GroupSettings or a success message with the updated settings values).

{
  "success": true,
  "settings": {
    "infoAdminOnly": true,    // Current state after update
    "messagesAdminOnly": false  // Current state after update
  },
  "message": "Group settings updated successfully."
}

Examples

curl -X PUT "https://api.wasend.dev/YOUR_SESSION_ID/groups/YOUR_GROUP_ID/settings" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "infoAdminOnly": true,
    "messagesAdminOnly": false
  }'
import { WasendClient, WasendConfig, GroupSettingsRequest, GroupSettingsResponse } from '@wasend/core'; // Adjust imports based on API.md

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 setGroupSettingsExample() {
  const requestBody: GroupSettingsRequest = {
    infoAdminOnly: true,    // Example: Only admins edit info
    messagesAdminOnly: false  // Example: Everyone can send messages
  };

  try {
    const response: GroupSettingsResponse = await client.setGroupSettings(sessionId, groupId, requestBody);
    if (response.success && response.settings) {
      console.log('Successfully updated group settings:');
      console.log(`  Info Admin Only: ${response.settings.infoAdminOnly}`);
      console.log(`  Messages Admin Only: ${response.settings.messagesAdminOnly}`);
      console.log(response.message);
    } else {
      console.error('Failed to update group settings:', response.error);
    }
  } catch (error) {
    console.error('Error updating group settings:', error);
  }
}

setGroupSettingsExample();
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 setGroupSettingsExample() {
  const requestBody = {
    infoAdminOnly: true,
    messagesAdminOnly: false
  };

  try {
    const response = await client.setGroupSettings(sessionId, groupId, requestBody);
    if (response.success && response.settings) {
      console.log('Successfully updated group settings:');
      console.log(`  Info Admin Only: ${response.settings.infoAdminOnly}`);
      console.log(`  Messages Admin Only: ${response.settings.messagesAdminOnly}`);
      console.log(response.message);
    } else {
      console.error('Failed to update group settings:', response.error);
    }
  } catch (error) {
    console.error('Error updating group settings:', error);
  }
}

setGroupSettingsExample();
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 = {
    'infoAdminOnly': True,
    'messagesAdminOnly': False
}

try:
    response = client.set_group_settings(session_id=session_id, group_id=group_id, request=request_body)
    if response.success and hasattr(response, 'settings') and response.settings:
        print("Successfully updated group settings:")
        print(f"  Info Admin Only: {response.settings.get('infoAdminOnly')}")
        print(f"  Messages Admin Only: {response.settings.get('messagesAdminOnly')}")
        print(response.message)
    else:
        print(f"Failed to update group settings: {response.error}")
except Exception as e:
    print(f"Error updating group settings: {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"

	infoAdminOnly := true
	messagesAdminOnly := false

	requestBody := &wasendcore.GroupSettingsRequest{ // Assuming GroupSettingsRequest type exists
		InfoAdminOnly:    &infoAdminOnly,    // Use pointers if fields are optional or API.md implies it
		MessagesAdminOnly: &messagesAdminOnly,
	}

	response, err := client.SetGroupSettings(sessionId, groupId, requestBody) // Assumes method exists
	if err != nil {
		log.Fatalf("Error updating group settings: %v", err)
	}

	if response.Success && response.Settings != nil {
		fmt.Println("Successfully updated group settings:")
		fmt.Printf("  Info Admin Only: %v\\n", *response.Settings.InfoAdminOnly)
		fmt.Printf("  Messages Admin Only: %v\\n", *response.Settings.MessagesAdminOnly)
		fmt.Println(response.Message)
	} else {
		fmt.Printf("Failed to update group settings: %s\\n", response.Error)
	}
}
using System;
using Wasend.Core; // Adjust imports for WasendConfig, GroupSettingsRequest, GroupSettingsResponse

public class SetGroupSettingsExample
{
    public static void Main(string[] args)
    {
        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 GroupSettingsRequest // Ensure this type matches API.md
        {
            InfoAdminOnly = true,
            MessagesAdminOnly = false
        };

        try
        {
            var response = client.SetGroupSettings(sessionId, groupId, requestBody);
            if (response.Success && response.Settings != null)
            {
                Console.WriteLine("Successfully updated group settings:");
                Console.WriteLine($"  Info Admin Only: {response.Settings.InfoAdminOnly}");
                Console.WriteLine($"  Messages Admin Only: {response.Settings.MessagesAdminOnly}");
                Console.WriteLine(response.Message);
            }
            else
            {
                Console.WriteLine($"Failed to update group settings: {response.Error}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error updating group settings: {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;

public class SetGroupSettingsHttp {
    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";

        boolean infoAdminOnly = true;
        boolean messagesAdminOnly = false;

        String requestPayload = String.format("{\"infoAdminOnly\": %b, \"messagesAdminOnly\": %b}", 
                                            infoAdminOnly, messagesAdminOnly);

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(baseUrl + "/" + sessionId + "/groups/" + groupId + "/settings"))
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .PUT(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 response
        } 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([
    'infoAdminOnly' => true,
    'messagesAdminOnly' => false
]);

$ch = curl_init($baseUrl . '/' . $sessionId . '/groups/' . $groupId . '/settings');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
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
?>
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}/settings")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = (uri.scheme == 'https')

request = Net::HTTP::Put.new(uri.path, {
  'Authorization' => "Bearer #{api_key}",
  'Content-Type' => 'application/json'
})
request.body = {
  infoAdminOnly: true,
  messagesAdminOnly: false
}.to_json

response_data = http.request(request)

puts "Response status: #{response_data.code}"
puts "Response body: #{response_data.body}"
# Parse JSON response
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)/settings") else {
    print("Invalid URL")
    exit(1)
}

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

let payload: [String: Any] = [
    "infoAdminOnly": true,
    "messagesAdminOnly": false
]

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 response
    }
    #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!({
        "infoAdminOnly": true,
        "messagesAdminOnly": false
    });

    let response = client.put(format!("{}/{}/groups/{}/settings", 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 response

    Ok(())
}

Response Fields

FieldTypeDescription
successbooleanWhether the operation was successful.
settingsobjectAn object containing the updated group settings.
messagestringA confirmation message.
errorstringOptional. Error message if the request fails.

Settings Object Fields

FieldTypeDescription
infoAdminOnlybooleantrue if only admins can edit group info.
messagesAdminOnlybooleantrue if only admins can send messages to the group.

Error Codes

CodeDescription
400Bad Request - Invalid parameters (e.g., missing fields, incorrect types).
401Unauthorized - Invalid or missing API key.
403Forbidden - User is not an admin of the group.
404Not Found - Session or group not found.
429Too Many Requests - Rate limit exceeded.
500Internal Server Error.

Notes

  • This endpoint provides a way to update both infoAdminOnly (who can edit group info) and messagesAdminOnly (who can send messages) settings in a single call.
  • Only group administrators can change these settings.
  • infoAdminOnly: true is often referred to as "restrict" mode.
  • messagesAdminOnly: true is often referred to as "announce" mode (making the group an announcement-only group).
  • Changes usually take effect immediately.
  • Refer to individual endpoints Set Group Info Admin Only and Set Group Messages Admin Only for more details on each specific setting.