import logging from telegram import CallbackQuery, Update, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import Application, CommandHandler, CallbackQueryHandler, ContextTypes, MessageHandler, filters import requests import json from datetime import datetime, timedelta from monitor import EventMonitor from dotenv import load_dotenv import os import asyncio # Load environment variables load_dotenv() # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler('logs/telegram_bot.log'), logging.StreamHandler() ] ) logger = logging.getLogger(__name__) class WeBookBot: def __init__(self, token): self.token = token self.url = "https://cdn.webook.com/" self.headers = { "Accept": "*/*", "Accept-Encoding": "gzip, deflate, br, zstd", "Accept-Language": "en-US,en;q=0.9,ar;q=0.8", "Content-Type": "application/json", "Origin": "https://webook.com", "Referer": "https://webook.com/", "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", } self.monitor = EventMonitor(self) self.user_credentials = {} self.application = None self.is_running = False def _get_events_payload(self, category=None, date_filter=None, price_min=None, price_max=None, zones=None, country_code="SA", limit=20, skip=0): """Generate the payload for the events API request with flexible filtering using the getShows query.""" now = datetime.now() tomorrow = now + timedelta(days=1) end_of_week = now + timedelta(days=7) # --- Construct Date Filter Clause (based on the structure from the new query) --- # The new query uses an OR condition for schedules that includes # events without a close date or those ending after a certain time, # combined with specific date range checks. date_schedule_or_clauses = [] # Add the clause for events without a close date or ending from now onwards # (Adjusting "2025-05-28T22:00:00.000Z" to a dynamic current time or relevant start point) # Let's use the start of today as a general lower bound for events that should be considered "current" start_of_today = now.replace(hour=0, minute=0, second=0, microsecond=0) date_schedule_or_clauses.append({ "OR": [ {"schedule":{"closeDateTime_exists":False}}, {"schedule":{"closeDateTime_gte": start_of_today.strftime("%Y-%m-%dT%H:%M:%S.000Z")}} ] }) # Add specific date range clause based on date_filter date_range_and_clause = {} if date_filter == 'today': start_of_day = now.replace(hour=0, minute=0, second=0, microsecond=0) end_of_day = now.replace(hour=23, minute=59, second=59, microsecond=999999) # Events active at any point today date_range_and_clause = { "AND": [ {"schedule": {"openDateTime_lte": end_of_day.strftime("%Y-%m-%dT%H:%M:%S.000Z")}}, {"schedule": {"closeDateTime_gte": start_of_day.strftime("%Y-%m-%dT%H:%M:%S.000Z")}} ] } elif date_filter == 'tomorrow': tomorrow_start = tomorrow.replace(hour=0, minute=0, second=0, microsecond=0) tomorrow_end = tomorrow.replace(hour=23, minute=59, second=59, microsecond=999999) # Events active at any point tomorrow date_range_and_clause = { "AND": [ {"schedule": {"openDateTime_lte": tomorrow_end.strftime("%Y-%m-%dT%H:%M:%S.000Z")}}, {"schedule": {"closeDateTime_gte": tomorrow_start.strftime("%Y-%m-%dT%H:%M:%S.000Z")}} ] } elif date_filter == 'this_week': start_of_week = now.replace(hour=0, minute=0, second=0, microsecond=0) end_of_week = end_of_week.replace(hour=23, minute=59, second=59, microsecond=999999) # Events active at any point this week date_range_and_clause = { "AND": [ {"schedule": {"openDateTime_lte": end_of_week.strftime("%Y-%m-%dT%H:%M:%S.000Z")}}, {"schedule": {"closeDateTime_gte": start_of_week.strftime("%Y-%m-%dT%H:%M:%S.000Z")}} ] } if date_range_and_clause: date_schedule_or_clauses.append(date_range_and_clause) # --- Construct Category Filter Clause --- category_clause = {} if category: # category can be a single slug or a list of slugs if isinstance(category, str): category = [category] # The new query uses 'category' with 'slug_in' directly within an OR in the main AND category_clause = {"OR": [{"category": {"slug_in": category}}]} # Changed cmsTags to category # --- Construct Price Filter Clause --- price_clause = {} price_and_clauses = [] if price_min is not None: price_and_clauses.append({"startingPrice_gte": price_min}) if price_max is not None: price_and_clauses.append({"startingPrice_lte": price_max}) if price_and_clauses: price_clause = {"AND": price_and_clauses} # --- Construct Zone Filter Clause --- zone_clause = {} if zones: # zones should be a list of slugs zone_clause = {"OR":[{"zone":{"slug_in": zones}}]} # --- Construct Country Filter Clause --- country_clause = {} if country_code: country_clause = {"OR":[{"location":{"countryCode": country_code}}]} # --- Build the main 'AND' array for the 'where' clause --- # Following the structure of the provided query payload and_clauses = [] # Add the zone filter if present if zone_clause: and_clauses.append(zone_clause) # Add the category filter if present if category_clause: and_clauses.append(category_clause) and_clauses.append({}) # Placeholder like in the example # Add the price filter if present if price_clause: and_clauses.append(price_clause) and_clauses.append({}) # Placeholder like in the example # Add the combined date schedule OR clause if it has content if date_schedule_or_clauses: # If only the 'closeDateTime_exists' part is present, don't wrap in an extra OR if len(date_schedule_or_clauses) == 1 and "OR" in date_schedule_or_clauses[0]: and_clauses.append(date_schedule_or_clauses[0]) else: and_clauses.append({"OR": date_schedule_or_clauses}) # Add the country filter if present if country_clause: and_clauses.append(country_clause) # Filter out empty placeholder clauses, but be careful if a placeholder is intended # Based on the example, there seem to be two empty placeholders that are kept. # Let's keep any empty dictionaries explicitly added. # and_clauses = [clause for clause in and_clauses if clause] # Removed this line to keep explicit {} # --- Construct the final 'where' clause --- where_clause = { "visibility_not": "private", # The top-level OR from the example, handling events without end date or ending from now # We've integrated this logic into date_schedule_or_clauses now, so this is redundant here # "OR": [ # {"schedule":{"closeDateTime_exists":False}}, # {"schedule":{"closeDateTime_gte": now.strftime("%Y-%m-%dT%H:%M:%S.000Z")}} # ], } if and_clauses: where_clause["AND"] = and_clauses return { "query": """query getEventListing($lang:String,$limit:Int,$skip:Int,$where:EventFilter,$order:[EventOrder]){ eventCollection(locale:$lang,limit:$limit,skip:$skip,where:$where,order:$order){ total items{ __typename sys{id}id title subtitle slug ticketingUrlSlug image11{title sys{id publishedAt}url width height contentType} image31{title sys{id publishedAt}url width height contentType} startingPrice currencyCode schedule{title openTitle openDateTime closeDateTime openScheduleText} isStreamingEvent zoneEntryIncluded streamingUrl buttonLabel cardButtonLabel eventType buttonLink zone{id slug title zoneLogo{title sys{id publishedAt}url width height contentType} sponsorLogo{title sys{id publishedAt}url width height contentType}} location{title address city countryCode seactionHeader location{lat lon} banner{title sys{id publishedAt}url width height contentType} accessibility} category{id title slug} isComingSoon organizationSlug carousalCollection(limit:10){ items{title sys{id publishedAt}url width height contentType} } } } }""", "variables": { "order": ["sys_publishedAt_DESC"], "lang": "ar-SA", "limit": limit, "skip": skip, "where": where_clause, }, "operationName": "getEventListing" } async def start_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """Handle the /start command""" keyboard = [ [ InlineKeyboardButton("🔑 Login to WeBook", callback_data='login_webook'), InlineKeyboardButton("â„šī¸ Help", callback_data='help') ], [ InlineKeyboardButton("👤 Set Account Info", callback_data='set_account_info'), InlineKeyboardButton("📊 Account Status", callback_data='account_status') ], [ InlineKeyboardButton("đŸŽĢ Browse Events", callback_data='browse_events') ] ] reply_markup = InlineKeyboardMarkup(keyboard) await update.message.reply_text( 'Welcome to WeBook Events Bot! 🎉\n' 'Please select an option:', reply_markup=reply_markup ) async def set_account_info_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """Handle the /setinfoaccountwebook command""" await update.message.reply_text( "Please enter your WeBook credentials in the following format:\n" "email:your.email@example.com\n" "password:yourpassword" ) context.user_data['awaiting_credentials'] = True async def account_status_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """Handle the /stateloginwebook command""" user_id = update.effective_user.id if user_id in self.user_credentials: await update.message.reply_text( f"✅ WeBook Account Status:\n" f"Email: {self.user_credentials[user_id]['email']}\n" f"Status: Logged In" ) else: await update.message.reply_text( "❌ No WeBook account configured.\n" "Use /setinfoaccountwebook to set up your account." ) async def help_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """Handle the /help command""" help_text = ( "🤖 *WeBook Bot Commands*\n\n" "/start - Start the bot and show main menu\n" "/setinfoaccountwebook - Set your WeBook account credentials\n" "/stateloginwebook - Check your WeBook account status\n" "/help - Show this help message\n" "/info - Show bot information\n\n" "To use the bot:\n" "1. Set your WeBook credentials using /setinfoaccountwebook\n" "2. Login using the 'Login to WeBook' button\n" "3. Browse and book events!" ) await update.message.reply_text(help_text, parse_mode='Markdown') async def info_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """Handle the /info command""" info_text = ( "🤖 *WeBook Bot Information*\n\n" "Version: 1.0.0\n" "Description: A Telegram bot for browsing and booking events on WeBook\n" "Features:\n" "- Browse events by category\n" "- Filter events by date\n" "- Book events automatically\n" "- Monitor for new events\n" "- Account management" ) await update.message.reply_text(info_text, parse_mode='Markdown') async def handle_credentials_input(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """Handle user input for WeBook credentials""" if not context.user_data.get('awaiting_credentials'): return try: text = update.message.text.strip() email = None password = None for line in text.split('\n'): if line.startswith('email:'): email = line.split(':', 1)[1].strip() elif line.startswith('password:'): password = line.split(':', 1)[1].strip() if email and password: user_id = update.effective_user.id self.user_credentials[user_id] = { 'email': email, 'password': password } context.user_data['awaiting_credentials'] = False await update.message.reply_text( "✅ WeBook credentials saved successfully!\n" "You can now use the 'Login to WeBook' button to log in." ) else: await update.message.reply_text( "❌ Invalid format. Please use:\n" "email:your.email@example.com\n" "password:yourpassword" ) except Exception as e: logger.error(f"Error handling credentials: {e}") await update.message.reply_text("❌ Error saving credentials. Please try again.") async def handle_login(self, query: CallbackQuery, context: ContextTypes.DEFAULT_TYPE): """Handle WeBook login button click""" user_id = query.from_user.id if user_id not in self.user_credentials: await query.edit_message_text( "❌ No WeBook credentials found.\n" "Please use /setinfoaccountwebook to set up your account first." ) return try: # Create login instance login = WeBookLogin( email=self.user_credentials[user_id]['email'], password=self.user_credentials[user_id]['password'] ) # Attempt login page = login.login() if page: await query.edit_message_text( "✅ Successfully logged in to WeBook!\n" "You can now browse and book events." ) # Store the page object for future use context.user_data['webook_page'] = page else: await query.edit_message_text( "❌ Login failed. Please check your credentials and try again." ) except Exception as e: logger.error(f"Login error: {e}") await query.edit_message_text( "❌ An error occurred during login. Please try again later." ) async def button_callback(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """Handle button callbacks""" query = update.callback_query await query.answer() try: callback_data = query.data if callback_data == 'login_webook': await self.handle_login(query, context) elif callback_data == 'help': await self.help_command(update, context) elif callback_data == 'set_account_info': await self.set_account_info_command(update, context) elif callback_data == 'account_status': await self.account_status_command(update, context) elif callback_data == 'browse_events': # Show the original event browsing interface await self.start_command(update, context) elif callback_data.startswith('category_'): selected_category = callback_data.replace('category_', '') # Toggle category selection (assuming single selection for simplicity for now) if context.user_data.get('category') == selected_category: context.user_data['category'] = None # Deselect else: context.user_data['category'] = selected_category # Select # Update the message to reflect the selected filter current_filters_text = self._get_current_filters_text(context.user_data) await query.edit_message_text( f'Welcome to WeBook Events Bot! 🎉\n' f'Please select filters or "Show Events":\n{current_filters_text}', reply_markup=query.message.reply_markup # Keep the existing buttons ) return # Don't fetch events yet elif callback_data.startswith('date_'): selected_date_filter = callback_data.replace('date_', '') # Toggle date filter selection (assuming single selection) if context.user_data.get('date_filter') == selected_date_filter: # Decide if you want to allow deselecting date, or keep a default # For now, let's allow changing but not deselecting to None pass # Do nothing if same button clicked again else: context.user_data['date_filter'] = selected_date_filter # Select # Update the message to reflect the selected filter current_filters_text = self._get_current_filters_text(context.user_data) await query.edit_message_text( f'Welcome to WeBook Events Bot! 🎉\n' f'Please select filters or "Show Events":\n{current_filters_text}', reply_markup=query.message.reply_markup # Keep the existing buttons ) return # Don't fetch events yet elif callback_data == 'reset_filters': # Reset all filters to default context.user_data['category'] = None context.user_data['date_filter'] = 'tomorrow' context.user_data['price_min'] = None context.user_data['price_max'] = None context.user_data['zones'] = None context.user_data['country_code'] = 'SA' # Update the message to reflect the reset filters current_filters_text = self._get_current_filters_text(context.user_data) await query.edit_message_text( f'Welcome to WeBook Events Bot! 🎉\n' f'Filters have been reset. Please select filters or "Show Events":\n{current_filters_text}', reply_markup=query.message.reply_markup # Keep the existing buttons ) return # Don't fetch events yet # --- Handle Pagination Button Presses --- elif callback_data.startswith('page_'): try: # callback_data will be 'page_X' where X is the new skip value new_skip = int(callback_data.replace('page_', '')) # Get current filters and total events from user_data current_category = context.user_data.get('category') current_date_filter = context.user_data.get('date_filter') current_price_min = context.user_data.get('price_min') current_price_max = context.user_data.get('price_max') current_zones = context.user_data.get('zones') current_country_code = context.user_data.get('country_code') current_limit = 10 # Assuming limit is always 20 for pagination # Update skip value in user_data context.user_data['skip'] = new_skip # Fetch events for the new page payload = self._get_events_payload( category=current_category, date_filter=current_date_filter, price_min=current_price_min, price_max=current_price_max, zones=current_zones, country_code=current_country_code, limit=current_limit, skip=new_skip # Use the new skip value ) response = requests.post(self.url, headers=self.headers, json=payload) response.raise_for_status() events = response.json()["data"]["eventCollection"]["items"] total_events = response.json()["data"]["eventCollection"]["total"] # Get total count # Indicate current filters applied in the response message filter_info = self._get_current_filters_text(context.user_data) if not events: # This shouldn't happen if total_events > 0, but as a fallback await query.edit_message_text(f"No events found for this page.\n{filter_info}") return # Format events into a readable card list with numbers message_parts = [f"đŸŽĢ Upcoming Events (Filtered - Page {int(new_skip/current_limit) + 1}/{int(total_events/current_limit) + (1 if total_events % current_limit > 0 else 0)} of {total_events}):\n{filter_info}\n"] # Add page info and total count for i, event in enumerate(events): # Display event number based on the current page and index event_number = new_skip + i + 1 message_parts.append(f"--- Event {event_number} ---") # Separator for cards message_parts.append(f"🏆 *{event.get('title', 'N/A')}*") # Bold title if event.get('subtitle'): message_parts.append(f"_{event.get('subtitle')}_") # Italic subtitle location_title = event.get('location', {}).get('title', 'N/A') message_parts.append(f"📍 Location: {location_title}") price = event.get('startingPrice', 'N/A') currency = event.get('currencyCode', 'N/A') message_parts.append(f"💰 Starting Price: {price} {currency}") # Price info # Display schedule dates more clearly open_date = event.get('schedule', {}).get('openDateTime') close_date = event.get('schedule', {}).get('closeDateTime') schedule_text = "🕒 Schedule: " if open_date: try: open_dt = datetime.fromisoformat(open_date.replace('Z', '+00:00')) schedule_text += f"Starts: {open_dt.strftime('%Y-%m-%d %H:%M')}" except ValueError: schedule_text += f"Starts: {open_date}" if close_date: try: close_dt = datetime.fromisoformat(close_date.replace('Z', '+00:00')) schedule_text += f", Ends: {close_dt.strftime('%Y-%m-%d %H:%M')}" except ValueError: schedule_text += f", Ends: {close_date}" if not open_date and not close_date: schedule_text += "Info Not Available" message_parts.append(schedule_text) # Optional: Add a link if available ticketing_slug = event.get('ticketingUrlSlug') if ticketing_slug and ticketing_slug != 'N/A': message_parts.append(f"[More Info/Tickets](https://webook.com/ar/events/{ticketing_slug})") message_parts.append("") # Add an empty line for spacing between cards # Add pagination and select buttons below the list pagination_buttons = [] # Check if there's a previous page if new_skip > 0: pagination_buttons.append(InlineKeyboardButton("âŦ…ī¸ Back", callback_data=f'page_{max(0, new_skip - current_limit)}')) # Check if there's a next page if new_skip + len(events) < total_events: pagination_buttons.append(InlineKeyboardButton("âžĄī¸ Next", callback_data=f'page_{new_skip + current_limit}')) # Add the "Select Event" button select_button = [InlineKeyboardButton("👆 Select Event by Number", callback_data='prompt_select_event')] # New callback data # Combine pagination and select buttons keyboard = [pagination_buttons] if pagination_buttons else [] keyboard.append(select_button) reply_markup = InlineKeyboardMarkup(keyboard) # Join all parts to form the final message message = "\n".join(message_parts) # Send the formatted message and update the buttons await query.edit_message_text(text=message, reply_markup=reply_markup, parse_mode='Markdown', disable_web_page_preview=True) # Use Markdown for bold/italic except (ValueError, TypeError) as e: logger.error(f"Error parsing page number from callback data: {e}") await query.edit_message_text("Sorry, there was an error processing the page request.") except Exception as e: logger.error(f"Error fetching paginated events: {str(e)}") await query.edit_message_text( "Sorry, there was an error fetching the next page of events. Please try again later." ) return # Handled pagination, return # --- Handle "Show Events" Button Press --- elif callback_data == 'show_events': # Fetch events with the selected filters from user_data current_category = context.user_data.get('category') current_date_filter = context.user_data.get('date_filter') current_price_min = context.user_data.get('price_min') current_price_max = context.user_data.get('price_max') current_zones = context.user_data.get('zones') current_country_code = context.user_data.get('country_code') # Reset skip to 0 for a new search context.user_data['skip'] = 0 current_limit = 10 payload = self._get_events_payload( category=current_category, date_filter=current_date_filter, price_min=current_price_min, price_max=current_price_max, zones=current_zones, country_code=current_country_code, limit=current_limit, # Pass limit skip=0 # Start from the first page ) response = requests.post(self.url, headers=self.headers, json=payload) response.raise_for_status() events = response.json()["data"]["eventCollection"]["items"] total_events = response.json()["data"]["eventCollection"]["total"] # Get total count # Indicate current filters applied in the response message filter_info = self._get_current_filters_text(context.user_data) if not events: await query.edit_message_text(f"No events found for the selected filters.\n{filter_info}") return # Store total events for pagination reference context.user_data['total_events'] = total_events # Store the currently displayed events to easily retrieve details when selecting by number context.user_data['current_event_list'] = events # Format events into a readable card list with numbers message_parts = [f"đŸŽĢ Upcoming Events (Filtered - Page 1/{int(total_events/current_limit) + (1 if total_events % current_limit > 0 else 0)} of {total_events}):\n{filter_info}\n"] # Add page info and total count for i, event in enumerate(events): # Display event number based on the current page (always 1 for initial show) and index event_number = context.user_data['skip'] + i + 1 message_parts.append(f"--- Event {event_number} ---") # Separator for cards message_parts.append(f"🏆 *{event.get('title', 'N/A')}*") # Bold title if event.get('subtitle'): message_parts.append(f"_{event.get('subtitle')}_") # Italic subtitle location_title = event.get('location', {}).get('title', 'N/A') message_parts.append(f"📍 Location: {location_title}") price = event.get('startingPrice', 'N/A') currency = event.get('currencyCode', 'N/A') message_parts.append(f"💰 Starting Price: {price} {currency}") # Price info # Display schedule dates more clearly open_date = event.get('schedule', {}).get('openDateTime') close_date = event.get('schedule', {}).get('closeDateTime') schedule_text = "🕒 Schedule: " if open_date: try: open_dt = datetime.fromisoformat(open_date.replace('Z', '+00:00')) schedule_text += f"Starts: {open_dt.strftime('%Y-%m-%d %H:%M')}" except ValueError: schedule_text += f"Starts: {open_date}" if close_date: try: close_dt = datetime.fromisoformat(close_date.replace('Z', '+00:00')) schedule_text += f", Ends: {close_dt.strftime('%Y-%m-%d %H:%M')}" except ValueError: schedule_text += f", Ends: {close_date}" if not open_date and not close_date: schedule_text += "Info Not Available" message_parts.append(schedule_text) # Optional: Add a link if available ticketing_slug = event.get('ticketingUrlSlug') if ticketing_slug and ticketing_slug != 'N/A': message_parts.append(f"[More Info/Tickets](https://webook.com/ar/events/{ticketing_slug})") message_parts.append("") # Add an empty line for spacing between cards # Add pagination and select buttons below the list pagination_buttons = [] # Check if there's a next page on the initial load if len(events) < total_events: pagination_buttons.append(InlineKeyboardButton("âžĄī¸ Next", callback_data=f'page_{current_limit}')) # Next page starts after the first limit # Add the "Select Event" button select_button = [InlineKeyboardButton("👆 Select Event by Number", callback_data='prompt_select_event')] # New callback data # Combine pagination and select buttons keyboard = [pagination_buttons] if pagination_buttons else [] keyboard.append(select_button) reply_markup = InlineKeyboardMarkup(keyboard) # Join all parts to form the final message message = "\n".join(message_parts) # Send the formatted message and update the buttons await query.edit_message_text(text=message, reply_markup=reply_markup, parse_mode='Markdown', disable_web_page_preview=True) # Use Markdown for bold/italic # --- Handle Prompt Select Event Button Press --- elif callback_data == 'prompt_select_event': await query.edit_message_text( f"{query.message.text_markdown_v2}\n\n" # Keep the existing event list f"Please reply with the number of the event you want to select (e.g., `1`, `5`, `12`)." # Prompt the user # Note: We cannot keep inline buttons here and also wait for a text reply easily. # A full ConversationHandler is needed for that. For simplicity, # we remove the inline buttons and expect a text reply. # You might want to add a "Cancel" button if you implement ConversationHandler. ) # You might set a state here in user_data if you implement a MessageHandler context.user_data['awaiting_event_number'] = True elif callback_data == 'start_monitoring': # Start monitoring setup flow await self._start_monitoring_setup(query, context) elif callback_data == 'stop_monitoring': # Stop monitoring user_id = query.from_user.id if await self.monitor.stop_monitoring(user_id): await query.edit_message_text( "✅ Event monitoring stopped successfully." ) else: await query.edit_message_text( "❌ No active monitoring found." ) else: # Handle other potential buttons here if needed await query.edit_message_text("Unknown button pressed.") return except Exception as e: logger.error(f"Error processing callback: {str(e)}") logger.error(f"Response content: {response.text if 'response' in locals() else 'No response'}") await query.edit_message_text( "Sorry, there was an error processing your request. Please try again later." ) async def _start_monitoring_setup(self, query: CallbackQuery, context: ContextTypes.DEFAULT_TYPE): """Start the monitoring setup process""" keyboard = [ [InlineKeyboardButton("🌍 Select Country", callback_data='monitor_country')], [InlineKeyboardButton("📅 Select Date Filter", callback_data='monitor_date')], [InlineKeyboardButton("đŸŽ¯ Select Category", callback_data='monitor_category')], [InlineKeyboardButton("💰 Set Price Range", callback_data='monitor_price')], [InlineKeyboardButton("✅ Start Monitoring", callback_data='confirm_monitoring')] ] reply_markup = InlineKeyboardMarkup(keyboard) await query.edit_message_text( "🔍 *Event Monitoring Setup*\n\n" "Please configure your monitoring preferences:", reply_markup=reply_markup, parse_mode='Markdown' ) # Initialize monitoring filters in user_data context.user_data['monitoring_filters'] = { 'country_code': 'SA', 'date_filter': 'today', 'category': None, 'price_min': None, 'price_max': None } def _get_current_filters_text(self, user_data): """Helper function to generate text summarizing current filters.""" category = user_data.get('category') date_filter = user_data.get('date_filter') price_min = user_data.get('price_min') price_max = user_data.get('price_max') zones = user_data.get('zones') country_code = user_data.get('country_code') filter_parts = [] filter_parts.append(f"Date: {date_filter.replace('_', ' ').title() if date_filter else 'Any'}") filter_parts.append(f"Category: {category if category else 'All'}") if price_min is not None or price_max is not None: price_text = "Price: " if price_min is not None: price_text += f"From {price_min} " if price_max is not None: price_text += f"To {price_max}" filter_parts.append(price_text) if zones: filter_parts.append(f"Zones: {', '.join(zones)}") if country_code: filter_parts.append(f"Country: {country_code}") return "Current Filters:\n" + "\n".join(filter_parts) async def handle_event_number_input(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """Handle the user's reply with an event number.""" # Check if the bot is expecting an event number from this user if context.user_data.get('awaiting_event_number'): try: event_number_str = update.message.text.strip() event_number = int(event_number_str) # Get the current list of events displayed to the user (this is just the current page) # Note: This logic is simplified. A robust solution should fetch the event # details based on the global index (event_number) and the full search results. # For now, let's try to find the event in the *currently displayed* list. current_events_on_page = context.user_data.get('current_event_list', []) current_skip = context.user_data.get('skip', 0) # Find the event corresponding to the number on the current page # event_number is 1-based global index. We need the 0-based index on the current page. event_index_on_page = event_number - 1 - current_skip if 0 <= event_index_on_page < len(current_events_on_page): selected_event = current_events_on_page[event_index_on_page] # Found the event. Now you can ask "what offer want" or proceed to booking. # For now, just confirm the selection. await update.message.reply_text( f"You selected event number {event_number}:\n" f"🏆 *{selected_event.get('title', 'N/A')}*\n" f"📍 Location: {selected_event.get('location', {}).get('title', 'N/A')}\n" f"What offer would you like to select for this event?" # Placeholder for next step , parse_mode='Markdown' ) # Reset the state context.user_data['awaiting_event_number'] = False context.user_data.pop('current_event_list', None) # Clear temporary data context.user_data.pop('skip', None) context.user_data.pop('total_events', None) else: # Number is out of range for the current page or invalid based on global index await update.message.reply_text( f"Invalid event number '{event_number_str}'. Please reply with a number from the list above." # You might want to redisplay the list or provide a "Cancel" option. ) # Keep state active to allow another attempt except ValueError: # User did not send a valid number await update.message.reply_text( f"That doesn't look like a number. Please reply with the number of the event you want to select." # Keep state active ) except Exception as e: logger.error(f"Error handling event number input: {e}") await update.message.reply_text("Sorry, there was an error processing your selection.") # Reset state on error context.user_data['awaiting_event_number'] = False context.user_data.pop('current_event_list', None) context.user_data.pop('skip', None) context.user_data.pop('total_events', None) async def send_message(self, user_id: int, message: str): """Helper method to send messages to users""" try: await self.application.bot.send_message( chat_id=user_id, text=message, parse_mode='Markdown', disable_web_page_preview=True ) except Exception as e: logger.error(f"Error sending message to user {user_id}: {e}") async def _make_request(self, payload: dict): """Make API request to WeBook""" response = requests.post(self.url, headers=self.headers, json=payload) response.raise_for_status() return response.json() async def start_bot(self): """Start the bot asynchronously""" if self.is_running: return False, "Bot is already running" try: self.application = Application.builder().token(self.token).build() # Add handlers self.application.add_handler(CommandHandler("start", self.start_command)) self.application.add_handler(CommandHandler("setinfoaccountwebook", self.set_account_info_command)) self.application.add_handler(CommandHandler("stateloginwebook", self.account_status_command)) self.application.add_handler(CommandHandler("help", self.help_command)) self.application.add_handler(CommandHandler("info", self.info_command)) self.application.add_handler(CallbackQueryHandler(self.button_callback)) self.application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_credentials_input)) # Start the bot logger.info("Starting bot...") await self.application.initialize() await self.application.start() await self.application.run_polling() self.is_running = True return True, "Bot started successfully" except Exception as e: logger.error(f"Error running bot: {str(e)}") self.is_running = False return False, f"Error starting bot: {str(e)}" async def stop_bot(self): """Stop the bot""" if not self.is_running: return False, "Bot is not running" try: if self.application: await self.application.stop() await self.application.shutdown() self.is_running = False return True, "Bot stopped successfully" return False, "No application instance found" except Exception as e: logger.error(f"Error stopping bot: {str(e)}") return False, f"Error stopping bot: {str(e)}" if __name__ == "__main__": # Get bot token from environment variable BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN') if not BOT_TOKEN: raise ValueError("TELEGRAM_BOT_TOKEN not found in environment variables") bot = WeBookBot(BOT_TOKEN) asyncio.run(bot.start_bot())