# Pamsika WhatsApp Ticketing Bot

![Pamsika Logo](https://pamsikaonline.com/images/logo.png)

## Project Overview

Pamsika WhatsApp Ticketing Bot is a Node.js-based chatbot designed to facilitate event ticketing and order management via WhatsApp. It integrates with PamsikaOnline, Malawi's leading e-commerce platform for events and ticketing, providing users with a seamless conversational interface to browse events, purchase tickets, and manage orders.

The bot leverages the [Baileys](https://github.com/WhiskeySockets/Baileys) library for WhatsApp Web API integration, Express.js for REST API endpoints, and PDFKit for generating ticket PDFs with QR codes.

## Features

- WhatsApp chatbot with session management and multi-language support (English and Chichewa).
- Browse available events and search events by keywords.
- Purchase tickets with payment options including Airtel Money and TNM Mpamba.
- Order management: view order history and detailed order status.
- Automatic generation and delivery of PDF tickets with QR codes.
- REST API endpoints to send text and media messages, and receive payment status updates.
- Scheduled tasks managed via cron jobs.
- Configurable settings and company information.
- Direct event access via event ID detection in messages.
- Visual event browsing with images and explicit number references.
- Robust state management for seamless navigation between menus.

## Installation

### Prerequisites

- Node.js (v14 or higher recommended)
- npm (Node package manager)

### Setup

1. Clone the repository:

   ```bash
   git clone https://github.com/BenMilanzi98/pamsika-whatsapp-bot.git
   cd pamsika-whatsapp-bot
   ```

2. Install dependencies:

   ```bash
   npm install
   ```

3. Ensure the following directories exist or will be created on first run:

   - `sessions/` - for WhatsApp session data
   - `users/` - for user data storage
   - `config/` - for configuration files

4. Default configuration files (`settings.json`, `company.json`) will be created automatically if missing. You can customize them as needed.

## Configuration

- `config/settings.json`: Contains bot settings such as welcome message, session timeout, and reply delay.
- `config/company.json`: Contains company details like name, description, website, support contact, email, and logo URL.
- `config/translations.json`: Contains language translations for multi-language support.
- User sessions and data are stored in the `users/` directory.
- WhatsApp authentication sessions are stored in the `sessions/` directory.
- Order and ticket data are stored in `database.json`.

## Recent Enhancements (May 2025)

### New Features

- **Direct Event Access**: Users can now directly access event details by mentioning an event ID in their messages. The bot recognizes patterns like "Event ID: 123", "Ticket #123", or similar variations and immediately shows the event details with purchase options.

- **Visual Event Browsing**: Updated the event browsing experience to show each event with its image and clearer instructions. Events now display with explicit number references (e.g., "Select this event by replying with *1*").

### Bug Fixes and Improvements

- **Fixed Navigation Issues**: Resolved issues with users getting stuck when navigating between different sections of the chatbot, particularly after checking orders.

- **Improved State Management**: Completely restructured the state management system to ensure seamless transitions between all states and prevent users from getting stuck in intermediate states.

- **Error Handling**: Added comprehensive error handling and recovery paths throughout the codebase, ensuring users always have a way to continue their journey even if errors occur.

- **Code Optimization**: Removed duplicate code, centralized imports, and improved overall code structure for better maintainability.

- **Memory Usage**: Optimized memory usage by properly cleaning up user state data when transitioning between different sections.

## Usage

### Running the Bot and Server

Start the Express server and WhatsApp bot:

```bash
PORT=3000 node server.js
```

The bot will generate a QR code in the terminal for WhatsApp authentication on first run.

### Deployment on chatbot.pamsikaonline.com

To run the bot on your shared hosting under the domain \`chatbot.pamsikaonline.com\`, follow these steps:

1. Ensure the DNS for \`chatbot.pamsikaonline.com\` points to your server's IP address.

2. Run the Node.js app on a non-privileged port (e.g., 3000 or 8080):

```bash
PORT=3000 node server.js
```

3. Configure a reverse proxy (e.g., Nginx or Apache) on your server to forward incoming HTTP(S) requests on port 80 (and 443 for HTTPS) to the Node.js app port.

Example Nginx configuration snippet:

```nginx
server {
    listen 80;
    server_name chatbot.pamsikaonline.com;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}
```

4. For HTTPS, set up SSL certificates (e.g., via Let's Encrypt) and update the proxy configuration accordingly.

5. Restart your web server to apply changes.

This approach avoids permission issues with binding to port 80 and provides better security and flexibility.

If you need assistance setting up the reverse proxy, please consult your hosting provider's documentation or let me know.

### WhatsApp Interaction Flow

- On first contact, users select their preferred language (English or Chichewa).
- Main menu options include:
  1. Browse Events
  2. Buy Ticket
  3. Search Events
  4. My Orders
  5. About Pamsika
- Users can browse events, view event details with images, and purchase tickets.
- Ticket purchase flow includes selecting quantity, payment method, and entering payment details.
- Users receive PDF tickets with QR codes via WhatsApp.
- Users can view their order history and order details.
- Sessions expire after a configurable timeout, with warnings sent before expiration.
- Users can reset the session anytime by sending `#startover`.
- Users can directly access event details by mentioning an event ID in their message (e.g., "Tell me about event ID 208").

### REST API Endpoints

- `POST /send-message`: Send a text message to a phone number.
- `POST /send-media`: Send a media message (image, video, document) to a phone number.
- `POST /payment-update`: Notify users of payment status updates for orders.

All endpoints are rate-limited to prevent abuse.

## File Structure

```
.
├── api/
│   └── pamsikaClient.js          # API client for PamsikaOnline
├── config/
│   ├── company.json              # Company info and support contacts
│   ├── settings.json             # Bot settings and session config
│   └── translations.json         # Language translations
├── features/
│   ├── about.js                  # About Pamsika feature handler
│   ├── menu.js                   # Main menu and message routing
│   ├── orders.js                 # Order management feature
│   ├── ticketing.js              # Ticket purchase and QR code generation
│   └── ...                      # Other feature modules
├── sessions/                     # WhatsApp session and auth data
├── users/                        # User session and state data
├── utils/
│   ├── database.js               # Database utilities and statistics
│   ├── menuUtils.js              # Menu message utilities
│   ├── reminders.js              # Reminder utilities
│   └── user.js                  # User data management
├── bot.js                       # WhatsApp bot core logic and connection
├── cron.js                      # Scheduled tasks and cron jobs
├── database.json                # Orders and statistics data
├── server.js                    # Express server and API endpoints
├── package.json                 # Project dependencies and scripts
└── README.md                    # This file
```

## Contribution

Contributions are welcome! Please follow these guidelines:

- Fork the repository and create a feature branch.
- Write clear, concise commit messages.
- Ensure code follows existing style and conventions.
- Test your changes thoroughly.
- Submit a pull request describing your changes.

## Support and Contact

For support, please contact:

- Phone: +265 995 684 047
- Email: inquiries@pamsikaonline.com
- Website: [https://pamsikaonline.com](https://pamsikaonline.com)

---

Thank you for using the Pamsika WhatsApp Ticketing Bot!
