WhatsApp API untuk Python: Library & Contoh Lengkap

Tutorial WhatsApp API dengan Python. pywhatkit, yowsup, dan Cloud API requests. Contoh kode kirim pesan, webhook, auto-reply!

WhatsApp API untuk Python
WhatsApp API untuk Python

Python developer? Mau bikin WhatsApp bot?

Kabar baik: bisa! Tapi dengan beberapa catatan.

Berbeda dengan Node.js yang punya library lengkap seperti Baileys, Python punya opsi yang lebih terbatas untuk unofficial API.

Tapi untuk Cloud API (official), Python sama powerful!


Library Options

Unofficial Libraries:

LibraryMethodEaseProduction Ready
pywhatkitWA Web automation⭐⭐⭐⭐⭐
yowsupProtocol implementation⭐⭐❌ (outdated)

Official (Cloud API):

LibraryMethod
requestsHTTP calls
httpxAsync HTTP
aiohttpAsync HTTP

Tutorial 1: pywhatkit (Quick & Easy)

Step 1: Install

bash

pip install pywhatkit

Step 2: Basic Usage

python

import pywhatkit as kit

# Kirim pesan (akan buka browser!)
# Format: nomor dengan kode negara, pesan, jam, menit
kit.sendwhatmsg("+6281234567890", "Hello from Python!", 15, 30)

# Kirim pesan instantly (tanpa jadwal)
kit.sendwhatmsg_instantly("+6281234567890", "Instant message!")

# Kirim ke group
kit.sendwhatmsg_to_group("GroupInviteLinkID", "Hello group!", 15, 30)

Cara Kerja pywhatkit:

1. Buka browser dengan WhatsApp Web
2. Login (jika belum)
3. Navigate ke chat target
4. Ketik pesan
5. Tekan send

⚠️ Perlu browser terbuka!
⚠️ Harus sudah login WA Web
⚠️ Tidak bisa terima pesan

Limitations:

❌ Butuh browser terbuka
❌ Tidak bisa receive message
❌ Tidak cocok untuk bot
❌ Tidak bisa run di server tanpa GUI
✅ Cocok untuk: kirim pesan sederhana, reminder, notifikasi manual

Step 1: Setup

bash

pip install requests python-dotenv

Step 2: Environment Variables

.env:

PHONE_NUMBER_ID=your_phone_number_id
ACCESS_TOKEN=your_access_token
VERIFY_TOKEN=your_verify_token

Step 3: Send Text Message

python

import requests
import os
from dotenv import load_dotenv

load_dotenv()

PHONE_NUMBER_ID = os.getenv('PHONE_NUMBER_ID')
ACCESS_TOKEN = os.getenv('ACCESS_TOKEN')
API_URL = f"https://graph.facebook.com/v17.0/{PHONE_NUMBER_ID}/messages"

def send_message(to: str, message: str) -> dict:
    """
    Kirim pesan text via WhatsApp Cloud API
    
    Args:
        to: Nomor tujuan (format: 628xxx)
        message: Isi pesan
    
    Returns:
        Response dari API
    """
    headers = {
        "Authorization": f"Bearer {ACCESS_TOKEN}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "messaging_product": "whatsapp",
        "to": to,
        "type": "text",
        "text": {"body": message}
    }
    
    response = requests.post(API_URL, headers=headers, json=payload)
    
    if response.status_code == 200:
        print(f"✅ Sent to {to}: {message}")
    else:
        print(f"❌ Error: {response.json()}")
    
    return response.json()

# Usage
send_message("6281234567890", "Hello from Python Cloud API!")

Step 4: Send Template Message

python

def send_template(to: str, template_name: str, language: str = "en_US") -> dict:
    """
    Kirim template message (untuk business-initiated conversation)
    """
    headers = {
        "Authorization": f"Bearer {ACCESS_TOKEN}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "messaging_product": "whatsapp",
        "to": to,
        "type": "template",
        "template": {
            "name": template_name,
            "language": {"code": language}
        }
    }
    
    response = requests.post(API_URL, headers=headers, json=payload)
    return response.json()

# Usage
send_template("6281234567890", "hello_world")

Step 5: Send Image

python

def send_image(to: str, image_url: str, caption: str = "") -> dict:
    """
    Kirim gambar via URL
    """
    headers = {
        "Authorization": f"Bearer {ACCESS_TOKEN}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "messaging_product": "whatsapp",
        "to": to,
        "type": "image",
        "image": {
            "link": image_url,
            "caption": caption
        }
    }
    
    response = requests.post(API_URL, headers=headers, json=payload)
    return response.json()

# Usage
send_image(
    "6281234567890", 
    "https://example.com/image.jpg",
    "Check out this image!"
)

Step 6: Send Document

python

def send_document(to: str, doc_url: str, filename: str, caption: str = "") -> dict:
    """
    Kirim dokumen (PDF, DOC, etc)
    """
    headers = {
        "Authorization": f"Bearer {ACCESS_TOKEN}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "messaging_product": "whatsapp",
        "to": to,
        "type": "document",
        "document": {
            "link": doc_url,
            "filename": filename,
            "caption": caption
        }
    }
    
    response = requests.post(API_URL, headers=headers, json=payload)
    return response.json()

# Usage
send_document(
    "6281234567890",
    "https://example.com/invoice.pdf",
    "invoice.pdf",
    "Here's your invoice"
)

Tutorial 3: Webhook dengan Flask

Step 1: Install Flask

bash

pip install flask

Step 2: Create Webhook Server

python

from flask import Flask, request, jsonify
import os
from dotenv import load_dotenv

load_dotenv()

app = Flask(__name__)

VERIFY_TOKEN = os.getenv('VERIFY_TOKEN')

@app.route('/webhook', methods=['GET'])
def verify_webhook():
    """
    Verify webhook untuk Meta/WhatsApp
    """
    mode = request.args.get('hub.mode')
    token = request.args.get('hub.verify_token')
    challenge = request.args.get('hub.challenge')
    
    if mode == 'subscribe' and token == VERIFY_TOKEN:
        print("✅ Webhook verified!")
        return challenge, 200
    else:
        return "Forbidden", 403

@app.route('/webhook', methods=['POST'])
def receive_message():
    """
    Receive incoming messages dari WhatsApp
    """
    data = request.get_json()
    
    if data.get('object') == 'whatsapp_business_account':
        for entry in data.get('entry', []):
            for change in entry.get('changes', []):
                value = change.get('value', {})
                
                # Process incoming messages
                messages = value.get('messages', [])
                for message in messages:
                    sender = message.get('from')
                    msg_type = message.get('type')
                    
                    if msg_type == 'text':
                        text = message.get('text', {}).get('body', '')
                        print(f"📩 From {sender}: {text}")
                        
                        # Handle message
                        handle_message(sender, text)
    
    return jsonify({"status": "ok"}), 200

def handle_message(sender: str, text: str):
    """
    Process incoming message dan auto-reply
    """
    text_lower = text.lower()
    
    if text_lower in ['halo', 'hi', 'hello']:
        send_message(sender, "Halo! 👋 Ada yang bisa dibantu?")
    
    elif text_lower == 'menu':
        menu = """📋 MENU:
        
1. INFO - Informasi
2. PRODUK - Lihat produk
3. ORDER - Cara order
4. CS - Chat admin

Ketik sesuai pilihan!"""
        send_message(sender, menu)
    
    elif text_lower == 'info':
        send_message(sender, "ℹ️ Kami adalah toko online terpercaya...")
    
    else:
        send_message(sender, "Maaf tidak mengerti. Ketik MENU untuk bantuan.")

if __name__ == '__main__':
    app.run(port=5000, debug=True)

Step 3: Run dengan ngrok (untuk testing)

bash

# Terminal 1: Run Flask
python app.py

# Terminal 2: Run ngrok
ngrok http 5000

# Copy URL ngrok (https://xxx.ngrok.io/webhook)
# Paste ke Meta Developer Console > Webhook settings

Tutorial 4: Async dengan FastAPI

Step 1: Install

bash

pip install fastapi uvicorn httpx

Step 2: FastAPI Webhook

python

from fastapi import FastAPI, Request, HTTPException
import httpx
import os

app = FastAPI()

PHONE_NUMBER_ID = os.getenv('PHONE_NUMBER_ID')
ACCESS_TOKEN = os.getenv('ACCESS_TOKEN')
VERIFY_TOKEN = os.getenv('VERIFY_TOKEN')
API_URL = f"https://graph.facebook.com/v17.0/{PHONE_NUMBER_ID}/messages"

@app.get("/webhook")
async def verify(request: Request):
    mode = request.query_params.get('hub.mode')
    token = request.query_params.get('hub.verify_token')
    challenge = request.query_params.get('hub.challenge')
    
    if mode == 'subscribe' and token == VERIFY_TOKEN:
        return int(challenge)
    raise HTTPException(status_code=403)

@app.post("/webhook")
async def receive(request: Request):
    data = await request.json()
    
    if data.get('object') == 'whatsapp_business_account':
        for entry in data.get('entry', []):
            for change in entry.get('changes', []):
                messages = change.get('value', {}).get('messages', [])
                
                for msg in messages:
                    sender = msg.get('from')
                    text = msg.get('text', {}).get('body', '')
                    
                    # Async reply
                    await send_message_async(sender, f"Received: {text}")
    
    return {"status": "ok"}

async def send_message_async(to: str, message: str):
    headers = {
        "Authorization": f"Bearer {ACCESS_TOKEN}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "messaging_product": "whatsapp",
        "to": to,
        "type": "text",
        "text": {"body": message}
    }
    
    async with httpx.AsyncClient() as client:
        response = await client.post(API_URL, headers=headers, json=payload)
        return response.json()

# Run: uvicorn app:app --reload

Complete Bot Example

python

"""
WhatsApp Bot dengan Python + Cloud API
"""

import os
import requests
from flask import Flask, request
from dotenv import load_dotenv

load_dotenv()

app = Flask(__name__)

# Config
PHONE_NUMBER_ID = os.getenv('PHONE_NUMBER_ID')
ACCESS_TOKEN = os.getenv('ACCESS_TOKEN')
VERIFY_TOKEN = os.getenv('VERIFY_TOKEN')
API_URL = f"https://graph.facebook.com/v17.0/{PHONE_NUMBER_ID}/messages"

# Response templates
RESPONSES = {
    'halo': 'Halo! 👋 Selamat datang!\n\nKetik MENU untuk lihat pilihan.',
    'menu': '📋 MENU:\n\n1. KATALOG - Lihat produk\n2. HARGA - Daftar harga\n3. ORDER - Cara pesan\n4. CS - Chat admin',
    'katalog': '📦 KATALOG:\n\n• Produk A - Rp 100.000\n• Produk B - Rp 150.000\n• Produk C - Rp 200.000',
    'harga': '💰 HARGA:\n\n• Produk A: Rp 100.000\n• Produk B: Rp 150.000\n• Produk C: Rp 200.000',
    'order': '🛒 CARA ORDER:\n\n1. Pilih produk\n2. Kirim format:\n   Nama:\n   Alamat:\n   Pesanan:\n3. Tunggu konfirmasi',
    'cs': '📞 Admin akan segera membalas!\n\nMohon tunggu ya 😊'
}

def send_message(to: str, message: str):
    headers = {
        "Authorization": f"Bearer {ACCESS_TOKEN}",
        "Content-Type": "application/json"
    }
    payload = {
        "messaging_product": "whatsapp",
        "to": to,
        "type": "text",
        "text": {"body": message}
    }
    requests.post(API_URL, headers=headers, json=payload)

@app.route('/webhook', methods=['GET'])
def verify():
    if request.args.get('hub.verify_token') == VERIFY_TOKEN:
        return request.args.get('hub.challenge')
    return "Error", 403

@app.route('/webhook', methods=['POST'])
def webhook():
    data = request.get_json()
    
    if data.get('object') == 'whatsapp_business_account':
        for entry in data.get('entry', []):
            for change in entry.get('changes', []):
                messages = change.get('value', {}).get('messages', [])
                
                for msg in messages:
                    sender = msg.get('from')
                    text = msg.get('text', {}).get('body', '').lower()
                    
                    # Find matching response
                    reply = RESPONSES.get(text, 
                        'Maaf tidak mengerti 😅\nKetik MENU untuk bantuan.')
                    
                    send_message(sender, reply)
    
    return "OK", 200

if __name__ == '__main__':
    app.run(port=5000)

FAQ

Library Python mana yang terbaik untuk WhatsApp API?

Untuk quick testing: pywhatkit (paling mudah, berbasis WA Web automation). Untuk production: requests/httpx library dengan Cloud API. Python tidak punya library sekomprehensif Baileys di Node.js, jadi untuk unofficial yang serius sebaiknya pakai Node.js.

Apakah pywhatkit bisa untuk production?

Tidak recommended. pywhatkit menggunakan WhatsApp Web dan membuka browser setiap kirim pesan. Cocok untuk testing atau kirim pesan sederhana sesekali, tapi tidak untuk bot atau high volume messaging. Untuk production, gunakan Cloud API.

Bagaimana buat webhook receiver dengan Python?

Gunakan Flask atau FastAPI untuk membuat endpoint yang menerima request dari WhatsApp Cloud API. Endpoint harus handle: (1) GET request untuk verification challenge, (2) POST request untuk incoming messages. Deploy ke server yang publicly accessible.


Kesimpulan

Python + WhatsApp = Possible dengan Cloud API!

Quick Reference:

Use CaseSolution
Quick testpywhatkit
ProductionCloud API + requests
AsyncFastAPI + httpx
WebhookFlask / FastAPI

Recommendation:

Testing sederhana → pywhatkit
Production bot → Cloud API + Flask/FastAPI
Butuh unofficial features → Pakai Node.js (Baileys)

Happy coding! 🐍

Atau Coba No-Code Solution — Gratis! →


Artikel Terkait