Set Group Messages Admin Only
Restrict or allow group messaging to admins only.
Set Group Messages Admin Only
This endpoint allows group administrators to configure whether only admins can send messages to the group. This is often known as an "announcement group" feature when enabled.
Endpoint
PUT /{sessionId}/groups/{groupId}/settings/security/messages-admin-only
Headers
Name | Type | Required | Description |
---|---|---|---|
Authorization | string | Yes | Bearer token for authentication |
Content-Type | string | Yes | application/json |
Path Parameters
Parameter | Type | Required | Description |
---|---|---|---|
sessionId | string | Yes | The session ID |
groupId | string | Yes | The group ID |
Request Body
Refer to SettingsSecurityChangeInfo
in API.md
but specifically the enabled
field for this context.
Field | Type | Required | Description |
---|---|---|---|
enabled | boolean | Yes | true to restrict messages to admins, false to allow all participants to send messages. |
Response
Returns a SettingsSecurityChangeInfo
object reflecting the updated state. Refer to API.md
.
{
"success": true,
"enabled": true, // or false, reflecting the new setting
"message": "Group messages setting 'messagesAdminOnly' updated successfully."
}
Examples
# To restrict messages to admins only
curl -X PUT "https://api.wasend.dev/YOUR_SESSION_ID/groups/YOUR_GROUP_ID/settings/security/messages-admin-only" \\
-H "Authorization: Bearer YOUR_API_KEY" \\
-H "Content-Type: application/json" \\
-d '{
"enabled": true
}'
# To allow all participants to send messages
curl -X PUT "https://api.wasend.dev/YOUR_SESSION_ID/groups/YOUR_GROUP_ID/settings/security/messages-admin-only" \\
-H "Authorization: Bearer YOUR_API_KEY" \\
-H "Content-Type: application/json" \\
-d '{
"enabled": false
}'
import { WasendClient, WasendConfig, SettingsSecurityChangeInfo } 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 setGroupMessagesAdminOnly(enabled: boolean) {
// The SDK might expect a more specific request type or just the boolean payload for this endpoint.
// For now, assuming it aligns with a general settings change that takes an 'enabled' flag.
const requestBody = { enabled };
try {
// Method name based on API.md structure for this endpoint.
const response: SettingsSecurityChangeInfo = await client.setGroupMessagesAdminOnly(sessionId, groupId, requestBody);
if (response.success) {
console.log(`Group messages admin-only set to ${response.enabled}: ${response.message}`);
} else {
console.error('Failed to set group messages admin-only:', response.error);
}
} catch (error) {
console.error('Error setting group messages admin-only:', error);
}
}
// Example usage: restrict to admins
setGroupMessagesAdminOnly(true);
// Example usage: allow all
// setGroupMessagesAdminOnly(false);
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 setGroupMessagesAdminOnly(enabled) {
const requestBody = { enabled };
try {
const response = await client.setGroupMessagesAdminOnly(sessionId, groupId, requestBody);
if (response.success) {
console.log(`Group messages admin-only set to ${response.enabled}: ${response.message}`);
} else {
console.error('Failed to set group messages admin-only:', response.error);
}
} catch (error) {
console.error('Error setting group messages admin-only:', error);
}
}
// Example usage:
setGroupMessagesAdminOnly(true);
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'
def set_group_messages_admin_only(enabled: bool):
request_body = {'enabled': enabled}
try:
response = client.set_group_messages_admin_only(session_id=session_id, group_id=group_id, request=request_body)
if response.success:
print(f"Group messages admin-only set to {response.enabled}: {response.message}")
else:
print(f"Failed to set group messages admin-only: {response.error}")
except Exception as e:
print(f"Error setting group messages admin-only: {e}")
# Example usage:
set_group_messages_admin_only(True)
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"
setEnabled := true // or false
// API.md indicates SettingsSecurityChangeInfo, which has an 'Enabled' field (pointer bool).
requestBody := &wasendcore.SettingsSecurityChangeInfo{
Enabled: &setEnabled,
}
response, err := client.SetGroupMessagesAdminOnly(sessionId, groupId, requestBody)
if err != nil {
log.Fatalf("Error setting group messages admin-only: %v", err)
}
if response.Success {
fmt.Printf("Group messages admin-only set to %v: %s\\n", *response.Enabled, response.Message)
} else {
fmt.Printf("Failed to set group messages admin-only: %s\\n", response.Error)
}
}
using System;
using Wasend.Core; // Adjust imports for WasendConfig, SettingsSecurityChangeInfo
public class SetGroupMessagesAdminOnlyExample
{
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";
bool enabled = true; // or false
// API.md indicates SettingsSecurityChangeInfo
var requestBody = new SettingsSecurityChangeInfo
{
Enabled = enabled
};
try
{
var response = client.SetGroupMessagesAdminOnly(sessionId, groupId, requestBody);
if (response.Success)
{
Console.WriteLine($"Group messages admin-only set to {response.Enabled}: {response.Message}");
}
else
{
Console.WriteLine($"Failed to set group messages admin-only: {response.Error}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error setting group messages admin-only: {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 SetGroupMessagesAdminOnlyHttp {
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 enableSetting = true; // or false
String requestPayload = String.format("{\"enabled\": %b}", enableSetting);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/" + sessionId + "/groups/" + groupId + "/settings/security/messages-admin-only"))
.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';
$enabled = true; // or false
$payload = json_encode(['enabled' => $enabled]);
$ch = curl_init($baseUrl . '/' . $sessionId . '/groups/' . $groupId . '/settings/security/messages-admin-only');
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'
enabled = true # or false
uri = URI("#{base_url}/#{session_id}/groups/#{group_id}/settings/security/messages-admin-only")
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 = { enabled: enabled }.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"
let enabled = true // or false
guard let url = URL(string: "\(baseUrl)/\(sessionId)/groups/\(groupId)/settings/security/messages-admin-only") 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] = ["enabled": enabled]
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 enabled = true; // or false
let client = Client::new();
let payload = json!({
"enabled": enabled
});
let response = client.put(format!("{}/{}/groups/{}/settings/security/messages-admin-only", 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
Field | Type | Description |
---|---|---|
success | boolean | Whether the operation was successful. |
enabled | boolean | The new state of the messagesAdminOnly setting. |
message | string | A confirmation message, e.g., "Group messages setting updated successfully." |
error | string | Optional. Error message if the request fails. |
Error Codes
Code | Description |
---|---|
400 | Bad Request - Invalid parameters (e.g., enabled field missing or not boolean). |
401 | Unauthorized - Invalid or missing API key. |
403 | Forbidden - User is not an admin of the group. |
404 | Not Found - Session or group not found. |
429 | Too Many Requests - Rate limit exceeded. |
500 | Internal Server Error. |
Notes
- This setting specifically controls whether only group administrators can send messages to the group.
- When
enabled
istrue
, regular participants cannot send messages, effectively making it an announcement group. They can still read messages. - When
enabled
isfalse
, all participants can send messages. - Only group administrators can change this setting.
- Changes take effect immediately within the WhatsApp group.
- This is distinct from the
infoAdminOnly
setting which controls who can edit group details.