-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsanstore.py
1364 lines (1127 loc) · 56.8 KB
/
sanstore.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.types import InlineKeyboardMarkup, InlineKeyboardButton
import subprocess
import json
import datetime
from datetime import datetime, timedelta
from uuid import uuid4
import base64
import telebot
import sqlite3
import os
import zipfile
import threading
import time
API_TOKEN = '7360190308:AAFCXEy6tEzRvCgzF44XzlcX3PRNV-vPkxo'
bot = telebot.TeleBot(API_TOKEN)
admin_id = 576495165
user_data = {}
DB_PATH = 'user_data.db'
BACKUP_DIR = 'backups/'
#================== DATABASE AREA ===========
# Database setup
def init_db():
conn = sqlite3.connect('user_data.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
balance INTEGER DEFAULT 0,
reseller_status TEXT DEFAULT 'non reseller')''')
cursor.execute('''CREATE TABLE IF NOT EXISTS redeem_codes (
code_name TEXT PRIMARY KEY,
balance INTEGER NOT NULL,
remaining_uses INTEGER NOT NULL,
total_uses INTEGER NOT NULL)''')
cursor.execute('''CREATE TABLE IF NOT EXISTS redeemed_codes (
user_id INTEGER NOT NULL,
code_name TEXT NOT NULL,
PRIMARY KEY (user_id, code_name))''')
# Check if the reseller_status column exists, if not, add it
cursor.execute("PRAGMA table_info(users)")
columns = [column[1] for column in cursor.fetchall()]
if 'reseller_status' not in columns:
cursor.execute("ALTER TABLE users ADD COLUMN reseller_status TEXT DEFAULT 'non reseller'")
conn.commit()
conn.close()
def get_user_data(user_id):
conn = sqlite3.connect('user_data.db')
cursor = conn.cursor()
cursor.execute('INSERT OR IGNORE INTO users (user_id, balance, reseller_status) VALUES (?, 0, "non reseller")', (user_id,))
cursor.execute('SELECT balance, reseller_status FROM users WHERE user_id = ?', (user_id,))
result = cursor.fetchone()
conn.close()
return {'balance': result[0], 'reseller_status': result[1]}
def update_balance(user_id, amount):
conn = sqlite3.connect('user_data.db')
cursor = conn.cursor()
cursor.execute('INSERT OR IGNORE INTO users (user_id, balance, reseller_status) VALUES (?, 0, "non reseller")', (user_id,))
cursor.execute('UPDATE users SET balance = balance + ? WHERE user_id = ?', (amount, user_id))
# Fetch the updated balance and current reseller status
cursor.execute('SELECT balance, reseller_status FROM users WHERE user_id = ?', (user_id,))
balance, reseller_status = cursor.fetchone()
# Update reseller status based on new balance and top-up rules
if reseller_status == 'reseller' and balance == 0:
# If balance reaches 0, downgrade to non reseller
cursor.execute('UPDATE users SET reseller_status = "non reseller" WHERE user_id = ?', (user_id,))
elif reseller_status != 'reseller' and amount >= 10000:
# If top-up is 30,000 or more, upgrade to reseller
cursor.execute('UPDATE users SET reseller_status = "reseller" WHERE user_id = ?', (user_id,))
elif reseller_status == 'reseller' and amount < 10000 and balance > 0:
# If top-up is below 30,000 but balance is still above 0, retain reseller status
pass
elif amount < 30000:
# If top-up is below 30,000 and user is not a reseller, keep status as non reseller
cursor.execute('UPDATE users SET reseller_status = "non reseller" WHERE user_id = ?', (user_id,))
conn.commit()
conn.close()
# Initialize the database
init_db()
#============================================
@bot.message_handler(commands=['start', 'menu'])
def send_welcome(message):
user_data = get_user_data(message.chat.id)
reseller_status = user_data['reseller_status']
vpn_price = 5000 if reseller_status == 'reseller' else 10000
markup = InlineKeyboardMarkup()
menu_vpn = InlineKeyboardButton("🛡️Menu VPN", callback_data="menu_vpn")
menu_topup = InlineKeyboardButton("💰Top Up", callback_data="topup")
menu_ceksaldo = InlineKeyboardButton("💳Cek Saldo", callback_data="cek_saldo")
markup.add(menu_vpn)
markup.add(menu_topup, menu_ceksaldo)
# Cek apakah user adalah admin
if message.chat.id == admin_id:
broadcast = InlineKeyboardButton("Broadcast", callback_data="broadcast")
markup.add(broadcast)
bot.send_message(
message.chat.id,
"*»»——— SAN STORE BOT ———««*\n\n"
"🔹 *VPN Premium & Kuota Murah* 🔹\n"
"🔒 *Kecepatan & Keamanan Terbaik*\n\n"
f"👤 *Owner: @Sanmaxx*\n"
f"💲 *Status: {reseller_status.capitalize()}*\n"
f"💵 *Harga VPN: {vpn_price}*\n\n"
"*»»——— Thanks for coming ———««*",
parse_mode='Markdown',
reply_markup=markup
)
@bot.callback_query_handler(func=lambda call: call.data in ["menu_vpn", "cek_saldo"])
def callback_query_handler(call):
user_data = get_user_data(call.message.chat.id)
if call.data == "menu_vpn":
menu_vpn(call.message)
elif call.data == "cek_saldo":
balance = user_data['balance']
bot.send_message(call.message.chat.id, f"Saldo Anda saat ini adalah: {balance}")
@bot.callback_query_handler(func=lambda call: call.data == "kembali")
def kembali_handler(call):
markup = InlineKeyboardMarkup()
menu_vpn = InlineKeyboardButton("🛡️Menu VPN", callback_data="menu_vpn")
menu_topup = InlineKeyboardButton("💰Top Up", callback_data="topup")
menu_ceksaldo = InlineKeyboardButton("💳Cek Saldo", callback_data="cek_saldo")
markup.add(menu_vpn)
markup.add(menu_topup, menu_ceksaldo)
# Cek apakah user adalah admin
if call.message.chat.id == admin_id:
broadcast = InlineKeyboardButton("Broadcast", callback_data="broadcast")
markup.add(broadcast)
bot.edit_message_text(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
text="*»»——— SAN STORE BOT ———««*\n\n"
"🔹 *VPN Premium & Kuota Murah* 🔹\n"
"🔒 *Kecepatan & Keamanan Terbaik*\n\n"
"👤 *Owner: @Sanmaxx*\n\n"
"*»»——— Thanks for coming ———««*",
parse_mode='Markdown',
reply_markup=markup
)
#======================== BAGIAN FUNGSI UNTUK SEMUA BUTTON MENU ====================
#----------------- PART SSH --------------
def menu_vpn(message):
markup = InlineKeyboardMarkup()
menu_ssh = InlineKeyboardButton("SSH/OVPN", callback_data="menu_ssh")
menu_vmess = InlineKeyboardButton("VMESS/XRAY", callback_data="menu_vmess")
menu_trojan = InlineKeyboardButton("TROJAN/XRAY", callback_data="menu_trojan")
kembali = InlineKeyboardButton("KEMBALI", callback_data="kembali")
markup.add(menu_ssh, menu_vmess, menu_trojan)
markup.add(kembali)
bot.edit_message_text(
chat_id=message.chat.id,
message_id=message.message_id,
text="*»»——— SAN STORE BOT ———««*\n\n"
"🔹*VPN Premium Rules*🔹\n"
"❌ *Dilarang Multi Login Melebihi ketentuan* \n\n"
"Banned Otomatis Tanpa pemberitahuan dan tidak menerima Refund atau Garansi dalam bentuk apapun\n"
"*»»——— Thanks for coming ———««*",
parse_mode='Markdown',
reply_markup=markup
)
#------------------------
@bot.callback_query_handler(func=lambda call: call.data == "menu_ssh")
def menu_ssh_handler(call):
sub_menu_ssh(call.message)
def sub_menu_ssh(message):
markup = InlineKeyboardMarkup()
ssh_create_button = InlineKeyboardButton("NEW SSH", callback_data="create_ssh")
ssh_renew_button = InlineKeyboardButton("RENEW SSH", callback_data="renew_ssh")
kembali = InlineKeyboardButton("KEMBALI", callback_data="kembali")
markup.add(ssh_create_button, ssh_renew_button)
markup.add(kembali)
bot.edit_message_text(
chat_id=message.chat.id,
message_id=message.message_id,
text="*»»——— SAN STORE BOT ———««*\n\n"
"🔹 *SSH PREMIUM* 🔹\n\n"
"Region : SG\n"
"ISP : DigitalOcean\n"
"Support : HP & STB\n"
"*»»——— Thanks for coming ———««*",
parse_mode='Markdown',
reply_markup=markup
)
@bot.callback_query_handler(func=lambda call: call.data in ["create_ssh", "renew_ssh"])
def handle_callback(call):
user_data = get_user_data(call.message.chat.id)
reseller_status = user_data['reseller_status']
vpn_price = 5000 if reseller_status == 'reseller' else 10000
if call.data == "create_ssh":
user_balance = user_data['balance']
if user_balance >= vpn_price:
update_balance(call.message.chat.id, -vpn_price)
create_ssh(call.message)
else:
bot.send_message(call.message.chat.id, "Saldo tidak cukup.")
elif call.data == "renew_ssh":
user_balance = user_data['balance']
if user_balance >= vpn_price:
update_balance(call.message.chat.id, -vpn_price)
renew_ssh(call.message)
else:
bot.send_message(call.message.chat.id, "Saldo tidak cukup.")
def create_ssh(message):
bot.edit_message_text(chat_id=message.chat.id, message_id=message.message_id, text="*Input Username:*", parse_mode='Markdown')
bot.register_next_step_handler(message, get_username_ssh)
def renew_ssh(message):
bot.edit_message_text(chat_id=message.chat.id, message_id=message.message_id, text="*Input Username:*", parse_mode='Markdown')
bot.register_next_step_handler(message, get_renew_ssh)
def get_username_ssh(message):
username = message.text.strip()
if username == '/start':
bot.send_message(message.chat.id, "Proses pembuatan username dihentikan. Ketikkan /start untuk memulai lagi.")
return # Stop processing and return
# Validasi username: tidak boleh mengandung spasi dan panjang maksimal 8 karakter
if ' ' in username or len(username) > 8:
bot.send_message(message.chat.id, 'Username tidak boleh mengandung spasi dan maksimal 8 karakter. Masukkan username lain:')
bot.register_next_step_handler(message, get_username_ssh)
elif username.lower() == 'root' or username in get_existing_users():
bot.send_message(message.chat.id, 'Username tidak valid atau sudah ada. Silakan masukkan username lain:')
bot.register_next_step_handler(message, get_username_ssh)
else:
bot.send_message(message.chat.id, '*🔐Input Password:*', parse_mode='Markdown')
bot.register_next_step_handler(message, get_password, username)
def get_password(message, username):
password = message.text.strip()
# Set default expiry to 30 days
expired_days = 30
# Call the create account function directly with 30 days expiry
create_account_action(username, password, expired_days, message)
def create_account_action(username, password, expired_days, message):
exp_date = (datetime.now() + timedelta(days=expired_days)).strftime('%Y-%m-%d')
# Membuat akun SSH
subprocess.run(['useradd', '-e', exp_date, '-s', '/bin/false', '-M', username])
subprocess.run(['sh', '-c', f'echo "{username}:{password}" | chpasswd'])
# Mendapatkan informasi IP dan domain
domain = subprocess.getoutput("cat /etc/xray/domain")
IP = subprocess.getoutput("curl -sS ifconfig.me")
# Mendapatkan tanggal expired
exp = subprocess.getoutput(f"chage -l {username} | grep 'Account expires' | awk -F': ' '{{print $2}}'")
def progress_bar(progress, total, length=20):
filled_length = int(length * progress // total)
bar = '█' * filled_length + '-' * (length - filled_length)
return f"[{bar}] {int((progress / total) * 100)}%"
# Total iterasi untuk animasi loading
total_steps = 10
# Mengirim pesan awal untuk progress bar
loading_message = bot.send_message(message.chat.id, "Loading [--------------------] 0%")
# Mengedit pesan animasi loading secara bertahap
for step in range(1, total_steps + 1):
bar_message = progress_bar(step, total_steps)
bot.edit_message_text(chat_id=message.chat.id, message_id=loading_message.message_id, text=f"Loading {bar_message}")
time.sleep(0.3) # Jeda waktu antar update
# Mengirim informasi akun kepada pengguna
result_message = (
f"━━━━━━━━━━━━━━━━━━━━━━\n"
f"• SSH ACCOUNT INFORMATION •\n"
f"━━━━━━━━━━━━━━━━━━━━━━\n"
f" Username : `{username}`\n"
f" Password : `{password}`\n"
f" Expired On : {exp}\n"
"━━━━━━━━━━━━━━━━━━━━━━━\n"
f" IP : {IP}\n"
f" Host : `{domain}`\n"
f" OpenSSH : 22\n"
f" Dropbear : 443\n"
f" SSH-WS : 80, 8880\n"
f" SSH-SSL-WS : 443\n"
f" SSH-UDP : 56-65545\n"
f" SSL/TLS :443\n"
f" UDPGW : 7100-7300\n"
f"━━━━━━━━━━━━━━━━━━━━━━\n"
f" GET /HTTP/1.1[crlf]Host: [host] [crlf]Upgrade: websocket[crlf][crlf]\n"
f"━━━━━━━━━━━━━━━━━━━━━━\n"
)
bot.edit_message_text(chat_id=message.chat.id, message_id=loading_message.message_id, text=result_message, parse_mode='Markdown')
# Tambahkan dictionary untuk melacak percobaan
user_attempts = {}
def get_renew_ssh(message):
username = message.text.strip()
user_id = message.chat.id
if username == '/start':
bot.send_message(message.chat.id, "Proses pembuatan username dihentikan. Ketikkan /start untuk memulai lagi.")
return # Stop processing and return
# Periksa apakah pengguna sudah ada di dalam sesi percobaan
if user_id not in user_attempts:
user_attempts[user_id] = 1 # Inisialisasi dengan 1 percobaan
else:
user_attempts[user_id] += 1 # Tambah percobaan jika sudah ada
# Jika username salah 3 kali, akhiri sesi
if user_attempts[user_id] > 3:
bot.send_message(message.chat.id, 'Anda telah salah memasukkan username sebanyak 3 kali. Silakan mulai dari awal.')
user_attempts.pop(user_id, None) # Hapus percobaan untuk user ini
return
# Jika username valid, reset percobaan dan lanjutkan proses perpanjangan
if username not in get_existing_users():
bot.send_message(message.chat.id, 'Username Ssh Tidak Ditemukan')
bot.register_next_step_handler(message, get_renew_ssh)
else:
user_attempts.pop(user_id, None) # Reset percobaan jika berhasil
renew_account_action(username, message)
def renew_account_action(username, message):
expired_days = 30
# Mendapatkan tanggal expired saat ini
current_exp = subprocess.getoutput(f"chage -l {username} | grep 'Account expires' | awk -F': ' '{{print $2}}'")
current_exp_date = datetime.strptime(current_exp.strip(), '%b %d, %Y')
new_exp_date = current_exp_date + timedelta(days=expired_days)
new_exp_str = new_exp_date.strftime('%Y-%m-%d')
# Memperbarui tanggal expired akun
subprocess.run(['chage', '-E', new_exp_str, username])
def progress_bar(progress, total, length=20):
filled_length = int(length * progress // total)
bar = '█' * filled_length + '-' * (length - filled_length)
return f"[{bar}] {int((progress / total) * 100)}%"
# Total iterasi untuk animasi loading
total_steps = 10
# Mengirim pesan awal untuk progress bar
loading_message = bot.send_message(message.chat.id, "Loading [--------------------] 0%")
# Mengedit pesan animasi loading secara bertahap
for step in range(1, total_steps + 1):
bar_message = progress_bar(step, total_steps)
bot.edit_message_text(chat_id=message.chat.id, message_id=loading_message.message_id, text=f"Loading {bar_message}")
time.sleep(0.3) # Jeda waktu antar update
# Mengirim informasi perpanjangan kepada pengguna
result_message = (
"━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
" • Successfully Renew •\n"
"━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
f"Username : {username}\n"
f"Masa Aktif : {new_exp_str}\n"
"━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
)
bot.edit_message_text(chat_id=message.chat.id, message_id=loading_message.message_id, text=result_message, parse_mode='Markdown')
def get_existing_users():
try:
users = subprocess.getoutput("cut -d: -f1 /etc/passwd").split()
return users
except Exception as e:
print(f"Error fetching existing users: {e}")
return []
#--------------------- PART VMESS -------------------
@bot.callback_query_handler(func=lambda call: call.data == "menu_vmess")
def menu_vmess_handler(call):
sub_menu_vmess(call.message)
def sub_menu_vmess(message):
markup = InlineKeyboardMarkup()
create_button = InlineKeyboardButton("NEW VMESS", callback_data="create_vmess")
renew_button = InlineKeyboardButton("RENEW VMESS", callback_data="renew_vmess")
kembali = InlineKeyboardButton("KEMBALI", callback_data="kembali")
markup.add(create_button, renew_button)
markup.add(kembali)
bot.edit_message_text(
chat_id=message.chat.id,
message_id=message.message_id,
text="*»»——— SAN STORE BOT ———««*\n\n"
"🔹 *VMESS PREMIUM* 🔹\n\n"
"Region : SG\n"
"ISP : DigitalOcean\n"
"Support : HP & STB\n"
"*»»——— Thanks for Order ———««*",
parse_mode='Markdown',
reply_markup=markup
)
#======================================#
@bot.callback_query_handler(func=lambda call: call.data in ["create_vmess", "renew_vmess"])
def handle_callback(call):
user_data = get_user_data(call.message.chat.id)
reseller_status = user_data['reseller_status']
vpn_price = 5000 if reseller_status == 'reseller' else 10000
if call.data == "create_vmess":
user_balance = user_data['balance']
if user_balance >= vpn_price:
update_balance(call.message.chat.id, -vpn_price)
create_vmess(call.message)
else:
bot.send_message(call.message.chat.id, "Saldo tidak cukup.")
elif call.data == "renew_vmess":
user_balance = user_data['balance']
if user_balance >= vpn_price:
update_balance(call.message.chat.id, -vpn_price)
renew_vmess(call.message)
else:
bot.send_message(call.message.chat.id, "Saldo tidak cukup.")
def create_vmess(message):
bot.edit_message_text(chat_id=message.chat.id, message_id=message.message_id, text="*Input Username:*", parse_mode='Markdown')
bot.register_next_step_handler(message, get_username_vmess)
def get_username_vmess(message):
username = message.text
if username == '/start':
bot.send_message(message.chat.id, "Proses pembuatan username dihentikan. Ketikkan /start untuk memulai lagi.")
return # Stop processing and return
if is_username_exists(username):
bot.send_message(message.chat.id, 'Nama sudah ada, Silahkan Masukkan Username Yang lain:')
bot.register_next_step_handler(message, get_username_vmess)
else:
# Automatically set expired to 30 days
expired_days = 30
exp_date = (datetime.now() + timedelta(days=expired_days)).strftime('%Y-%m-%d')
domain = subprocess.getoutput("cat /etc/xray/domain")
uuid = str(uuid4())
# Update config.json
config_path = '/etc/xray/config.json'
with open(config_path, 'r+') as file:
config_data = file.read()
# Insert new user details
new_user_entry = f'\n### {username} {exp_date}\n}},{{"id": "{uuid}","alterId": 0,"email": "{username}"'
# Find the position to insert for #vmess
vmess_pos = config_data.find('#vmess')
if (vmess_pos != -1):
insert_pos = config_data.find('\n', vmess_pos)
config_data = config_data[:insert_pos] + new_user_entry + config_data[insert_pos:]
# Find the position to insert for #vmessgrpc
vmessgrpc_pos = config_data.find('#vmessgrpc')
if (vmessgrpc_pos != -1):
insert_pos = config_data.find('\n', vmessgrpc_pos)
config_data = config_data[:insert_pos] + new_user_entry + config_data[insert_pos:]
# Write back the updated config
file.seek(0)
file.write(config_data)
file.truncate()
# VMESS links
asu = {
"v": "2",
"ps": username,
"add": domain,
"port": "443",
"id": uuid,
"aid": "0",
"net": "ws",
"path": "/vmess",
"type": "none",
"host": domain,
"tls": "tls"
}
ask = {
"v": "2",
"ps": username,
"add": domain,
"port": "80",
"id": uuid,
"aid": "0",
"net": "ws",
"path": "/vmess",
"type": "none",
"host": domain,
"tls": "none"
}
grpc = {
"v": "2",
"ps": username,
"add": domain,
"port": "443",
"id": uuid,
"aid": "0",
"net": "grpc",
"path": "vmess-grpc",
"type": "none",
"host": domain,
"tls": "tls"
}
vmesslink1 = f"vmess://{base64.urlsafe_b64encode(json.dumps(asu).encode()).decode()}"
vmesslink2 = f"vmess://{base64.urlsafe_b64encode(json.dumps(ask).encode()).decode()}"
vmesslink3 = f"vmess://{base64.urlsafe_b64encode(json.dumps(grpc).encode()).decode()}"
# Restart services
subprocess.run(['systemctl', 'restart', 'xray'])
subprocess.run(['service', 'cron', 'restart'])
def progress_bar(progress, total, length=20):
filled_length = int(length * progress // total)
bar = '█' * filled_length + '-' * (length - filled_length)
return f"[{bar}] {int((progress / total) * 100)}%"
# Total iterasi untuk animasi loading
total_steps = 10
# Mengirim pesan awal untuk progress bar
loading_message = bot.send_message(message.chat.id, "Loading [--------------------] 0%")
# Mengedit pesan animasi loading secara bertahap
for step in range(1, total_steps + 1):
bar_message = progress_bar(step, total_steps)
bot.edit_message_text(chat_id=message.chat.id, message_id=loading_message.message_id, text=f"Loading {bar_message}")
time.sleep(0.5) # Jeda waktu antar update
# Send result
result_message = (
f"━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
f" • CREATE VMESS USER •\n"
f"━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
f"Remarks : {username}\n"
f"Expired On : {exp_date}\n"
f"Domain : {domain}\n"
f"Port TLS : 443\n"
f"Port none TLS : 80\n"
f"Port GRPC : 443\n"
f"id : {uuid}\n"
f"alterId : 0\n"
f"Security : auto\n"
f"Network : ws\n"
f"Path : /vmess\n"
f"Path WSS : wss://bug.com/vmess\n"
f"ServiceName : vmess-grpc\n"
f"━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
f"Link TLS : \n`{vmesslink1}`\n"
f"\n"
f"Link none TLS : \n`{vmesslink2}`\n"
f"\n"
f"Link GRPC : \n`{vmesslink3}`\n"
f"━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
)
bot.edit_message_text(chat_id=message.chat.id, message_id=loading_message.message_id, text=result_message, parse_mode='Markdown')
# Check if username exists
def is_username_exists(username):
config_path = '/etc/xray/config.json'
try:
with open(config_path, 'r') as file:
config_data = file.read()
return f'### {username} ' in config_data
except FileNotFoundError:
return False
def renew_vmess(message):
bot.edit_message_text(chat_id=message.chat.id, message_id=message.message_id, text="*Input Username:*", parse_mode='Markdown')
bot.register_next_step_handler(message, get_renew_username)
def get_renew_username(message):
username = message.text
if username == '/start':
bot.send_message(message.chat.id, "Proses pembuatan username dihentikan. Ketikkan /start untuk memulai lagi.")
return # Stop processing and return
if is_username_exists(username):
# Automatically set additional expiration to 30 days
additional_days = 30
renew_callback_vmess(username, additional_days, message.chat.id)
else:
bot.send_message(message.chat.id, 'Username tidak ditemukan. Silahkan masukkan username yang benar:')
bot.register_next_step_handler(message, get_renew_username)
def renew_callback_vmess(username, additional_days, chat_id):
try:
config_path = '/etc/xray/config.json'
with open(config_path, 'r+') as file:
config_data = file.read()
# Find and update expiration date in #vmess
user_pos = config_data.find(f'### {username} ')
if user_pos == -1:
bot.send_message(chat_id, 'Username tidak ditemukan.')
return
# Get current expiration date
start_pos = user_pos + len(f'### {username} ')
end_pos = config_data.find('\n', start_pos)
current_exp_date = config_data[start_pos:end_pos].strip()
current_exp_date = datetime.strptime(current_exp_date, '%Y-%m-%d')
# Calculate new expiration date
new_exp_date = (current_exp_date + timedelta(days=additional_days)).strftime('%Y-%m-%d')
# Update expiration date in config
config_data = config_data[:start_pos] + new_exp_date + config_data[end_pos:]
# Find and update expiration date in #vmessgrpc
user_pos_grpc = config_data.find(f'### {username} ', end_pos)
if user_pos_grpc != -1:
start_pos_grpc = user_pos_grpc + len(f'### {username} ')
end_pos_grpc = config_data.find('\n', start_pos_grpc)
config_data = config_data[:start_pos_grpc] + new_exp_date + config_data[end_pos_grpc:]
# Write back updated config
file.seek(0)
file.write(config_data)
file.truncate()
# Restart services
subprocess.run(['systemctl', 'restart', 'xray'])
subprocess.run(['service', 'cron', 'restart'])
def progress_bar(progress, total, length=20):
filled_length = int(length * progress // total)
bar = '█' * filled_length + '-' * (length - filled_length)
return f"[{bar}] {int((progress / total) * 100)}%"
# Total iterasi untuk animasi loading
total_steps = 10
# Mengirim pesan awal untuk progress bar
loading_message = bot.send_message(chat_id, "Loading [--------------------] 0%")
# Mengedit pesan animasi loading secara bertahap
for step in range(1, total_steps + 1):
bar_message = progress_bar(step, total_steps)
bot.edit_message_text(chat_id=chat_id, message_id=loading_message.message_id, text=f"Loading {bar_message}")
time.sleep(0.3) # Jeda waktu antar update
# Send confirmation message
bot.edit_message_text(chat_id=chat_id, message_id=loading_message.message_id,
text=(
f"━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
f" • RENEW VMESS USER •\n"
f"━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
f"Remarks : {username}\n"
f"Expired On : {new_exp_date}\n"
f"━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
),
parse_mode='Markdown')
except Exception as e:
bot.send_message(chat_id, f'Error: {str(e)}')
#------------------------ TROJAN PAGE --------------------
@bot.callback_query_handler(func=lambda call: call.data == "menu_trojan")
def menu_trojan_handler(call):
sub_menu_trojan(call.message)
def sub_menu_trojan(message):
markup = InlineKeyboardMarkup()
create_button = InlineKeyboardButton("NEW TROJAN ", callback_data="create_trojan")
renew_button = InlineKeyboardButton("RENEW TROJAN", callback_data="renew_trojan")
kembali = InlineKeyboardButton("KEMBALI", callback_data="kembali")
markup.add(create_button, renew_button)
markup.add(kembali)
bot.edit_message_text(
chat_id=message.chat.id,
message_id=message.message_id,
text="*»»——— SAN STORE BOT ———««*\n\n"
"🔹 *TROJAN PREMIUM* 🔹\n\n"
"Region : SG\n"
"ISP : DigitalOcean\n"
"Support : HP & STB\n"
"*»»——— Thanks for coming ———««*",
parse_mode='Markdown',
reply_markup=markup
)
#======================================#
@bot.callback_query_handler(func=lambda call: call.data in ["create_trojan", "renew_trojan"])
def handle_callback(call):
user_data = get_user_data(call.message.chat.id)
reseller_status = user_data['reseller_status']
vpn_price = 5000 if reseller_status == 'reseller' else 10000
if call.data == "create_trojan":
user_balance = user_data['balance']
if user_balance >= vpn_price:
update_balance(call.message.chat.id, -vpn_price)
create_trojan(call.message)
else:
bot.send_message(call.message.chat.id, "Saldo tidak cukup.")
elif call.data == "renew_trojan":
user_balance = user_data['balance']
if user_balance >= vpn_price:
update_balance(call.message.chat.id, -vpn_price)
renew_trojan(call.message)
else:
bot.send_message(call.message.chat.id, "Saldo tidak cukup.")
def create_trojan(message):
bot.edit_message_text(chat_id=message.chat.id, message_id=message.message_id, text="*Input Username:*", parse_mode='Markdown')
bot.register_next_step_handler(message, get_username_trojan)
def get_username_trojan(message):
username = message.text
if username == '/start':
bot.send_message(message.chat.id, "Proses pembuatan username dihentikan. Ketikkan /start untuk memulai lagi.")
return # Stop processing and return
if is_username_exists(username):
bot.send_message(message.chat.id, 'Nama sudah ada, Pilih Nama lain:')
bot.register_next_step_handler(message, get_username_trojan)
else:
# Automatically set expiration to 30 days
expired_days = 30
exp_date = (datetime.now() + timedelta(days=expired_days)).strftime('%Y-%m-%d')
domain = subprocess.getoutput("cat /etc/xray/domain")
uuid = str(uuid4())
# Update config.json
config_path = '/etc/xray/config.json'
with open(config_path, 'r+') as file:
config_data = file.read()
# Insert new user details for trojanws and trojangrpc
new_user_entry = f'\n#! {username} {exp_date}\n}},{{"password": "{uuid}","email": "{username}"'
# Find the position to insert for #trojanws
trojanws_pos = config_data.find('#trojanws')
if trojanws_pos != -1:
insert_pos = config_data.find('\n', trojanws_pos)
config_data = config_data[:insert_pos] + new_user_entry + config_data[insert_pos:]
# Find the position to insert for #trojangrpc
trojangrpc_pos = config_data.find('#trojangrpc')
if trojangrpc_pos != -1:
insert_pos = config_data.find('\n', trojangrpc_pos)
config_data = config_data[:insert_pos] + new_user_entry + config_data[insert_pos:]
# Write back the updated config
file.seek(0)
file.write(config_data)
file.truncate()
# Trojan links
tr = '443' # Assuming the port is 443 for simplicity
trojanlink1 = f"trojan://{uuid}@{domain}:{tr}?mode=gun&security=tls&type=grpc&serviceName=trojan-grpc&sni={domain}#{username}"
trojanlink2 = f"trojan://{uuid}@bug.com:{tr}?path=%2Ftrojan-ws&security=tls&host={domain}&type=ws&sni={domain}#{username}"
# Restart services
subprocess.run(['systemctl', 'restart', 'xray'])
subprocess.run(['service', 'cron', 'restart'])
def progress_bar(progress, total, length=20):
filled_length = int(length * progress // total)
bar = '█' * filled_length + '-' * (length - filled_length)
return f"[{bar}] {int((progress / total) * 100)}%"
# Total iterasi untuk animasi loading
total_steps = 10
# Mengirim pesan awal untuk progress bar
loading_message = bot.send_message(message.chat.id, "Loading [--------------------] 0%")
# Mengedit pesan animasi loading secara bertahap
for step in range(1, total_steps + 1):
bar_message = progress_bar(step, total_steps)
bot.edit_message_text(chat_id=message.chat.id, message_id=loading_message.message_id, text=f"Loading {bar_message}")
time.sleep(0.3) # Jeda waktu antar update
# Send result
result_message = (
f"━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
f" • CREATE TROJAN USER •\n"
f"━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
f"Remarks : {username}\n"
f"Expired On : {exp_date}\n"
f"Host/IP : {domain}\n"
f"Port : {tr}\n"
f"Key : {uuid}\n"
f"Path : /trojan-ws\n"
f"Path WSS : wss://bug.com/trojan-ws\n"
f"ServiceName : trojan-grpc\n"
f"━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
f"Link WS : \n`{trojanlink2}`\n"
f"\n"
f"Link GRPC : \n`{trojanlink1}`\n"
f"━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
)
bot.edit_message_text(chat_id=message.chat.id, message_id=loading_message.message_id, text=result_message, parse_mode='Markdown')
def is_username_exists_trojan(username):
config_path = '/etc/xray/config.json'
try:
with open(config_path, 'r') as file:
config_data = file.read()
# Cek apakah nama pengguna muncul dalam konfigurasi dengan format yang tepat
return f'#! {username} ' in config_data
except FileNotFoundError:
return False
def renew_trojan(message):
bot.edit_message_text(chat_id=message.chat.id, message_id=message.message_id, text="*Input Username:*", parse_mode='Markdown')
bot.register_next_step_handler(message, get_username_for_renew)
def get_username_for_renew(message):
username = message.text
if username == '/start':
bot.send_message(message.chat.id, "Proses pembuatan username dihentikan. Ketikkan /start untuk memulai lagi.")
return # Stop processing and return
if is_username_exists_trojan(username):
# Automatically set additional expiration to 30 days
additional_days = 30
renew_callback_trojan(username, additional_days, message.chat.id)
else:
bot.send_message(message.chat.id, 'Username tidak ditemukan, silakan coba lagi.')
bot.register_next_step_handler(message, get_username_for_renew)
def renew_callback_trojan(username, additional_days, chat_id):
try:
# Update expiration date in config.json
config_path = '/etc/xray/config.json'
with open(config_path, 'r+') as file:
config_data = file.read()
# Find user entry and update expiration date
user_entry_start = config_data.find(f'#! {username} ')
if user_entry_start != -1:
# Find current expiration date
current_exp_date_str = config_data[user_entry_start + len(f'#! {username} '):].split('\n', 1)[0].strip()
try:
current_exp_date = datetime.strptime(current_exp_date_str, '%Y-%m-%d')
except ValueError:
bot.send_message(chat_id, 'Tanggal kedaluwarsa tidak valid dalam konfigurasi.')
return
new_exp_date = (current_exp_date + timedelta(days=additional_days)).strftime('%Y-%m-%d')
# Replace old expiration date with new one
config_data = config_data[:user_entry_start + len(f'#! {username} ')] + new_exp_date + config_data[user_entry_start + len(f'#! {username} ') + len(current_exp_date_str):]
# Write back the updated config
file.seek(0)
file.write(config_data)
file.truncate()
# Update expiration date in #trojangrpc
trojangrpc_pos = config_data.find(f'#trojangrpc')
if trojangrpc_pos != -1:
user_entry_start = config_data.find(f'#! {username} ', trojangrpc_pos)
if user_entry_start != -1:
current_exp_date_str = config_data[user_entry_start + len(f'#! {username} '):].split('\n', 1)[0].strip()
new_exp_date = (datetime.strptime(current_exp_date_str, '%Y-%m-%d') + timedelta(days=additional_days)).strftime('%Y-%m-%d')
config_data = config_data[:user_entry_start + len(f'#! {username} ')] + new_exp_date + config_data[user_entry_start + len(f'#! {username} ') + len(current_exp_date_str):]
file.seek(0)
file.write(config_data)
file.truncate()
# Restart services
subprocess.run(['systemctl', 'restart', 'xray'])
subprocess.run(['service', 'cron', 'restart'])
def progress_bar(progress, total, length=20):
filled_length = int(length * progress // total)
bar = '█' * filled_length + '-' * (length - filled_length)
return f"[{bar}] {int((progress / total) * 100)}%"
# Total iterasi untuk animasi loading
total_steps = 10
# Mengirim pesan awal untuk progress bar
loading_message = bot.send_message(chat_id, "Loading [--------------------] 0%")
# Mengedit pesan animasi loading secara bertahap
for step in range(1, total_steps + 1):
bar_message = progress_bar(step, total_steps)
bot.edit_message_text(chat_id=chat_id, message_id=loading_message.message_id, text=f"Loading {bar_message}")
time.sleep(0.3) # Jeda waktu antar update
bot.edit_message_text(chat_id=chat_id, message_id=loading_message.message_id,
text=(
f"━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
f" • RENEW TROJAN USER •\n"
f"━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
f"Remarks : {username}\n"
f"Expired On : {new_exp_date}\n"
f"━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
),
parse_mode='Markdown')
else:
bot.send_message(chat_id, f'Pengguna {username} tidak ditemukan dalam konfigurasi.')
except Exception as e:
bot.send_message(chat_id, f'Error: {str(e)}')
#================== COMMAND DELETE ACCOUNT ===========
@bot.message_handler(commands=['admin'])
def start_command(message):
# Check if the user is the admin
if message.chat.id == 576495165:
# Create an inline keyboard
markup = InlineKeyboardMarkup()
ssh = InlineKeyboardButton("DELETE SSH", callback_data="delete_ssh")
vmess = InlineKeyboardButton("DELETE VMESS", callback_data="delete_vmess")
trojan = InlineKeyboardButton("DELETE TROJAN", callback_data="delete_trojan")
markup.add(ssh)
markup.add(vmess, trojan)
bot.send_message(message.chat.id, "Halo Tuan....", reply_markup=markup)
else:
# If the user is not the admin, deny access
bot.send_message(message.chat.id, "Access denied. You are not authorized to use this bot.")
# Callback handler for specific inline button data
@bot.callback_query_handler(func=lambda call: call.data in ["delete_ssh", "delete_vmess", "delete_trojan"])
def handle_callback(call):
if call.data == "delete_ssh":
delete_ssh_account(call.message)
elif call.data == "delete_vmess":
delete_vmess(call.message)
elif call.data == "delete_trojan":
delete_trojan(call.message)
#=============== DELETE SSH ======================
def delete_ssh_account(message):
bot.send_message(message.chat.id, 'Input the SSH username to delete:')
bot.register_next_step_handler(message, handle_delete_username)
def handle_delete_username(message):
username = message.text
if is_user_exists(username):
try:
# Delete the user account
subprocess.run(['userdel', '-r', username], check=True)
bot.send_message(message.chat.id, f'User {username} has been deleted successfully.')
except Exception as e:
bot.send_message(message.chat.id, f'Error deleting user {username}: {str(e)}')
else:
bot.send_message(message.chat.id, 'User does not exist. Please provide a valid username.')
def is_user_exists(username):