Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

55 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 

Repository files navigation

Chatbot Poliedro - Backend

Overview

The Chatbot Poliedro Backend is a conversational ordering system designed to streamline restaurant operations in Poliedro schools. It processes customer orders through WhatsApp using a state-machine conversational flow, manages menu items from a database, and persists orders for kitchen integration. This backend service handles all server-side logic for the restaurant ordering chatbot, providing a seamless interface between customers and the restaurant system.

Context

This repository is part of the Chatbot Poliedro project, an integrated solution developed for 3rd-semester Computer Science students at Instituto Mauá de Tecnologia (IMT). The backend service works in conjunction with a Kitchen Display System (KDS) to optimize restaurant operations by reducing wait times and improving order accuracy. This codebase specifically handles the WhatsApp messaging interface and order processing pipeline, allowing customers to place orders directly through chat without visiting the physical counter.

Technologies

  • Python 3.x - Programming language
  • Flask 3.1.0 - Web framework for HTTP endpoints
  • Twilio 9.5.2 - WhatsApp messaging integration
  • Supabase 2.15.0 - Backend-as-a-service database (PostgreSQL)
  • Gunicorn 23.0.0 - Production WSGI server
  • Gotrue 2.12.0 - Authentication client for Supabase
  • Realtime 2.4.2 - Real-time database subscriptions
  • Storage3 0.11.3 - Cloud storage client
  • Pytest 8.3.5 & Pytest-mock 3.14.0 - Testing framework

Architecture

The backend implements a state-machine architecture for managing conversational flow:

User WhatsApp Message
        ↓
   Twilio Webhook
        ↓
  Flask Route Handler
        ↓
  State Machine Logic
  (Fetch Menu, Track Order)
        ↓
  Supabase Database
  (Read menu, Write orders)
        ↓
  TwiML Response
        ↓
   WhatsApp Message

Key Components:

  1. Flask Application (main.py)

    • Single POST endpoint /mensagem receives messages from Twilio
    • Manages user session state and conversation context
    • Processes menu selection and order confirmation
  2. State Machine States:

    • inicio - Initial greeting
    • menu - Main menu selection (dishes or beverages)
    • escolhendo_prato - Dish selection from menu
    • confirmar_prato - Dish confirmation
    • pergunta_bebida - Beverage inquiry
    • escolhendo_bebida - Beverage selection
    • confirmar_bebida - Beverage confirmation
    • observacao - Order notes/observations
    • confirmacao - Final order summary and confirmation
  3. Data Management:

    • User sessions stored in-memory with 5-minute timeout
    • Menu items (dishes and beverages) fetched from Supabase Cardapio_Pratos and Cardapio_Bebidas tables
    • Orders persisted to Supabase Pedidos table
    • Prevents duplicate concurrent orders (maximum 2 active orders per user)
  4. Database Integration:

    • Supabase client initialized with API credentials
    • Dynamic menu loading on application startup
    • Order insertion with automatic ID generation

Features

  • WhatsApp Integration - Native chat interface via Twilio webhook
  • Conversational Ordering - Guided state-machine dialogue for seamless ordering
  • Menu Management - Dynamic menu items fetched from database
  • Order Tracking - Unique order IDs with confirmation
  • Session Management - User-specific state tracking with automatic timeout after 5 minutes of inactivity
  • Order Validation - Prevents more than 2 concurrent active orders per user
  • Order Customization - Support for optional observation notes/special requests
  • Price Calculation - Real-time total calculation with formatted currency display
  • Data Persistence - All orders permanently stored in Supabase database

Repository Structure

backend-chatbot/
├── main.py              # Main Flask application with state machine logic
├── requirements.txt     # Python dependencies (Flask, Twilio, Supabase, etc.)
├── Procfile             # Heroku deployment configuration
├── README.md            # This file
└── .git/                # Git version control

Key File Descriptions:

  • main.py - Core application containing Flask routes, state machine implementation, and Supabase integration. Handles incoming WhatsApp messages and orchestrates the entire conversation flow.
  • requirements.txt - Complete list of Python package dependencies with pinned versions for reproducible deployments.
  • Procfile - Configuration for Heroku deployment, specifying the command to run the application using Gunicorn.

Installation

Prerequisites

  • Python 3.8 or higher
  • pip (Python package manager)
  • Supabase account and project
  • Twilio account with WhatsApp sandbox enabled

Steps

  1. Clone the repository:

    git clone https://github.com/PI-2025-ChatBot/backend-chatbot.git
    cd backend-chatbot
  2. Create a virtual environment:

    python -m venv venv
  3. Activate the virtual environment:

    • On Windows:
      venv\Scripts\activate
    • On macOS/Linux:
      source venv/bin/activate
  4. Install dependencies:

    pip install -r requirements.txt
  5. Configure environment variables in main.py:

    • SUPABASE_URL - Your Supabase project URL
    • SUPABASE_KEY - Your Supabase API key
  6. Ensure your Supabase database has the following tables:

    • Cardapio_Pratos - Menu dishes with columns: id, nome, preco, descricao
    • Cardapio_Bebidas - Menu beverages with columns: id, nome, preco
    • Pedidos - Orders with columns: id, email, prato, bebida, total, observacao, ativo

Usage

Running Locally

python main.py

The Flask application will start in debug mode on http://localhost:5000.

Deploying to Production

The application is configured for Heroku deployment:

git push heroku main

Testing the Chatbot

  1. Configure Twilio webhook to point to your deployed endpoint: https://your-app-url/mensagem
  2. Send a message to your Twilio WhatsApp number
  3. Follow the conversational prompts to place an order

Example Flow

User: [sends any message]
Bot: "Olá, aqui é o bot de atendimento do restaurante Comida Boa.
      Digite o número da opção desejada:
      1 - Escolher prato
      2 - Escolher bebida
      0 - Cancelar pedido"

User: 1
Bot: [displays available dishes with prices]

User: [selects a dish]
Bot: [shows dish details and asks for confirmation]

User: 1 (confirm)
Bot: [asks about beverage]

User: 1 (yes to beverage)
Bot: [displays beverage menu]

User: [selects beverage]
Bot: [confirms beverage and asks about notes]

User: [adds observation or skips]
Bot: [shows order summary]

User: 1 (confirm order)
Bot: "Pedido confirmado! ✅
      Número do pedido: [ID]"

My Contributions

  • Implemented the core Flask REST API for WhatsApp message handling
  • Designed and developed the conversational state machine architecture
  • Integrated Supabase client for dynamic menu loading and order persistence
  • Implemented session management with inactivity timeout (5-minute window)
  • Created order validation logic preventing concurrent duplicate orders
  • Developed price calculation and currency formatting for Brazilian Real (R$)
  • Implemented order summary and confirmation workflow
  • Configured production deployment with Gunicorn and Procfile

Future Improvements

  • Move sensitive credentials (Supabase URL and API key) to environment variables
  • Implement persistent session storage (Redis or database) to support multi-instance deployments
  • Add order history endpoint for customers to track previous orders
  • Implement administrative endpoints for menu management without database access
  • Add support for multiple restaurant locations with location selection
  • Implement payment integration for online payment processing
  • Add real-time order status updates to customers
  • Implement rate limiting and abuse prevention measures
  • Add logging and monitoring for production debugging
  • Create comprehensive test suite with pytest
  • Implement database connection pooling for better performance
  • Add support for order cancellation within a time window

Team

This project was developed by a team of Computer Science students from the 3rd semester at Instituto Mauá de Tecnologia (IMT), as part of the Interdisciplinary Integrator Project (PII) in partnership with Poliedro System of Education.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages