cuatrolabs-auth-ms / list_wati_templates.py
MukeshKapoor25's picture
docs: Add OTP cache fallback implementation and WATI troubleshooting guides
bd3bf31
#!/usr/bin/env python3
"""
List all WATI templates and their status.
This helps identify the correct template name and approval status.
"""
import asyncio
import httpx
import sys
import os
import json
# Add app directory to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'app'))
from app.core.config import settings
async def list_wati_templates():
"""List all available WATI templates."""
print("=" * 80)
print("WATI Templates List")
print("=" * 80)
api_endpoint = settings.WATI_API_ENDPOINT
access_token = settings.WATI_ACCESS_TOKEN
print(f"\nAPI Endpoint: {api_endpoint}")
print(f"Token Length: {len(access_token)}")
url = f"{api_endpoint}/api/v1/getMessageTemplates"
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json"
}
print(f"\nFetching templates from: {url}")
print("-" * 80)
try:
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.get(url, headers=headers)
print(f"\nResponse Status: {response.status_code}")
if response.status_code == 200:
data = response.json()
templates = data.get('messageTemplates', [])
if not templates:
print("\n⚠️ No templates found!")
print(" Please create templates in WATI Dashboard first.")
return
print(f"\n✅ Found {len(templates)} template(s):\n")
# Group by status
approved = []
pending = []
rejected = []
other = []
for template in templates:
status = template.get('status', 'UNKNOWN')
if status == 'APPROVED':
approved.append(template)
elif status == 'PENDING':
pending.append(template)
elif status == 'REJECTED':
rejected.append(template)
else:
other.append(template)
# Display approved templates
if approved:
print("✅ APPROVED TEMPLATES (Ready to use):")
print("-" * 80)
for t in approved:
name = t.get('elementName', 'N/A')
category = t.get('category', 'N/A')
language = t.get('language', 'N/A')
print(f"\n Name: {name}")
print(f" Category: {category}")
print(f" Language: {language}")
print(f" Status: ✅ APPROVED")
# Check if this is our OTP template
if name == settings.WATI_OTP_TEMPLATE_NAME:
print(f" >>> THIS IS YOUR CONFIGURED OTP TEMPLATE <<<")
# Show template content if available
if 'templateText' in t:
print(f" Content: {t['templateText'][:100]}...")
print()
# Display pending templates
if pending:
print("\n⏳ PENDING TEMPLATES (Awaiting approval):")
print("-" * 80)
for t in pending:
name = t.get('elementName', 'N/A')
print(f" - {name} (Category: {t.get('category', 'N/A')})")
if name == settings.WATI_OTP_TEMPLATE_NAME:
print(f" ⚠️ THIS IS YOUR CONFIGURED OTP TEMPLATE - WAITING FOR APPROVAL")
print()
# Display rejected templates
if rejected:
print("\n❌ REJECTED TEMPLATES:")
print("-" * 80)
for t in rejected:
name = t.get('elementName', 'N/A')
print(f" - {name} (Category: {t.get('category', 'N/A')})")
if name == settings.WATI_OTP_TEMPLATE_NAME:
print(f" ❌ YOUR CONFIGURED OTP TEMPLATE WAS REJECTED")
print(f" Action: Modify and resubmit in WATI Dashboard")
print()
# Display other status templates
if other:
print("\n⚠️ OTHER STATUS TEMPLATES:")
print("-" * 80)
for t in other:
name = t.get('elementName', 'N/A')
status = t.get('status', 'UNKNOWN')
print(f" - {name}: {status}")
print()
# Check configured template
print("\n" + "=" * 80)
print("Configuration Check")
print("=" * 80)
configured_template = settings.WATI_OTP_TEMPLATE_NAME
print(f"\nConfigured OTP Template: '{configured_template}'")
# Find configured template
found = False
for t in templates:
if t.get('elementName') == configured_template:
found = True
status = t.get('status', 'UNKNOWN')
if status == 'APPROVED':
print(f"✅ Status: APPROVED - Ready to use!")
elif status == 'PENDING':
print(f"⏳ Status: PENDING - Waiting for WhatsApp approval")
print(f" This can take 24-48 hours")
print(f" Check WATI Dashboard for updates")
elif status == 'REJECTED':
print(f"❌ Status: REJECTED - Template was rejected by WhatsApp")
print(f" Action: Modify template and resubmit")
else:
print(f"⚠️ Status: {status}")
break
if not found:
print(f"❌ Template '{configured_template}' NOT FOUND!")
print(f"\n Possible issues:")
print(f" 1. Template name mismatch (case-sensitive)")
print(f" 2. Template not created in WATI Dashboard")
print(f" 3. Template deleted")
print(f"\n Available template names:")
for t in templates:
print(f" - {t.get('elementName')}")
# Save full response for debugging
with open('wati_templates_response.json', 'w') as f:
json.dump(data, f, indent=2)
print(f"\n📄 Full response saved to: wati_templates_response.json")
elif response.status_code == 403:
print("\n❌ 403 Forbidden")
print(" Possible causes:")
print(" 1. Invalid or expired access token")
print(" 2. Token doesn't have permission to list templates")
print(" 3. API endpoint mismatch")
print(f"\n Response: {response.text}")
elif response.status_code == 401:
print("\n❌ 401 Unauthorized")
print(" Token is invalid or expired")
print(" Action: Generate new token from WATI Dashboard")
print(f"\n Response: {response.text}")
else:
print(f"\n⚠️ Unexpected status code: {response.status_code}")
print(f" Response: {response.text}")
except httpx.TimeoutException:
print("\n❌ Request timeout")
print(" WATI API is not responding")
except Exception as e:
print(f"\n❌ Error: {str(e)}")
import traceback
traceback.print_exc()
print("\n" + "=" * 80)
print("Next Steps:")
print("=" * 80)
print("\n1. If template is APPROVED:")
print(" - Verify template name matches configuration")
print(" - Test OTP sending")
print("\n2. If template is PENDING:")
print(" - Wait for WhatsApp approval (24-48 hours)")
print(" - Use SMS fallback in the meantime")
print("\n3. If template is REJECTED:")
print(" - Check rejection reason in WATI Dashboard")
print(" - Modify template according to guidelines")
print(" - Resubmit for approval")
print("\n4. If template NOT FOUND:")
print(" - Create template in WATI Dashboard")
print(" - Or update WATI_OTP_TEMPLATE_NAME in .env")
print("\n" + "=" * 80)
if __name__ == "__main__":
asyncio.run(list_wati_templates())