File size: 44,836 Bytes
f959aff
 
 
 
 
 
 
 
 
479470a
f959aff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deb2780
479470a
 
f959aff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deb2780
 
f959aff
 
deb2780
 
f959aff
 
deb2780
 
f959aff
 
 
 
deb2780
 
f959aff
 
 
deb2780
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f959aff
 
 
 
 
 
 
 
deb2780
 
 
 
 
 
 
 
 
 
 
 
f959aff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deb2780
f959aff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deb2780
f959aff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
479470a
 
 
 
 
f959aff
479470a
f959aff
 
479470a
 
 
 
 
 
 
f959aff
 
 
479470a
 
 
 
 
f959aff
 
 
479470a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f959aff
 
 
 
 
 
 
 
479470a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
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())