commit 389a0baa9c8706e216042d5df7ad19176b721c57 Author: root Date: Thu Jan 15 00:13:51 2026 +0300 Added new codes diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..584ee46 Binary files /dev/null and b/.DS_Store differ diff --git a/Building a Professional Scheduler Bot MVP.html b/Building a Professional Scheduler Bot MVP.html new file mode 100644 index 0000000..bc6ffbf --- /dev/null +++ b/Building a Professional Scheduler Bot MVP.html @@ -0,0 +1,1111 @@ + + + + + + Building a Professional Scheduler Bot MVP + + + +
+ +
+
+

Upgrading to Scheduler Bot MVP

+
Slide 1 of 12
+
+ +
+
πŸ€–πŸ“…
+

From Basic Bot to Professional MVP

+

Transform your simple scheduler into a robust, user-friendly application

+
+ +
+

What You'll Build

+

A complete scheduler bot MVP with:

+
    +
  • Database for user-specific schedules
  • +
  • Interactive setup wizard
  • +
  • Multiple schedule management
  • +
  • Better error handling and UX
  • +
+
+ + +
+ + +
+
+

Analyzing Current Code Issues

+
Slide 2 of 12
+
+ +
πŸ”
+ +
+

Major Problems in Current Code:

+
    +
  • No Database: Single CSV file for all users
  • +
  • Fixed Schedule: Can't customize per user
  • +
  • Wrong Period Time: Period_7 has incorrect time (10:00-10:40)
  • +
  • Missing Periods: Only 7 periods instead of 13
  • +
  • No Error Handling: Crashes easily
  • +
  • Basic Features: Limited commands
  • +
+
+ +
+

Critical Bug Found!

+

In your current code, Period_7 has wrong times:

+
'Period_7': ('10:00', '10:40'), # WRONG! Should be 14:20-15:00
+

Also missing Periods 8-13 from your CSV template!

+
+ + +
+ + +
+
+

MVP Architecture Design

+
Slide 3 of 12
+
+ +
πŸ—οΈ
+ +
+

Choose: SQLite vs NoSQL

+

For our scheduler, SQLite is better because:

+
    +
  • Structured schedule data (days, periods, classes)
  • +
  • Easy queries (find classes by day/time)
  • +
  • Built into Python - no extra setup
  • +
  • Reliable and ACID compliant
  • +
+
+ +
+
+

Database Schema

+
    +
  • users table (user info)
  • +
  • classes table (schedule entries)
  • +
  • Simple, clean structure
  • +
+
+ +
+

Key Features

+
    +
  • User-specific schedules
  • +
  • Interactive setup wizard
  • +
  • Multiple schedule support
  • +
  • Better error handling
  • +
+
+
+ + +
+ + +
+
+

Step 1: Fix Period Times

+
Slide 4 of 12
+
+ +
⏰
+ +
+
+

Current (WRONG):

+
+ PERIOD_TIMES = { + 'Period_1': ('09:00', '09:40'), + 'Period_2': ('10:00', '10:40'), + 'Period_3': ('11:00', '11:40'), + 'Period_4': ('11:50', '12:30'), + 'Period_5': ('12:40', '13:20'), + 'Period_6': ('13:30', '14:10'), + 'Period_7': ('10:00', '10:40'), # WRONG! +} +
+
+
+

Fixed Version:

+
+ PERIODS = [ + (1, "09:00-09:40"), + (2, "10:00-10:40"), + (3, "11:00-11:40"), + (4, "11:50-12:30"), + (5, "12:40-13:20"), + (6, "13:30-14:10"), + (7, "14:20-15:00"), + (8, "15:20-16:00"), + (9, "16:15-16:55"), + (10, "17:05-17:45"), + (11, "17:55-18:35"), + (12, "18:45-19:20"), + (13, "19:20-20:00") +] +
+
+
+ +
+

Why This Matters:

+

Your current Period_7 (10:00-10:40) overlaps with Period_2! This causes wrong class detection.

+

The correct times match your CSV template with all 13 periods.

+
+ + +
+ + +
+
+

Step 2: Database Setup

+
Slide 5 of 12
+
+ +
πŸ—„οΈ
+ +
+

Create SQLite Database

+

Add this database class to your code:

+
+ +
+ import sqlite3 +import datetime + +class SimpleDatabase: + def __init__(self, db_file="schedule_bot.db"): + self.db_file = db_file + self.init_database() + + def init_database(self): + """Initialize database with tables""" + conn = sqlite3.connect(self.db_file) + cursor = conn.cursor() + + # Users table + cursor.execute(''' + CREATE TABLE IF NOT EXISTS users ( + user_id INTEGER PRIMARY KEY, + username TEXT, + first_name TEXT, + last_name TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + ) + ''') + + # Classes table - one row per class entry + cursor.execute(''' + CREATE TABLE IF NOT EXISTS classes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER, + day TEXT, + period INTEGER, + period_time TEXT, + subject TEXT, + class_group TEXT, + room TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users (user_id) + ) + ''') + + conn.commit() + conn.close() +
+ +
+

Test Database Setup:

+
+ # Initialize database
+ db = SimpleDatabase()
+ # Check if database file was created
+ print("Database initialized successfully") +
+
+ + +
+ + +
+
+

Step 3: Interactive Setup Wizard

+
Slide 6 of 12
+
+ +
πŸ§™β€β™‚οΈ
+ +
+

Add Conversation Handler

+

Replace your simple commands with an interactive setup:

+
+ +
+ from telegram.ext import ConversationHandler +from telegram import ReplyKeyboardMarkup, KeyboardButton + +# Conversation states +SELECT_DAY, SELECT_PERIOD, ENTER_SUBJECT, ENTER_GROUP, ENTER_ROOM = range(5) + +async def setup_start(update: Update, context: ContextTypes.DEFAULT_TYPE): + """Start the setup conversation""" + await update.message.reply_text( + "πŸ“… Let's add a class to your schedule.\n" + "First, select the day:", + reply_markup=ReplyKeyboardMarkup( + [["Monday"], ["Tuesday"], ["Wednesday"], + ["Thursday"], ["Friday"], ["Cancel"]], + resize_keyboard=True, one_time_keyboard=True + ) + ) + return SELECT_DAY +
+ +
+

Benefits:

+
    +
  • Users can create their own schedules
  • +
  • No need for CSV files
  • +
  • Interactive and user-friendly
  • +
  • Multiple schedules per user
  • +
+
+ + +
+ + +
+
+

Step 4: Enhanced Commands

+
Slide 7 of 12
+
+ +
🎯
+ +
+
+

Current Commands:

+
    +
  • /start - Basic welcome
  • +
  • /whereami - Current class
  • +
  • /schedule - Today's schedule
  • +
  • /tomorrow - Tomorrow's schedule
  • +
  • /help - Basic help
  • +
+
+
+

Enhanced MVP Commands:

+
    +
  • /setup - Interactive schedule setup
  • +
  • /whereami - Enhanced with next class info
  • +
  • /today - Today's detailed schedule
  • +
  • /tomorrow - Tomorrow's schedule
  • +
  • /week - Full weekly overview
  • +
  • /clear - Remove all classes
  • +
  • /help - Comprehensive help
  • +
+
+
+ +
+ async def where_am_i(update: Update, context: ContextTypes.DEFAULT_TYPE): + """Enhanced: Show current OR next class""" + user_id = update.effective_user.id + now = datetime.datetime.now() + current_day = now.strftime("%A") + current_time = now.strftime("%H:%M") + + # Get current class from database + current_class = db.get_current_class(user_id, current_day, current_time) + + if current_class: + response = f"🎯 You should be in class now!\nπŸ“š {current_class['subject']}" + else: + # Find next class + next_class = db.get_next_class(user_id, current_day, current_time) + if next_class: + response = f"βœ… Free period!\n➑️ Next: {next_class['subject']} at {next_class['time']}" + else: + response = f"πŸŽ‰ No more classes today!" +
+ + +
+ + +
+
+

Step 5: Better Error Handling

+
Slide 8 of 12
+
+ +
πŸ›‘οΈ
+ +
+

Current Issues:

+
    +
  • Crashes if CSV file missing
  • +
  • No user input validation
  • +
  • Poor error messages
  • +
  • No logging for debugging
  • +
+
+ +
+

Add Professional Error Handling:

+
+ import logging + +# Setup logging +logging.basicConfig( + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + level=logging.INFO +) +logger = logging.getLogger(__name__) + +def save_class(user_id, day, period, subject, group, room): + """Save class with error handling""" + try: + if not all([day, period, subject]): + raise ValueError("Missing required fields") + + db.save_class(user_id, day, period, subject, group, room) + logger.info(f"Class saved for user {user_id}") + return True + except Exception as e: + logger.error(f"Error saving class: {e}") + return False +
+
+ + +
+ + +
+
+

Step 6: Update Requirements

+
Slide 9 of 12
+
+ +
πŸ“¦
+ +
+
+

Current requirements.txt:

+
+ # Missing file or minimal content +
+
+
+

Updated requirements.txt:

+
+ python-telegram-bot==20.3 +python-dotenv==1.0.0 +pandas==2.1.0 # Optional for CSV import +
+
+
+ +
+

Environment Variables (.env file):

+
+ # Create .env file in project root
+ BOT_TOKEN=your_actual_bot_token_here
+ # Remove token from code for security! +
+
+ +
+

Install Dependencies:

+
+ pip install -r requirements.txt
+ # Or install individually:
+ pip install python-telegram-bot python-dotenv +
+
+ + +
+ + +
+
+

Complete MVP Structure

+
Slide 10 of 12
+
+ +
πŸ“
+ +
+

Project Structure:

+
+ +
+ scheduler_bot_mvp/ +β”œβ”€β”€ scheduler_bot.py # Main bot file +β”œβ”€β”€ requirements.txt # Dependencies +β”œβ”€β”€ .env # Environment variables +β”œβ”€β”€ schedule_bot.db # SQLite database (auto-created) +β”œβ”€β”€ simple_database.py # Database class (optional) +└── README.md # Documentation +
+ +
+
+

Database Functions:

+
    +
  • save_user() - Store user info
  • +
  • save_class() - Add class entry
  • +
  • get_user_classes() - Get schedule
  • +
  • get_current_class() - Find current
  • +
  • clear_schedule() - Remove all
  • +
+
+ +
+

Bot Commands:

+
    +
  • /setup - Interactive wizard
  • +
  • /whereami - Smart detection
  • +
  • /today - Daily schedule
  • +
  • /week - Weekly overview
  • +
  • /clear - Clean slate
  • +
+
+
+ + +
+ + +
+
+

Testing Your MVP

+
Slide 11 of 12
+
+ +
πŸ§ͺ
+ +
+

Step-by-Step Testing:

+
    +
  1. Run the bot: python scheduler_bot.py
  2. +
  3. Open Telegram and find your bot
  4. +
  5. Send /start command
  6. +
  7. Use /setup to add classes
  8. +
  9. Test /whereami throughout day
  10. +
  11. Try /today and /week
  12. +
  13. Test error cases (wrong inputs)
  14. +
+
+ +
+

Expected Behavior:

+
    +
  • βœ… Database file created automatically
  • +
  • βœ… Interactive setup works with keyboards
  • +
  • βœ… /whereami shows current or next class
  • +
  • βœ… /week displays full schedule
  • +
  • βœ… /clear removes all classes
  • +
  • βœ… Error messages are user-friendly
  • +
+
+ + +
+ + +
+
+

Next Steps & Challenges

+
Slide 12 of 12
+
+ +
πŸš€
+ +
+

Enhancement Challenges:

+
+ +
+
+

Easy Enhancements:

+
    +
  • Add /edit command to modify classes
  • +
  • Implement /export to generate CSV
  • +
  • Add /import from CSV feature
  • +
  • Create /reminders for upcoming classes
  • +
+
+ +
+

Advanced Features:

+
    +
  • Multiple schedule versions
  • +
  • Class notifications (10 min before)
  • +
  • Teacher/room-specific searches
  • +
  • Web interface for management
  • +
+
+
+ +
+

Key Improvements Made:

+
    +
  1. βœ… Fixed period times (all 13 periods)
  2. +
  3. βœ… Added SQLite database
  4. +
  5. βœ… Created interactive setup wizard
  6. +
  7. βœ… Enhanced commands with better UX
  8. +
  9. βœ… Added proper error handling
  10. +
  11. βœ… Implemented user-specific schedules
  12. +
+
+ + +
+ + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + + + \ No newline at end of file diff --git a/scheduler_bots/.DS_Store b/scheduler_bots/.DS_Store new file mode 100644 index 0000000..661d402 Binary files /dev/null and b/scheduler_bots/.DS_Store differ diff --git a/scheduler_bots/README.md b/scheduler_bots/README.md new file mode 100644 index 0000000..a45900e --- /dev/null +++ b/scheduler_bots/README.md @@ -0,0 +1,60 @@ +# Scheduler Bots + +This directory contains Telegram scheduler bots that help manage schedules. + +## Setup Instructions + +1. Create a virtual environment: + ``` + python -m venv venv + ``` + +2. Activate the virtual environment: + - On macOS/Linux: `source venv/bin/activate` + - On Windows: `venv\Scripts\activate` + +3. Install required packages: + ``` + pip install -r requirements.txt + ``` + +## Running the bots + +### Method 1: Using Python command (Recommended) +``` +python telegram_scheduler_v1.py +``` +or +``` +python telegram_scheduler_v2.py +``` + +### Method 2: Direct execution +Make sure you've activated the virtual environment first: +``` +source venv/bin/activate # On macOS/Linux +./telegram_scheduler_v1.py +``` +or +``` +./telegram_scheduler_v2.py +``` + +## Troubleshooting + +If you encounter "pandas library not found" error: + +1. Make sure you've activated the virtual environment: + ``` + source venv/bin/activate + ``` + +2. Verify pandas is installed: + ``` + pip list | grep pandas + ``` + +3. If not installed, install requirements: + ``` + pip install -r requirements.txt + ``` \ No newline at end of file diff --git a/scheduler_bots/requirements.txt b/scheduler_bots/requirements.txt new file mode 100644 index 0000000..c44578c --- /dev/null +++ b/scheduler_bots/requirements.txt @@ -0,0 +1,13 @@ +anyio==4.12.0 +certifi==2025.11.12 +h11==0.16.0 +httpcore==1.0.9 +httpx==0.28.1 +idna==3.11 +numpy==2.3.5 +pandas==2.3.3 +python-dateutil==2.9.0.post0 +python-telegram-bot==22.5 +pytz==2025.2 +six==1.17.0 +tzdata==2025.2 diff --git a/scheduler_bots/schedule_template RS.csv b/scheduler_bots/schedule_template RS.csv new file mode 100644 index 0000000..46d65d3 --- /dev/null +++ b/scheduler_bots/schedule_template RS.csv @@ -0,0 +1,11 @@ +Day,1 (9:00-9:40),2 (10:00-10:40),3 (11:00-11:40),4 (11:50-12:30),5 (12:40-13:20),6 (13:30-14:10),7 (14:20-15:00),8 (15:20-16:00),9 (16:15-16:55),10 (17:05-17:45),11 (17:55-18:35),12 (18:45-19:20),13 (19:20-20:00) +Monday,,"Subject: Maths Class: 2А/2Π’/2Π‘ E5 +Room: B24",,,Subject: ICT Class: 6A/6B Room: B24,,Subject: ICT Class: 7C/7D Room: B24,Subject: ICT Class: 10ABC Room: B24,Subject: ICT Class: 7A/7B Room: B24,,,, +Tuesday,"Subject: Π’Π΅Ρ…Π½ΠΎΡ‚Ρ€Π΅ΠΊ Class: 7A/7B/7C/7D/7E Room: B24, B02",Subject: Π’Π΅Ρ…Π½ΠΎΡ‚Ρ€Π΅ΠΊ Class: 6A/6B/6C/6D Room: B24,,,,,,Subject: ICT Class: 9ABC Room: B24,Subject: ICT Class: 8ABC Room: B24,Subject: ICT Class: 11A Room: B24,,, +Wednesday,,,,Subject: ICT Class: 6C/6D Room: B24,,"Subject: Maths Class: 1А/1Π’/1Π‘ E6 +Room: B24",,,,,,, +Thursday,,Subject: Π’Π΅Ρ…Π½ΠΎΡ‚Ρ€Π΅ΠΊ Class: 7A/7B/7C/7D/7E Room: B24,Subject: Π’Π΅Ρ…Π½ΠΎΡ‚Ρ€Π΅ΠΊ Class: 7A/7B/7C/7D/7E Room: B24,"Subject: Maths Class: 1А/1Π’/1Π‘ E6 +Room: B24",,,Subject: Maths Class: 2А/2Π’/2Π‘ E6 Room: B24,,Subject: ICT Class: 10ABC Room: B24,Subject: ICT Class: 11A Room: B24,,, +Friday,,,Subject: Π’Π΅Ρ…Π½ΠΎΡ‚Ρ€Π΅ΠΊ Class: 6A/6B/6C/6D Room: B24,Subject: Π’Π΅Ρ…Π½ΠΎΡ‚Ρ€Π΅ΠΊ Class: 6A/6B/6C/6D Room: B24,,Subject: ICT Class: 10ABC Room: B24,,,Subject: ICT Class: 11A Room: B24,,,, +Saturday,,,,,,,,,,,,, +Sunday,,,,,,,,,,,,, \ No newline at end of file diff --git a/scheduler_bots/telegram_scheduler_v2.py b/scheduler_bots/telegram_scheduler_v2.py new file mode 100644 index 0000000..3fe3034 --- /dev/null +++ b/scheduler_bots/telegram_scheduler_v2.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python +""" +Enhanced Scheduler Bot with CSV support +""" + +try: + import pandas as pd +except ImportError: + print("❌ Error: pandas library not found!") + print("Please install required packages using:") + print("pip install -r requirements.txt") + exit(1) + +import datetime +from telegram import Update +from telegram.ext import Application, CommandHandler, ContextTypes + +# πŸ”‘ REPLACE THIS with your bot token from @BotFather +BOT_TOKEN = "8248686383:AAGN5UJ73H9i7LQzIBR3TjuJgUGNTFyRHk8" + + +def load_schedule(): + """ + Load schedule from CSV file using pandas + Returns a dictionary with day-wise schedule + """ + try: + # Read CSV file + df = pd.read_csv('schedule.csv') + schedule = {} + + # Process each row (each day) + for _, row in df.iterrows(): + day = row['Day'] + schedule[day] = [] + + # Process each time slot column + time_slots = ['Period_1', 'Period_2', 'Period_3', 'Period_4', 'Period_5','Period_6', 'Period_7'] + + for slot in time_slots: + # Check if class exists for this time slot + if pd.notna(row[slot]) and str(row[slot]).strip(): + class_info = str(row[slot]) + schedule[day].append((slot, class_info)) + + return schedule + + except FileNotFoundError: + print("❌ Error: schedule.csv file not found!") + print("Please create schedule.csv in the same folder") + return {} + except Exception as e: + print(f"❌ Error loading schedule: {e}") + return {} + + +# Load schedule at startup +SCHEDULE = load_schedule() + +# Time mapping for periods +PERIOD_TIMES = { + 'Period_1': ('09:00', '09:40'), + 'Period_2': ('10:00', '10:40'), + 'Period_3': ('11:00', '11:40'), + 'Period_4': ('11:50', '12:30'), + 'Period_5': ('12:40', '13:20'), + 'Period_6': ('13:30', '14:10'), + 'Period_7': ('10:00', '10:40'), + +} + + +async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): + """Send welcome message when command /start is issued.""" + await update.message.reply_text( + "πŸ€– Hello! I'm your enhanced class scheduler bot!\n" + "Use /whereami to find your current class\n" + "Use /schedule to see today's full schedule\n" + "Use /tomorrow to see tomorrow's schedule\n" + "Use /help for all commands" + ) + + +async def where_am_i(update: Update, context: ContextTypes.DEFAULT_TYPE): + """Tell user where they should be right now.""" + if not SCHEDULE: + await update.message.reply_text("❌ Schedule not loaded. Check schedule.csv file.") + return + + now = datetime.datetime.now() + current_time = now.strftime("%H:%M") + current_day = now.strftime("%A") + + await update.message.reply_text(f"πŸ“… Today is {current_day}") + await update.message.reply_text(f"⏰ Current time: {current_time}") + + # Check if we have schedule for today + if current_day not in SCHEDULE: + await update.message.reply_text("😊 No classes scheduled for today!") + return + + # Find current class + found_class = False + for period, class_info in SCHEDULE[current_day]: + start_time, end_time = PERIOD_TIMES[period] + + if start_time <= current_time <= end_time: + await update.message.reply_text(f"🎯 You should be in: {class_info}") + found_class = True + break + + if not found_class: + await update.message.reply_text("😊 No class right now! Free period.") + + +async def schedule(update: Update, context: ContextTypes.DEFAULT_TYPE): + """Show today's full schedule.""" + if not SCHEDULE: + await update.message.reply_text("❌ Schedule not loaded. Check schedule.csv file.") + return + + current_day = datetime.datetime.now().strftime("%A") + + if current_day not in SCHEDULE or not SCHEDULE[current_day]: + await update.message.reply_text("😊 No classes scheduled for today!") + return + + schedule_text = f"πŸ“š {current_day}'s Schedule:\n\n" + for period, class_info in SCHEDULE[current_day]: + start, end = PERIOD_TIMES[period] + schedule_text += f"⏰ {start}-{end}: {class_info}\n" + + await update.message.reply_text(schedule_text) + + +async def tomorrow(update: Update, context: ContextTypes.DEFAULT_TYPE): + """Show tomorrow's schedule.""" + if not SCHEDULE: + await update.message.reply_text("❌ Schedule not loaded. Check schedule.csv file.") + return + + tomorrow_date = datetime.datetime.now() + datetime.timedelta(days=1) + tomorrow_day = tomorrow_date.strftime("%A") + + if tomorrow_day not in SCHEDULE or not SCHEDULE[tomorrow_day]: + await update.message.reply_text(f"😊 No classes scheduled for {tomorrow_day}!") + return + + schedule_text = f"πŸ“š {tomorrow_day}'s Schedule:\n\n" + for period, class_info in SCHEDULE[tomorrow_day]: + start, end = PERIOD_TIMES[period] + schedule_text += f"⏰ {start}-{end}: {class_info}\n" + + await update.message.reply_text(schedule_text) + + +async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE): + """Send help message with all commands.""" + await update.message.reply_text( + "Available commands:\n" + "/start - Start the bot\n" + "/whereami - Find your current class\n" + "/schedule - Show today's schedule\n" + "/tomorrow - Show tomorrow's schedule\n" + "/help - Show this help message" + ) + + +def main(): + """Start the bot.""" + if not SCHEDULE: + print("❌ Failed to load schedule. Please check schedule.csv file.") + print("Make sure schedule.csv exists in the same folder") + return + + # Create the Application + application = Application.builder().token(BOT_TOKEN).build() + + # Add command handlers + application.add_handler(CommandHandler("start", start)) + application.add_handler(CommandHandler("whereami", where_am_i)) + application.add_handler(CommandHandler("schedule", schedule)) + application.add_handler(CommandHandler("tomorrow", tomorrow)) + application.add_handler(CommandHandler("help", help_command)) + + # Start the Bot + print("πŸ€– Enhanced scheduler bot is running...") + print("πŸ“Š Schedule loaded successfully!") + print("πŸ“… Available days:", list(SCHEDULE.keys())) + print("Press Ctrl+C to stop the bot") + + application.run_polling() + + +if __name__ == "__main__": + main() \ No newline at end of file