WhatsApp Chatbot library for Python based on SDKWA API with Telegraf-like interface
Project description
SDKWA WhatsApp Chatbot - Python SDK
A Python chatbot library that provides a Telegraf-like interface for building WhatsApp bots using the SDKWA WhatsApp API. This library is inspired by the popular Telegraf framework for Telegram bots, bringing the same elegant API design to WhatsApp.
Features
🚀 Telegraf-Like API - Familiar and intuitive interface for Telegram developers
🤖 Easy Bot Creation - Simple WhatsAppBot class with clean configuration
🎭 Scenes & Wizards - Create complex conversation flows and step-by-step interactions
💾 Session Management - Built-in session storage with memory and file backends
🔧 Middleware Support - Compose functionality with middleware pattern
📱 Media Handling - Send and receive photos, documents, audio, video, locations, and contacts
⌨️ Command Handling - Handle /start, /help, and custom commands
🎯 Event Filtering - Listen for specific message types and patterns
🌐 Webhook Support - Built-in webhook support for Flask and FastAPI
🔒 Type Safe - Full type hints for better development experience
Installation
pip install sdkwa-whatsapp-chatbot
Quick Start
1. Basic Bot
import os
from sdkwa_whatsapp_chatbot import WhatsAppBot
# Create bot
bot = WhatsAppBot({
'idInstance': os.getenv('ID_INSTANCE'),
'apiTokenInstance': os.getenv('API_TOKEN_INSTANCE')
})
# Handle text messages
@bot.on('text')
async def handle_text(ctx):
await ctx.reply(f"You said: {ctx.message.text}")
# Handle commands
@bot.start()
async def start_command(ctx):
await ctx.reply('Welcome to my WhatsApp bot!')
@bot.command('hello')
async def hello_command(ctx):
await ctx.reply('Hello there! 👋')
# Launch bot
bot.launch()
2. Bot with Sessions
from sdkwa_whatsapp_chatbot import WhatsAppBot, session
bot = WhatsAppBot({
'idInstance': os.getenv('ID_INSTANCE'),
'apiTokenInstance': os.getenv('API_TOKEN_INSTANCE')
})
# Enable sessions
bot.use(session())
@bot.command('count')
async def count_command(ctx):
# Access session data
count = ctx.session.get('count', 0) + 1
ctx.session['count'] = count
await ctx.reply(f"You've used this command {count} times!")
bot.launch()
3. Bot with Scenes (Conversation Flows)
from sdkwa_whatsapp_chatbot import WhatsAppBot, session, BaseScene, Stage
bot = WhatsAppBot({
'idInstance': os.getenv('ID_INSTANCE'),
'apiTokenInstance': os.getenv('API_TOKEN_INSTANCE')
})
# Create a greeting scene
greeting_scene = BaseScene('greeting')
@greeting_scene.enter()
async def enter_greeting(ctx):
await ctx.reply("What's your name?")
@greeting_scene.on('text')
async def handle_name(ctx):
name = ctx.message.text
ctx.session['name'] = name
await ctx.reply(f"Nice to meet you, {name}!")
await ctx.scene.leave_scene(ctx)
# Create stage and register scene
stage = Stage([greeting_scene])
# Use middleware
bot.use(session())
bot.use(stage.middleware())
# Command to enter scene
@bot.command('greet')
async def start_greeting(ctx):
await ctx.scene_manager.enter('greeting', ctx)
bot.launch()
4. Wizard Scene (Step-by-Step)
from sdkwa_whatsapp_chatbot import WhatsAppBot, session, Stage
from sdkwa_whatsapp_chatbot.scenes import WizardScene
bot = WhatsAppBot({
'idInstance': os.getenv('ID_INSTANCE'),
'apiTokenInstance': os.getenv('API_TOKEN_INSTANCE')
})
# Create registration wizard
wizard = WizardScene('registration')
@wizard.step
async def ask_name(ctx):
await ctx.reply("Step 1: What's your name?")
@wizard.step
async def ask_age(ctx):
name = ctx.message.text
await ctx.wizard.next({'name': name})
await ctx.reply("Step 2: How old are you?")
@wizard.step
async def finish(ctx):
age = ctx.message.text
await ctx.wizard.next({'age': age})
# Get all collected data
data = ctx.wizard.get_all_data()
name = data.get(0, {}).get('name')
age = data.get(1, {}).get('age')
await ctx.reply(f"Registration complete!\nName: {name}\nAge: {age}")
await ctx.wizard.complete()
# Setup
stage = Stage([wizard])
bot.use(session())
bot.use(stage.middleware())
@bot.command('register')
async def start_wizard(ctx):
await ctx.scene_manager.enter('registration', ctx)
bot.launch()
API Reference
Bot Creation
from sdkwa_whatsapp_chatbot import WhatsAppBot
# Configuration options
config = {
'idInstance': 'your-instance-id',
'apiTokenInstance': 'your-api-token',
'apiUrl': 'https://api.sdkwa.pro' # Optional
}
bot = WhatsAppBot(config)
Event Handlers
# Listen for specific update types
@bot.on('message') # All messages
@bot.on('text') # Text messages only
@bot.on(['text', 'photo']) # Multiple types
# Listen for text patterns
@bot.hears('hello') # Exact match
@bot.hears(r'hello.*') # Regex pattern
# Listen for commands
@bot.command('start') # /start command
@bot.start() # Alias for /start
@bot.help() # Alias for /help
Context Methods
async def handler(ctx):
# Send messages
await ctx.reply('Hello!')
await ctx.reply_with_photo('https://example.com/photo.jpg', caption='Photo')
await ctx.reply_with_document('https://example.com/doc.pdf')
await ctx.reply_with_location(40.7128, -74.0060, 'New York')
await ctx.reply_with_contact('+1234567890', 'John', 'Doe')
# Message info
text = ctx.message.text
chat_id = ctx.chat_id
sender = ctx.from_user
# Command helpers
command = ctx.get_command() # Get command name
args = ctx.get_command_args() # Get command arguments
# Session access
ctx.session['key'] = 'value'
value = ctx.session.get('key')
Session Management
from sdkwa_whatsapp_chatbot import session, MemorySessionStore, FileSessionStore
# Use memory store (default)
bot.use(session())
# Use file store
bot.use(session(store=FileSessionStore('sessions.json')))
# Custom session key
def custom_key(ctx):
return f"{ctx.chat_id}:{ctx.from_user.get('id', 'anonymous')}"
bot.use(session(key_generator=custom_key))
Scene Management
from sdkwa_whatsapp_chatbot import BaseScene, Stage
# Create scene
scene = BaseScene('my_scene')
@scene.enter()
async def on_enter(ctx):
await ctx.reply("Entered scene!")
@scene.leave()
async def on_leave(ctx):
await ctx.reply("Left scene!")
@scene.on('text')
async def handle_text(ctx):
await ctx.reply("In scene: " + ctx.message.text)
# Scene state management
@scene.on('text')
async def save_data(ctx):
scene.update_state(ctx, {'user_input': ctx.message.text})
state = scene.get_state(ctx)
# Create stage
stage = Stage([scene])
bot.use(stage.middleware())
# Scene navigation
@bot.command('enter')
async def enter_scene(ctx):
await ctx.scene_manager.enter('my_scene', ctx)
Wizard Scenes
from sdkwa_whatsapp_chatbot.scenes import WizardScene
wizard = WizardScene('my_wizard')
@wizard.step
async def step1(ctx):
await ctx.reply("Step 1: Enter your name")
@wizard.step
async def step2(ctx):
name = ctx.message.text
await ctx.wizard.next({'name': name})
await ctx.reply("Step 2: Enter your age")
@wizard.step
async def step3(ctx):
age = ctx.message.text
await ctx.wizard.next({'age': age})
# Get all data
all_data = ctx.wizard.get_all_data()
await ctx.reply(f"Done! Name: {all_data[0]['name']}, Age: {all_data[1]['age']}")
await ctx.wizard.complete()
# Wizard navigation
async def handler(ctx):
await ctx.wizard.next() # Next step
await ctx.wizard.previous() # Previous step
await ctx.wizard.jump_to(2) # Jump to step
progress = ctx.wizard.progress # Get progress info
Media Handling
# Send media
await ctx.reply_with_photo(
photo_url='https://example.com/photo.jpg',
caption='A nice photo'
)
await ctx.reply_with_document(
document_url='https://example.com/doc.pdf',
caption='Important document'
)
# Handle received media
@bot.on('message')
async def handle_media(ctx):
if ctx.message.message_type == 'imageMessage':
await ctx.reply("Received a photo!")
# Download URL: ctx.message.file_url
elif ctx.message.message_type == 'documentMessage':
await ctx.reply(f"Received document: {ctx.message.file_name}")
Webhook Support
# Flask webhook
from flask import Flask
app = Flask(__name__)
bot.flask_webhook(app, '/webhook')
# FastAPI webhook
from fastapi import FastAPI
app = FastAPI()
bot.fastapi_webhook(app, '/webhook')
# Custom webhook
callback = bot.webhook_callback()
# Use callback in your web framework
Error Handling
@bot.catch
async def error_handler(error, ctx):
print(f"Error: {error}")
if ctx:
await ctx.reply("Sorry, something went wrong!")
Examples
The examples/ directory contains several complete examples:
hello_bot.py- Simple hello botecho_bot.py- Echo messages and filesscene_bot.py- Conversation sceneswizard_bot.py- Step-by-step wizardsmedia_bot.py- Media file handling
Configuration
Environment Variables
export ID_INSTANCE="your_instance_id"
export API_TOKEN_INSTANCE="your_api_token"
Configuration Object
config = {
'idInstance': 'your-instance-id',
'apiTokenInstance': 'your-api-token',
'apiUrl': 'https://api.sdkwa.pro', # Optional
# Bot options
'polling_interval': 1, # Seconds between polls
'max_retries': 3, # Max retry attempts
'retry_delay': 5 # Delay between retries
}
bot = WhatsAppBot(config)
Getting SDKWA Credentials
- Sign up at SDKWA
- Create a new WhatsApp instance
- Get your
idInstanceandapiTokenInstancefrom the dashboard - Use these credentials in your bot configuration
Comparison with JavaScript Version
This Python library provides the same functionality as the JavaScript @sdkwa/whatsapp-chatbot package:
| Feature | JavaScript | Python | Status |
|---|---|---|---|
| Basic Bot | ✅ | ✅ | Complete |
| Commands | ✅ | ✅ | Complete |
| Scenes | ✅ | ✅ | Complete |
| Sessions | ✅ | ✅ | Complete |
| Middleware | ✅ | ✅ | Complete |
| Media Files | ✅ | ✅ | Complete |
| Webhooks | ✅ | ✅ | Complete |
| Error Handling | ✅ | ✅ | Complete |
Requirements
- Python 3.8+
sdkwa-whatsapp-api-client>= 1.0.0typing-extensions>= 4.0.0pydantic>= 2.0.0
Development
Setting up development environment
# Clone the repository
git clone https://github.com/sdkwa/whatsapp-chatbot-python.git
cd whatsapp-chatbot-python
# Install in development mode
pip install -e .
# Install development dependencies
pip install -e .[dev]
# Run tests
pytest
# Format code
black sdkwa_whatsapp_chatbot/
isort sdkwa_whatsapp_chatbot/
# Type checking
mypy sdkwa_whatsapp_chatbot/
Development Setup
Using Make (Recommended)
# Install development dependencies
make install-dev
# Run tests
make test
# Format code
make format
# Check formatting
make format-check
# Run linting
make lint
# Build package
make build
# Clean build artifacts
make clean
Manual Setup
# Clone repository
git clone https://github.com/sdkwa/whatsapp-chatbot-python.git
cd whatsapp-chatbot-python
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install in development mode
pip install -e .[dev]
# Set up pre-commit hooks (optional but recommended)
pip install pre-commit
pre-commit install
# Run tests
pytest
# Format code
black .
isort .
# Type checking
mypy sdkwa_whatsapp_chatbot
Publishing
For maintainers, see PUBLISHING.md for detailed instructions on publishing to PyPI.
Contributing
We welcome contributions! Please see our Contributing Guide for details.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
Changelog
v1.0.0
- Initial release
- Telegraf-like API for WhatsApp bots
- Scene and wizard support
- Session management
- Media handling
- Webhook support
- Complete examples and documentation
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file sdkwa_whatsapp_chatbot-1.0.3.tar.gz.
File metadata
- Download URL: sdkwa_whatsapp_chatbot-1.0.3.tar.gz
- Upload date:
- Size: 40.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c1b0a40e66cdf516473eb50906426e6255412025d52cb2af0acac4c50e07a0ef
|
|
| MD5 |
107222cd3c36cfdeb0a15aaacb0811da
|
|
| BLAKE2b-256 |
fcdaf6803d59a7db0179f83d59ef4080f113096bed7827a68e006b6f7983167e
|
Provenance
The following attestation bundles were made for sdkwa_whatsapp_chatbot-1.0.3.tar.gz:
Publisher:
publish.yml on sdkwa/whatsapp-chatbot-python
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
sdkwa_whatsapp_chatbot-1.0.3.tar.gz -
Subject digest:
c1b0a40e66cdf516473eb50906426e6255412025d52cb2af0acac4c50e07a0ef - Sigstore transparency entry: 270339734
- Sigstore integration time:
-
Permalink:
sdkwa/whatsapp-chatbot-python@50e66df331383351ac53cf41b9fbbda48561921e -
Branch / Tag:
refs/tags/1.0.3 - Owner: https://github.com/sdkwa
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@50e66df331383351ac53cf41b9fbbda48561921e -
Trigger Event:
release
-
Statement type:
File details
Details for the file sdkwa_whatsapp_chatbot-1.0.3-py3-none-any.whl.
File metadata
- Download URL: sdkwa_whatsapp_chatbot-1.0.3-py3-none-any.whl
- Upload date:
- Size: 25.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cb043160e8577f1f797c7be3053e3ac7b777087c5e5dfc52a6c5988515aaf254
|
|
| MD5 |
61b60bfe7cb6e0206f676184c9f799bb
|
|
| BLAKE2b-256 |
6f6fa863ef0ed02344b0fba1fc83d51f2a05bb5bda11a176ff0efefc51c810e4
|
Provenance
The following attestation bundles were made for sdkwa_whatsapp_chatbot-1.0.3-py3-none-any.whl:
Publisher:
publish.yml on sdkwa/whatsapp-chatbot-python
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
sdkwa_whatsapp_chatbot-1.0.3-py3-none-any.whl -
Subject digest:
cb043160e8577f1f797c7be3053e3ac7b777087c5e5dfc52a6c5988515aaf254 - Sigstore transparency entry: 270339741
- Sigstore integration time:
-
Permalink:
sdkwa/whatsapp-chatbot-python@50e66df331383351ac53cf41b9fbbda48561921e -
Branch / Tag:
refs/tags/1.0.3 - Owner: https://github.com/sdkwa
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@50e66df331383351ac53cf41b9fbbda48561921e -
Trigger Event:
release
-
Statement type: