Untitled
5 hours ago in Plain Text
import os
import logging
import re
from telegram import Update, ReplyKeyboardMarkup, KeyboardButton
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
from firebase_admin import credentials, firestore, initialize_app
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Set up logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
# Initialize Firebase
try:
# Use environment variables for Firebase credentials
firebase_config = {
"type": "service_account",
"project_id": os.getenv('FIREBASE_PROJECT_ID'),
"private_key_id": os.getenv('FIREBASE_PRIVATE_KEY_ID'),
"private_key": os.getenv('FIREBASE_PRIVATE_KEY').replace('\\n', '\n') if os.getenv('FIREBASE_PRIVATE_KEY') else None,
"client_email": os.getenv('FIREBASE_CLIENT_EMAIL'),
"client_id": os.getenv('FIREBASE_CLIENT_ID'),
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": os.getenv('FIREBASE_CLIENT_CERT_URL'),
"universe_domain": "googleapis.com"
}
# Check if all required environment variables are set
required_vars = ['FIREBASE_PROJECT_ID', 'FIREBASE_PRIVATE_KEY', 'FIREBASE_CLIENT_EMAIL']
missing_vars = [var for var in required_vars if not os.getenv(var)]
if missing_vars:
raise ValueError(f"Missing required environment variables: {', '.join(missing_vars)}")
cred = credentials.Certificate(firebase_config)
firebase_app = initialize_app(cred)
db = firestore.client()
logger.info("Firebase initialized successfully")
except Exception as e:
logger.error(f"Error initializing Firebase: {e}")
raise
# Telegram Bot Token
BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
if not BOT_TOKEN:
logger.error("TELEGRAM_BOT_TOKEN environment variable is not set")
raise ValueError("TELEGRAM_BOT_TOKEN environment variable is not set")
def normalize_phone_number(phone_number):
"""Normalize phone number by removing all non-digit characters except leading +"""
if not phone_number:
return ""
# If starts with +, keep it and remove all other non-digit characters
if phone_number.startswith('+'):
return '+' + re.sub(r'\D', '', phone_number[1:])
else:
# Otherwise, just remove all non-digit characters
return re.sub(r'\D', '', phone_number)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /start is issued."""
try:
user = update.effective_user
args = context.args
logger.info(f"Start command received from user {user.id} with args: {args}")
if args:
verification_code = args[0]
logger.info(f"Verification code: {verification_code}")
await handle_verification(update, context, verification_code)
else:
# Ask for phone number if no verification code provided
keyboard = [[KeyboardButton("Share Phone Number", request_contact=True)]]
reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True, one_time_keyboard=True)
await update.message.reply_text(
"Welcome to Dopamine Quiz Bot! 👋\n\n"
"To verify your phone number, please share your contact using the button below.",
reply_markup=reply_markup
)
except Exception as e:
logger.error(f"Error in start command: {e}", exc_info=True)
await update.message.reply_text("An error occurred. Please try again.")
async def handle_verification(update: Update, context: ContextTypes.DEFAULT_TYPE, verification_code: str) -> None:
"""Handle verification code from the start command."""
try:
logger.info(f"Handling verification for code: {verification_code}")
# Look up the verification code in Firestore
verification_ref = db.collection('telegramVerifications').document(verification_code)
verification_doc = verification_ref.get()
logger.info(f"Verification document exists: {verification_doc.exists}")
if not verification_doc.exists:
await update.message.reply_text("Invalid verification code. Please try again from the website.")
return
verification_data = verification_doc.to_dict()
logger.info(f"Verification data: {verification_data}")
user_id = verification_data.get('userId')
expected_phone = verification_data.get('phone')
if not user_id or not expected_phone:
logger.error("No user ID or phone found in verification data")
await update.message.reply_text("Invalid verification data. Please try again from the website.")
return
# Get the user document to check if it exists
user_ref = db.collection('users').document(user_id)
user_doc = user_ref.get()
logger.info(f"User document exists: {user_doc.exists}")
if not user_doc.exists:
await update.message.reply_text("User not found. Please try again from the website.")
return
# Check if user has a phone number in their Telegram profile
if not update.effective_user.phone_number:
await update.message.reply_text(
"Phone number not found in your Telegram profile. "
"Please share your contact using the button below.",
reply_markup=ReplyKeyboardMarkup(
[[KeyboardButton("Share Phone Number", request_contact=True)]],
resize_keyboard=True,
one_time_keyboard=True
)
)
return
# Get and normalize the phone numbers for comparison
user_phone = normalize_phone_number(update.effective_user.phone_number)
expected_phone_normalized = normalize_phone_number(expected_phone)
logger.info(f"User phone: {user_phone}, Expected phone: {expected_phone_normalized}")
# Verify that the phone numbers match
if user_phone != expected_phone_normalized:
await update.message.reply_text(
"❌ Phone number verification failed!\n\n"
f"Your Telegram phone number ({user_phone}) does not match "
f"the expected phone number ({expected_phone_normalized}).\n\n"
"Please make sure you're using the same phone number that you registered with."
)
return
# Update user document in Firestore to mark phone as verified
update_data = {
'phoneVerified': True,
'telegramUsername': update.effective_user.username,
'telegramId': update.effective_user.id,
'verifiedAt': firestore.SERVER_TIMESTAMP
}
logger.info(f"Updating user document with: {update_data}")
await user_ref.update(update_data)
# Delete the verification code to prevent reuse
verification_ref.delete()
logger.info("Verification document deleted")
await update.message.reply_text(
"✅ Your phone number has been verified successfully!\n\n"
"You can now return to the website to continue."
)
logger.info(f"User {user_id} verified successfully via code {verification_code}")
except Exception as e:
logger.error(f"Error in handle_verification: {e}", exc_info=True)
await update.message.reply_text("An error occurred during verification. Please try again.")
async def handle_contact(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle the user's shared contact."""
try:
contact = update.message.contact
user_id = contact.user_id
logger.info(f"Contact shared by user {user_id}")
if user_id and user_id != update.effective_user.id:
await update.message.reply_text("Please share your own contact information.")
return
phone_number = contact.phone_number
if not phone_number:
await update.message.reply_text("No phone number found in contact.")
return
logger.info(f"Phone number received: {phone_number}")
# Normalize the shared phone number
shared_phone_normalized = normalize_phone_number(phone_number)
logger.info(f"Normalized shared phone: {shared_phone_normalized}")
# Check if this phone number exists in any pending verification
verifications_ref = db.collection('telegramVerifications')
found = False
# We need to iterate through all verifications and compare normalized phone numbers
all_verifications = verifications_ref.stream()
for doc in all_verifications:
verification_data = doc.to_dict()
logger.info(f"Checking verification data: {verification_data}")
expected_phone = verification_data.get('phone')
user_id = verification_data.get('userId')
if not expected_phone or not user_id:
continue
# Normalize the expected phone number for comparison
expected_phone_normalized = normalize_phone_number(expected_phone)
if shared_phone_normalized == expected_phone_normalized:
# Get user document
user_ref = db.collection('users').document(user_id)
user_doc = user_ref.get()
if not user_doc.exists:
continue
# Update user document
await user_ref.update({
'phoneVerified': True,
'telegramUsername': update.effective_user.username,
'telegramId': update.effective_user.id,
'verifiedAt': firestore.SERVER_TIMESTAMP
})
# Delete the verification document
doc.reference.delete()
found = True
logger.info(f"User {user_id} verified successfully via contact sharing")
break
if found:
await update.message.reply_text(
"✅ Your phone number has been verified successfully!\n\n"
"You can now return to the website to continue."
)
else:
await update.message.reply_text(
"No pending verification found for this phone number. "
"Please start the verification process from the website first."
)
except Exception as e:
logger.error(f"Error in handle_contact: {e}", exc_info=True)
await update.message.reply_text("An error occurred while processing your contact. Please try again.")
async def debug_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Debug command to check bot status."""
try:
user = update.effective_user
message = (
f"🤖 *Bot Debug Information*\n\n"
f"*User ID:* {user.id}\n"
f"*Username:* {user.username}\n"
f"*First Name:* {user.first_name}\n"
f"*Last Name:* {user.last_name}\n"
f"*Phone:* {user.phone_number or 'Not available'}\n\n"
f"Bot is running correctly. Use /start with your verification code to begin."
)
await update.message.reply_text(message, parse_mode='Markdown')
except Exception as e:
logger.error(f"Error in debug_command: {e}")
await update.message.reply_text("Error generating debug information.")
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /help is issued."""
try:
await update.message.reply_text(
"🤖 *Dopamine Quiz Bot Help*\n\n"
"This bot helps verify your phone number for the Dopamine Quiz website.\n\n"
"*How to use:*\n"
"1. Start the verification process on the website\n"
"2. Click the 'Verify via Telegram' button\n"
"3. This bot will automatically verify your phone number\n\n"
"If you have any issues, please contact support.\n\n"
"Use /debug to check bot status.",
parse_mode='Markdown'
)
except Exception as e:
logger.error(f"Error in help_command: {e}")
async def status_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Check verification status."""
try:
# Check if user exists in our database
user_id = update.effective_user.id
users_ref = db.collection('users')
query = users_ref.where('telegramId', '==', user_id).stream()
verified = False
for doc in query:
user_data = doc.to_dict()
if user_data.get('phoneVerified'):
verified = True
break
if verified:
await update.message.reply_text(
"✅ Your phone number is already verified!\n\n"
"You can return to the website to continue."
)
else:
await update.message.reply_text(
"Your phone number is not yet verified.\n\n"
"Please start the verification process from the website first."
)
except Exception as e:
logger.error(f"Error in status_command: {e}")
await update.message.reply_text("An error occurred while checking your status. Please try again.")
async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Log errors caused by Updates."""
logger.error(f"Exception while handling an update: {context.error}", exc_info=context.error)
def main() -> None:
"""Start the bot."""
# Create the Application and pass it your bot's token.
application = Application.builder().token(BOT_TOKEN).build()
# Add handlers
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help_command))
application.add_handler(CommandHandler("status", status_command))
application.add_handler(CommandHandler("debug", debug_command))
application.add_handler(MessageHandler(filters.CONTACT, handle_contact))
# Add error handler
application.add_error_handler(error_handler)
# Run the bot until the user presses Ctrl-C
logger.info("Bot started successfully")
application.run_polling()
if __name__ == "__main__":
main()
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