# WhatsApp Bot with AI and Academic Notifications

This project implements a multifunctional WhatsApp bot that uses the Baileys library for WhatsApp connection, OpenAI (GPT and DALL-E) for intelligent conversation capabilities and image generation, Prisma with a PostgreSQL database for data persistence, and `node-cron` for scheduling academic notifications.

The following sections detail how to install, configure, and use this bot.


## Installation Requirements

To implement and run this WhatsApp bot project, you will need the following software installed in your development environment or server:

1.  **Node.js**: The latest LTS version is recommended. Node.js is essential for running the bot's JavaScript code. You can download it from [https://nodejs.org/](https://nodejs.org/).
2.  **npm (Node Package Manager)**: Usually installed automatically with Node.js. npm is used to manage project dependencies.
3.  **PostgreSQL**: The project uses Prisma with a PostgreSQL database to store information about users, conversations, and messages. You will need a running PostgreSQL instance. You can download it from [https://www.postgresql.org/download/](https://www.postgresql.org/download/).
4.  **Git (Optional but recommended)**: To clone the repository if the source code is hosted on a platform like GitHub.

Once you have these prerequisites installed, you can proceed with the project setup.


### Project Dependencies

The project has a number of Node.js dependencies managed via npm. These dependencies will be installed automatically in one of the configuration steps, but it is useful to be aware of them:

*   **@hapi/boom**: For creating HTTP-friendly error objects.
*   **@prisma/client**: Prisma client to interact with the database.
*   **@whiskeysockets/baileys**: The main library for interacting with the WhatsApp Web API.
*   **dotenv**: To load environment variables from a `.env` file.
*   **node-cron**: For scheduling recurring tasks (cron jobs).
*   **openai**: Official OpenAI client for interacting with their AI models (GPT, DALL-E).
*   **pg**: PostgreSQL client for Node.js, used by Prisma.
*   **pino**: A very fast logger for Node.js.
*   **pino-pretty**: To format Pino output मानव-पठनीय during development.
*   **prisma**: Prisma CLI tool for database migrations and client generation.
*   **qrcode**: For generating QR codes, used for WhatsApp authentication.

It also includes `nodemon` as a development dependency to facilitate automatic server restarts during code changes.



## Configuration Steps

Follow these steps to configure the project in your local environment:

1.  **Get the Source Code**:
    *   If you have the project as a ZIP file (as in this case), unzip it to your desired directory.
    *   If it were in a Git repository, you would clone the repository: `git clone <REPOSITORY_URL>` and then navigate to the project directory: `cd project-directory-name`.

2.  **Install Project Dependencies**:
    Open a terminal in the project's root directory and run the following command to install all dependencies listed in the `package.json` file:
    ```bash
    npm install
    ```

3.  **Configure Environment Variables**:
    *   The project uses a `.env` file to manage environment variables. In the project's root directory, you will find a file named `.env` (which was included in the zip). You will need to edit this file with your own credentials and settings.
    *   Open the `.env` file with a text editor. You will need to configure the following variables:
        *   `OPENAI_API_KEY`: Your OpenAI API key. You can get it from [https://platform.openai.com/account/api-keys](https://platform.openai.com/account/api-keys).
        *   `DATABASE_URL`: The connection URL for your main PostgreSQL database. The general format is `postgresql://USER:PASSWORD@HOST:PORT/DATABASE_NAME`.
            For example: `postgresql://admin:password123@localhost:5432/whatsapp_bot_db`
        *   `ACADEMIC_DATABASE_URL`: The connection URL for your PostgreSQL database for academic notifications. This can be the same database or a different one, depending on your setup. Follow the same format as `DATABASE_URL`.
            For example: `postgresql://admin:password123@localhost:5432/academic_db`

    An example of the `.env` file content would be:
    ```env
    # OpenAI API Key
    OPENAI_API_KEY=your_openai_api_key_here

    # PostgreSQL
    DATABASE_URL="postgresql://your_user:your_password@your_host:5432/your_main_database"
    ACADEMIC_DATABASE_URL="postgresql://your_user:your_password@your_host:5432/your_academic_database"
    ```

4.  **Set Up PostgreSQL Database**:
    *   Ensure your PostgreSQL server is running.
    *   Create the databases you specified in the `DATABASE_URL` and `ACADEMIC_DATABASE_URL` variables (if they are different). You can use a PostgreSQL administration tool like `psql` or pgAdmin.
        For example, using `psql`:
        ```sql
        CREATE DATABASE whatsapp_bot_db;
        CREATE DATABASE academic_db; -- If it's a separate database
        ```

5.  **Apply Database Migrations with Prisma**:
    Prisma uses migrations to manage your database schema. To apply the migrations and create the necessary tables according to the `prisma/schema.prisma` file, run the following command in the terminal from the project's root directory:
    ```bash
    npx prisma migrate deploy
    ```
    This command will read the schema and apply the necessary changes to your PostgreSQL database.

6.  **Generate Prisma Client (Optional - Usually done with `migrate deploy`)**:
    If for some reason the Prisma client is not generated automatically, you can run:
    ```bash
    npx prisma generate
    ```
    This will generate the Prisma client in `node_modules/@prisma/client` based on your `schema.prisma`.

After completing these steps, the project should be configured and ready to run.



## Usage Instructions

Once the project is configured, follow these steps to start and use the WhatsApp bot:

1.  **Start the Bot**:
    *   Open a terminal in the project's root directory.
    *   Run the following command to start the bot:
        ```bash
        npm start
        ```
    *   If you prefer the bot to restart automatically when you make code changes (for development), you can use:
        ```bash
        npm run dev
        ```

2.  **Scan the QR Code**:
    *   When starting the bot for the first time, or if authentication credentials are invalid, a QR code will be generated in the terminal.
    *   Additionally, the bot will attempt to save this QR code as an image in the `src/qr/qr-code.png` file.
    *   Open WhatsApp on your mobile phone.
    *   Go to `Settings` > `Linked Devices` > `Link a Device`.
    *   Scan the QR code displayed in the terminal or in the image file.

3.  **Connection Confirmation**:
    *   Once the QR code is successfully scanned, the terminal will display a message indicating that the bot has connected to WhatsApp correctly.
    *   Session credentials will be saved in the `src/auth_info_baileys` folder. As long as this folder exists and the credentials are valid, you will not need to scan the QR code every time you start the bot.

4.  **Interact with the Bot**:
    *   You can now send messages to the WhatsApp number linked to the bot.
    *   **Natural Conversation**: Simply send text messages to the bot. The bot will use the OpenAI service to process your message and respond.
        *   Example: `"Hello, how are you?"`
        *   Example: `"Tell me a joke about programmers."`
    *   **Image Generation**: You can ask the bot to generate images.
        *   Example: `"Generate an image of an astronaut cat"`
    *   **Available Commands**: The bot also responds to specific commands starting with `!`. You can see the list of commands by sending `!menu` or `!help`.
        *   `!ping`: Responds with `pong 🏓` to check if the bot is active.
        *   `!menu` or `!help` or `!ayuda`: Displays the command menu and usage examples.
        *   `!info`: Displays information about the bot, such as its status and assistant version.

5.  **Academic Notifications (Cron Job)**:
    *   The bot has a feature to send scheduled academic notifications. This functionality runs in the background according to the configuration in `src/cron/academicNotifications.js` and uses the database specified in `ACADEMIC_DATABASE_URL`.

6.  **View Logs**:
    *   The bot uses `pino` to log information about its operation, including received messages, sent responses, and potential errors. These logs will be displayed in the terminal where the bot is running.

Remember that for the bot to function correctly, it must remain running on your server or development environment, and the internet connection must be stable.


## Troubleshooting

Here are some common problems and their possible solutions:

1.  **The bot does not start or closes unexpectedly**:
    *   **Check logs**: Review the terminal output for error messages. `pino` errors can provide clues about what is failing.
    *   **Environment variables**: Ensure the `.env` file is correctly configured and that all necessary variables (especially `OPENAI_API_KEY`, `DATABASE_URL`, `ACADEMIC_DATABASE_URL`) have valid values.
    *   **Dependencies**: Confirm that all dependencies were installed correctly with `npm install`. If in doubt, you can delete the `node_modules` folder and the `package-lock.json` file and run `npm install` again.
    *   **Node.js version**: Make sure you are using a compatible version of Node.js (LTS is recommended).

2.  **QR code is not generated or cannot be scanned**:
    *   **Internet connection**: Verify that the server running the bot has a stable internet connection.
    *   **Write permissions**: Ensure the script has permission to write to the `src/qr/` directory if you are trying to save the QR code as a file.
    *   **Terminal too small**: Sometimes, if the terminal window is too small, the QR code may not display correctly. Try enlarging the window.
    *   **WhatsApp client**: Make sure your WhatsApp application on your phone is up to date.

3.  **The bot disconnects frequently (loggedOut)**:
    *   This can happen if the WhatsApp session is invalidated. It might be because WhatsApp Web was used in another browser or computer, or due to WhatsApp policies.
    *   If you see the `DisconnectReason.loggedOut` error, you will need to delete the `src/auth_info_baileys` folder and restart the bot to scan a new QR code.

4.  **Errors related to Prisma or the database**:
    *   **Database connection**: Verify that the connection URL in `DATABASE_URL` (and `ACADEMIC_DATABASE_URL`) is correct and that the PostgreSQL server is accessible and running.
    *   **Database credentials**: Ensure that the database username and password are correct and that the user has the necessary permissions on the specified databases.
    *   **Migrations not applied**: If you see errors about tables or columns not existing, make sure you have run `npx prisma migrate deploy` correctly.
    *   **Prisma client not generated**: If there are errors related to the Prisma client, run `npx prisma generate`.

5.  **OpenAI API errors**:
    *   **Invalid API key**: Verify that your `OPENAI_API_KEY` in the `.env` file is correct and active.
    *   **API limits**: You might have reached your OpenAI account's usage limits. Check your OpenAI dashboard.
    *   **Network issues**: Ensure the server can connect to OpenAI's servers.

6.  **The bot does not respond to messages or responds incorrectly**:
    *   **Bot logs**: Check the logs to see if the message is being received and if there are errors during processing by the `assistantService`.
    *   **`assistantService` logic**: If the bot responds but incorrectly, the problem might be in the logic of `src/services/assistantService.js` or in how it interacts with the OpenAI API.
    *   **OpenAI API status**: Check the OpenAI API status, as there might be temporary service interruptions.

7.  **The academic notifications cron job does not work**:
    *   **Cron configuration**: Review the syntax and logic in `src/cron/academicNotifications.js`.
    *   **Connection to `ACADEMIC_DATABASE_URL`**: Ensure the connection to the academic database is correct and that the database contains the necessary data for notifications.
    *   **Logs**: Look for specific logs related to the cron job.

8.  **Problems with `npm install`**:
    *   **Dependency conflicts**: Conflicts can sometimes arise. Try deleting `package-lock.json` and `node_modules` and running `npm install` again.
    *   **Permissions**: On some systems, you might need `sudo` to install packages globally, although this is not recommended for project dependencies. Ensure you have write permissions in the project directory.

If you still have problems after checking these points, we recommend searching for the specific error message online or checking the issues in the Baileys repository or other involved libraries, as other users may have faced similar problems.

