-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1476 lines (1256 loc) · 66 KB
/
Copy pathmain.py
File metadata and controls
1476 lines (1256 loc) · 66 KB
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
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import asyncio
import logging
import qrcode
from PIL import Image, ImageDraw, ImageFont
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, BotCommand, LabeledPrice, InputMediaPhoto
from telegram.ext import Application, CommandHandler, MessageHandler, CallbackQueryHandler, ContextTypes, filters, PreCheckoutQueryHandler
from SecShare import SecShareBot
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
class TelegramSecShareBot:
def __init__(self, bot_token: str):
self.secshare = SecShareBot(bot_token)
self.application = Application.builder().token(bot_token).build()
# Telegram Stars configuration
self.stars_provider_token = os.getenv('STARS_PROVIDER_TOKEN')
self.contact_info = os.getenv('CONTACT_INFO', 'Contact admin for support')
self.premium_prices = {
'1day': LabeledPrice('SecShare Premium - 1 Day', 50), # 50 stars = $0.50
'1week': LabeledPrice('SecShare Premium - 1 Week', 150), # 150 stars = $1.50
'1month': LabeledPrice('SecShare Premium - 1 Month', 300), # 300 stars = $3.00
'3months': LabeledPrice('SecShare Premium - 3 Months', 500), # 500 stars = $5.00
'1year': LabeledPrice('SecShare Premium - 1 Year', 1000), # 1000 stars = $10.00
}
self._setup_handlers()
self._setup_commands()
def _setup_commands(self):
"""Setup bot commands for better UX"""
self.commands = [
BotCommand("start", "🚀 Start the bot"),
BotCommand("sendfile", "📁 Send a file"),
BotCommand("sendmessage", "💬 Send a message"),
BotCommand("receive", "📥 Receive a package"),
BotCommand("stats", "📊 View your usage stats"),
BotCommand("help", "❓ Get help"),
BotCommand("premium", "⭐ Upgrade to premium"),
BotCommand("airdrop", "📱 AirDrop-style sharing")
]
def _setup_handlers(self):
"""Setup all bot handlers"""
self.application.add_handler(CommandHandler("start", self.start_command))
self.application.add_handler(CommandHandler("sendfile", self.sendfile_command))
self.application.add_handler(CommandHandler("sendmessage", self.sendmessage_command))
self.application.add_handler(CommandHandler("receive", self.receive_command))
self.application.add_handler(CommandHandler("help", self.help_command))
self.application.add_handler(CommandHandler("stats", self.stats_command))
self.application.add_handler(CommandHandler("premium", self.premium_command))
self.application.add_handler(CommandHandler("airdrop", self.airdrop_command))
# Handle text messages (for password-protected transfers)
self.application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_text))
# Handle file uploads (documents, photos, videos, audio, voice)
self.application.add_handler(MessageHandler(filters.Document.ALL, self.handle_document))
self.application.add_handler(MessageHandler(filters.PHOTO, self.handle_photo))
self.application.add_handler(MessageHandler(filters.VIDEO, self.handle_video))
self.application.add_handler(MessageHandler(filters.AUDIO, self.handle_audio))
self.application.add_handler(MessageHandler(filters.VOICE, self.handle_voice))
# Handle callback queries (buttons)
self.application.add_handler(CallbackQueryHandler(self.handle_callback))
# Handle Telegram Stars payments
if self.stars_provider_token:
self.application.add_handler(PreCheckoutQueryHandler(self.precheckout_callback))
# Add handler for successful payments
self.application.add_handler(MessageHandler(filters.SUCCESSFUL_PAYMENT, self.successful_payment_callback))
async def precheckout_callback(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle pre-checkout queries for Telegram Stars"""
query = update.pre_checkout_query
await query.answer(ok=True)
async def successful_payment_callback(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle successful payments"""
payment_info = update.message.successful_payment
user_id = update.effective_user.id
# Determine subscription type based on amount
if payment_info.total_amount == 50: # 1 day
subscription_type = "1 day"
duration_days = 1
elif payment_info.total_amount == 150: # 1 week
subscription_type = "1 week"
duration_days = 7
elif payment_info.total_amount == 300: # 1 month
subscription_type = "1 month"
duration_days = 30
elif payment_info.total_amount == 500: # 3 months
subscription_type = "3 months"
duration_days = 90
elif payment_info.total_amount == 1000: # 1 year
subscription_type = "1 year"
duration_days = 365
else:
subscription_type = "unknown"
duration_days = 30
# Upgrade user to premium
user = self.secshare._get_user(user_id)
user.is_premium = True
self.secshare._save_data()
# Log the payment
logger.info(f"User {user_id} upgraded to premium ({subscription_type})")
# Send confirmation message
await update.message.reply_text(
f"🎉 Payment successful! You're now a SecShare Premium user!\n\n"
f"📅 Subscription: {subscription_type}\n"
f"⭐ Amount: {payment_info.total_amount} stars\n"
f"🔓 New limits: 1GB files, 20 transfers/day\n\n"
f"Thank you for upgrading! 🚀"
)
async def start_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /start command"""
user = update.effective_user
# Check if this is a transfer link (has start parameter)
if context.args:
transfer_id = context.args[0]
logger.info(f"User {user.id} accessed transfer via start command: {transfer_id}")
# Try to get the transfer
transfer = self.secshare.get_transfer(transfer_id)
if transfer:
if transfer.password_hash:
# Password protected - ask for password
context.user_data['waiting_for_password'] = transfer_id
await update.message.reply_text(
f"🔐 This transfer is password protected.\n\n"
f"📁 Type: {'File' if transfer.is_file else 'Message'}\n"
f"⏰ Expires: 15 minutes\n\n"
f"Please enter the password:"
)
else:
await self._send_transfer_content(update, transfer)
return
else:
await update.message.reply_text(
"❌ Transfer not found or expired.\n\n"
"The transfer may have:\n"
"• Expired (15 minutes)\n"
"• Been already received\n"
"• Been deleted\n\n"
"Please ask the sender to create a new transfer."
)
return
# Regular start command - show welcome message
welcome_text = f"""
🔐 Welcome to SecShare, {user.first_name}!
I'm your secure file and password sharing bot. Here's what I can do:
📤 Send Files: Upload any file and get a secure link
🔑 Send Messages: Share sensitive text securely
🔒 Password Protection: Add passwords to your transfers
⏰ Auto-Expiry: Transfers expire in 15 minutes
🗑️ Auto-Delete: Files are deleted after being received
Free Plan:
• 50MB max file size
• 5 transfers per day
• Basic encryption
Premium Plan:
• 1GB max file size
• 20 transfers per day
• Advanced security features
Just send me a file or text to get started!
Commands:
/sendfile - Send a file
/sendmessage - Send a message
/receive - Receive a package
/stats - View your usage stats
/help - Show this help
/premium - Upgrade to premium
"""
keyboard = [
[InlineKeyboardButton("📁 Send File", callback_data="send_file")],
[InlineKeyboardButton("💬 Send Message", callback_data="send_message")],
[InlineKeyboardButton("📥 Receive Package", callback_data="receive_package")],
[InlineKeyboardButton("📱 AirDrop Sharing", callback_data="airdrop")],
[InlineKeyboardButton("📊 My Stats", callback_data="stats")],
[InlineKeyboardButton("⭐ I'm Interested in Premium", callback_data="premium_interest")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(welcome_text, reply_markup=reply_markup)
async def sendfile_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /sendfile command"""
await update.message.reply_text(
"📁 Please upload the file you want to share securely.\n\n"
"Supported file types:\n"
"• Documents (PDF, DOC, TXT, etc.)\n"
"• Images (JPG, PNG, GIF, etc.)\n"
"• Videos (MP4, AVI, MOV, etc.)\n"
"• Audio files (MP3, WAV, etc.)\n"
"• Voice messages\n\n"
"Max size: 50MB (free) / 1GB (premium)"
)
async def sendmessage_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /sendmessage command"""
await update.message.reply_text(
"💬 Please type the message or password you want to share securely.\n\n"
"Your message will be encrypted and shared via a secure link."
)
context.user_data['waiting_for_message'] = True
async def receive_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /receive command"""
await update.message.reply_text(
"📥 To receive a package:\n\n"
"1. Click the secure link shared with you\n"
"2. Or paste the transfer ID here\n"
"3. Enter password if required\n"
"4. Confirm receipt to auto-delete\n\n"
"🔗 Paste the transfer ID or link here:"
)
context.user_data['waiting_for_transfer_id'] = True
async def help_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /help command"""
help_text = """
🔐 SecShare Help
Quick Commands:
/sendfile - Send a file
/sendmessage - Send a message
/receive - Receive a package
/stats - View your usage stats
/premium - Upgrade to premium
/airdrop - AirDrop-style sharing
How to use:
1. Send a File: Use /sendfile or upload any file
2. Send Text: Use /sendmessage or type your message
3. Add Password: Reply with a password when prompted
4. Share Link: Send the link to your recipient
5. QR Code: Generate QR code for easy sharing
6. Auto-Cleanup: Files are deleted after being received
Sharing Options:
• 🔗 Direct Link: Copy and share the secure link
• 📱 QR Code: Generate QR code for instant sharing
• 📤 Telegram Share: Use Telegram's built-in sharing
• 📱 AirDrop Style: Scan QR code for instant transfer
Supported File Types:
• Documents (PDF, DOC, TXT, etc.)
• Images (JPG, PNG, GIF, etc.)
• Videos (MP4, AVI, MOV, etc.)
• Audio files (MP3, WAV, etc.)
• Voice messages
Security Features:
• End-to-end encryption
• Password protection
• Auto-expiry (15 minutes)
• Secure file storage
• No logs kept
• QR code sharing
Need help? Use the "I'm Interested in Premium" button to contact support.
"""
await update.message.reply_text(help_text)
async def stats_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /stats command"""
user_id = update.effective_user.id
stats = self.secshare.get_user_stats(user_id)
stats_text = f"""
📊 Your Statistics
👤 Plan: {'⭐ Premium' if stats['is_premium'] else '🆓 Free'}
📤 Transfers Today: {stats['transfers_used_today']}/{stats['max_transfers_per_day']}
📈 Total Transfers: {stats['total_transfers']}
💾 Max File Size: {stats['max_file_size_mb']}MB
"""
keyboard = []
if not stats['is_premium']:
keyboard.append([InlineKeyboardButton("⭐ I'm Interested in Premium", callback_data="premium_interest")])
keyboard.append([InlineKeyboardButton("🔙 Back to Menu", callback_data="back_to_menu")])
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(stats_text, reply_markup=reply_markup)
async def premium_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /premium command with Telegram Stars integration"""
user_id = update.effective_user.id
user = self.secshare._get_user(user_id)
if user.is_premium:
premium_text = """
⭐ You're already a SecShare Premium user!
🔓 Your current benefits:
• 1GB max file size
• 20 transfers per day
• Advanced security features
• Priority support
Thank you for being a premium user! 🚀
"""
keyboard = [[InlineKeyboardButton("🔙 Back to Menu", callback_data="back_to_menu")]]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(premium_text, reply_markup=reply_markup)
return
if self.stars_provider_token:
# Show Telegram Stars payment options
premium_text = f"""
⭐ SecShare Premium
Upgrade to unlock advanced features:
🔓 Increased Limits:
• 1GB file size (vs 50MB free)
• 20 transfers per day (vs 5 free)
• Priority support
🔒 Enhanced Security:
• Advanced encryption
• Password protection
• Secure file transfer
💰 Pricing Options:
• 1 Day - ⭐ 50 stars
• 1 Week - ⭐ 150 stars
• 1 Month - ⭐ 300 stars
• 3 Months - ⭐ 500 stars
• 1 Year - ⭐ 1000 stars
⚠️ BETA WARNING:
This bot is currently in beta state. It is not recommended to make long-term purchases yet. For any questions, contact: {self.contact_info}
Choose your subscription plan:
"""
keyboard = [
[InlineKeyboardButton("💳 1 Day - ⭐ 50", callback_data="pay_1day")],
[InlineKeyboardButton("💳 1 Week - ⭐ 150", callback_data="pay_1week")],
[InlineKeyboardButton("💳 1 Month - ⭐ 300", callback_data="pay_1month")],
[InlineKeyboardButton("💳 3 Months - ⭐ 500", callback_data="pay_3months")],
[InlineKeyboardButton("💳 1 Year - ⭐ 1000", callback_data="pay_1year")],
[InlineKeyboardButton("🔙 Back to Menu", callback_data="back_to_menu")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(premium_text, reply_markup=reply_markup)
else:
# Fallback to admin notification
premium_text = f"""
⭐ SecShare Premium
Upgrade to unlock advanced features:
🔓 Increased Limits:
• 1GB file size (vs 50MB free)
• 20 transfers per day (vs 5 free)
• Priority support
🔒 Enhanced Security:
• Advanced encryption
• Password protection
• Secure file transfer
💰 Pricing:
• ⭐ 50 stars/day
• ⭐ 150 stars/week
• ⭐ 300 stars/month
• ⭐ 500 stars/3 months
• ⭐ 1000 stars/year
⚠️ BETA WARNING:
This bot is currently in beta state. It is not recommended to make long-term purchases yet. For any questions, contact: {self.contact_info}
Click the button below to express interest in premium features!
"""
keyboard = [[InlineKeyboardButton("⭐ I'm Interested in Premium", callback_data="premium_interest")]]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(premium_text, reply_markup=reply_markup)
async def airdrop_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /airdrop command for AirDrop-style sharing"""
airdrop_text = """
📱 SecShare AirDrop
Share files and messages instantly with nearby devices!
How it works:
1. 📤 Send a file or message
2. 📱 Generate QR code
3. 📱 Recipient scans QR code
4. ✅ Instant secure transfer
Features:
• 🔒 End-to-end encryption
• ⚡ Instant transfer
• 📱 QR code sharing
• 🗑️ Auto-cleanup
• 🔐 Password protection
Perfect for:
• 📄 Document sharing
• 🖼️ Photo sharing
• 🎵 Music sharing
• 🔑 Password sharing
• 📝 Note sharing
Just send me a file or message to get started!
"""
keyboard = [
[InlineKeyboardButton("📁 Send File", callback_data="send_file")],
[InlineKeyboardButton("💬 Send Message", callback_data="send_message")],
[InlineKeyboardButton("📥 Receive Package", callback_data="receive_package")],
[InlineKeyboardButton("📱 AirDrop Sharing", callback_data="airdrop")],
[InlineKeyboardButton("📊 My Stats", callback_data="stats")],
[InlineKeyboardButton("⭐ I'm Interested in Premium", callback_data="premium_interest")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(airdrop_text, reply_markup=reply_markup)
async def handle_text(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle text messages"""
user_id = update.effective_user.id
text = update.message.text
logger.info(f"Received text from user {user_id}: {text[:50]}...")
# Check if waiting for message
if context.user_data.get('waiting_for_message'):
logger.info(f"User {user_id} is waiting for message input")
del context.user_data['waiting_for_message']
try:
transfer_id = await self.secshare.create_text_transfer(user_id, text)
await self._send_transfer_link(update, transfer_id, "text")
logger.info(f"Created text transfer {transfer_id} for user {user_id}")
except ValueError as e:
await update.message.reply_text(f"❌ {str(e)}")
logger.error(f"Error creating text transfer for user {user_id}: {e}")
except Exception as e:
logger.error(f"Unexpected error creating text transfer for user {user_id}: {e}")
await update.message.reply_text("❌ An error occurred while creating your transfer. Please try again.")
return
# Check if waiting for transfer ID
if context.user_data.get('waiting_for_transfer_id'):
logger.info(f"User {user_id} is waiting for transfer ID input")
del context.user_data['waiting_for_transfer_id']
# Extract transfer ID from text (remove bot username if present)
transfer_id = text.split('/')[-1] if '/' in text else text
transfer_id = transfer_id.split('?start=')[-1] if '?start=' in transfer_id else transfer_id
logger.info(f"User {user_id} provided transfer ID: {transfer_id}")
transfer = self.secshare.get_transfer(transfer_id)
if transfer:
if transfer.password_hash:
context.user_data['waiting_for_password'] = transfer_id
await update.message.reply_text("🔐 This transfer is password protected. Please enter the password:")
else:
await self._send_transfer_content(update, transfer)
else:
await update.message.reply_text("❌ Transfer not found or expired.")
return
# Check if this is a password for a transfer
if 'waiting_for_password' in context.user_data:
transfer_id = context.user_data['waiting_for_password']
logger.info(f"User {user_id} provided password for transfer {transfer_id}")
transfer = self.secshare.get_transfer(transfer_id, text)
if transfer:
await self._send_transfer_link(update, transfer_id, "file" if transfer.is_file else "text", transfer.file_name if transfer.is_file else None)
del context.user_data['waiting_for_password']
else:
await update.message.reply_text("❌ Invalid password. Please try again.")
return
# Check if this is a transfer ID
if len(text) == 22 and text.replace('-', '').replace('_', '').isalnum():
logger.info(f"User {user_id} provided transfer ID directly: {text}")
transfer = self.secshare.get_transfer(text)
if transfer:
if transfer.password_hash:
context.user_data['waiting_for_password'] = text
await update.message.reply_text("🔐 This transfer is password protected. Please enter the password:")
else:
await self._send_transfer_content(update, transfer)
else:
await update.message.reply_text("❌ Transfer not found or expired.")
return
# Create a new text transfer (default behavior)
try:
logger.info(f"Creating default text transfer for user {user_id}")
logger.info(f"Text content length: {len(text)} characters")
logger.info(f"User data: {context.user_data}")
# Check if user exists and get their info
user = self.secshare._get_user(user_id)
logger.info(f"User info: {user}")
transfer_id = await self.secshare.create_text_transfer(user_id, text)
logger.info(f"Transfer created successfully: {transfer_id}")
await self._send_transfer_link(update, transfer_id, "text")
logger.info(f"Created default text transfer {transfer_id} for user {user_id}")
except ValueError as e:
await update.message.reply_text(f"❌ {str(e)}")
logger.error(f"ValueError creating default text transfer for user {user_id}: {e}")
logger.error(f"ValueError details: {type(e).__name__}: {str(e)}")
except Exception as e:
logger.error(f"Unexpected error creating default text transfer for user {user_id}: {e}")
logger.error(f"Exception type: {type(e).__name__}")
logger.error(f"Exception details: {str(e)}")
import traceback
logger.error(f"Full traceback: {traceback.format_exc()}")
await update.message.reply_text("❌ An error occurred while creating your transfer. Please try again.")
async def handle_document(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle document uploads"""
user_id = update.effective_user.id
document = update.message.document
logger.info(f"Received document from user {user_id}: {document.file_name} ({document.file_size} bytes)")
try:
# Check file size first
if document.file_size is None:
await update.message.reply_text("❌ Unable to determine file size. Please try again.")
return
# Ensure temp directory exists with proper permissions
temp_dir = self.secshare.config['temp_dir']
os.makedirs(temp_dir, exist_ok=True)
# Test write permissions
test_file = os.path.join(temp_dir, "test_write.tmp")
try:
with open(test_file, 'w') as f:
f.write("test")
os.remove(test_file)
except Exception as e:
logger.error(f"Temp directory not writable: {e}")
await update.message.reply_text("❌ Server storage error. Please try again later.")
return
# Download the file
file = await context.bot.get_file(document.file_id)
file_path = os.path.join(temp_dir, f"{document.file_id}_{document.file_name}")
logger.info(f"Downloading file to {file_path}")
await file.download_to_drive(file_path)
# Verify file was downloaded and has correct size
if not os.path.exists(file_path):
raise Exception("File download failed - file not found on disk")
actual_size = os.path.getsize(file_path)
if actual_size != document.file_size:
logger.warning(f"File size mismatch: expected {document.file_size}, got {actual_size}")
logger.info(f"File downloaded successfully: {file_path} ({actual_size} bytes)")
# Create transfer
transfer_id = await self.secshare.create_file_transfer(
user_id, file_path, document.file_name, document.file_size
)
logger.info(f"Created file transfer {transfer_id} for user {user_id}")
await self._send_transfer_link(update, transfer_id, "file", document.file_name)
except ValueError as e:
await update.message.reply_text(f"❌ {str(e)}")
logger.error(f"ValueError in document handling for user {user_id}: {e}")
except Exception as e:
logger.error(f"Error handling document for user {user_id}: {e}")
await update.message.reply_text("❌ An error occurred while processing your file. Please try again.")
# Clean up any partially downloaded file
if 'file_path' in locals() and os.path.exists(file_path):
try:
os.remove(file_path)
logger.info(f"Cleaned up partial file: {file_path}")
except Exception as cleanup_error:
logger.error(f"Failed to cleanup partial file: {cleanup_error}")
async def handle_photo(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle photo uploads"""
user_id = update.effective_user.id
photo = update.message.photo[-1] # Get the largest photo
try:
# Download the file
file = await context.bot.get_file(photo.file_id)
file_path = f"{self.secshare.config['temp_dir']}/{photo.file_id}_image.jpg"
await file.download_to_drive(file_path)
# Create transfer
transfer_id = await self.secshare.create_file_transfer(
user_id, file_path, "image.jpg", photo.file_size
)
await self._send_transfer_link(update, transfer_id, "file", "image.jpg")
except ValueError as e:
await update.message.reply_text(f"❌ {str(e)}")
except Exception as e:
logger.error(f"Error handling photo: {e}")
await update.message.reply_text("❌ An error occurred while processing your image.")
async def handle_video(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle video uploads"""
user_id = update.effective_user.id
video = update.message.video
try:
# Download the file
file = await context.bot.get_file(video.file_id)
file_path = f"{self.secshare.config['temp_dir']}/{video.file_id}_video.mp4"
await file.download_to_drive(file_path)
# Create transfer
transfer_id = await self.secshare.create_file_transfer(
user_id, file_path, "video.mp4", video.file_size
)
await self._send_transfer_link(update, transfer_id, "file", "video.mp4")
except ValueError as e:
await update.message.reply_text(f"❌ {str(e)}")
except Exception as e:
logger.error(f"Error handling video: {e}")
await update.message.reply_text("❌ An error occurred while processing your video.")
async def handle_audio(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle audio uploads"""
user_id = update.effective_user.id
audio = update.message.audio
try:
# Download the file
file = await context.bot.get_file(audio.file_id)
file_path = f"{self.secshare.config['temp_dir']}/{audio.file_id}_{audio.file_name or 'audio.mp3'}"
await file.download_to_drive(file_path)
# Create transfer
transfer_id = await self.secshare.create_file_transfer(
user_id, file_path, audio.file_name or "audio.mp3", audio.file_size
)
await self._send_transfer_link(update, transfer_id, "file", audio.file_name or "audio.mp3")
except ValueError as e:
await update.message.reply_text(f"❌ {str(e)}")
except Exception as e:
logger.error(f"Error handling audio: {e}")
await update.message.reply_text("❌ An error occurred while processing your audio.")
async def handle_voice(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle voice message uploads"""
user_id = update.effective_user.id
voice = update.message.voice
try:
# Download the file
file = await context.bot.get_file(voice.file_id)
file_path = f"{self.secshare.config['temp_dir']}/{voice.file_id}_voice.ogg"
await file.download_to_drive(file_path)
# Create transfer
transfer_id = await self.secshare.create_file_transfer(
user_id, file_path, "voice.ogg", voice.file_size
)
await self._send_transfer_link(update, transfer_id, "file", "voice.ogg")
except ValueError as e:
await update.message.reply_text(f"❌ {str(e)}")
except Exception as e:
logger.error(f"Error handling voice: {e}")
await update.message.reply_text("❌ An error occurred while processing your voice message.")
async def handle_callback(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle button callbacks"""
query = update.callback_query
await query.answer()
if query.data == "send_file":
await query.edit_message_text(
"📁 Please upload the file you want to share securely.\n\n"
"Supported file types:\n"
"• Documents (PDF, DOC, TXT, etc.)\n"
"• Images (JPG, PNG, GIF, etc.)\n"
"• Videos (MP4, AVI, MOV, etc.)\n"
"• Audio files (MP3, WAV, etc.)\n"
"• Voice messages\n\n"
"Max size: 50MB (free) / 1GB (premium)"
)
elif query.data == "send_message":
await query.edit_message_text(
"💬 Please type the message or password you want to share securely.\n\n"
"Your message will be encrypted and shared via a secure link."
)
context.user_data['waiting_for_message'] = True
elif query.data == "receive_package":
await query.edit_message_text(
"📥 To receive a package:\n\n"
"1. Click the secure link shared with you\n"
"2. Or paste the transfer ID here\n"
"3. Enter password if required\n"
"4. Confirm receipt to auto-delete\n\n"
"🔗 Paste the transfer ID or link here:"
)
context.user_data['waiting_for_transfer_id'] = True
elif query.data == "stats":
user_id = update.effective_user.id
stats = self.secshare.get_user_stats(user_id)
stats_text = f"""
📊 Your Statistics
👤 Plan: {'⭐ Premium' if stats['is_premium'] else '🆓 Free'}
📤 Transfers Today: {stats['transfers_used_today']}/{stats['max_transfers_per_day']}
📈 Total Transfers: {stats['total_transfers']}
💾 Max File Size: {stats['max_file_size_mb']}MB
"""
await query.edit_message_text(stats_text)
elif query.data == "airdrop":
airdrop_text = """
📱 SecShare AirDrop
Share files and messages instantly with nearby devices!
How it works:
1. 📤 Send a file or message
2. 📱 Generate QR code
3. 📱 Recipient scans QR code
4. ✅ Instant secure transfer
Features:
• 🔒 End-to-end encryption
• ⚡ Instant transfer
• 📱 QR code sharing
• 🗑️ Auto-cleanup
• 🔐 Password protection
Perfect for:
• 📄 Document sharing
• 🖼️ Photo sharing
• 🎵 Music sharing
• 🔑 Password sharing
• 📝 Note sharing
Just send me a file or message to get started!
"""
keyboard = [
[InlineKeyboardButton("📁 Send File", callback_data="send_file")],
[InlineKeyboardButton("💬 Send Message", callback_data="send_message")],
[InlineKeyboardButton("📥 Receive Package", callback_data="receive_package")],
[InlineKeyboardButton("🔙 Back to Menu", callback_data="back_to_menu")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(airdrop_text, reply_markup=reply_markup)
elif query.data == "pay_1day":
if self.stars_provider_token:
try:
await context.bot.send_invoice(
chat_id=update.effective_chat.id,
title="SecShare Premium - 1 Day",
description="Upgrade to SecShare Premium for 1 day",
payload="premium_1day",
provider_token=self.stars_provider_token,
currency="USD",
prices=[self.premium_prices['1day']],
start_parameter="premium_1day",
photo_url="https://your-bot-logo-url.com/logo.png", # Optional
photo_width=512,
photo_height=512,
photo_size=512,
need_name=False,
need_phone_number=False,
need_email=False,
need_shipping_address=False,
send_phone_number_to_provider=False,
send_email_to_provider=False,
is_flexible=False,
disable_notification=False,
protect_content=True
)
except Exception as e:
logger.error(f"Error sending 1 day invoice: {e}")
await query.edit_message_text("❌ Payment system temporarily unavailable. Please try again later.")
else:
await query.edit_message_text("❌ Payment system not configured.")
elif query.data == "pay_1week":
if self.stars_provider_token:
try:
await context.bot.send_invoice(
chat_id=update.effective_chat.id,
title="SecShare Premium - 1 Week",
description="Upgrade to SecShare Premium for 1 week",
payload="premium_1week",
provider_token=self.stars_provider_token,
currency="USD",
prices=[self.premium_prices['1week']],
start_parameter="premium_1week",
photo_url="https://your-bot-logo-url.com/logo.png", # Optional
photo_width=512,
photo_height=512,
photo_size=512,
need_name=False,
need_phone_number=False,
need_email=False,
need_shipping_address=False,
send_phone_number_to_provider=False,
send_email_to_provider=False,
is_flexible=False,
disable_notification=False,
protect_content=True
)
except Exception as e:
logger.error(f"Error sending 1 week invoice: {e}")
await query.edit_message_text("❌ Payment system temporarily unavailable. Please try again later.")
else:
await query.edit_message_text("❌ Payment system not configured.")
elif query.data == "pay_1month":
if self.stars_provider_token:
try:
await context.bot.send_invoice(
chat_id=update.effective_chat.id,
title="SecShare Premium - 1 Month",
description="Upgrade to SecShare Premium for 1 month",
payload="premium_1month",
provider_token=self.stars_provider_token,
currency="USD",
prices=[self.premium_prices['1month']],
start_parameter="premium_1month",
photo_url="https://your-bot-logo-url.com/logo.png", # Optional
photo_width=512,
photo_height=512,
photo_size=512,
need_name=False,
need_phone_number=False,
need_email=False,
need_shipping_address=False,
send_phone_number_to_provider=False,
send_email_to_provider=False,
is_flexible=False,
disable_notification=False,
protect_content=True
)
except Exception as e:
logger.error(f"Error sending 1 month invoice: {e}")
await query.edit_message_text("❌ Payment system temporarily unavailable. Please try again later.")
else:
await query.edit_message_text("❌ Payment system not configured.")
elif query.data == "pay_3months":
if self.stars_provider_token:
try:
await context.bot.send_invoice(
chat_id=update.effective_chat.id,
title="SecShare Premium - 3 Months",
description="Upgrade to SecShare Premium for 3 months",
payload="premium_3months",
provider_token=self.stars_provider_token,
currency="USD",
prices=[self.premium_prices['3months']],
start_parameter="premium_3months",
photo_url="https://your-bot-logo-url.com/logo.png", # Optional
photo_width=512,
photo_height=512,
photo_size=512,
need_name=False,
need_phone_number=False,
need_email=False,
need_shipping_address=False,
send_phone_number_to_provider=False,
send_email_to_provider=False,
is_flexible=False,
disable_notification=False,
protect_content=True
)
except Exception as e:
logger.error(f"Error sending 3 months invoice: {e}")
await query.edit_message_text("❌ Payment system temporarily unavailable. Please try again later.")
else:
await query.edit_message_text("❌ Payment system not configured.")
elif query.data == "pay_1year":
if self.stars_provider_token:
try:
await context.bot.send_invoice(
chat_id=update.effective_chat.id,
title="SecShare Premium - 1 Year",
description="Upgrade to SecShare Premium for 1 year",
payload="premium_1year",
provider_token=self.stars_provider_token,
currency="USD",
prices=[self.premium_prices['1year']],
start_parameter="premium_1year",
photo_url="https://your-bot-logo-url.com/logo.png", # Optional
photo_width=512,
photo_height=512,
photo_size=512,
need_name=False,
need_phone_number=False,
need_email=False,
need_shipping_address=False,
send_phone_number_to_provider=False,
send_email_to_provider=False,
is_flexible=False,
disable_notification=False,
protect_content=True
)
except Exception as e:
logger.error(f"Error sending 1 year invoice: {e}")
await query.edit_message_text("❌ Payment system temporarily unavailable. Please try again later.")
else:
await query.edit_message_text("❌ Payment system not configured.")
elif query.data == "premium_interest":
premium_interest_text = f"""
⭐ Interested in SecShare Premium?
Thank you for your interest! Premium features include:
🔓 Increased Limits:
• 1GB file size (vs 50MB free)
• 20 transfers per day (vs 5 free)
• Priority support
🔒 Enhanced Security:
• Advanced encryption
• Password protection
• Secure file transfer
💰 Pricing Options:
• 1 Day - ⭐ 50 stars
• 1 Week - ⭐ 150 stars
• 1 Month - ⭐ 300 stars
• 3 Months - ⭐ 500 stars
• 1 Year - ⭐ 1000 stars
For questions or support, contact: {self.contact_info}
Choose your subscription plan:
"""
keyboard = [
[InlineKeyboardButton("⭐ 1 Day - 50 stars", callback_data="pay_1day")],
[InlineKeyboardButton("⭐ 1 Week - 150 stars", callback_data="pay_1week")],
[InlineKeyboardButton("⭐ 1 Month - 300 stars", callback_data="pay_1month")],
[InlineKeyboardButton("⭐ 3 Months - 500 stars", callback_data="pay_3months")],
[InlineKeyboardButton("⭐ 1 Year - 1000 stars", callback_data="pay_1year")],
[InlineKeyboardButton("🔙 Back to Menu", callback_data="back_to_menu")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(premium_interest_text, reply_markup=reply_markup)
elif query.data == "back_to_menu":
welcome_text = f"""
🔐 Welcome to SecShare!
I'm your secure file and password sharing bot. Here's what I can do:
📤 Send Files: Upload any file and get a secure link
🔑 Send Messages: Share sensitive text securely