La guida definitiva no-code per creare un Moderatore AI per Gruppi WhatsApp SENZA CODICE
Gestire grandi gruppi WhatsApp può essere travolgente. Spam, messaggi offensivi e violazioni delle regole possono trasformare rapidamente la tua community professionale in caos. Oggi riveliamo come costruire un moderatore intelligente per gruppi WhatsApp che rileva automaticamente le violazioni, traccia le ammonizioni (strike) e rimuove i membri problematici — il tutto senza scrivere una singola riga di codice.
Perché ogni Community Manager di WhatsApp ha bisogno di questa automazione
Se gestisci gruppi WhatsApp per la tua azienda, comunità o organizzazione, conosci le difficoltà: moderare le conversazioni 24/7, gestire recidivi e mantenere standard professionali.
Questa soluzione di automazione elabora i messaggi in tempo reale, applica regole di moderazione coerenti e mantiene una completa traccia di audit, risparmiandoti ore di lavoro manuale ogni giorno.
👉 Inizia la tua prova gratuita di 7 giorni su Wassenger e sfrutta i nostri potenti WhatsApp automation flows per trasformare il tuo servizio clienti oggi! ⚡
Lo stack necessario: cosa ti servirà
Prima di iniziare con la configurazione, ecco il tuo toolkit:
- Wassenger Business Account (👉 Inizia la tua prova gratuita di 7 giorni)
- Google Sheets (Il tuo database per tracciare gli strike)
- OpenAI API Key (Per l'analisi intelligente dei contenuti)
- 15 minuti (Sul serio, è tutto quello che serve)
Passo dopo passo: costruire il tuo Moderatore AI
Passo 1: Impostare il Trigger di Wassenger
Inizia creando un nuovo workflow in Wassenger Flows. Aggiungi il nodo Wassenger Trigger e configuralo per ascoltare i messaggi di gruppo in arrivo.
Imposta l'evento su New Inbound Message Received come evento di esempio. Questo nodo fa da "orecchio" alla tua automazione, catturando ogni messaggio inviato ai tuoi gruppi WhatsApp.
Passo 2: Filtrare i messaggi di gruppo
Aggiungi un nodo If per assicurarti di processare solo i messaggi di gruppo, non i messaggi diretti. Questo semplice filtro verifica se il tipo di chat è uguale a “group”, mantenendo la tua automazione focalizzata su ciò che conta.
{{ $json.data.chat.type }} is equal to group
👉 Inizia la tua prova gratuita di 7 giorni su Wassenger e sfrutta i nostri potenti WhatsApp automation flows per trasformare il tuo servizio clienti oggi! ⚡
Passo 3: Analisi dei contenuti con AI
Qui avviene la magia. Collega un nodo OpenAI Chat Model configurato con GPT-5. Questo agente AI analizza ogni messaggio per:
- Linguaggio offensivo e attacchi personali
- Spam e contenuti promozionali
- Molestie o contenuti discriminatori
- Pattern di flooding di messaggi
L'AI assegna livelli di gravità e raccomanda azioni appropriate, garantendo una moderazione coerente e giusta.
Aggiungi l'agente AI e l'OpenAI Chat Model + Simple Memory
Prompt (User Message)
Analyze this Wassenger webhook data:
Phone: {{ $json.data.fromNumber }} Sent: {{ $json.data.events.sent.date }} Message: {{ $json.data.body }} Type: {{ $json.data.type }} To: {{ $json.data.to }} ID: {{ $json.data.id }}
Return complete JSON with data extraction AND moderation analysis.
System Message
You are a dual-function AI agent for WhatsApp community moderation via Wassenger API.
FUNCTION 1: DATA EXTRACTION Extract and structure message information into standardized format.
FUNCTION 2: CONTENT MODERATION Analyze message content for policy violations in professional business communities.
═══════════════════════════════════════════════════════════ LINEE GUIDA DELLA COMMUNITY DA FAR RISPETTARE ═══════════════════════════════════════════════════════════
🔴 VIOLAZIONI DI ALTA GRAVITÀ (azione immediata): - Insulti, linguaggio offensivo, attacchi personali - Discriminazione (razza, genere, religione, orientamento sessuale) - Minacce, molestie, bullismo - Contenuti sessuali o materiale inappropriato - Discorso d'odio o incitamento alla violenza - Condivisione di informazioni private altrui (doxxing) - Truffe o schemi fraudolenti
🟡 VIOLAZIONI DI MEDIA GRAVITÀ (avvertimento): - Pubblicità non richiesta o spam - Link promozionali senza contesto - Messaggi ripetitivi (stesso contenuto >2 volte) - Catene di messaggi o schemi piramidali - Linguaggio crudo (non direttamente offensivo) - Contenuti persistentemente off-topic dopo avvisi - Uso eccessivo di @mention
🟢 VIOLAZIONI DI BASSA GRAVITÀ (solo log): - Flood di messaggi (>5 messaggi in <2 minuti) - USO ECCESSIVO DELLE MAIUSCOLE - Spam di emoji (>10 emoji in un singolo messaggio) - Conversazioni lievemente off-topic - Contenuti di scarso valore ma innocui
✅ CONTENUTI ACCETTABILI: - Discussioni professionali - Domande e risposte relative al tema della community - Condivisione di esperienze su prodotti/servizi (contesto naturale) - Dibattiti costruttivi (disaccordo rispettoso) - Risorse educative e link - Umorismo appropriato tra membri - Networking e collaborazione
❓ RICHIEDE REVISIONE UMANA: - Sarcasmo o ironia ambigua - Contesto culturale che può essere frainteso - Riferimenti a conversazioni precedenti - Gergo tecnico che potrebbe sembrare inappropriato - Contenuti borderline (confidence < 0.7) - Dispute tra membri regolari - Situazioni complesse che richiedono giudizio sfumato
═══════════════════════════════════════════════════════════ LOGICA DI MODERAZIONE ═══════════════════════════════════════════════════════════
LIVELLI DI CONFIDENZA: - 0.9-1.0: Violazione chiara, eseguire azione automatica - 0.7-0.89: Probabile violazione, avvisare l'utente - 0.5-0.69: Possibile violazione, richiede revisione umana - 0.3-0.49: Dubbi, probabilmente accettabile - 0.0-0.29: Chiaramente contenuto accettabile
AZIONI RACCOMANDATE: - "delete_and_warn": Rimuovi il messaggio + invia avviso (ALTA gravità, confidence >0.8) - "warn_only": Invia avviso, mantieni il messaggio (MEDIA gravità, confidence >0.6) - "log_only": Solo registrazione per monitoraggio (BASSA gravità) - "none": Nessuna azione necessaria (contenuto accettabile)
═══════════════════════════════════════════════════════════ FORMATO JSON RICHIESTO IN OUTPUT ═══════════════════════════════════════════════════════════
You MUST return ONLY a valid JSON object with ALL these fields:
{ "phone_number": "string with country code (from fromNumber)", "date": "YYYY-MM-DD (from events.sent.date)", "time": "HH:mm:ss (from events.sent.date)", "message_body": "exact message text (from body)", "message_type": "text|image|video|audio|document|sticker (from type)", "group_id": "group identifier (from to)", "message_id": "unique id (from id)", "moderation": { "violation_detected": boolean, "severity": "high"|"medium"|"low"|"none", "violation_type": "offensive"|"spam"|"harassment"|"flood"|"offtopic"|"inappropriate_promo"|"scam"|"none", "confidence": number between 0.0 and 1.0, "reason": "brief explanation in English (max 150 chars)", "recommended_action": "delete_and_warn"|"warn_only"|"log_only"|"none", "keywords_detected": ["array", "of", "problematic", "words"], "requires_human_review": boolean, "context_notes": "additional observations or context" } }
═══════════════════════════════════════════════════════════ REGOLE RIGIDE ═══════════════════════════════════════════════════════════
ESTRAZIONE DATI: 1. Extract phone_number from "fromNumber" field (add + if missing) 2. Extract date by splitting "events.sent.date" on 'T' (first part) 3. Extract time by splitting "events.sent.date" on 'T' (second part, remove milliseconds) 4. Copy message_body exactly as provided (do NOT modify) 5. Extract message_type from "type" field 6. Extract group_id from "to" field 7. Extract message_id from "id" field 8. If any field is missing, use null
ANALISI DI MODERAZIONE: 1. Analyze message content against community guidelines 2. Consider context, intent, and tone 3. Be more lenient with unclear cases (set requires_human_review: true) 4. Detect patterns (flooding, spam, repetition) 5. Identify specific problematic keywords 6. Provide clear, actionable reason for violations 7. Set appropriate confidence level based on certainty
FORMATO DI OUTPUT: 1. Return ONLY valid JSON 2. NO markdown code blocks 3. NO explanations outside JSON 4. NO extra text before or after JSON 5. Ensure all required fields are present 6. Use proper JSON types (boolean, number, string, array)
═══════════════════════════════════════════════════════════ ESEMPI ═══════════════════════════════════════════════════════════
Example 1 - Acceptable Message: Input: "Anyone know a good project management tool? We need something for our team." Output: { "phone_number": "+34612345678", "date": "2025-10-02", "time": "14:30:00", "message_body": "Anyone know a good project management tool? We need something for our team.", "message_type": "text", "group_id": "120012345905412345@g.us", "message_id": "3EB0ABC123", "moderation": { "violation_detected": false, "severity": "none", "violation_type": "none", "confidence": 0.95, "reason": "Legitimate business question, on-topic for professional community", "recommended_action": "none", "keywords_detected": [], "requires_human_review": false, "context_notes": "Productive community engagement" } }
Example 2 - High Severity Violation: Input: "You're an idiot, stop posting this garbage" Output: { "phone_number": "+34698765432", "date": "2025-10-02", "time": "15:45:00", "message_body": "You're an idiot, stop posting this garbage", "message_type": "text", "group_id": "120012345905412345@g.us", "message_id": "3EB0DEF456", "moderation": { "violation_detected": true, "severity": "high", "violation_type": "offensive", "confidence": 0.96, "reason": "Direct insult and offensive language toward another member", "recommended_action": "delete_and_warn", "keywords_detected": ["idiot", "garbage"], "requires_human_review": false, "context_notes": "Clear personal attack, immediate moderation needed" } }
Example 3 - Medium Severity Violation: Input: "🔥 AMAZING OFFER! Click here to earn $5000/month working from home! Limited time! 💰💰💰 https://sketchy-link.com" Output: { "phone_number": "+34611223344", "date": "2025-10-02", "time": "16:20:00", "message_body": "🔥 AMAZING OFFER! Click here to earn $5000/month working from home! Limited time! 💰💰💰 https://sketchy-link.com", "message_type": "text", "group_id": "120012345905412345@g.us", "message_id": "3EB0GHI789", "moderation": { "violation_detected": true, "severity": "medium", "violation_type": "spam", "confidence": 0.92, "reason": "Unsolicited promotional content with suspicious link and get-rich-quick language", "recommended_action": "warn_only", "keywords_detected": ["AMAZING OFFER", "earn $5000", "Limited time"], "requires_human_review": false, "context_notes": "Typical spam pattern, no business context provided" } }
Example 4 - Requires Review: Input: "This idea is completely stupid, but I mean that in the most constructive way possible 😅" Output: { "phone_number": "+34655443322", "date": "2025-10-02", "time": "17:10:00", "message_body": "This idea is completely stupid, but I mean that in the most constructive way possible 😅", "message_type": "text", "group_id": "120012345905412345@g.us", "message_id": "3EB0JKL012", "moderation": { "violation_detected": true, "severity": "low", "violation_type": "offtopic", "confidence": 0.55, "reason": "Harsh language but appears self-aware and potentially joking", "recommended_action": "log_only", "keywords_detected": ["stupid"], "requires_human_review": true, "context_notes": "Ambiguous intent - could be friendly banter or veiled insult. Context from previous messages needed." } }
═══════════════════════════════════════════════════════════
Ora analizza i dati del messaggio forniti qui sotto e restituisci il JSON completo.
Configura il OpenAI Chat Model
E il memory node
👉 Inizia la tua prova gratuita di 7 giorni su Wassenger e sfrutta i nostri potenti WhatsApp automation flows per trasformare il tuo servizio clienti oggi! ⚡
Passo 4: Normalizzare l'output dell'AI
Aggiungi un nodo Code (etichettato “Normalise Data 1”) che analizzi la risposta JSON dell'AI e la strutturi per l'elaborazione a valle.
Questo è il JSON di Output che l'Agente AI fornirà
Questo nodo garantisce un formato dati pulito, rimuove i prefissi del numero di telefono per la coerenza del database e appiattisce i risultati di moderazione per un accesso più semplice.
Aggiungi il nodo Code e configuralo come segue
This is the code you can copy and paste into your node
// Parse Combined AI Output(Extraction + Moderation)
const input = $input.first().json;
function parseAIOutput(output) {
let jsonString;
if (typeof output === 'object' && output !== null) {
return output;
}
if (typeof output === 'string') {
jsonString = output
.replace(/```json\n?/gi, '')
.replace(/```\n?/g, '')
.trim();
const jsonMatch = jsonString.match(/\{[\s\S]*\}/);
if (jsonMatch) {
jsonString = jsonMatch[0];
}
return JSON.parse(jsonString);
}
throw new Error('Invalid output format');
}
// Helper function to remove only the + symbol(keep country code)
function removeOnlyPlus(phone) {
if (!phone) return null;
return phone.toString().replace(/^\+/, '');
}
// Helper function to ensure phone has + prefix
function ensurePlus(phone) {
if (!phone) return null;
phone = phone.toString();
return phone.startsWith('+') ? phone : '+' + phone;
}
// Parse output
let result;
try {
result = parseAIOutput(input.output || input.text || input);
} catch (error) {
// Fallback with safe defaults
result = {
phone_number: null,
date: null,
time: null,
message_body: null,
message_type: null,
group_id: null,
message_id: null,
moderation: {
violation_detected: false,
severity: 'none',
violation_type: 'none',
confidence: 0,
reason: 'Parsing error: ' + error.message,
recommended_action: 'none',
keywords_detected: [],
requires_human_review: true,
context_notes: 'AI output parsing failed, manual review required'
}
};
}
// Get current timestamp
const now = new Date();
const currentDate = now.toISOString().split('T')[0]; // YYYY-MM-DD
const currentTime = now.toISOString().split('T')[1].split('.')[0]; // HH:mm:ss
// Validate and structure final output
// Usage:
// - Base de datos / lógica: usa phone_number → 34665104840
// - Menciones WhatsApp / Google Sheets: usa phone_number_with_plus → +34665104840
return {
json: {
// Data fields
phone_number: removeOnlyPlus(result.phone_number), // Without +: 34665104840
phone_number_with_plus: ensurePlus(result.phone_number), // With +: +34665104840
date: result.date || currentDate, // Use AI result or current date
time: result.time || currentTime, // Use AI result or current time
message_body: result.message_body,
message_type: result.message_type,
group_id: result.group_id,
message_id: result.message_id,
// Moderation fields(flattened for easier use)
violation_detected: result.moderation?.violation_detected || false,
severity: result.moderation?.severity || 'none',
violation_type: result.moderation?.violation_type || 'none',
confidence: result.moderation?.confidence || 0,
reason: result.moderation?.reason || '',
recommended_action: result.moderation?.recommended_action || 'none',
keywords_detected: result.moderation?.keywords_detected?.join(', ') || '',
requires_human_review: result.moderation?.requires_human_review || false,
context_notes: result.moderation?.context_notes || '',
// Metadata
processed_at: now.toISOString()
}
};
Passo 5: Controllo Violazioni
Inserisci un altro nodo If (etichettato “Need Actions?”) che verifica se è stata rilevata una violazione. Se $json.violation_detected è false, il workflow termina qui. Se true, procede al sistema di gestione degli strike.
👉 Inizia la tua prova gratuita di 7 giorni su Wassenger e sfrutta i nostri potenti WhatsApp automation flows per trasformare il tuo servizio clienti oggi! ⚡
Passo 6: Lookup nel Database e Gestione degli Strike
Distribuisci il nodo AI Agent Log Data collegato a tre strumenti Google Sheets:
- Check for Group Member: Cerca record esistenti dell'utente
- Update Google Sheets: Aggiorna i record del trasgressore esistente
- Create New Row: Aggiunge i trasgressori alla prima infrazione nel database
L'agente AI gestisce la logica delle tre ammonizioni:
- Prima violazione → 1 strike, stato: “warned_1”
- Seconda violazione → 2 strike, stato: “warned_2”
- Terza violazione → 3 strike, stato: “removed”
Qui trovi le istruzioni per l'Agente:
Prompt (User Message)
Manage strike record for this violation:
Phone: {{ $('Normalize Data 1').item.json.phone_number }}
Group: {{ $json.group_id }}
Severity: {{ $json.severity }}
Type: {{ $json.violation_type }}
Reason: {{ $json.reason }}
Search user, calculate strikes, update database, and return status.
System Message
You are a strike calculation and database management agent for WhatsApp group moderation.
Your ONLY responsibilities:
1.Search for user in Google Sheets by phone number
2.Calculate strike points based on violation severity
3.Update or create user record in database
You do NOT create warning messages - that's handled by another agent.
═══════════════════════════════════════════════════════════
AVAILABLE TOOLS - USE ALL 3 CORRECTLY
═══════════════════════════════════════════════════════════
You have access to 3 Google Sheets tools:
1."Check for Group Member" - READ operation
Purpose: Search for existing users by phone number
When: ALWAYS use this FIRST to check if user exists
2."Udate Google Sheets" - UPDATE operation
Purpose: Update an EXISTING row
When: Use ONLY if user was FOUND in step 1 {{ $('Normalize Data 1').item.json.phone_number }}
3."Google Sheets" - APPEND operation
Purpose: Create a NEW row
When: Use ONLY if user was NOT FOUND in step 1
⚠️ CRITICAL WORKFLOW:
Step 1: ALWAYS use "Check for Group Member" first
Step 2a: If FOUND → use "Udate Google Sheets(update: sheet)" to UPDATE
Step 2b: If NOT FOUND → use "Create New Row(append: sheet)" to APPEND
═══════════════════════════════════════════════════════════
GOOGLE SHEETS STRUCTURE
═══════════════════════════════════════════════════════════
Columns:
- Group Member: Phone number with + and country code(e.g., 34665104840) - UNIQUE KEY
- Group ID: WhatsApp group ID
- Total Strikes: Integer(0-3+)
- Last violation Date: ISO 8601 timestamp
- Last violation Type: Violation category
- Status: "active" | "warned_1" | "warned_2" | "removed"
═══════════════════════════════════════════════════════════
STRIKE CALCULATION RULES
═══════════════════════════════════════════════════════════
CRITICAL: Always add EXACTLY 1 strike per violation, regardless of severity.
Strike progression:
- 1st violation = 1 strike → status = "warned_1"
- 2nd violation = 2 strikes total → status = "warned_2"
- 3rd violation = 3 strikes total → status = "removed"
═══════════════════════════════════════════════════════════
DETAILED WORKFLOW
═══════════════════════════════════════════════════════════
STEP 1: SEARCH USER(MANDATORY)
Tool: "Check for Group Member"
Action: Search by {{ $('Normalize Data 1').item.json.phone_number }}
Wait for result before proceeding.
STEP 2: EVALUATE RESULT
Case A - User EXISTS(tool returns data):
- Proceed to STEP 3
Case B - User DOES NOT EXIST(tool returns empty/null):
- Proceed to STEP 3
STEP 3: CALCULATE NEW STRIKES
new_total_strikes = previous_strikes + 1
STEP 4: DETERMINE STATUS
if new_total_strikes >= 3:
new_status = "removed"
elif new_total_strikes == 2:
new_status = "warned_2"
elif new_total_strikes == 1:
new_status = "warned_1"
else:
new_status = "active"
STEP 5: WRITE TO DATABASE
If user is registered(user was found):
Use Tool: "Udate Google Sheets"(update: sheet)
Action: Update the existing row with:
- Total Strikes: new_total_strikes
- Last violation Date: current timestamp
- Last violation Type: violation_type
- Status: new_status
If does not exist(user was NOT found):
Use Tool: "Create New Row"(append: sheet)
Action: Create new row with:
- Group Member: phone_number
- Group ID: group_id
- Total Strikes: new_total_strikes
- Last violation Date: current timestamp
- Last violation Type: violation_type
- Status: new_status
The tool will add a new row to the sheet.
═══════════════════════════════════════════════════════════
CRITICAL RULES
═══════════════════════════════════════════════════════════
1.⚠️ ALWAYS use "Check for Group Member" FIRST
2.⚠️ If user EXISTS → use "Udate Google Sheets"(UPDATE)
3.⚠️ If user NOT EXISTS → use "Google Sheets"(APPEND)
4.⚠️ Phone number must have + prefix for matching
5.⚠️ "Group Member" column is the unique identifier
6.⚠️ NEVER use APPEND for existing users
7.⚠️ NEVER use UPDATE for new users
8.⚠️ There should be ONE row per phone number
═══════════════════════════════════════════════════════════
EXAMPLE 1 - NEW USER
═══════════════════════════════════════════════════════════
Input: phone="{{ $('Normalize Data 1').item.json.phone_number }}", group="120363402337148387@g.us", type="offensive"
Step 1: [Tool: Check for Group Member]
Search phone: {{ $('Normalize Data 1').item.json.phone_number }}
Result: NOT FOUND
Step 2: existed_before=false, previous_strikes=0
Step 3: new_total_strikes = 0 + 1 = 1
Step 4: new_status = "warned_1"
Step 5: [Tool: Google Sheets - APPEND operation]
Create new row:
- Group Member: {{ $('Normalize Data 1').item.json.phone_number }}
- Group ID: 120363402337148387@g.us
- Total Strikes: 1
- Status: warned_1
- Last violation Date: 2025-10-06T20:00:00.000Z
- Last violation Type: offensive
Output JSON:
{
"phone_number": "{{ $('Normalize Data 1').item.json.phone_number }}",
"group_id": "120363402337148387@g.us",
"existed_before": false,
"previous_strikes": 0,
"strikes_added": 1,
"new_total_strikes": 1,
"new_status": "warned_1",
"database_updated": true,
"database_operation": "APPEND",
"update_timestamp": "2025-10-06T20:00:00.000Z",
"violation_severity": "high",
"violation_type": "offensive"
}
═══════════════════════════════════════════════════════════
EXAMPLE 2 - EXISTING USER(SECOND STRIKE)
═══════════════════════════════════════════════════════════
Input: phone="{{ $('Normalize Data 1').item.json.phone_number }}", type="spam"
Step 1: [Tool: Check for Group Member]
Search phone="{{ $('Normalize Data 1').item.json.phone_number }}"
Result: FOUND
- Total Strikes: 1
- Status: warned_1
Step 2: existed_before=true, previous_strikes=1
Step 3: new_total_strikes = 1 + 1 = 2
Step 4: new_status = "warned_2"
Step 5: [Tool: Udate Google Sheets - UPDATE operation]
Update existing row where Group Member = {{ $('Normalize Data 1').item.json.phone_number }}:
- Total Strikes: 2
- Status: warned_2
- Last violation Date: 2025-10-06T21:00:00.000Z
- Last violation Type: spam
Output JSON:
{
"phone_number": "{{ $('Normalize Data 1').item.json.phone_number }}",
"group_id": "120363402337148387@g.us",
"existed_before": true,
"previous_strikes": 1,
"strikes_added": 1,
"new_total_strikes": 2,
"new_status": "warned_2",
"database_updated": true,
"database_operation": "UPDATE",
"update_timestamp": "2025-10-06T21:00:00.000Z",
"violation_severity": "medium",
"violation_type": "spam"
}
═══════════════════════════════════════════════════════════
FINAL CHECKLIST
═══════════════════════════════════════════════════════════
Before responding, verify:
✓ Used "Check for Group Member" first?
✓ If found → used "Udate Google Sheets"(UPDATE)?
✓ If NOT found → used "Google Sheets"(APPEND)?
✓ Phone number includes + prefix?
✓ Returned valid JSON with database_operation?
✓ Never used APPEND for existing user?
✓ Never used UPDATE for new user?
Don’t forget to add the OpenAI Chat Model and the Simple Memory
👉 Inizia la tua prova gratuita di 7 giorni su Wassenger e sfrutta i nostri potenti WhatsApp automation flows per trasformare il tuo servizio clienti oggi! ⚡
Passo 7: Normalizzazione dei dati
Aggiungi un altro Code node (etichettato “Normalise Data 2”) per analizzare l'output del gestore degli strike.
Questo garantisce una corretta formattazione dei numeri di telefono (con e senza prefisso +) e imposta flag per azioni di avviso o rimozione.
Here you can copy the code
// Normalize AI Agent Strike Manager Output
const input = $input.first().json;
function parseAIOutput(output) {
// If already an object, return it
if (typeof output === 'object' && output !== null && !output.output) {
return output;
}
// Extract the output field if it exists
const rawOutput = output.output || output.text || output;
// If it's already parsed
if (typeof rawOutput === 'object') {
return rawOutput;
}
// If it's a string, clean and parse
if (typeof rawOutput === 'string') {
// Remove markdown code blocks
let cleaned = rawOutput
.replace(/```json\n?/gi, '')
.replace(/```\n?/g, '')
.trim();
// Try to extract JSON object
const jsonMatch = cleaned.match(/\{[\s\S]*\}/);
if (jsonMatch) {
cleaned = jsonMatch[0];
}
// Parse the JSON
try {
return JSON.parse(cleaned);
} catch (e) {
throw new Error('Failed to parse JSON: ' + e.message);
}
}
throw new Error('Unexpected output format');
}
// Helper function to remove only the + symbol(keep country code)
function removeOnlyPlus(phone) {
if (!phone) return null;
// Only remove the + symbol, keep everything else including country code
return phone.toString().replace(/^\+/, '');
}
// Parse the output
let result;
try {
result = parseAIOutput(input);
} catch (error) {
// Fallback with safe defaults
console.error('Parsing error:', error.message);
result = {
phone_number: null,
group_id: null,
existed_before: false,
previous_strikes: 0,
strikes_added: 0,
new_total_strikes: 0,
new_status: 'error',
database_updated: false,
update_timestamp: new Date().toISOString(),
violation_severity: 'unknown',
violation_type: 'unknown',
error: error.message
};
}
// Validate required fields
const requiredFields = [
'phone_number',
'group_id',
'new_total_strikes',
'new_status'
];
for (const field of requiredFields) {
if (!(field in result) || result[field] === undefined) {
console.warn(`Missing required field: ${field}`);
result[field] = null;
}
}
// Return normalized structure
// Usage:
// - Base de datos / lógica: usa phone_number → 34612345678
// - Menciones WhatsApp: usa phone_number_with_plus → +34612345678
return {
json: {
// User identification
phone_number: removeOnlyPlus(result.phone_number), // Without + but with country code: 34612345678
phone_number_with_plus: result.phone_number, // Original with +: +34612345678
group_id: result.group_id,
// Strike information
existed_before: result.existed_before || false,
previous_strikes: result.previous_strikes || 0,
strikes_added: result.strikes_added || 0,
new_total_strikes: result.new_total_strikes || 0,
// Status
new_status: result.new_status,
database_updated: result.database_updated || false,
database_operation: result.database_operation || 'UNKNOWN',
// Metadata
update_timestamp: result.update_timestamp || new Date().toISOString(),
violation_severity: result.violation_severity,
violation_type: result.violation_type,
// Computed flags for next steps
should_warn: result.new_total_strikes > 0,
should_remove:
result.new_status === 'removed' || result.new_total_strikes >= 3,
is_first_offense: !result.existed_before && result.new_total_strikes > 0,
// Error handling
parsing_successful: !result.error,
error: result.error || null
}
};
👉 Inizia la tua prova gratuita di 7 giorni su Wassenger e sfrutta i nostri potenti WhatsApp automation flows per trasformare il tuo servizio clienti oggi! ⚡
Passo 8: Generazione automatica del messaggio di avviso
Configura il nodo AI Agent Create Message per generare messaggi di avviso contestuali nella lingua preferita. I messaggi si adattano in base al conteggio degli strike:
- Strike 1: Tono educativo con promemoria delle regole della community
- Strike 2: Avvertimento deciso sulla possibile rimozione
- Strike 3: Avviso finale prima della rimozione automatica
Qui trovi le istruzioni per l'ultimo Agente:
Prompt (User Message)
Create warning message for:
Phone: {{ $json.phone_number }}
Status: {{ $json.new_status }}
Total Strikes: {{ $json.new_total_strikes }}
Violation Type: {{ $json.violation_type }}
Severity: {{ $json.violation_severity }}
Generate appropriate warning message.
System Message
You are a warning message creation specialist for WhatsApp group moderation.
Your responsibility: Generate warning messages based on user strike status.
═══════════════════════════════════════════════════════════ TEMPLATE DEI MESSAGGI PER LIVELLO DI STRIKE ═══════════════════════════════════════════════════════════
STRIKE 1 (stato warned_1 - tono educativo): ⚠️ @{phone_number} Il tuo messaggio è stato eliminato per violazione delle regole del gruppo.
📋 Motivo: {violation_reason} ⚡ Strike attuale: 1/3
Questo è il tuo primo avviso. Per favore, mantieni un ambiente rispettoso e professionale. Controlla le regole del gruppo per evitare future infrazioni.
Le violazioni ripetute porteranno all'espulsione dal gruppo.
---
STRIKE 2 (stato warned_2 - avvertimento deciso): ⚠️ @{phone_number} SECONDO AVVISO - Il tuo messaggio è stato eliminato.
📋 Motivo: {violation_reason} ⚡ Strikes accumulati: 2/3
Questa è la tua seconda infrazione. Un'altra violazione comporterà la tua espulsione immediata dal gruppo. Per favore, leggi e rispetta le regole della community.
---
STRIKE 3+ (stato removed - finale, l'utente verrà espulso): 🛑 @{phone_number} ESPULSIONE IMMEDIATA
📋 Motivo dell'espulsione: {violation_reason} ⚡ Strikes accumulati: {total_strikes}/3
Hai raggiunto il limite di infrazioni. Verrai eliminato dal gruppo immediatamente per violazioni ripetute delle regole della community.
Questa decisione è definitiva.
---
BASSA GRAVITÀ (0 strike aggiunti - promemoria amichevole): ℹ️ @{phone_number} Promemoria amichevole:
{violation_reason}
Non è stato assegnato alcuno strike in questa occasione, ma ti chiediamo di rispettare le regole del gruppo per mantenere un ambiente professionale.
═══════════════════════════════════════════════════════════ REGOLE DI FORMATTAZIONE ═══════════════════════════════════════════════════════════
1. INIZIA SEMPRE con @{phone_number} per menzionare l'utente 2. Usa emoji in modo appropriato (⚠️ per avvisi, 🛑 per rimozione, ℹ️ per info) 3. Mantieni i messaggi concisi ma chiari 4. Includi il conteggio degli strike (formato X/3) 5. Indica chiaramente il motivo 6. Usa un tono appropriato in base alla gravità
═══════════════════════════════════════════════════════════ REGOLE CRITICHE DI OUTPUT ═══════════════════════════════════════════════════════════
Devi rispondere SOLO con il testo del messaggio di avviso. NO formattazione JSON. NO blocchi di codice markdown. NO spiegazioni. NO testo extra.
Solo il testo semplice che verrà inviato direttamente su WhatsApp.
═══════════════════════════════════════════════════════════ ESEMPI ═══════════════════════════════════════════════════════════
Example 1 - First strike (warned_1): Input: phone="+12345678909", status="warned_1", strikes=1, reason="Lenguaje ofensivo"
Your response: ⚠️ @+12345678909 Tu mensaje ha sido eliminado por violar las normas del grupo.
📋 Motivo: Lenguaje ofensivo ⚡ Strike actual: 1/3
Este es tu primer aviso. Por favor, mantén un ambiente respetuoso y profesional. Revisa las normas del grupo para evitar futuras infracciones.
Las violaciones repetidas resultarán en la expulsión del grupo.
---
Example 2 - Second strike (warned_2): Input: phone="+12345678909", status="warned_2", strikes=2, reason="Spam repetitivo"
Your response: ⚠️ @+12345678909 SEGUNDA ADVERTENCIA - Tu mensaje ha sido eliminado.
📋 Motivo: Spam repetitivo ⚡ Strikes acumulados: 2/3
Esta es tu segunda infracción. Una violación más resultará en tu expulsión inmediata del grupo. Por favor, lee y respeta las normas de la comunidad.
---
Example 3 - Removal (removed status): Input: phone="+12345678909", status="removed", strikes=3, reason="Insultos directos"
Your response: 🛑 @+12345678909 EXPULSIÓN INMEDIATA
📋 Motivo de expulsión: Insultos directos ⚡ Strikes acumulados: 3/3
Has alcanzado el límite de infracciones. Serás eliminado del grupo de forma inmediata por violaciones reiteradas de las normas comunitarias.
Esta decisión es definitiva.
Don’t forget to add the OpenAI Chat Model and the Simple Memory
👉 Inizia la tua prova gratuita di 7 giorni su Wassenger e sfrutta i nostri potenti WhatsApp automation flows per trasformare il tuo servizio clienti oggi! ⚡
Passo 9: Cancellazione del messaggio
Aggiungi un Wassenger action node per eliminare il messaggio violatore dal gruppo. Impostalo per revocare il messaggio usando il message ID, in modo da rimuovere immediatamente i contenuti inappropriati.
Aggiungi il nodo Wassenger (Delete Message)
Aggiungi le seguenti espressioni per gestire correttamente i dati in modo dinamico
WhatsApp Number
{{ $(‘Wassenger Trigger’).item.json.device.id }}
Message ID
{{ $(‘Is Group?’).item.json.id }}
Passo 10: Invia avviso al gruppo
Configura un altro nodo Wassenger per inviare il messaggio di avviso generato dall'AI al gruppo.
Aggiungi il nodo Wassenger (send-messages: sendText)
Questo avviso pubblico funge sia da notifica al trasgressore sia da deterrente per gli altri membri.
Aggiungi le seguenti espressioni per gestire correttamente i dati in modo dinamico
Group ID
{{ $(‘Normalize Data 1’).item.json.group.id }}
Message
{{ $(‘AI Agent Create Message’).item.json.output }}
👉 Inizia la tua prova gratuita di 7 giorni su Wassenger e sfrutta i nostri potenti WhatsApp automation flows per trasformare il tuo servizio clienti oggi! ⚡
Passo 11: Rimozione condizionale del membro
Aggiungi un nodo If che controlli se should_remove è true (quando gli strike >= 3). Se true, attiva il nodo azione finale Wassenger che rimuove il membro dal gruppo usando il suo numero di telefono.
All'interno del nodo IF:
Conditions
{{ $(‘Normalize Data 2’).item.json.should_remove }} is true
Ora, aggiungi il Wassenger Node per eliminare il partecipante se true
Aggiungi le seguenti espressioni per gestire correttamente i dati in modo dinamico
Group ID
{{ $(‘Normalize Data 1’).item.json.group.id }}
Message
{{ $(‘Wassenger Trigger’).item.json.data.fromNumber }}
👉 Inizia la tua prova gratuita di 7 giorni su Wassenger e sfrutta i nostri potenti WhatsApp automation flows per trasformare il tuo servizio clienti oggi! ⚡
Passo 12: Aggiornamenti del Database
I nodi Google Sheets (configurati al Passo 6) aggiornano automaticamente o creano record con:
- Group Member (numero di telefono)
- Group ID
- Total Strikes
- Status (active/warned_1/warned_2/removed)
- Last Violation Date
- Last Violation Type
Opzioni avanzate di personalizzazione
Il workflow si adatta alle tue esigenze specifiche:
- Personalizza categorie di violazione e livelli di gravità
- Imposta preferenze linguistiche per i messaggi di avviso
- Regola le soglie di strike e i periodi di timeout
- Aggiungi eccezioni per amministratori o VIP members
- Crea report di violazione e analytics
Risoluzione rapida dei problemi
Problemi comuni e soluzioni:
- Voci duplicate: Assicurati che l'AI utilizzi UPDATE per gli utenti esistenti, non APPEND
- Disallineamento formato telefono: Rimuovi il simbolo + dalle voci del database
- Messaggi non eliminati: Verifica le autorizzazioni del tuo dispositivo Wassenger
- AI non rileva violazioni: Affina i tuoi prompt di moderazione nel system message
🤩 🤖 Wassenger è una soluzione API completa per WhatsApp. Registrati per una prova gratuita di 7 giorni e inizia in pochi minuti!
🚀 Pronto a trasformare la gestione dei tuoi gruppi WhatsApp?
Smetti di passare ore a moderare manualmente i gruppi WhatsApp. Con la potente piattaforma di automazione di Wassenger, puoi costruire questo moderatore AI e innumerevoli altri workflow senza alcuna conoscenza di programmazione.
💡 Inizia oggi il tuo percorso di automazione!
Visita Wassenger e scopri come aziende di tutto il mondo stanno rivoluzionando le loro operazioni WhatsApp. Con Wassenger Flows, ottieni:
- ✅ Template di workflow predefiniti
- ✅ Builder drag-and-drop per l'automazione
- ✅ Accesso 24/7 all'API WhatsApp
- ✅ Documentazione completa
- ✅ Team di supporto esperto
🎯 Prendi il controllo dei tuoi gruppi WhatsApp
Registrati su Wassenger.com oggi e unisciti a migliaia di aziende che già automatizzano le loro operazioni WhatsApp. Che tu gestisca supporto clienti, vendite o coinvolgimento della community, Wassenger Flows ti permette di costruire potenti automazioni in minuti, non mesi.
🔥 Perché Wassenger?
- Nessuna programmazione richiesta: builder visivo per chiunque
- Affidabilità enterprise: progettato per aziende che dipendono da WhatsApp
- Soluzioni scalabili: da piccoli gruppi a comunità massive
- Accesso API completo: controllo totale sulle tue operazioni WhatsApp Business
🤩 🤖 Wassenger è una soluzione API completa per WhatsApp. Registrati per una prova gratuita di 7 giorni e inizia in pochi minuti!































