Skip to content

Petrosbid/nut_telegramBot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🍽️ University Food Reservation Telegram Bot

Python Telegram License

A comprehensive, automated Telegram bot for managing food reservations at the University of Kerman (Shahid Bahonar University). This intelligent bot provides seamless meal booking, automated reminders, credit charging, and smart food basket management directly through Telegram.

📋 Table of Contents

✨ Features

🔐 Authentication & User Management

  • Secure Login System: Integrated captcha-solving login flow with university credentials
  • Session Management: Persistent session management with automatic keep-alive
  • User Preferences: Store and manage user preferences including name, gender, and settings
  • Privacy Controls: Complete data deletion capability with confirmation dialog

🍜 Food Menu & Reservations

  • Daily Menu Viewing: View today's food menu without login
  • Weekly Menu Access: Browse current and next week's food options
  • Automated Reservations: Select and reserve meals automatically for any day
  • Meal Type Selection: Choose from breakfast, lunch, and dinner options
  • Menu Caching: Optimized menu data caching for faster access

🤖 Automated Systems

  • Daily Menu Reminders: Get automatic reminders about daily food options (configurable schedule)
  • Reservation Reminders: Automated reminders for next week's reservations
  • Smart Queue System: Automatic food basket purchasing with intelligent queue management
  • Status Monitoring: Real-time credit balance and reservation status checks
  • Background Processing: Asynchronous job scheduler for all automated tasks

💳 Credit Management

  • Balance Checking: Real-time credit balance monitoring
  • Quick Charge Options: Pre-defined charge amounts (50K, 100K, 200K, 500K)
  • Custom Amount Charging: User-defined charge amounts
  • Low Credit Alerts: Automatic notifications when credit is below threshold (200,000)

🧺 Food Basket System

  • Multi-Site Support: Choose from different campus cafeterias
  • Automated Queue Processing: Automated food searching and purchasing
  • Queue Status Tracking: Real-time position monitoring in purchase queue
  • Smart Food Selection: Automatically find preferred food options

📊 Status & Monitoring

  • Comprehensive Status Dashboard: View credit, current reservations, and pending actions
  • Reservation History: Track all current week's reservations
  • Credit Alerts: Get notified about low credit situations
  • Queue Management: Monitor and manage your place in food basket queue

🚀 Key Highlights

  • 100% Automated: Fully automated reservation and purchase system
  • Smart Scheduling: APScheduler-powered automated task execution
  • Web Scraping: Selenium-based web scraping for university portal interaction
  • Database-Driven: SQLite database for user data and menu caching
  • Persian Language Support: Complete RTL support with Jalali date system
  • Async/Await Architecture: Built with modern Python async/await patterns
  • Session Persistence: Maintains logged-in sessions across operations
  • Error Handling: Comprehensive error handling and logging system

🛠️ Technology Stack

Core Technologies

  • Python 3.8+: Modern Python with async/await support
  • python-telegram-bot: Advanced Telegram Bot API framework
  • Selenium: Web automation and scraping
  • SQLite3: Lightweight database for user management
  • APScheduler: Advanced task scheduling

Key Libraries

  • telegram: Telegram Bot API wrapper
  • selenium: Web driver automation
  • beautifulsoup4: HTML parsing and content extraction
  • jdatetime: Persian (Jalali) date system support
  • httpx: Async HTTP client
  • apscheduler: Task scheduling framework

📦 Installation

Prerequisites

  • Python 3.8 or higher
  • Chrome browser (for Selenium)
  • Telegram Bot Token from @BotFather

Step 1: Clone the Repository

git clone https://github.com/yourusername/nut_telegramBot.git
cd nut_telegramBot

Step 2: Install Dependencies

pip install -r requirements.txt

Step 3: Configure the Bot

  1. Get your Telegram bot token from @BotFather
  2. Open main.py and update the TOKEN variable:
TOKEN = "YOUR_BOT_TOKEN_HERE"

Step 4: Run the Bot

python main.py

⚙️ Configuration

Environment Variables

The bot requires the following configuration in main.py:

TOKEN = "YOUR_BOT_TOKEN"              # Telegram Bot API Token
DB_FILE = "food_bot.db"                # SQLite database file
LOW_CREDIT_THRESHOLD = 200000          # Credit alert threshold
LOGIN_URL = "https://nut.uk.ac.ir/Login.aspx"  # University login page
RESERVATION_URL = "https://nut.uk.ac.ir/Reservation/Reservation.aspx"  # Reservation page

Adjusting Reminder Times

Default reminder schedules:

  • Daily Menu Reminder: 10:00 AM (configurable in scheduler)
  • Reservation Reminder: Triggered when next week becomes available
  • Low Credit Alerts: Automatic on status check

📱 Usage

Starting the Bot

  1. Open Telegram and search for your bot
  2. Send /start command
  3. Choose from available options

Available Commands

Core Commands

  • /start - Show main menu and start interaction
  • /logout - Log out from university portal
  • /cancel - Cancel current operation
  • /todaymenu - View today's food menu
  • /menu - Return to main menu
  • /refresh - Refresh menu cache manually
  • /deletedata - Delete stored user data

Natural Language Commands

  • غذای امروز چیه - What's today's food? (Persian)
  • منوی امروز - Today's menu (Persian)

Main Features Usage

1. Login to University System

/start → "ورود به سایت دانشگاه" → Enter credentials → Solve captcha

2. View Today's Menu

/start → "امروز غذا چی داریم؟"

No login required!

3. Make a Reservation

Login → "رزرو/مشاهده غذا (این هفته)" → Select meal type → Select date → Confirm

4. Charge Credit

Login → "افزایش اعتبار" → Select amount or enter custom → Confirm → Proceed to payment

5. Food Basket Automation

Login → "خرید از سبد غذایی" → Select cafeteria → Select meal → Select food → Join queue

6. Check Status

Login → "بررسی وضعیت کلی"

View credit balance, reservations, and queue status.

7. Manage Reminders

From main menu (no login required):

  • Enable/disable daily menu reminders
  • Enable/disable next week reservation reminders

📁 Project Structure

nut_telegramBot/
├── main.py                      # Main bot application
├── food_bot.db                  # SQLite database
├── user_data.json              # User session data (generated)
├── basket.html                  # Basket interface template
├── charge.html                  # Charge interface template
├── login_page.html             # Login interface template
├── menu_next_week.HTML         # Menu template
├── verify.html                  # Verification template
├── captcha.png                 # Captcha image
├── chrome.exe                   # Chrome driver
└── README.md                    # This file

Key Components in main.py

  • WebScraper Class: Handles all web scraping and university portal interactions
  • Database Functions: User management and menu caching
  • Bot Handlers: Message and callback handlers for all bot features
  • Scheduler Tasks: Automated reminder and processing jobs
  • Conversation States: State machine for managing user flows

🎯 Key Features Explained

1. Web Scraping System

The bot uses Selenium WebDriver to:

  • Log into the university portal
  • Parse food menus from HTML
  • Handle CAPTCHA solving with user input
  • Perform automated form submissions
  • Maintain session cookies

2. Database Architecture

SQLite database with three main tables:

  • users: User credentials, preferences, and settings
  • menu_cache: Cached food menus by date and meal type
  • food_basket_queue: Queue management for automated purchases

3. Automated Scheduler

APScheduler manages:

  • Daily menu reminder jobs
  • Reservation reminder jobs
  • Food basket processing queue
  • Session keep-alive tasks

4. Queue System

Intelligent food basket queue:

  • Automatically processes food purchases
  • Handles multiple users simultaneously
  • Updates user on queue status
  • Allows manual queue cancellation

🗄️ Database Schema

Users Table

CREATE TABLE users (
    chat_id INTEGER PRIMARY KEY,
    full_name TEXT,
    gender TEXT,
    username TEXT NOT NULL,
    password TEXT NOT NULL,
    reservation_reminder_enabled BOOLEAN DEFAULT FALSE,
    daily_menu_reminder_enabled BOOLEAN DEFAULT FALSE,
    next_week_reservation_reminder_enabled BOOLEAN DEFAULT FALSE
);

Menu Cache Table

CREATE TABLE menu_cache (
    date_jalali TEXT NOT NULL,
    meal_type TEXT NOT NULL,
    week_type TEXT NOT NULL,
    food_options_json TEXT,
    PRIMARY KEY (date_jalali, meal_type, week_type)
);

Food Basket Queue Table

CREATE TABLE food_basket_queue (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    chat_id INTEGER NOT NULL,
    cafeteria TEXT NOT NULL,
    meal_type TEXT NOT NULL,
    food_name TEXT NOT NULL,
    queue_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
    status TEXT DEFAULT 'waiting'
);

🔧 API Reference

WebScraper Methods

  • login(username, password, captcha) - Authenticate user
  • get_full_menu_state(week_type) - Fetch complete menu
  • reserve_food(date, meal_type, food_name) - Make reservation
  • charge_credit(amount) - Process credit charge
  • get_credit_balance() - Get current balance
  • get_current_reservations() - Get all active reservations
  • logout() - End session

Bot Commands

All commands use the standard Telegram Bot API with ConversationHandler pattern for multi-step interactions.

🐛 Troubleshooting

Common Issues

1. Bot Not Responding

  • Check if bot is running
  • Verify TOKEN is correct
  • Check internet connection

2. Login Failed

  • Verify university credentials
  • Ensure CAPTCHA is solved correctly
  • Check if university site is accessible

3. Web Scraping Errors

  • Ensure Chrome browser is installed
  • Check if chrome.exe is in project directory
  • Verify university site structure hasn't changed

4. Database Errors

  • Delete food_bot.db and restart bot
  • Check file permissions
  • Ensure SQLite3 is installed

5. Scheduler Not Working

  • Check bot is running continuously
  • Verify APScheduler is installed
  • Check system time settings

Debug Mode

Enable detailed logging:

logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    level=logging.DEBUG  # Change from INFO to DEBUG
)

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Development Guidelines

  • Follow PEP 8 style guide
  • Add comments for complex logic
  • Update this README for new features
  • Test thoroughly before submitting PR

📝 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • University of Kerman (Shahid Bahonar University) for the food portal
  • python-telegram-bot developers
  • Selenium WebDriver contributors
  • Persian (Jalali) date system support: jdatetime

📞 Support

For support, issues, or feature requests:

  • Open an issue on GitHub
  • Contact the bot administrator
  • Check existing issues for solutions

📊 Project Statistics

  • Total Lines of Code: 2,200+
  • Database Tables: 3
  • Bot States: 15 conversation states
  • Automated Jobs: Multiple scheduled tasks
  • Supported Meal Types: Breakfast, Lunch, Dinner
  • Language Support: Persian (Farsi) with RTL text

🔮 Future Enhancements

Potential improvements:

  • Multi-language support (English)
  • User statistics and analytics
  • Food rating system
  • Notification preferences per user
  • Bulk reservation feature
  • Admin panel for statistics
  • Docker containerization
  • Redis caching layer
  • REST API for external integrations

Made with ❤️ for University Students

Automate your food reservations, save time, never miss a meal!

About

automated Telegram bot for managing food reservations at nut website

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages