Hey there, fellow developer! Ready to dive into the world of WhatsApp Business API integration? You're in for a treat. We'll be using the nifty whatsapp-python package to make our lives easier. Let's get cracking!
Before we jump in, make sure you've got:
pip install whatsapp-python
)Alright, let's get our hands dirty:
from whatsapp import Client # Initialize the client with your credentials client = Client( phone_number="your_phone_number", api_key="your_api_key", api_secret="your_api_secret" )
Easy peasy, right? Now we're ready to rock and roll!
Sending a text message is as simple as:
client.send_message("recipient_number", "Hello, World!")
Want to spice things up with some media?
client.send_image("recipient_number", "path/to/image.jpg", "Check out this cool pic!") client.send_document("recipient_number", "path/to/document.pdf", "Here's that report you asked for")
For those pre-approved templates:
client.send_template("recipient_number", "template_name", {"1": "John", "2": "Doe"})
To receive messages, you'll need to set up a webhook. Here's a quick Flask example:
from flask import Flask, request app = Flask(__name__) @app.route('/webhook', methods=['POST']) def webhook(): data = request.json # Process incoming message return '', 200 if __name__ == '__main__': app.run(port=5000)
Process those incoming messages like a pro:
def process_message(message): if message['type'] == 'text': # Handle text message elif message['type'] == 'image': # Handle image message # ... handle other types
client.add_contact("contact_number", "John Doe") client.remove_contact("contact_number")
contact_info = client.get_contact("contact_number")
group_id = client.create_group("My Awesome Group", ["number1", "number2"]) client.add_participant(group_id, "new_number") client.remove_participant(group_id, "number_to_remove")
broadcast_id = client.create_broadcast_list(["number1", "number2"]) client.send_broadcast(broadcast_id, "Hello, everyone!")
status = client.get_message_status("message_id") print(f"Message status: {status}")
Always wrap your API calls in try-except blocks:
try: client.send_message("recipient_number", "Hello!") except WhatsAppError as e: print(f"Oops! Something went wrong: {e}")
Remember to respect rate limits and implement exponential backoff for retries. And hey, keep those API credentials safe!
Use the sandbox environment for testing:
client = Client( phone_number="your_phone_number", api_key="your_api_key", api_secret="your_api_secret", sandbox=True )
Don't forget to implement proper logging:
import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.info("Sending message...")
And there you have it! You're now equipped to build a robust WhatsApp Business API integration. Remember, practice makes perfect, so keep experimenting and building cool stuff. If you get stuck, the whatsapp-python documentation is your best friend. Now go forth and code!