Handling Zalo OA API Via Python Script

Zalo OA API Wrapper Simple Handle Your OA {API} {JSON} {}

A simple API script for interacting with the Zalo Official Account (OA). This script provides an easy-to-use interface to manage users, retrieve user information, send and receive messages, and more. Ideal for automating interactions with your Zalo OA and building customer engagement tools.

✨ Features

🚀 Installation

  1. Clone the repository:
    git clone https://github.com/nh4ttruong/zalo-oa-api.git
    cd zalo-oa-api
    
  2. Install dependencies:
    pip install -r requirements.txt
    

🔧 Setup

  1. Obtain Zalo OA Access Token:
    • Go to the Zalo API Explorer
    • Choose OA Access Token and click Get Access Token
    • Accept the Terms of Use and copy the generated Access Token
  2. Configure Your API Credentials:
    • Create a .env file in the project root
    • Add your Zalo OA API credentials:
      ZALO_OA_ACCESS_TOKEN=your_ZALO_OA_ACCESS_TOKEN
      
  3. Run the script:
    python main.py
    

📝 Usage Examples

Sending a Text Message

from dependencies.messages import *

# User ID of the recipient
user_id = "7186086631826132217"
message_text = "Hello, this is a test message"

# Send a text message to the specified user
send_text_message(ZALO_OA_ACCESS_TOKEN, user_id, message_text)

Sending a Message with an Image

from dependencies.messages import *
from dependencies.upload import *

# Specify the user ID and message content
user_id = "7186086631826132217"
users = [{"user_id": user} for user in user_id.split(",")]
message_text = "Hello, here's an image for you!"

# Upload the image and retrieve the attachment ID
attachment_id = upload_media(ZALO_OA_ACCESS_TOKEN, file_path=IMAGE_FILE_PATH, type="image")

# Send the message along with the image
send_message_to_users(ZALO_OA_ACCESS_TOKEN, users, message_text=message_text, image_file=IMAGE_FILE_PATH)

Sending to Multiple Users

from dependencies.messages import *
from dependencies.upload import *
from dependencies.users import *

# Check if all users should receive the message
if SEND_ALL_USERS == 'True':
    users = get_all_users(ZALO_OA_ACCESS_TOKEN)
else:
    # Use a comma-separated list of user IDs
    users = [{"user_id": user.strip()} for user in SEND_USER_LIST.split(",")]

# Send text or image message based on configuration
if SEND_MESSAGE_TEXT == 'True':
    if SEND_MESSAGE_WITH_IMAGE == 'True':
        send_message_to_users(ZALO_OA_ACCESS_TOKEN, users, message_text=MESSAGE_CONTENT, image_file=IMAGE_FILE_PATH)
    else:
        send_message_to_users(ZALO_OA_ACCESS_TOKEN, users, message_text=MESSAGE_CONTENT)
elif SEND_MESSAGE_WITH_IMAGE == 'True':
    send_message_to_users(ZALO_OA_ACCESS_TOKEN, users, message_text=MESSAGE_CONTENT, image_file=IMAGE_FILE_PATH)
else:
    print("No message to send")

📚 Documentation

For more details on the Zalo OA API, visit the official documentation.