Building ClassmateBot With Python, Django, Twilio WhatsApp API, and Google ADK
Introduction
In an era where mobile messaging apps dominate communication, ClassmateBot represents an innovative approach to education delivery—bringing personalized, AI-powered learning directly to students through WhatsApp. This article explores the architecture, design decisions, and implementation details of a sophisticated educational platform that combines Django, Google's Agent Development Kit (ADK), and AI to create bite-sized, engaging learning experiences.
The Vision: Microlearning Meets Messaging
ClassmateBot is built on a fundamental insight: students are already on WhatsApp. Rather than asking them to download yet another educational app, ClassmateBot meets learners where they are, delivering content in small, digestible "bites" that can be consumed between classes, on the bus, or during short breaks.
The platform offers three core experiences:
Structured Lessons: Content broken into bite-sized chunks with progress tracking
Interactive Quizzes: AI-generated questions with immediate feedback and points
Custom Course Generation: User-specified content created on-demand by AI agents
System Architecture: A Tale of Two Services
ClassmateBot's architecture is elegantly split into two complementary services:
1. The Django Backend: The Operational Core
The Django backend serves as the system's operational hub, handling:
User authentication and session management
Content storage and retrieval
Real-time WhatsApp message processing via Twilio webhooks
Progress tracking and gamification
RESTful APIs for all CRUD operations
Key Design Pattern: Command Pattern with Registry
The system implements a sophisticated command pattern where WhatsApp messages are parsed and routed through a central registry:
python
COMMAND_REGISTRY = {
"/help": {"class": HelpCommand, ...},
"/create-account": {"class": CreateAccountCommand, ...},
"/start-lesson": {"class": StartLessonCommand, "additional_args": ["subject_id"], ...},
"/generate-course": {"class": GenerateCourseCommand, "additional_args": ["preferences"], ...},
}
This architecture allows for easy extensibility—adding new commands is as simple as registering a new handler class.
2. The ADK Service: The Intelligence Layer
Google's Agent Development Kit powers the AI content generation pipeline. When a user requests a custom course with /generate-course, a sophisticated multi-agent system springs into action:
The Six-Agent Pipeline:
Curriculum Planner Agent: Analyzes user preferences and structures the learning plan
Content Drafter Agent: Writes the initial lesson content
Content Reviewer Agent: Provides quality assurance feedback
Content Refiner Agent: Improves content based on review
JSON Assembler Agent: Formats the output with schema validation
Backend Processing Agent: Orchestrates database operations and user notifications
This pipeline embodies the principle of separation of concerns—each agent has a single, well-defined responsibility, making the system more maintainable and allowing individual agents to be swapped or improved independently.
State Management: The User Journey
ClassmateBot implements a state machine to track user context:
idle → in_lesson → idle
idle → in_quiz → idle
idle → in_generation → idle
Each state determines how the system interprets incoming messages. When a user is in_quiz, their messages are treated as answers. When in_lesson, they're navigating through content. When in_generation, they're waiting for AI content creation.
This state management is backed by a JSON context field that stores session-specific data like current question index, topic progress, and user preferences.
The Data Model: Structured for Learning
ClassmateBot's data model reflects deep thinking about the learning experience:
Content Hierarchy
Subject → Topic → Bite
Subjects are broad categories (e.g., "Astrophysics") Topics are specific lessons within a subject (e.g., "Black Holes") Bites are the smallest units of content, designed for WhatsApp delivery
Progress Tracking
The system maintains granular progress tracking through:
Checkpoints: Mark individual bite completion
Milestones: Celebrate topic completion
Points: Gamify the experience with rewards for quiz completion, correct answers, and streaks
Assessment System
Quizzes consist of:
Questions linked to topics
Options with correctness flags and explanations
Answers recording user selections
This structure enables sophisticated analytics while remaining simple enough for rapid query performance.
AI Integration: Two Approaches to Content Generation
ClassmateBot uses AI in two distinct ways:
1. Structured Content Decomposition
When topics are created (either by admins or AI), the generate_bites() method uses Gemini to intelligently split content:
The prompt instructs the AI to:
Identify conceptual blocks
Group sentences for cohesion
Extract content verbatim (no summarization)
Preserve sequence
This ensures that long-form content becomes WhatsApp-friendly without losing pedagogical coherence.
2. Dynamic Quiz Generation
The generate_quizzes() function creates assessments on-the-fly:
Takes any text as input
Generates multiple-choice questions
Uses uppercase/lowercase convention to mark correct answers
Produces explanations for each option
This automation means every topic can have immediate assessment without manual question authoring.
Real-Time Communication: The Twilio Integration
The WhatsApp webhook is where the magic happens. Every incoming message triggers:
Authentication: Verify the user exists
State Check: Determine the user's current context
Routing: Direct to appropriate handler (command, quiz, lesson, or generation)
Response: Send formatted reply via Twilio
Clever Message Formatting: The system uses markdown-style formatting that WhatsApp supports:
*bold*for emphasis_italic_for instructionsEmojis for visual appeal (📚, ✅, 🎉)
Tables using pipe characters for structured data
Asynchronous Processing: Fire and Forget
Custom course generation is computationally expensive (2-3 minutes). To keep the user experience responsive, ClassmateBot uses a clever pattern:
User sends
/generate-course python for beginnersBackend immediately responds with acknowledgment
Backend triggers ADK service in a separate thread
User state changes to
in_generationWhen complete, ADK service calls back to notify the user
This "fire and forget" pattern ensures the WhatsApp webhook remains responsive while heavy AI processing happens asynchronously.
Security Considerations
The system implements multi-layered security:
API Protection
Internal endpoints (used by ADK service to create subjects, enroll users, etc.) require a secret header:
python
class IsADKWorker(permissions.BasePermission):
def has_permission(self, request, view):
provided_key = request.headers.get('X-ADK-Worker-Secret')
expected_key = settings.ADK_WORKER_SECRET
return provided_key == expected_key
Authentication
User endpoints require token authentication via Django REST Framework's built-in system.
Data Validation
Pydantic schemas enforce strict validation on AI-generated content before it enters the database.
Scalability Patterns
ClassmateBot is architected for scale:
Database Optimization
Selective field updates:
save(update_fields=[...])Bulk operations:
Bite.objects.bulk_create([...])Query optimization:
select_related()andprefetch_related()for relationshipsUnique constraints prevent duplicate enrollments
Stateless Design
The ADK service is stateless—each request is self-contained. This allows horizontal scaling of the AI pipeline.
Caching Opportunities
Though not yet implemented, the architecture supports:
Redis caching of frequently accessed subjects
Query result caching for popular topics
Session storage for active quiz states
The Developer Experience
ClassmateBot demonstrates modern Python development practices:
Environment Management
Uses uv for fast, reproducible dependency management and python-decouple for configuration.
Containerization
Includes a multi-stage Dockerfile optimized for production:
Uses UV's bytecode compilation for performance
Implements proper entrypoint scripts
Separates dependencies from application code
API Documentation
Leverages drf-spectacular for automatic OpenAPI/Swagger documentation.
Admin Interface
Custom Django admin with inlines provides efficient content management.
Lessons Learned and Future Directions
What Works Well
The bite-sized approach: Users engage more with small content chunks
State machine pattern: Makes complex conversational flows manageable
AI agent pipeline: Sequential processing ensures quality output
Command registry: Extensible and maintainable message routing
Technical Metrics
For those interested in the scale:
13 Database Models: Account, State, Subject, Topic, Bite, Quiz, Question, Option, Answer, Enrollment, Checkpoint, Milestone, Point
10+ Commands: Covering account management, content access, and AI generation
3 State Handlers: For quiz, lesson, and generation modes
6 AI Agents: In the content generation pipeline
6 Backend Tools: For ADK-to-Django communication
Conclusion: Education Reimagined
ClassmateBot represents more than just a technical achievement—it's a reimagining of how education can be delivered in the mobile-first era. By combining the ubiquity of WhatsApp, the intelligence of large language models, and thoughtful software engineering, it creates a learning experience that is:
Accessible: No app downloads, works on any phone
Personalized: AI generates content based on individual preferences
Engaging: Gamification and bite-sized content fight attention spans
Scalable: Architecture supports thousands of concurrent learners
As AI continues to advance and messaging platforms evolve, systems like ClassmateBot point toward a future where education is not a destination you visit, but a conversation you have—anytime, anywhere, in the palm of your hand.
Try It Yourself
The project is open-source under the MIT License. To get started:
bash
# Clone the repository
git clone https://github.com/iyanuashiri/classmatebot-project.git
# Backend setup with UV
cd backend
uv sync
uv run python manage.py migrate
uv run python manage.py runserver
# ADK service setup
cd adk-service
uv sync
uv run adk api_server
Set up your Twilio webhook, configure your environment variables, and start building the future of education.