curl -X GET "https://zapclass.com.br/api/groups/list" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP"
curl -X GET "https://zapclass.com.br/api/groups/list?force=true" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP"
curl -X GET "https://zapclass.com.br/api/groups/list?noparticipants=true" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP"
curl -X GET "https://zapclass.com.br/api/groups/list?force=true&noparticipants=true" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP"
const response = await fetch("https://zapclass.com.br/api/groups/list", {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP",
},
});
const data = await response.json();
if (data.success) {
console.log(`Total de grupos: ${data.groups.length}`);
data.groups.forEach((group) => {
console.log(`- ${group.name} (${group.participants?.length || 0} membros)`);
});
}
async function listGroups(options = {}) {
const { force = false, noparticipants = false } = options;
const params = new URLSearchParams();
if (force) params.append("force", "true");
if (noparticipants) params.append("noparticipants", "true");
const url = `https://zapclass.com.br/api/groups/list${
params.toString() ? "?" + params.toString() : ""
}`;
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP",
},
});
const data = await response.json();
if (!data.success) {
throw new Error(data.message);
}
return data.groups;
}
// Uso - listar com cache
const groups = await listGroups();
console.log(`Grupos em cache: ${groups.length}`);
// Uso - forçar atualização sem participantes
const freshGroups = await listGroups({
force: true,
noparticipants: true,
});
console.log(`Grupos atualizados: ${freshGroups.length}`);
async function analyzeGroups() {
const response = await fetch(
"https://zapclass.com.br/api/groups/list?force=true",
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP",
},
}
);
const data = await response.json();
if (!data.success) {
throw new Error(data.message);
}
const groups = data.groups;
// Estatísticas
const stats = {
total: groups.length,
totalParticipants: 0,
withAnnounce: 0,
withRestrict: 0,
avgParticipants: 0,
largestGroup: null,
smallestGroup: null,
};
groups.forEach((group) => {
const participantCount = group.participants?.length || 0;
stats.totalParticipants += participantCount;
if (group.announce) stats.withAnnounce++;
if (group.restrict) stats.withRestrict++;
if (
!stats.largestGroup ||
participantCount > (stats.largestGroup.participants?.length || 0)
) {
stats.largestGroup = group;
}
if (
!stats.smallestGroup ||
participantCount < (stats.smallestGroup.participants?.length || 0)
) {
stats.smallestGroup = group;
}
});
stats.avgParticipants = (stats.totalParticipants / stats.total).toFixed(1);
console.log("═══════════════════════════════");
console.log(" ANÁLISE DE GRUPOS");
console.log("═══════════════════════════════");
console.log(`\nTotal de grupos: ${stats.total}`);
console.log(`Total de participantes: ${stats.totalParticipants}`);
console.log(`Média de participantes: ${stats.avgParticipants}`);
console.log(`\nGrupos apenas admin: ${stats.withAnnounce}`);
console.log(`Grupos com edição restrita: ${stats.withRestrict}`);
console.log(
`\nMaior grupo: ${stats.largestGroup.name} (${
stats.largestGroup.participants?.length || 0
} membros)`
);
console.log(
`Menor grupo: ${stats.smallestGroup.name} (${
stats.smallestGroup.participants?.length || 0
} membros)`
);
return stats;
}
// Uso
await analyzeGroups();
async function filterGroups(criteria) {
const response = await fetch(
"https://zapclass.com.br/api/groups/list?force=true",
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP",
},
}
);
const data = await response.json();
if (!data.success) {
throw new Error(data.message);
}
let filtered = data.groups;
// Filtrar por nome
if (criteria.nameContains) {
filtered = filtered.filter((g) =>
g.name.toLowerCase().includes(criteria.nameContains.toLowerCase())
);
}
// Filtrar por número mínimo de participantes
if (criteria.minParticipants) {
filtered = filtered.filter(
(g) => (g.participants?.length || 0) >= criteria.minParticipants
);
}
// Filtrar por número máximo de participantes
if (criteria.maxParticipants) {
filtered = filtered.filter(
(g) => (g.participants?.length || 0) <= criteria.maxParticipants
);
}
// Filtrar apenas grupos onde sou admin
if (criteria.onlyAdmin) {
filtered = filtered.filter((g) =>
g.participants?.some((p) => p.admin && p.isMe)
);
}
// Filtrar por modo announce
if (criteria.announce !== undefined) {
filtered = filtered.filter((g) => g.announce === criteria.announce);
}
return filtered;
}
// Uso - grupos com "vendas" no nome e mais de 10 membros
const vendas = await filterGroups({
nameContains: "vendas",
minParticipants: 10,
});
console.log(`Grupos de vendas (10+ membros): ${vendas.length}`);
vendas.forEach((g) => console.log(` - ${g.name}`));
// Uso - grupos onde sou admin
const myAdminGroups = await filterGroups({ onlyAdmin: true });
console.log(`\nGrupos onde sou admin: ${myAdminGroups.length}`);
async function exportGroupsToCSV() {
const response = await fetch(
"https://zapclass.com.br/api/groups/list?force=true&noparticipants=true",
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP",
},
}
);
const data = await response.json();
if (!data.success) {
throw new Error(data.message);
}
// Cabeçalho CSV
let csv = "ID,Nome,Descrição,Participantes,Apenas Admin,Edição Restrita\n";
// Adiciona cada grupo
data.groups.forEach((group) => {
const row = [
group.id,
`"${group.name.replace(/"/g, '""')}"`,
`"${(group.description || "").replace(/"/g, '""')}"`,
group.participants?.length || 0,
group.announce ? "Sim" : "Não",
group.restrict ? "Sim" : "Não",
].join(",");
csv += row + "\n";
});
return csv;
}
// Uso
const csv = await exportGroupsToCSV();
console.log("CSV gerado:");
console.log(csv);
// Em Node.js, salvar em arquivo:
// const fs = require('fs');
// fs.writeFileSync('grupos.csv', csv, 'utf8');
<?php
$url = 'https://zapclass.com.br/api/groups/list';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);
if ($data['success']) {
echo "Total de grupos: " . count($data['groups']) . "\n\n";
foreach ($data['groups'] as $group) {
$participantCount = isset($group['participants']) ? count($group['participants']) : 0;
echo "- {$group['name']} ({$participantCount} membros)\n";
}
} else {
echo "Erro: " . $data['message'];
}
curl_close($ch);
?>
<?php
function listGroups($force = false, $noparticipants = false) {
$params = [];
if ($force) $params[] = 'force=true';
if ($noparticipants) $params[] = 'noparticipants=true';
$url = 'https://zapclass.com.br/api/groups/list';
if (!empty($params)) {
$url .= '?' . implode('&', $params);
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);
curl_close($ch);
if (!$data['success']) {
throw new Exception($data['message']);
}
return $data['groups'];
}
// Uso - listar com cache
$groups = listGroups();
echo "Grupos em cache: " . count($groups) . "\n";
// Uso - forçar atualização sem participantes
$freshGroups = listGroups(true, true);
echo "Grupos atualizados: " . count($freshGroups) . "\n";
?>
<?php
function analyzeGroups() {
$url = 'https://zapclass.com.br/api/groups/list?force=true';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);
curl_close($ch);
if (!$data['success']) {
throw new Exception($data['message']);
}
$groups = $data['groups'];
$stats = [
'total' => count($groups),
'totalParticipants' => 0,
'withAnnounce' => 0,
'withRestrict' => 0,
'largestGroup' => null,
'smallestGroup' => null
];
foreach ($groups as $group) {
$participantCount = isset($group['participants']) ? count($group['participants']) : 0;
$stats['totalParticipants'] += $participantCount;
if ($group['announce'] ?? false) $stats['withAnnounce']++;
if ($group['restrict'] ?? false) $stats['withRestrict']++;
if (!$stats['largestGroup'] ||
$participantCount > (count($stats['largestGroup']['participants'] ?? []) ?: 0)) {
$stats['largestGroup'] = $group;
}
if (!$stats['smallestGroup'] ||
$participantCount < (count($stats['smallestGroup']['participants'] ?? []) ?: 0)) {
$stats['smallestGroup'] = $group;
}
}
$stats['avgParticipants'] = $stats['total'] > 0
? round($stats['totalParticipants'] / $stats['total'], 1)
: 0;
echo "═══════════════════════════════\n";
echo " ANÁLISE DE GRUPOS\n";
echo "═══════════════════════════════\n\n";
echo "Total de grupos: {$stats['total']}\n";
echo "Total de participantes: {$stats['totalParticipants']}\n";
echo "Média de participantes: {$stats['avgParticipants']}\n\n";
echo "Grupos apenas admin: {$stats['withAnnounce']}\n";
echo "Grupos com edição restrita: {$stats['withRestrict']}\n\n";
if ($stats['largestGroup']) {
$largestCount = count($stats['largestGroup']['participants'] ?? []);
echo "Maior grupo: {$stats['largestGroup']['name']} ({$largestCount} membros)\n";
}
if ($stats['smallestGroup']) {
$smallestCount = count($stats['smallestGroup']['participants'] ?? []);
echo "Menor grupo: {$stats['smallestGroup']['name']} ({$smallestCount} membros)\n";
}
return $stats;
}
// Uso
try {
analyzeGroups();
} catch (Exception $e) {
echo "Erro: " . $e->getMessage();
}
?>
<?php
class GroupListManager {
private $token;
private $baseUrl = 'https://zapclass.com.br/api';
public function __construct($token) {
$this->token = $token;
}
public function list($force = false, $noparticipants = false) {
$params = [];
if ($force) $params[] = 'force=true';
if ($noparticipants) $params[] = 'noparticipants=true';
$url = $this->baseUrl . '/groups/list';
if (!empty($params)) {
$url .= '?' . implode('&', $params);
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
"Authorization: Bearer {$this->token}"
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
if (!$data['success']) {
throw new Exception($data['message']);
}
return $data['groups'];
}
public function filter($criteria) {
$groups = $this->list(true);
$filtered = $groups;
if (isset($criteria['nameContains'])) {
$filtered = array_filter($filtered, function($g) use ($criteria) {
return stripos($g['name'], $criteria['nameContains']) !== false;
});
}
if (isset($criteria['minParticipants'])) {
$filtered = array_filter($filtered, function($g) use ($criteria) {
return (count($g['participants'] ?? []) >= $criteria['minParticipants']);
});
}
if (isset($criteria['maxParticipants'])) {
$filtered = array_filter($filtered, function($g) use ($criteria) {
return (count($g['participants'] ?? []) <= $criteria['maxParticipants']);
});
}
return array_values($filtered);
}
public function exportCSV($filename = 'grupos.csv') {
$groups = $this->list(true, true);
$fp = fopen($filename, 'w');
// Cabeçalho
fputcsv($fp, ['ID', 'Nome', 'Descrição', 'Participantes', 'Apenas Admin', 'Edição Restrita']);
// Dados
foreach ($groups as $group) {
fputcsv($fp, [
$group['id'],
$group['name'],
$group['description'] ?? '',
count($group['participants'] ?? []),
($group['announce'] ?? false) ? 'Sim' : 'Não',
($group['restrict'] ?? false) ? 'Sim' : 'Não'
]);
}
fclose($fp);
return $filename;
}
public function getStats() {
$groups = $this->list(true);
$stats = [
'total' => count($groups),
'totalParticipants' => array_sum(array_map(function($g) {
return count($g['participants'] ?? []);
}, $groups))
];
$stats['avgParticipants'] = $stats['total'] > 0
? round($stats['totalParticipants'] / $stats['total'], 1)
: 0;
return $stats;
}
}
// Uso
$manager = new GroupListManager('zt_BppKZWtzvj1X2SbJAuOSkA0Z63uDBQ0wkb28NJaloKeOUnHk');
try {
// Listar todos os grupos
$groups = $manager->list();
echo "Total: " . count($groups) . " grupos\n\n";
// Filtrar grupos
$vendas = $manager->filter(['nameContains' => 'vendas']);
echo "Grupos de vendas: " . count($vendas) . "\n\n";
// Exportar para CSV
$file = $manager->exportCSV('meus_grupos.csv');
echo "CSV exportado: {$file}\n\n";
// Estatísticas
$stats = $manager->getStats();
echo "Estatísticas:\n";
echo "- Total de grupos: {$stats['total']}\n";
echo "- Total de participantes: {$stats['totalParticipants']}\n";
echo "- Média de participantes: {$stats['avgParticipants']}\n";
} catch (Exception $e) {
echo "Erro: " . $e->getMessage();
}
?>
{
"success": true,
"groups": [
{
"id": "120363324255083289@g.us",
"name": "Equipe de Vendas",
"description": "Grupo oficial da equipe",
"announce": false,
"restrict": false,
"createdAt": 1672531200000,
"profilePicUrl": "https://example.com/pic.jpg",
"participants": [
{
"jid": "5511999999999@s.whatsapp.net",
"number": "5511999999999",
"admin": true,
"superAdmin": true
},
{
"jid": "5511888888888@s.whatsapp.net",
"number": "5511888888888",
"admin": false
}
]
},
{
"id": "120363324255083290@g.us",
"name": "Suporte Técnico",
"description": null,
"announce": true,
"restrict": true,
"participants": [
{
"jid": "5511777777777@s.whatsapp.net",
"admin": true
}
]
}
]
}
{
"success": true,
"groups": [
{
"id": "120363324255083289@g.us",
"name": "Equipe de Vendas",
"description": "Grupo oficial da equipe",
"announce": false,
"restrict": false,
"createdAt": 1672531200000,
"profilePicUrl": "https://example.com/pic.jpg"
},
{
"id": "120363324255083290@g.us",
"name": "Suporte Técnico",
"description": null,
"announce": true,
"restrict": true,
"createdAt": 1672617600000
}
]
}
{
"success": true,
"groups": []
}
{
"success": false,
"message": "Erro ao recuperar lista de grupos"
}
{
"success": false,
"message": "Falha na conexão com o WhatsApp. Verifique sua instância"
}
Grupos
Listar Grupos
Recuperar lista completa de grupos do WhatsApp
GET
/
groups
/
list
curl -X GET "https://zapclass.com.br/api/groups/list" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP"
curl -X GET "https://zapclass.com.br/api/groups/list?force=true" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP"
curl -X GET "https://zapclass.com.br/api/groups/list?noparticipants=true" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP"
curl -X GET "https://zapclass.com.br/api/groups/list?force=true&noparticipants=true" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP"
const response = await fetch("https://zapclass.com.br/api/groups/list", {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP",
},
});
const data = await response.json();
if (data.success) {
console.log(`Total de grupos: ${data.groups.length}`);
data.groups.forEach((group) => {
console.log(`- ${group.name} (${group.participants?.length || 0} membros)`);
});
}
async function listGroups(options = {}) {
const { force = false, noparticipants = false } = options;
const params = new URLSearchParams();
if (force) params.append("force", "true");
if (noparticipants) params.append("noparticipants", "true");
const url = `https://zapclass.com.br/api/groups/list${
params.toString() ? "?" + params.toString() : ""
}`;
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP",
},
});
const data = await response.json();
if (!data.success) {
throw new Error(data.message);
}
return data.groups;
}
// Uso - listar com cache
const groups = await listGroups();
console.log(`Grupos em cache: ${groups.length}`);
// Uso - forçar atualização sem participantes
const freshGroups = await listGroups({
force: true,
noparticipants: true,
});
console.log(`Grupos atualizados: ${freshGroups.length}`);
async function analyzeGroups() {
const response = await fetch(
"https://zapclass.com.br/api/groups/list?force=true",
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP",
},
}
);
const data = await response.json();
if (!data.success) {
throw new Error(data.message);
}
const groups = data.groups;
// Estatísticas
const stats = {
total: groups.length,
totalParticipants: 0,
withAnnounce: 0,
withRestrict: 0,
avgParticipants: 0,
largestGroup: null,
smallestGroup: null,
};
groups.forEach((group) => {
const participantCount = group.participants?.length || 0;
stats.totalParticipants += participantCount;
if (group.announce) stats.withAnnounce++;
if (group.restrict) stats.withRestrict++;
if (
!stats.largestGroup ||
participantCount > (stats.largestGroup.participants?.length || 0)
) {
stats.largestGroup = group;
}
if (
!stats.smallestGroup ||
participantCount < (stats.smallestGroup.participants?.length || 0)
) {
stats.smallestGroup = group;
}
});
stats.avgParticipants = (stats.totalParticipants / stats.total).toFixed(1);
console.log("═══════════════════════════════");
console.log(" ANÁLISE DE GRUPOS");
console.log("═══════════════════════════════");
console.log(`\nTotal de grupos: ${stats.total}`);
console.log(`Total de participantes: ${stats.totalParticipants}`);
console.log(`Média de participantes: ${stats.avgParticipants}`);
console.log(`\nGrupos apenas admin: ${stats.withAnnounce}`);
console.log(`Grupos com edição restrita: ${stats.withRestrict}`);
console.log(
`\nMaior grupo: ${stats.largestGroup.name} (${
stats.largestGroup.participants?.length || 0
} membros)`
);
console.log(
`Menor grupo: ${stats.smallestGroup.name} (${
stats.smallestGroup.participants?.length || 0
} membros)`
);
return stats;
}
// Uso
await analyzeGroups();
async function filterGroups(criteria) {
const response = await fetch(
"https://zapclass.com.br/api/groups/list?force=true",
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP",
},
}
);
const data = await response.json();
if (!data.success) {
throw new Error(data.message);
}
let filtered = data.groups;
// Filtrar por nome
if (criteria.nameContains) {
filtered = filtered.filter((g) =>
g.name.toLowerCase().includes(criteria.nameContains.toLowerCase())
);
}
// Filtrar por número mínimo de participantes
if (criteria.minParticipants) {
filtered = filtered.filter(
(g) => (g.participants?.length || 0) >= criteria.minParticipants
);
}
// Filtrar por número máximo de participantes
if (criteria.maxParticipants) {
filtered = filtered.filter(
(g) => (g.participants?.length || 0) <= criteria.maxParticipants
);
}
// Filtrar apenas grupos onde sou admin
if (criteria.onlyAdmin) {
filtered = filtered.filter((g) =>
g.participants?.some((p) => p.admin && p.isMe)
);
}
// Filtrar por modo announce
if (criteria.announce !== undefined) {
filtered = filtered.filter((g) => g.announce === criteria.announce);
}
return filtered;
}
// Uso - grupos com "vendas" no nome e mais de 10 membros
const vendas = await filterGroups({
nameContains: "vendas",
minParticipants: 10,
});
console.log(`Grupos de vendas (10+ membros): ${vendas.length}`);
vendas.forEach((g) => console.log(` - ${g.name}`));
// Uso - grupos onde sou admin
const myAdminGroups = await filterGroups({ onlyAdmin: true });
console.log(`\nGrupos onde sou admin: ${myAdminGroups.length}`);
async function exportGroupsToCSV() {
const response = await fetch(
"https://zapclass.com.br/api/groups/list?force=true&noparticipants=true",
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP",
},
}
);
const data = await response.json();
if (!data.success) {
throw new Error(data.message);
}
// Cabeçalho CSV
let csv = "ID,Nome,Descrição,Participantes,Apenas Admin,Edição Restrita\n";
// Adiciona cada grupo
data.groups.forEach((group) => {
const row = [
group.id,
`"${group.name.replace(/"/g, '""')}"`,
`"${(group.description || "").replace(/"/g, '""')}"`,
group.participants?.length || 0,
group.announce ? "Sim" : "Não",
group.restrict ? "Sim" : "Não",
].join(",");
csv += row + "\n";
});
return csv;
}
// Uso
const csv = await exportGroupsToCSV();
console.log("CSV gerado:");
console.log(csv);
// Em Node.js, salvar em arquivo:
// const fs = require('fs');
// fs.writeFileSync('grupos.csv', csv, 'utf8');
<?php
$url = 'https://zapclass.com.br/api/groups/list';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);
if ($data['success']) {
echo "Total de grupos: " . count($data['groups']) . "\n\n";
foreach ($data['groups'] as $group) {
$participantCount = isset($group['participants']) ? count($group['participants']) : 0;
echo "- {$group['name']} ({$participantCount} membros)\n";
}
} else {
echo "Erro: " . $data['message'];
}
curl_close($ch);
?>
<?php
function listGroups($force = false, $noparticipants = false) {
$params = [];
if ($force) $params[] = 'force=true';
if ($noparticipants) $params[] = 'noparticipants=true';
$url = 'https://zapclass.com.br/api/groups/list';
if (!empty($params)) {
$url .= '?' . implode('&', $params);
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);
curl_close($ch);
if (!$data['success']) {
throw new Exception($data['message']);
}
return $data['groups'];
}
// Uso - listar com cache
$groups = listGroups();
echo "Grupos em cache: " . count($groups) . "\n";
// Uso - forçar atualização sem participantes
$freshGroups = listGroups(true, true);
echo "Grupos atualizados: " . count($freshGroups) . "\n";
?>
<?php
function analyzeGroups() {
$url = 'https://zapclass.com.br/api/groups/list?force=true';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);
curl_close($ch);
if (!$data['success']) {
throw new Exception($data['message']);
}
$groups = $data['groups'];
$stats = [
'total' => count($groups),
'totalParticipants' => 0,
'withAnnounce' => 0,
'withRestrict' => 0,
'largestGroup' => null,
'smallestGroup' => null
];
foreach ($groups as $group) {
$participantCount = isset($group['participants']) ? count($group['participants']) : 0;
$stats['totalParticipants'] += $participantCount;
if ($group['announce'] ?? false) $stats['withAnnounce']++;
if ($group['restrict'] ?? false) $stats['withRestrict']++;
if (!$stats['largestGroup'] ||
$participantCount > (count($stats['largestGroup']['participants'] ?? []) ?: 0)) {
$stats['largestGroup'] = $group;
}
if (!$stats['smallestGroup'] ||
$participantCount < (count($stats['smallestGroup']['participants'] ?? []) ?: 0)) {
$stats['smallestGroup'] = $group;
}
}
$stats['avgParticipants'] = $stats['total'] > 0
? round($stats['totalParticipants'] / $stats['total'], 1)
: 0;
echo "═══════════════════════════════\n";
echo " ANÁLISE DE GRUPOS\n";
echo "═══════════════════════════════\n\n";
echo "Total de grupos: {$stats['total']}\n";
echo "Total de participantes: {$stats['totalParticipants']}\n";
echo "Média de participantes: {$stats['avgParticipants']}\n\n";
echo "Grupos apenas admin: {$stats['withAnnounce']}\n";
echo "Grupos com edição restrita: {$stats['withRestrict']}\n\n";
if ($stats['largestGroup']) {
$largestCount = count($stats['largestGroup']['participants'] ?? []);
echo "Maior grupo: {$stats['largestGroup']['name']} ({$largestCount} membros)\n";
}
if ($stats['smallestGroup']) {
$smallestCount = count($stats['smallestGroup']['participants'] ?? []);
echo "Menor grupo: {$stats['smallestGroup']['name']} ({$smallestCount} membros)\n";
}
return $stats;
}
// Uso
try {
analyzeGroups();
} catch (Exception $e) {
echo "Erro: " . $e->getMessage();
}
?>
<?php
class GroupListManager {
private $token;
private $baseUrl = 'https://zapclass.com.br/api';
public function __construct($token) {
$this->token = $token;
}
public function list($force = false, $noparticipants = false) {
$params = [];
if ($force) $params[] = 'force=true';
if ($noparticipants) $params[] = 'noparticipants=true';
$url = $this->baseUrl . '/groups/list';
if (!empty($params)) {
$url .= '?' . implode('&', $params);
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
"Authorization: Bearer {$this->token}"
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
if (!$data['success']) {
throw new Exception($data['message']);
}
return $data['groups'];
}
public function filter($criteria) {
$groups = $this->list(true);
$filtered = $groups;
if (isset($criteria['nameContains'])) {
$filtered = array_filter($filtered, function($g) use ($criteria) {
return stripos($g['name'], $criteria['nameContains']) !== false;
});
}
if (isset($criteria['minParticipants'])) {
$filtered = array_filter($filtered, function($g) use ($criteria) {
return (count($g['participants'] ?? []) >= $criteria['minParticipants']);
});
}
if (isset($criteria['maxParticipants'])) {
$filtered = array_filter($filtered, function($g) use ($criteria) {
return (count($g['participants'] ?? []) <= $criteria['maxParticipants']);
});
}
return array_values($filtered);
}
public function exportCSV($filename = 'grupos.csv') {
$groups = $this->list(true, true);
$fp = fopen($filename, 'w');
// Cabeçalho
fputcsv($fp, ['ID', 'Nome', 'Descrição', 'Participantes', 'Apenas Admin', 'Edição Restrita']);
// Dados
foreach ($groups as $group) {
fputcsv($fp, [
$group['id'],
$group['name'],
$group['description'] ?? '',
count($group['participants'] ?? []),
($group['announce'] ?? false) ? 'Sim' : 'Não',
($group['restrict'] ?? false) ? 'Sim' : 'Não'
]);
}
fclose($fp);
return $filename;
}
public function getStats() {
$groups = $this->list(true);
$stats = [
'total' => count($groups),
'totalParticipants' => array_sum(array_map(function($g) {
return count($g['participants'] ?? []);
}, $groups))
];
$stats['avgParticipants'] = $stats['total'] > 0
? round($stats['totalParticipants'] / $stats['total'], 1)
: 0;
return $stats;
}
}
// Uso
$manager = new GroupListManager('zt_BppKZWtzvj1X2SbJAuOSkA0Z63uDBQ0wkb28NJaloKeOUnHk');
try {
// Listar todos os grupos
$groups = $manager->list();
echo "Total: " . count($groups) . " grupos\n\n";
// Filtrar grupos
$vendas = $manager->filter(['nameContains' => 'vendas']);
echo "Grupos de vendas: " . count($vendas) . "\n\n";
// Exportar para CSV
$file = $manager->exportCSV('meus_grupos.csv');
echo "CSV exportado: {$file}\n\n";
// Estatísticas
$stats = $manager->getStats();
echo "Estatísticas:\n";
echo "- Total de grupos: {$stats['total']}\n";
echo "- Total de participantes: {$stats['totalParticipants']}\n";
echo "- Média de participantes: {$stats['avgParticipants']}\n";
} catch (Exception $e) {
echo "Erro: " . $e->getMessage();
}
?>
{
"success": true,
"groups": [
{
"id": "120363324255083289@g.us",
"name": "Equipe de Vendas",
"description": "Grupo oficial da equipe",
"announce": false,
"restrict": false,
"createdAt": 1672531200000,
"profilePicUrl": "https://example.com/pic.jpg",
"participants": [
{
"jid": "5511999999999@s.whatsapp.net",
"number": "5511999999999",
"admin": true,
"superAdmin": true
},
{
"jid": "5511888888888@s.whatsapp.net",
"number": "5511888888888",
"admin": false
}
]
},
{
"id": "120363324255083290@g.us",
"name": "Suporte Técnico",
"description": null,
"announce": true,
"restrict": true,
"participants": [
{
"jid": "5511777777777@s.whatsapp.net",
"admin": true
}
]
}
]
}
{
"success": true,
"groups": [
{
"id": "120363324255083289@g.us",
"name": "Equipe de Vendas",
"description": "Grupo oficial da equipe",
"announce": false,
"restrict": false,
"createdAt": 1672531200000,
"profilePicUrl": "https://example.com/pic.jpg"
},
{
"id": "120363324255083290@g.us",
"name": "Suporte Técnico",
"description": null,
"announce": true,
"restrict": true,
"createdAt": 1672617600000
}
]
}
{
"success": true,
"groups": []
}
{
"success": false,
"message": "Erro ao recuperar lista de grupos"
}
{
"success": false,
"message": "Falha na conexão com o WhatsApp. Verifique sua instância"
}
Retorna todos os grupos aos quais a instância conectada pertence, com opções para controlar o cache e o detalhamento dos participantes.
Opções de Listagem
Recuperação de Grupos
Recuperação de Grupos
Como funciona a listagem de grupos disponíveis.Dados retornados:
- ID único de cada grupo (JID)
- Nome do grupo
- Descrição (se disponível)
- Foto de perfil (URL)
- Número total de participantes
- Configurações do grupo (anúncios, restrições)
- Lista completa de participantes (opcional)
Controle de Cache
Controle de Cache
Gerenciamento de atualização dos dados de grupos.Modo cache (
force=false):- Retorna dados armazenados localmente
- Resposta mais rápida
- Economiza recursos do servidor
- Pode conter informações ligeiramente desatualizadas
force=true):- Busca dados diretamente do WhatsApp
- Informações em tempo real
- Maior tempo de resposta
- Use quando precisar de dados precisos e atuais
Otimização com Participantes
Otimização com Participantes
Controle da inclusão de dados de participantes.Com participantes (
noparticipants=false):- Retorna lista completa de membros de cada grupo
- Inclui informações de administradores
- Resposta mais pesada
- Ideal para análises detalhadas
noparticipants=true):- Retorna apenas informações básicas do grupo
- Resposta mais leve e rápida
- Reduz uso de banda e processamento
- Perfeito para listagens simples
noparticipants=true quando não precisar dos membros.Casos de Uso
Casos de Uso
Situações comuns para listar grupos programaticamente.Aplicações:
- Dashboards de monitoramento de grupos
- Sistemas de backup e auditoria
- Ferramentas de análise de participação
- Seleção de grupos para envio de mensagens
- Relatórios de gestão de comunidades
- Sincronização com sistemas CRM
- Automação de tarefas em múltiplos grupos
Authorization
string
required
Chave de autenticação da sua conexão, utilizada no header Authorization como
Bearer Token.
Você encontra sua API Key no botão API da sua conexão no painel ZapClass.
A chave sempre começa com o prefixo
Exemplo:
Você encontra sua API Key no botão API da sua conexão no painel ZapClass.
A chave sempre começa com o prefixo
zc_. Exemplo:
zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aPQuery Parameters
boolean
Forçar atualização do cache de grupos.
Exemplo:
true: Busca dados atualizados do WhatsApp false: Usa informações em cache (padrão) Exemplo:
trueboolean
Omitir lista de participantes na resposta.
Exemplo:
true: Retorna grupos sem participantes false: Inclui lista completa de participantes (padrão) Exemplo:
trueDica de Performance: Use
noparticipants=true quando precisar apenas de
informações básicas dos grupos. Isso reduz significativamente o tamanho da
resposta e o tempo de processamento.curl -X GET "https://zapclass.com.br/api/groups/list" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP"
curl -X GET "https://zapclass.com.br/api/groups/list?force=true" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP"
curl -X GET "https://zapclass.com.br/api/groups/list?noparticipants=true" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP"
curl -X GET "https://zapclass.com.br/api/groups/list?force=true&noparticipants=true" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP"
const response = await fetch("https://zapclass.com.br/api/groups/list", {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP",
},
});
const data = await response.json();
if (data.success) {
console.log(`Total de grupos: ${data.groups.length}`);
data.groups.forEach((group) => {
console.log(`- ${group.name} (${group.participants?.length || 0} membros)`);
});
}
async function listGroups(options = {}) {
const { force = false, noparticipants = false } = options;
const params = new URLSearchParams();
if (force) params.append("force", "true");
if (noparticipants) params.append("noparticipants", "true");
const url = `https://zapclass.com.br/api/groups/list${
params.toString() ? "?" + params.toString() : ""
}`;
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP",
},
});
const data = await response.json();
if (!data.success) {
throw new Error(data.message);
}
return data.groups;
}
// Uso - listar com cache
const groups = await listGroups();
console.log(`Grupos em cache: ${groups.length}`);
// Uso - forçar atualização sem participantes
const freshGroups = await listGroups({
force: true,
noparticipants: true,
});
console.log(`Grupos atualizados: ${freshGroups.length}`);
async function analyzeGroups() {
const response = await fetch(
"https://zapclass.com.br/api/groups/list?force=true",
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP",
},
}
);
const data = await response.json();
if (!data.success) {
throw new Error(data.message);
}
const groups = data.groups;
// Estatísticas
const stats = {
total: groups.length,
totalParticipants: 0,
withAnnounce: 0,
withRestrict: 0,
avgParticipants: 0,
largestGroup: null,
smallestGroup: null,
};
groups.forEach((group) => {
const participantCount = group.participants?.length || 0;
stats.totalParticipants += participantCount;
if (group.announce) stats.withAnnounce++;
if (group.restrict) stats.withRestrict++;
if (
!stats.largestGroup ||
participantCount > (stats.largestGroup.participants?.length || 0)
) {
stats.largestGroup = group;
}
if (
!stats.smallestGroup ||
participantCount < (stats.smallestGroup.participants?.length || 0)
) {
stats.smallestGroup = group;
}
});
stats.avgParticipants = (stats.totalParticipants / stats.total).toFixed(1);
console.log("═══════════════════════════════");
console.log(" ANÁLISE DE GRUPOS");
console.log("═══════════════════════════════");
console.log(`\nTotal de grupos: ${stats.total}`);
console.log(`Total de participantes: ${stats.totalParticipants}`);
console.log(`Média de participantes: ${stats.avgParticipants}`);
console.log(`\nGrupos apenas admin: ${stats.withAnnounce}`);
console.log(`Grupos com edição restrita: ${stats.withRestrict}`);
console.log(
`\nMaior grupo: ${stats.largestGroup.name} (${
stats.largestGroup.participants?.length || 0
} membros)`
);
console.log(
`Menor grupo: ${stats.smallestGroup.name} (${
stats.smallestGroup.participants?.length || 0
} membros)`
);
return stats;
}
// Uso
await analyzeGroups();
async function filterGroups(criteria) {
const response = await fetch(
"https://zapclass.com.br/api/groups/list?force=true",
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP",
},
}
);
const data = await response.json();
if (!data.success) {
throw new Error(data.message);
}
let filtered = data.groups;
// Filtrar por nome
if (criteria.nameContains) {
filtered = filtered.filter((g) =>
g.name.toLowerCase().includes(criteria.nameContains.toLowerCase())
);
}
// Filtrar por número mínimo de participantes
if (criteria.minParticipants) {
filtered = filtered.filter(
(g) => (g.participants?.length || 0) >= criteria.minParticipants
);
}
// Filtrar por número máximo de participantes
if (criteria.maxParticipants) {
filtered = filtered.filter(
(g) => (g.participants?.length || 0) <= criteria.maxParticipants
);
}
// Filtrar apenas grupos onde sou admin
if (criteria.onlyAdmin) {
filtered = filtered.filter((g) =>
g.participants?.some((p) => p.admin && p.isMe)
);
}
// Filtrar por modo announce
if (criteria.announce !== undefined) {
filtered = filtered.filter((g) => g.announce === criteria.announce);
}
return filtered;
}
// Uso - grupos com "vendas" no nome e mais de 10 membros
const vendas = await filterGroups({
nameContains: "vendas",
minParticipants: 10,
});
console.log(`Grupos de vendas (10+ membros): ${vendas.length}`);
vendas.forEach((g) => console.log(` - ${g.name}`));
// Uso - grupos onde sou admin
const myAdminGroups = await filterGroups({ onlyAdmin: true });
console.log(`\nGrupos onde sou admin: ${myAdminGroups.length}`);
async function exportGroupsToCSV() {
const response = await fetch(
"https://zapclass.com.br/api/groups/list?force=true&noparticipants=true",
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP",
},
}
);
const data = await response.json();
if (!data.success) {
throw new Error(data.message);
}
// Cabeçalho CSV
let csv = "ID,Nome,Descrição,Participantes,Apenas Admin,Edição Restrita\n";
// Adiciona cada grupo
data.groups.forEach((group) => {
const row = [
group.id,
`"${group.name.replace(/"/g, '""')}"`,
`"${(group.description || "").replace(/"/g, '""')}"`,
group.participants?.length || 0,
group.announce ? "Sim" : "Não",
group.restrict ? "Sim" : "Não",
].join(",");
csv += row + "\n";
});
return csv;
}
// Uso
const csv = await exportGroupsToCSV();
console.log("CSV gerado:");
console.log(csv);
// Em Node.js, salvar em arquivo:
// const fs = require('fs');
// fs.writeFileSync('grupos.csv', csv, 'utf8');
<?php
$url = 'https://zapclass.com.br/api/groups/list';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);
if ($data['success']) {
echo "Total de grupos: " . count($data['groups']) . "\n\n";
foreach ($data['groups'] as $group) {
$participantCount = isset($group['participants']) ? count($group['participants']) : 0;
echo "- {$group['name']} ({$participantCount} membros)\n";
}
} else {
echo "Erro: " . $data['message'];
}
curl_close($ch);
?>
<?php
function listGroups($force = false, $noparticipants = false) {
$params = [];
if ($force) $params[] = 'force=true';
if ($noparticipants) $params[] = 'noparticipants=true';
$url = 'https://zapclass.com.br/api/groups/list';
if (!empty($params)) {
$url .= '?' . implode('&', $params);
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);
curl_close($ch);
if (!$data['success']) {
throw new Exception($data['message']);
}
return $data['groups'];
}
// Uso - listar com cache
$groups = listGroups();
echo "Grupos em cache: " . count($groups) . "\n";
// Uso - forçar atualização sem participantes
$freshGroups = listGroups(true, true);
echo "Grupos atualizados: " . count($freshGroups) . "\n";
?>
<?php
function analyzeGroups() {
$url = 'https://zapclass.com.br/api/groups/list?force=true';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer zc_6FrX2qjM4bHT9pR6cC0sD8wLkG3nE2tZfV5uN1aP'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);
curl_close($ch);
if (!$data['success']) {
throw new Exception($data['message']);
}
$groups = $data['groups'];
$stats = [
'total' => count($groups),
'totalParticipants' => 0,
'withAnnounce' => 0,
'withRestrict' => 0,
'largestGroup' => null,
'smallestGroup' => null
];
foreach ($groups as $group) {
$participantCount = isset($group['participants']) ? count($group['participants']) : 0;
$stats['totalParticipants'] += $participantCount;
if ($group['announce'] ?? false) $stats['withAnnounce']++;
if ($group['restrict'] ?? false) $stats['withRestrict']++;
if (!$stats['largestGroup'] ||
$participantCount > (count($stats['largestGroup']['participants'] ?? []) ?: 0)) {
$stats['largestGroup'] = $group;
}
if (!$stats['smallestGroup'] ||
$participantCount < (count($stats['smallestGroup']['participants'] ?? []) ?: 0)) {
$stats['smallestGroup'] = $group;
}
}
$stats['avgParticipants'] = $stats['total'] > 0
? round($stats['totalParticipants'] / $stats['total'], 1)
: 0;
echo "═══════════════════════════════\n";
echo " ANÁLISE DE GRUPOS\n";
echo "═══════════════════════════════\n\n";
echo "Total de grupos: {$stats['total']}\n";
echo "Total de participantes: {$stats['totalParticipants']}\n";
echo "Média de participantes: {$stats['avgParticipants']}\n\n";
echo "Grupos apenas admin: {$stats['withAnnounce']}\n";
echo "Grupos com edição restrita: {$stats['withRestrict']}\n\n";
if ($stats['largestGroup']) {
$largestCount = count($stats['largestGroup']['participants'] ?? []);
echo "Maior grupo: {$stats['largestGroup']['name']} ({$largestCount} membros)\n";
}
if ($stats['smallestGroup']) {
$smallestCount = count($stats['smallestGroup']['participants'] ?? []);
echo "Menor grupo: {$stats['smallestGroup']['name']} ({$smallestCount} membros)\n";
}
return $stats;
}
// Uso
try {
analyzeGroups();
} catch (Exception $e) {
echo "Erro: " . $e->getMessage();
}
?>
<?php
class GroupListManager {
private $token;
private $baseUrl = 'https://zapclass.com.br/api';
public function __construct($token) {
$this->token = $token;
}
public function list($force = false, $noparticipants = false) {
$params = [];
if ($force) $params[] = 'force=true';
if ($noparticipants) $params[] = 'noparticipants=true';
$url = $this->baseUrl . '/groups/list';
if (!empty($params)) {
$url .= '?' . implode('&', $params);
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
"Authorization: Bearer {$this->token}"
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
if (!$data['success']) {
throw new Exception($data['message']);
}
return $data['groups'];
}
public function filter($criteria) {
$groups = $this->list(true);
$filtered = $groups;
if (isset($criteria['nameContains'])) {
$filtered = array_filter($filtered, function($g) use ($criteria) {
return stripos($g['name'], $criteria['nameContains']) !== false;
});
}
if (isset($criteria['minParticipants'])) {
$filtered = array_filter($filtered, function($g) use ($criteria) {
return (count($g['participants'] ?? []) >= $criteria['minParticipants']);
});
}
if (isset($criteria['maxParticipants'])) {
$filtered = array_filter($filtered, function($g) use ($criteria) {
return (count($g['participants'] ?? []) <= $criteria['maxParticipants']);
});
}
return array_values($filtered);
}
public function exportCSV($filename = 'grupos.csv') {
$groups = $this->list(true, true);
$fp = fopen($filename, 'w');
// Cabeçalho
fputcsv($fp, ['ID', 'Nome', 'Descrição', 'Participantes', 'Apenas Admin', 'Edição Restrita']);
// Dados
foreach ($groups as $group) {
fputcsv($fp, [
$group['id'],
$group['name'],
$group['description'] ?? '',
count($group['participants'] ?? []),
($group['announce'] ?? false) ? 'Sim' : 'Não',
($group['restrict'] ?? false) ? 'Sim' : 'Não'
]);
}
fclose($fp);
return $filename;
}
public function getStats() {
$groups = $this->list(true);
$stats = [
'total' => count($groups),
'totalParticipants' => array_sum(array_map(function($g) {
return count($g['participants'] ?? []);
}, $groups))
];
$stats['avgParticipants'] = $stats['total'] > 0
? round($stats['totalParticipants'] / $stats['total'], 1)
: 0;
return $stats;
}
}
// Uso
$manager = new GroupListManager('zt_BppKZWtzvj1X2SbJAuOSkA0Z63uDBQ0wkb28NJaloKeOUnHk');
try {
// Listar todos os grupos
$groups = $manager->list();
echo "Total: " . count($groups) . " grupos\n\n";
// Filtrar grupos
$vendas = $manager->filter(['nameContains' => 'vendas']);
echo "Grupos de vendas: " . count($vendas) . "\n\n";
// Exportar para CSV
$file = $manager->exportCSV('meus_grupos.csv');
echo "CSV exportado: {$file}\n\n";
// Estatísticas
$stats = $manager->getStats();
echo "Estatísticas:\n";
echo "- Total de grupos: {$stats['total']}\n";
echo "- Total de participantes: {$stats['totalParticipants']}\n";
echo "- Média de participantes: {$stats['avgParticipants']}\n";
} catch (Exception $e) {
echo "Erro: " . $e->getMessage();
}
?>
{
"success": true,
"groups": [
{
"id": "120363324255083289@g.us",
"name": "Equipe de Vendas",
"description": "Grupo oficial da equipe",
"announce": false,
"restrict": false,
"createdAt": 1672531200000,
"profilePicUrl": "https://example.com/pic.jpg",
"participants": [
{
"jid": "5511999999999@s.whatsapp.net",
"number": "5511999999999",
"admin": true,
"superAdmin": true
},
{
"jid": "5511888888888@s.whatsapp.net",
"number": "5511888888888",
"admin": false
}
]
},
{
"id": "120363324255083290@g.us",
"name": "Suporte Técnico",
"description": null,
"announce": true,
"restrict": true,
"participants": [
{
"jid": "5511777777777@s.whatsapp.net",
"admin": true
}
]
}
]
}
{
"success": true,
"groups": [
{
"id": "120363324255083289@g.us",
"name": "Equipe de Vendas",
"description": "Grupo oficial da equipe",
"announce": false,
"restrict": false,
"createdAt": 1672531200000,
"profilePicUrl": "https://example.com/pic.jpg"
},
{
"id": "120363324255083290@g.us",
"name": "Suporte Técnico",
"description": null,
"announce": true,
"restrict": true,
"createdAt": 1672617600000
}
]
}
{
"success": true,
"groups": []
}
{
"success": false,
"message": "Erro ao recuperar lista de grupos"
}
{
"success": false,
"message": "Falha na conexão com o WhatsApp. Verifique sua instância"
}
⌘I

