Skip to main content

An asynchronous Python wrapper for the Baileys WhatsApp API.

Project description

PyWaBot

PyPI version

PyWaBot is a powerful, asynchronous, and unofficial Python library for interacting with the WhatsApp Business Platform. Built on a Baileys-based API server, it provides a high-level, easy-to-use interface for sending messages, handling events, and managing your WhatsApp bot.

Features

  • Asynchronous by Design: Built with asyncio for high performance and non-blocking operations.
  • Easy to Use: A high-level, intuitive API for common WhatsApp actions.
  • Pairing Code Login: Easily connect your bot by requesting a pairing code—no need to scan a QR code.
  • Rich Media Support: Send and receive text, images, videos, documents, and more.
  • Session Management: Programmatically list and delete active WhatsApp sessions.
  • Event-Driven: Use simple decorators to handle incoming messages and commands.

Installation

You can install PyWaBot directly from PyPI:

pip install pywabot

Getting Started: Your First Connection

Follow these steps to get your bot connected and running in minutes.

1. Get Your API Key

The library communicates with a secure API server that requires an API key. A utility script is included to generate one for you.

First, create a file named api_key_manager.py in your project's root directory and add the following code:

# tools/api_key_manager.py
import secrets
import json
import os
import argparse

API_KEY_FILE = ".api_key.json"

def generate_api_key():
    """Generates and saves a new API key."""
    api_key = secrets.token_hex(24)
    with open(API_KEY_FILE, "w") as f:
        json.dump({"api_key": api_key}, f, indent=4)
    print(f"Generated new API key and saved to {API_KEY_FILE}")
    print(f"Your API Key: {api_key}")
    return api_key

def get_api_key():
    """Retrieves the saved API key."""
    if not os.path.exists(API_KEY_FILE):
        return None
    with open(API_KEY_FILE, "r") as f:
        try:
            data = json.load(f)
            return data.get("api_key")
        except (json.JSONDecodeError, AttributeError):
            return None

def main():
    parser = argparse.ArgumentParser(
        description="A simple tool to generate and manage the API key for PyWaBot.",
        epilog="Example usage: python api_key_manager.py generate"
    )
    subparsers = parser.add_subparsers(dest="action", required=True, help="Available actions")
    subparsers.add_parser("generate", help="Generate a new API key and save it.")
    subparsers.add_parser("get", help="Get the currently saved API key.")
    args = parser.parse_args()

    if args.action == "generate":
        generate_api_key()
    elif args.action == "get":
        key = get_api_key()
        if key:
            print(f"API Key: {key}")
        else:
            print(f"API key not found. Generate one using: python api_key_manager.py generate")

if __name__ == "__main__":
    main()

Now, run the script from your terminal to generate the key:

python api_key_manager.py generate

This will create a .api_key.json file in your project root. Keep this file secure and do not share it.

2. Connect Your Bot with a Pairing Code

Create a file named my_bot.py and use the following code to connect your bot. This example shows how to request a pairing code if the bot is not already connected.

# my_bot.py
import asyncio
from pywabot import PyWaBot

# --- Configuration ---
# Give your session a unique name to distinguish it from other bots
SESSION_NAME = "my_first_bot" 
# Replace with the API key you generated
API_KEY = "your_api_key"

async def main():
    """Initializes the bot and connects using a pairing code if needed."""
    bot = PyWaBot(session_name=SESSION_NAME, api_key=API_KEY)

    print("Attempting to connect the bot...")
    if not await bot.connect():
        print("\nConnection failed. A pairing code is required.")
        
        try:
            phone_number = input("Enter your WhatsApp phone number (e.g., 6281234567890): ")
            if phone_number:
                code = await bot.request_pairing_code(phone_number)
                if code:
                    print(f"\n>>> Your Pairing Code: {code} <<<")
                    print("Go to WhatsApp on your phone > Linked Devices > Link with phone number.")
                    print("Enter the code to connect your bot.")
                    
                    print("\nWaiting for connection...")
                    if await bot.wait_for_connection(timeout=120):
                        print("Bot connected successfully!")
                    else:
                        print("Connection timed out. Please try running the script again.")
                else:
                    print("Could not request a pairing code. Please check your API key and server status.")
        except Exception as e:
            print(f"An error occurred: {e}")
            return

    print("Bot is connected and ready to listen for messages!")
    # The bot will keep running until you stop it (e.g., with Ctrl+C)
    await bot.start_listening()

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nBot stopped.")

To run your bot:

  1. Replace "your_api_key" with the key from your .api_key.json file.
  2. Run the script: python my_bot.py.
  3. When prompted, enter your WhatsApp phone number (including the country code, without + or 00).
  4. You will receive a pairing code in the terminal.
  5. On your phone, go to WhatsApp > Settings > Linked Devices > Link a device > Link with phone number instead and enter the code.
  6. Your bot will connect and be ready!

Simple Echo Bot Example

Here is a complete example of a bot that replies to any message it receives.

# echo_bot.py
import asyncio
from pywabot import PyWaBot

# --- Configuration ---
SESSION_NAME = "echo_bot_session"
API_KEY = "your_api_key"

# Initialize the bot
bot = PyWaBot(session_name=SESSION_NAME, api_key=API_KEY)

@bot.on_message
async def echo_handler(message):
    """This handler is triggered for any incoming message."""
    # Ignore messages sent by the bot itself
    if message.from_me:
        return

    print(f"Received message from {message.sender_name}: '{message.text}'")
    
    # Formulate a reply
    reply_text = f"You said: '{message.text}'"
    
    # Simulate typing and send the reply
    await bot.typing(message.chat, duration=1)
    await bot.send_message(message.chat, reply_text, reply_chat=message)
    print(f"Sent reply to {message.sender_name}")

async def main():
    """Connects the bot and starts listening for messages."""
    print("Connecting echo bot...")
    if await bot.connect():
        print("Echo bot connected and listening!")
        await bot.start_listening()
    else:
        print("Failed to connect. Please run the connection script first to pair your device.")

if __name__ == "__main__":
    asyncio.run(main())

Session Management

You can programmatically manage your bot's sessions.

List Active Sessions

To see all sessions currently running on the server under your API key:

import asyncio
from pywabot import PyWaBot

API_KEY = "API_TOKEN"

async def list_active_sessions():
    """Fetches and prints all active session names."""
    print("Listing active sessions...")
    try:
        sessions = await PyWaBot.list_sessions(api_key=API_KEY)
        if sessions:
            print("Found active sessions:")
            for session_name in sessions.get("sessions"):
                print(f"- {session_name}")
        else:
            print("No active sessions found.")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    asyncio.run(list_active_sessions())

Delete a Session

To log out and delete a specific session from the server:

import asyncio
from pywabot import PyWaBot

API_KEY = "your_api_key"
SESSION_TO_DELETE = "my_first_bot" # The name of the session you want to delete

async def delete_a_session():
    """Deletes a specified session from the server."""
    print(f"Attempting to delete session: '{SESSION_TO_DELETE}'...")
    try:
        success = await PyWaBot.delete_session(SESSION_TO_DELETE, api_key=API_KEY)
        if success:
            print(f"Session '{SESSION_TO_DELETE}' was successfully deleted.")
        else:
            print(f"Failed to delete session '{SESSION_TO_DELETE}'. It may not exist.")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    asyncio.run(delete_a_session())

More Examples

This library can do much more! For detailed examples on sending images, videos, GIFs, managing groups, handling media, and more, please check out the files in the examples/ directory of this project.

Support & Community

For questions, support, or to connect with other developers, join our community:

Get Support on Lynk.id

Disclaimer

This is an unofficial library and is not affiliated with, authorized, maintained, sponsored, or endorsed by WhatsApp or Meta. Please use it responsibly and in accordance with WhatsApp's Terms of Service.

License

This project is licensed under the MIT License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pywabot-0.3.7.tar.gz (19.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pywabot-0.3.7-py3-none-any.whl (18.9 kB view details)

Uploaded Python 3

File details

Details for the file pywabot-0.3.7.tar.gz.

File metadata

  • Download URL: pywabot-0.3.7.tar.gz
  • Upload date:
  • Size: 19.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for pywabot-0.3.7.tar.gz
Algorithm Hash digest
SHA256 ee57f535c5fee70b8618da3dd03fd24b65ff2f25f29ea2c802b1b786415de31a
MD5 02b6170e7dff23ac4343f65711ddcdaa
BLAKE2b-256 ee89f5341eb66c86c32d46a909c9e632897ae96d9a863371b3e39767f51d6e6f

See more details on using hashes here.

Provenance

The following attestation bundles were made for pywabot-0.3.7.tar.gz:

Publisher: python-publish.yml on khazulys/pywabot

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file pywabot-0.3.7-py3-none-any.whl.

File metadata

  • Download URL: pywabot-0.3.7-py3-none-any.whl
  • Upload date:
  • Size: 18.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for pywabot-0.3.7-py3-none-any.whl
Algorithm Hash digest
SHA256 2ed626f2d5166a8dcc2ae62949879dadda0b9bab79a1fc0daa7d9f876198cd88
MD5 017334f7977f049871f223e5224e5031
BLAKE2b-256 e9ae8318cd65be3a409c3b28f3b227ba76ad0c258d69f25594428629991f53b1

See more details on using hashes here.

Provenance

The following attestation bundles were made for pywabot-0.3.7-py3-none-any.whl:

Publisher: python-publish.yml on khazulys/pywabot

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page