-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1394 lines (1202 loc) · 55 KB
/
main.py
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 telebot
from telebot import types
from pymongo import MongoClient
import logging
from datetime import datetime, timedelta
import sqlite3
import requests
import os
from dotenv import load_dotenv
import validators
import hashlib
import json
import uuid
import base64
# 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__)
# Get environment variables
ADMIN_CHAT_ID = int(os.getenv('ADMIN_CHAT_ID'))
BOT_TOKEN = os.getenv('BOT_TOKEN')
MONGO_URL = os.getenv('MONGO_URL')
TRANZZO_TOKEN = os.getenv('TRANZZO_TOKEN')
PAYPAL_WEEK_INVOICE = os.getenv('PAYPAL_WEEK_INVOICE')
PAYPAL_MONTH_INVOICE = os.getenv('PAYPAL_MONTH_INVOICE')
CRYPTOCLOUD_TOKEN = os.getenv('CRYPTOCLOUD_TOKEN')
CRYPTOCLOUD_SHOP_ID = os.getenv('CRYPTOCLOUD_SHOP_ID')
KOFI_1WEEK = os.getenv('KOFI_1WEEK')
KOFI_1MONTH = os.getenv('KOFI_1MONTH')
CRYPTOMUS_MERCHANT_ID = os.getenv('CRYPTOMUS_MERCHANT_ID')
CRYPTOMUS_API_KEY = os.getenv('CRYPTOMUS_API_KEY')
OXAPAY_MERCHANT_KEY = os.getenv('OXAPAY_MERCHANT_KEY')
# MongoDB setup
client = MongoClient(MONGO_URL)
db = client['redeem_db']
one_week_prem = db['1week_prem']
one_month_prem = db['1month_prem']
users_collection = db['users']
transactionsCollection = db['transactions']
# Initialize bot
bot = telebot.TeleBot(BOT_TOKEN)
def check_user_id(user_id):
# Convert user_id to string before checking
user = users_collection.find_one({'user_id': str(user_id)})
if user is None:
return False
# Check if premium has expired
if 'expiry' in user and user['expiry']:
if user['expiry'] < datetime.now():
# Remove expired user
users_collection.delete_one({'user_id': str(user_id)})
one_week_prem.delete_one({'user_id': str(user_id)})
one_month_prem.delete_one({'user_id': str(user_id)})
return False
return True
# Function to create the premium keyboard
def create_premium_keyboard():
keyboard = types.InlineKeyboardMarkup(row_width=1)
# Add buy premium button
buy_premium = types.InlineKeyboardButton(
text="Buy Premium",
callback_data="buy_premium"
)
# Add other buttons
report_button = types.InlineKeyboardButton(
text="Report Problem or Suggestion",
callback_data="report_problem"
)
link_button = types.InlineKeyboardButton(
text="Visit our Telegram",
url="https://t.me/nekozuX"
)
keyboard.add(buy_premium, report_button, link_button)
return keyboard
def payment_methods_keyboard():
keyboard = types.InlineKeyboardMarkup(row_width=1)
# Add premium options
stars_button = types.InlineKeyboardButton(
text="Telegram Stars",
callback_data="stars_payment"
)
paypal_button = types.InlineKeyboardButton(
text="Paypal",
callback_data="paypal_payment"
)
crypto_button = types.InlineKeyboardButton(
text="Crypto",
callback_data="crypto_payment"
)
kofi_button = types.InlineKeyboardButton(
text="Kofi",
callback_data="kofi_payment"
)
backs = types.InlineKeyboardButton(
text="Back",
callback_data="back"
)
keyboard.add(stars_button, paypal_button, crypto_button, kofi_button, backs)
return keyboard
def paypal_keyboard():
keyboard = types.InlineKeyboardMarkup(row_width=1)
week_button = types.InlineKeyboardButton(
text="1 Week Premium (€1/1$)",
url=PAYPAL_WEEK_INVOICE
)
month_button = types.InlineKeyboardButton(
text="1 Month Premium (€6/6$)",
url=PAYPAL_MONTH_INVOICE
)
photo_button = types.InlineKeyboardButton(
text="Send Payment Screenshot",
callback_data="send_payment_screenshot"
)
backs = types.InlineKeyboardButton(
text="Back",
callback_data="back"
)
keyboard.add(week_button, month_button, photo_button, backs)
return keyboard
def paynow(payment_type):
keyboard = types.InlineKeyboardMarkup(row_width=1)
# Add premium options with appropriate callback data
week_button = types.InlineKeyboardButton(
text="1 Week Premium" + (" (46 Stars)"),
callback_data=f"{payment_type}_week"
)
month_button = types.InlineKeyboardButton(
text="1 Month Premium" + (" (276 Stars)"),
callback_data=f"{payment_type}_month"
)
backs = types.InlineKeyboardButton(
text="Back",
callback_data="back"
)
keyboard.add(week_button, month_button, backs)
return keyboard
def kofi():
keyboard = types.InlineKeyboardMarkup(row_width=1)
week_button = types.InlineKeyboardButton(
text="1 Week Premium (€1/1$)",
url=KOFI_1WEEK
)
month_button = types.InlineKeyboardButton(
text="1 Month Premium (€6/6$)",
url=KOFI_1MONTH
)
photo_button = types.InlineKeyboardButton(
text="Send Kofi Payment link",
callback_data="send_payment_link"
)
backs = types.InlineKeyboardButton(
text="Back",
callback_data="back"
)
keyboard.add(week_button, month_button, photo_button, backs)
return keyboard
def setup_database():
try:
# Use /tmp directory for SQLite database on Vercel
db_path = '/tmp/support_bot.db'
with sqlite3.connect(db_path) as conn:
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS conversations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
status TEXT NOT NULL,
created_at TIMESTAMP NOT NULL,
closed_at TIMESTAMP)''')
c.execute('''CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
conversation_id INTEGER NOT NULL,
from_user BOOLEAN NOT NULL,
message_text TEXT NOT NULL,
timestamp TIMESTAMP NOT NULL,
FOREIGN KEY (conversation_id) REFERENCES conversations (id))''')
conn.commit()
logger.info("Database setup completed successfully")
except Exception as e:
logger.error(f"Error setting up database: {e}")
setup_database()
# Handler for the '/start' command
@bot.message_handler(commands=['start'])
def handle_start(message):
try:
# Create the inline keyboard with all the buttons
keyboard = create_premium_keyboard()
# Send the message with the inline keyboard
bot.send_message(
message.chat.id,
"🌟 Welcome to Nekozu Support And Payment! Choose an option below:",
reply_markup=keyboard
)
except Exception as e:
bot.reply_to(message, "Sorry, there was an error. Please try again later.")
print(f"Error in start handler: {e}")
@bot.callback_query_handler(func=lambda call: call.data == "buy_premium")
def handleprem(call):
keyboard = payment_methods_keyboard()
bot.edit_message_reply_markup(call.message.chat.id, call.message.id, reply_markup=keyboard)
@bot.callback_query_handler(func=lambda call: call.data in ["stars_payment"])
def handlepay(call):
payment_type = "stars"
keyboard = paynow(payment_type)
text = """"
Here is payment using telegram stars
1. Select your premium duration
2. Then you will get invoice. Click it
3. After payment, you will automatically activated the premium!
If you have a trouble with payment, please contact us using /start and select report problem or suggestion
"""
bot.edit_message_reply_markup(text, call.message.chat.id, call.message.id, reply_markup=keyboard)
@bot.callback_query_handler(func=lambda call: call.data == "back")
def handleback(call):
keyboard = create_premium_keyboard()
bot.edit_message_reply_markup(call.message.chat.id, call.message.id, reply_markup=keyboard)
@bot.callback_query_handler(func=lambda call: call.data.startswith(("stars_", "tranzzo_")))
def handle_premium_selection(call):
try:
chat_id = call.message.chat.id
payment_type, duration = call.data.split("_")
# Set up prices based on selection and payment type
if payment_type == "stars":
if duration == "week":
amount = 46
title = "1 Week Premium Access"
description = "7 days of premium features"
currency = "XTR"
provider_token = "" # Leave empty for Stars payment
else:
amount = 276
title = "1 Month Premium Access"
description = "30 days of premium features"
currency = "XTR"
provider_token = "" # Leave empty for Stars payment
# Create prices array with single price
prices = [
types.LabeledPrice(label=title, amount=amount)
]
# Send invoice
bot.send_invoice(
chat_id=chat_id,
title=title,
description=description,
invoice_payload=f"premium_{duration}_{payment_type}",
provider_token=provider_token,
currency=currency,
prices=prices,
start_parameter="premium-subscription",
need_name=False,
need_phone_number=False,
need_email=False,
need_shipping_address=False,
is_flexible=False
)
except telebot.apihelper.ApiTelegramException as telegram_error:
logger.error(f"Telegram API error: {telegram_error}")
error_message = "There was an error processing your payment request. Please try again later."
if "STARS_INVOICE_INVALID" in str(telegram_error):
error_message = "Invalid Stars payment configuration. Please contact support."
bot.answer_callback_query(call.id, error_message, show_alert=True)
except Exception as e:
logger.error(f"Error in premium selection handler: {e}")
bot.answer_callback_query(call.id, "An unexpected error occurred. Please try again later.", show_alert=True)
@bot.pre_checkout_query_handler(func=lambda query: True)
def handle_pre_checkout_query(pre_checkout_query):
try:
bot.answer_pre_checkout_query(pre_checkout_query.id, ok=True)
except Exception as e:
logger.error(f"Error in pre-checkout handler: {e}")
bot.answer_pre_checkout_query(
pre_checkout_query.id,
ok=False,
error_message="Sorry, there was an error processing your payment. Please try again later."
)
@bot.message_handler(content_types=['successful_payment'])
def handle_successful_payment(message):
try:
payment_info = message.successful_payment
duration = "1week" if payment_info.total_amount == 46 else "1month"
expiry = datetime.now() + timedelta(weeks=1 if duration == "1week" else 4)
# Prepare payment data
payment_data = {
'user_id': str(message.from_user.id),
'expiry_date': expiry
}
# Store payment in appropriate collection
if duration == "1week":
one_week_prem.insert_one(payment_data)
else:
one_month_prem.insert_one(payment_data)
# Update user's premium status
users_collection.update_one(
{'user_id': str(message.from_user.id)},
{
'$set': {
'is_premium': True,
'premium_start': datetime.now(),
'premium_duration': duration,
'expiry': expiry
}
},
upsert=True
)
# Send success message
bot.send_message(
message.chat.id,
f"✨ Thank you! Your payment of {payment_info.total_amount} Amount has been received!\n\n"
f"▶️ Your {duration} premium subscription is now active\n\nYou can check it using /info command!"
"🎉 Enjoy your premium features!"
)
bot.send_message(
ADMIN_CHAT_ID,
f"Someone just bought premium with amount {payment_info.total_amount}"
)
except Exception as e:
logger.error(f"Error in payment success handler: {e}")
bot.reply_to(
message,
"Your payment was received, but there was an error updating your premium status. "
"Please contact support using /start and select report with your screenshot the error."
)
@bot.callback_query_handler(func=lambda call: call.data == "paypal_payment")
def handle_paypal(call):
keyboard = paypal_keyboard()
text = """
Here is a payment guide for paypal payment:
1. Select your premium duration
2. Click the invoice link
3. Pay it
4. After payment, click the send payment screenshot button to verify your payment
5. Send your success payment screenshot
6. Wait until admin accept it
7. Enjoy your premium features!
If you have a trouble with payment, please contact us using /start and select report problem or suggestion
"""
bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.id, text=text, reply_markup=keyboard)
@bot.callback_query_handler(func=lambda call: call.data == "send_payment_screenshot")
def handle_send_payment_screenshot(call):
force_reply = types.ForceReply(selective=True)
msg = bot.send_message(call.message.chat.id, "Please send your payment screenshot.", reply_markup=force_reply)
bot.register_next_step_handler(msg, process_payment_screenshot)
@bot.message_handler(content_types=['photo'])
def process_payment_screenshot(message):
# Check if this is a response to send_payment_screenshot
if not hasattr(message, 'reply_to_message') or not message.reply_to_message or \
not hasattr(message.reply_to_message, 'text') or \
message.reply_to_message.text != "Please send your payment screenshot. Make sure to send correct screenshot and replying to this message":
return
try:
# Create admin verification keyboard
keyboard = types.InlineKeyboardMarkup(row_width=2)
week_accept = types.InlineKeyboardButton("Accept 1 Week", callback_data=f"accept_week_{message.from_user.id}")
month_accept = types.InlineKeyboardButton("Accept 1 Month", callback_data=f"accept_month_{message.from_user.id}")
reject = types.InlineKeyboardButton("Reject", callback_data=f"reject_{message.from_user.id}")
keyboard.add(week_accept, month_accept, reject)
# Forward screenshot to admin with verification buttons
bot.forward_message(ADMIN_CHAT_ID, message.chat.id, message.message_id)
admin_msg = f"Payment screenshot from:\nUser ID: {message.from_user.id}\nUsername: @{message.from_user.username}\n\nPlease verify:"
bot.send_message(ADMIN_CHAT_ID, admin_msg, reply_markup=keyboard)
# Send confirmation to user
bot.reply_to(message, "Thank you! Your payment screenshot has been received and is being reviewed. Please wait for confirmation.")
except Exception as e:
logger.error(f"Error processing payment screenshot: {e}")
bot.reply_to(message, "Sorry, there was an error processing your screenshot. Please try again or contact support.")
@bot.callback_query_handler(func=lambda call: call.data.startswith(('accept_week_', 'accept_month_', 'reject_')))
def handle_admin_verification(call):
try:
action, user_id = call.data.rsplit('_', 1) # Split from right to handle underscores in user_id
if action == 'reject':
# Send rejection message to user
bot.send_message(int(user_id), "❌ Your payment screenshot was rejected. Please ensure you sent the correct screenshot and try again.")
bot.answer_callback_query(call.id, "Rejection sent to user")
elif action in ['accept_week', 'accept_month']:
duration = "1week" if action == 'accept_week' else "1month"
expiry = datetime.now() + timedelta(weeks=1 if duration == "1week" else 4)
# Add user to appropriate collection
payment_data = {
'user_id': str(user_id), # Convert to string to match check_user_id format
'expiry_date': expiry
}
if duration == "1week":
one_week_prem.insert_one(payment_data)
else:
one_month_prem.insert_one(payment_data)
# Update user's premium status in users collection
users_collection.update_one(
{'user_id': str(user_id)}, # Convert to string to match check_user_id format
{
'$set': {
'is_premium': True,
'premium_start': datetime.now(),
'premium_duration': duration,
'expiry': expiry
}
},
upsert=True
)
# Send confirmation to user
bot.send_message(
int(user_id),
f"✨ Your payment has been verified!\n\n▶️ Your {duration} premium subscription is now active.\n\n"
"You can check it using /info command!\n🎉 Enjoy your premium features!"
)
bot.answer_callback_query(call.id, f"Premium {duration} activated for user")
# Update admin message
bot.edit_message_reply_markup(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
reply_markup=None
)
# Update admin message text
action_text = "rejected" if action == "reject" else f"accepted ({duration})"
bot.edit_message_text(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
text=f"{call.message.text}\n\nStatus: {action_text}"
)
except Exception as e:
logger.error(f"Error in admin verification: {e}")
bot.answer_callback_query(call.id, f"Error processing verification: {str(e)}", show_alert=True)
@bot.callback_query_handler(func=lambda call: call.data == "crypto_payment")
def handle_crypto(call):
message = """
Here is a payment guide for crypto payment:
Using crypto payment has a service fee and network fee, so there might be a slight difference in the amount you need to pay.
Supported currencies:
CryptoCloud:
- BTC (Bitcoin)
- ETH (Ethereum)
- LTC (Litecoin)
- USDT (TRC20)
- USDT (ERC20)
- USDC (TRC20)
- TUSD (TRC20)
- TON (Toncoin)
CryptoMus:
- AVAX (Avalanche)
- BCH (Bitcoin Cash)
- BNB (Binance Smart Chain)
- BTC (Bitcoin)
- DAI (Ethereum, Binance Smart Chain, Polygon)
- DASH (Dash)
- DOGE (Dogecoin)
- ETH (Arbitrum, Ethereum, Binance Smart Chain)
- HMSTR (Toncoin)
- LTC (Litecoin)
- POL (Polygon, Ethereum)
- SHIB (Ethereum)
- TON (Toncoin)
- TRX (Tron)
- USDC (Ethereum, Binance Smart Chain, Arbitrum, Polygon, Avalanche)
- USDT (Toncoin, Avalanche, Arbitrum, Binance Smart Chain, Ethereum, Polygon, Tron)
- VERSE (Ethereum)
- XMR (Monero)
Oxapay:
- Bitcoin Cash (BCH)
- Binance Coin (BNB)
- Bitcoin (BTC)
- Dogecoin (DOGE)
- Dogs (DOGS)
- Ethereum (ETH)
- Litecoin (LTC)
- NotCoin (NOT)
- Polygon (POL)
- Shiba Inu (SHIB)
- Solana (SOL)
- Toncoin (TON)
- Tron (TRX)
- USD Coin (USDC)
- Tether (USDT)
- Monero (XMR)
How to pay?
1. First, select the crypto gateway you want to pay here
2. After that, select your premium duration
3. You will get a payment link to pay
4. Open the link, and select crypto currencies also crypto network
5. Pay with the amount shown in the link
6. After payment, click the check payment button to verify your payment
7. Enjoy your premium features!
If you have a trouble with payment, please contact us using /start and select report problem or suggestion
"""
keyboard = types.InlineKeyboardMarkup(row_width=1)
cryptocloud = types.InlineKeyboardButton("CryptoCloud", callback_data="cryptocloud")
cryptomus = types.InlineKeyboardButton("CryptoMus", callback_data="cryptomus")
oxapay = types.InlineKeyboardButton("Oxapay", callback_data="oxapay")
backs = types.InlineKeyboardButton("Back", callback_data="back")
keyboard.add(cryptocloud, cryptomus, oxapay, backs)
bot.edit_message_text(message, call.message.chat.id, call.message.id, reply_markup=keyboard)
@bot.callback_query_handler(func=lambda call: call.data == "cryptocloud")
def handle_cryptocloud(call):
try:
# Create keyboard with duration options
keyboard = types.InlineKeyboardMarkup()
keyboard.row(
types.InlineKeyboardButton("1 Week ($1)", callback_data="duration_1week"),
types.InlineKeyboardButton("1 Month ($6)", callback_data="duration_1month")
)
bot.edit_message_text(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
text="Please select your premium subscription duration:",
reply_markup=keyboard
)
except Exception as e:
logger.error(f"Error creating payment: {e}")
bot.answer_callback_query(call.id, "Error creating payment. Please try again later.", show_alert=True)
@bot.callback_query_handler(func=lambda call: call.data.startswith("duration_"))
def handle_duration_selection(call):
try:
duration = call.data.split("_")[1]
amount = 1 if duration == "1week" else 6
# Create payment invoice
create_url = "https://api.cryptocloud.plus/v2/invoice/create"
create_data = {
"amount": amount,
"shop_id": CRYPTOCLOUD_SHOP_ID,
"currency": "USD"
}
headers = {
"Authorization": f"Token {CRYPTOCLOUD_TOKEN}"
}
create_response = requests.post(create_url, headers=headers, json=create_data)
if create_response.status_code == 200:
invoice_data = create_response.json()
if invoice_data["status"] == "success":
invoice_uuid = invoice_data["result"]["uuid"]
pay_url = invoice_data["result"]["link"]
# Create keyboard with payment URL
keyboard = types.InlineKeyboardMarkup()
keyboard.add(
types.InlineKeyboardButton("Pay Now", url=pay_url),
types.InlineKeyboardButton("Check Payment", callback_data=f"check_{invoice_uuid}")
)
bot.edit_message_text(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
text=f"Please complete your payment for {duration} premium subscription.\nAmount: ${amount}",
reply_markup=keyboard
)
else:
bot.answer_callback_query(call.id, "Failed to create payment invoice", show_alert=True)
else:
bot.answer_callback_query(call.id, "Error creating payment", show_alert=True)
except Exception as e:
logger.error(f"Error processing duration selection: {e}")
bot.answer_callback_query(call.id, "Error processing selection. Please try again.", show_alert=True)
@bot.callback_query_handler(func=lambda call: call.data.startswith("check_"))
def check_payment_status(call):
try:
invoice_uuid = call.data.split("_")[1]
info_url = "https://api.cryptocloud.plus/v2/invoice/merchant/info"
headers = {
"Authorization": f"Token {CRYPTOCLOUD_TOKEN}"
}
check_data = {
"uuids": [invoice_uuid]
}
response = requests.post(info_url, headers=headers, json=check_data)
if response.status_code == 200:
data = response.json()
if data["status"] == "success":
for invoice in data["result"]:
if invoice["status"] == "overpaid":
bot.answer_callback_query(call.id, "Payment confirmed! Processing your premium activation...", show_alert=True)
# Get duration from invoice amount
duration = "1week" if invoice["amount"] == 1 else "1month"
expiry = datetime.now() + timedelta(weeks=1 if duration == "1week" else 4)
# Add user to appropriate collection
payment_data = {
'user_id': str(call.from_user.id),
'expiry_date': expiry
}
if duration == "1week":
one_week_prem.insert_one(payment_data)
else:
one_month_prem.insert_one(payment_data)
# Update user's premium status in users collection
users_collection.update_one(
{'user_id': str(call.from_user.id)},
{
'$set': {
'is_premium': True,
'premium_start': datetime.now(),
'premium_duration': duration,
'expiry': expiry
}
},
upsert=True
)
# Send confirmation to user
bot.edit_message_text(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
text=f"✨ Your payment has been verified!\n\n▶️ Your {duration} premium subscription is now active.\n\n"
"You can check it using /info command!\n🎉 Enjoy your premium features!"
)
return
elif invoice["status"] == "created":
bot.answer_callback_query(call.id, "Payment pending. Please complete the payment.", show_alert=True)
return
bot.answer_callback_query(call.id, "Please paid the payment first", show_alert=True)
except Exception as e:
logger.error(f"Error checking payment status: {e}")
bot.answer_callback_query(call.id, "Error checking payment status", show_alert=True)
def create_sign(payload, api_key):
json_data = json.dumps(payload)
base64_data = base64.b64encode(json_data.encode()).decode()
return hashlib.md5(f"{base64_data}{api_key}".encode()).hexdigest()
@bot.callback_query_handler(func=lambda call: call.data == "cryptomus")
def handle_cryptomus(call):
try:
# Create keyboard with duration options
keyboard = types.InlineKeyboardMarkup()
keyboard.row(
types.InlineKeyboardButton("1 Week ($1)", callback_data="durationmus_1week"),
types.InlineKeyboardButton("1 Month ($6)", callback_data="durationmus_1month")
)
bot.edit_message_text(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
text="Please select your premium subscription duration:",
reply_markup=keyboard
)
except Exception as e:
logger.error(f"Error creating payment: {e}")
bot.answer_callback_query(call.id, "Error creating payment. Please try again later.", show_alert=True)
@bot.callback_query_handler(func=lambda call: call.data.startswith("durationmus_"))
def handle_duration_selection_cryptomus(call):
try:
duration = call.data.split("_")[1]
amount = 1 if duration == "1week" else 6
# Cryptomus credentials
merchant_id = CRYPTOMUS_MERCHANT_ID
api_key = CRYPTOMUS_API_KEY
order_id = str(uuid.uuid4())
payment_data = {
"amount": str(amount),
"currency": "USD",
"order_id": order_id
}
headers = {
'merchant': merchant_id,
'sign': create_sign(payment_data, api_key),
'Content-Type': 'application/json'
}
response = requests.post(
'https://api.cryptomus.com/v1/payment',
headers=headers,
json=payment_data
)
result = response.json().get('result', {})
payment_url = result.get('url')
payment_uuid = result.get('uuid')
if not payment_url or not payment_uuid:
raise Exception("Failed to create payment")
# Create keyboard with payment URL and check status button
keyboard = types.InlineKeyboardMarkup(row_width=1)
keyboard.add(
types.InlineKeyboardButton("Pay Now", url=payment_url),
types.InlineKeyboardButton("Check Payment Status", callback_data=f"checkmus_{payment_uuid}_{duration}")
)
bot.edit_message_text(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
text=f"Please complete your payment of ${amount} USD\nPayment will expire in 1 hours",
reply_markup=keyboard
)
except Exception as e:
bot.answer_callback_query(call.id, "Error creating payment. Please try again.")
bot.send_message(ADMIN_CHAT_ID, f"Payment creation error: {str(e)}")
@bot.callback_query_handler(func=lambda call: call.data.startswith("checkmus_"))
def check_payment_status(call):
try:
_, payment_uuid, duration = call.data.split("_")
merchant_id = CRYPTOMUS_MERCHANT_ID
api_key = CRYPTOMUS_API_KEY
payment_data = {
"uuid": payment_uuid
}
headers = {
'merchant': merchant_id,
'sign': create_sign(payment_data, api_key),
'Content-Type': 'application/json'
}
response = requests.post(
'https://api.cryptomus.com/v1/payment/info',
headers=headers,
json=payment_data
)
result = response.json().get('result', {})
payment_status = result.get('payment_status')
if payment_status == 'paid':
# Calculate expiry date
expiry = datetime.now() + timedelta(weeks=1 if duration == "1week" else 4)
# Store payment data
payment_data = {
'user_id': str(call.from_user.id),
'expiry_date': expiry,
}
if duration == "1week":
one_week_prem.insert_one(payment_data)
else:
one_month_prem.insert_one(payment_data)
# Update user's premium status
users_collection.update_one(
{'user_id': str(call.from_user.id)},
{
'$set': {
'is_premium': True,
'premium_start': datetime.now(),
'premium_duration': duration,
'expiry': expiry
}
},
upsert=True
)
bot.edit_message_text(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
text=f"✨ Payment successful!\n\n▶️ Your {duration} premium is now active\n\nUse /info to check your status!",
reply_markup=None
)
bot.send_message(
ADMIN_CHAT_ID,
f"New premium user via Cryptomus: {call.from_user.username} ({call.from_user.id})"
)
else:
bot.answer_callback_query(
call.id,
f"Payment status: {payment_status}. Please complete payment.",
show_alert=True
)
except Exception as e:
bot.answer_callback_query(call.id, "Error checking payment status. Please try again.")
bot.send_message(ADMIN_CHAT_ID, f"Payment status check error: {str(e)}")
@bot.callback_query_handler(func=lambda call: call.data == "oxapay")
def handle_oxapay(call):
try:
# Create keyboard with duration options
keyboard = types.InlineKeyboardMarkup()
keyboard.row(
types.InlineKeyboardButton("1 Week ($1)", callback_data="durationoxa_1week"),
types.InlineKeyboardButton("1 Month ($6)", callback_data="durationoxa_1month")
)
bot.edit_message_text(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
text="Please select your premium subscription duration:",
reply_markup=keyboard
)
except Exception as e:
logger.error(f"Error creating payment: {e}")
bot.answer_callback_query(call.id, "Error creating payment. Please try again later.", show_alert=True)
@bot.callback_query_handler(func=lambda call: call.data.startswith("durationoxa_"))
def handle_duration_selection_oxapay(call):
try:
duration = call.data.split("_")[1]
amount = 1 if duration == "1week" else 6
# Create payment request
url = 'https://api.oxapay.com/merchants/request'
order_id = str(uuid.uuid4())
data = {
'merchant': OXAPAY_MERCHANT_KEY,
'amount': amount,
'currency': 'USD',
'lifeTime': 1440,
'feePaidByPayer': 1,
'underPaidCover': 0,
'callbackUrl': 'https://t.me/nekopaybot',
'returnUrl': 'https://t.me/nekopaybot',
'description': f'Premium {duration}',
'orderId': order_id,
}
response = requests.post(url, data=json.dumps(data))
result = response.json()
if result.get('result') == 100: # Success
payment_url = result.get('payLink')
track_id = result.get('trackId')
# Create keyboard with payment URL and check status button
keyboard = types.InlineKeyboardMarkup(row_width=1)
keyboard.add(
types.InlineKeyboardButton("Pay Now", url=payment_url),
types.InlineKeyboardButton("Check Payment Status", callback_data=f"checkoxa_{track_id}_{duration}")
)
bot.edit_message_text(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
text=f"Please complete your payment of ${amount} USD\nPayment will expire in 24 hours",
reply_markup=keyboard
)
else:
raise Exception(f"Payment creation failed: {result.get('message')}")
except Exception as e:
bot.answer_callback_query(call.id, "Error creating payment. Please try again.")
bot.send_message(ADMIN_CHAT_ID, f"Oxapay payment creation error: {str(e)}")
@bot.callback_query_handler(func=lambda call: call.data.startswith("checkoxa_"))
def check_oxapay_status(call):
try:
# Split the callback data correctly - only expecting 3 parts
_, track_id, duration = call.data.split("_")
# Check payment status
url = 'https://api.oxapay.com/merchants/inquiry'
data = {
'merchant': OXAPAY_MERCHANT_KEY,
'trackId': track_id
}
response = requests.post(url, data=json.dumps(data))
result = response.json()
if result.get('status') == 'Paid':
# Calculate expiry date
expiry = datetime.now() + timedelta(weeks=1 if duration == "1week" else 4)
# Store payment data
payment_data = {
'user_id': str(call.from_user.id),
'expiry_date': expiry,
'payment_track_id': track_id
}
if duration == "1week":
one_week_prem.insert_one(payment_data)
else:
one_month_prem.insert_one(payment_data)
# Update user's premium status
users_collection.update_one(
{'user_id': str(call.from_user.id)},
{
'$set': {
'is_premium': True,
'premium_start': datetime.now(),
'premium_duration': duration,
'expiry': expiry
}
},
upsert=True
)
bot.edit_message_text(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
text=f"✨ Payment successful!\n\n▶️ Your {duration} premium is now active\n\nUse /info to check your status!",
reply_markup=None
)
bot.send_message(
ADMIN_CHAT_ID,
f"New premium user via Oxapay: {call.from_user.username} ({call.from_user.id})"
)
else:
bot.answer_callback_query(
call.id,
f"Payment status: {result.get('status')}. Please complete payment.",
show_alert=True
)
except Exception as e:
bot.answer_callback_query(call.id, "Error checking payment status. Please try again.")
bot.send_message(ADMIN_CHAT_ID, f"Oxapay status check error: {str(e)}")
@bot.callback_query_handler(func=lambda call: call.data == "kofi_payment")
def handle_kofi(call):
try:
keyboard = kofi()
text = """
How to pay with kofi?
1. Select the duration you want to buy at here button