-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1667 lines (1459 loc) · 77.6 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 os
import sys
import time
import json
import yaml
import psutil
import signal
import locale
import random
import logging
import telebot
import datetime
import requests
import traceback
import subprocess
from telebot import types
from langdetect import detect
from langcodes import Language
from yht_helper import YHTHelper
from youtube_helper import YoutubeHelper
from yht.station_helper import get_all_stations, get_proper_station, yht_hour_helper
# global variables
active_process = {}
youtube_urls = {}
train_services = {}
usernames = {}
instagram_command_flags = {}
# change them to your own paths
VIDEO_FOLDER = os.path.join(os.getcwd(), 'credentials', 'instagram', 'tutun.sabri_raspi', 'content')
class CustomPopen(subprocess.Popen):
creation_time = None
working_directory = None
wait_to_finish = None
def dump_those_args(self):
return self.args, self.creation_time
def __str__(self) -> str:
return f'PID: {self.pid}\n Command: {self.args}\n Time: {self.creation_time.strftime("%H:%M:%S")}'
# read the bot token from the json file
with open('bot_config.json') as f:
data = json.load(f)
token = data['bot_token']
owner_id = data['owner_id']
whitelist = data['white_list']
# get the station names for the yht command
get_all_stations()
# create a bot object
bot = telebot.TeleBot(token)
## create and run a process
def process_handler(executable: list, wait_to_finish: bool, process_name: str, chat_id, cwd=None):
global bot, active_process
process = CustomPopen(executable,
cwd=cwd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
process.creation_time = datetime.datetime.now()
process.working_directory = cwd
process.wait_to_finish = wait_to_finish
if(wait_to_finish):
# add the process to the active process list
if chat_id not in active_process:
active_process[chat_id] = {}
if process_name in active_process[chat_id]:
active_process[chat_id][process_name].append(process)
else:
active_process[chat_id][process_name] = [process]
# wait for the process to complete
stdout, stderr = process.communicate()
# get the exit code
exit_code = process.returncode
if(exit_code != 0):
stderr_str = stderr.decode('utf-8')
return (False, stderr_str)
# decode stdout
stdout_str = stdout.decode('utf-8')
output = stdout_str.strip().split('\n')
# remove the process from the active process list
active_process[chat_id][process_name].remove(process)
if len(active_process[chat_id][process_name]) == 0:
del active_process[chat_id][process_name]
if len(active_process[chat_id]) == 0:
del active_process[chat_id]
return (True, output[-1].strip())
else:
if chat_id not in active_process:
active_process[chat_id] = {}
# check if active process have key with chat id
if chat_id in active_process and process_name in active_process[chat_id]:
active_process[chat_id][process_name].append(process)
else:
active_process[chat_id][process_name] = [process]
if process_name in ['gramaddict', 'instagram']:
stdout, stderr = process.communicate()
# check return code
if process.returncode != 0:
bot.send_message(chat_id, f'Bir hata oluştu: {process.returncode}')
stdout_str = stdout.decode('utf-8')
output = stdout_str.strip()
if output != '':
f = open(f'temp_{chat_id}_out.txt', 'w')
f.write(stdout_str)
f.close()
bot.send_document(chat_id, open(f'temp_{chat_id}_out.txt', 'rb'))
os.remove(f'temp_{chat_id}_out.txt')
stderr_str = stderr.decode('utf-8').strip()
if(stderr_str != ''):
f = open(f'temp_{chat_id}_err.txt', 'w')
f.write(stderr_str)
f.close()
bot.send_document(chat_id, open(f'temp_{chat_id}_err.txt', 'rb'))
os.remove(f'temp_{chat_id}_err.txt')
# remove the process from the active process list
active_process[chat_id][process_name].remove(process)
if len(active_process[chat_id][process_name]) == 0:
del active_process[chat_id][process_name]
if len(active_process[chat_id]) == 0:
del active_process[chat_id]
# kill the adb server
if process_name == 'gramaddict':
try:
os.system('adb kill-server')
except Exception as e:
bot.send_message(chat_id, f'ADB sunucusu kapatılırken bir hata oluştu. {e}')
# dump active process to a file
def dump_active_process():
global active_process
process_hold = {'active_process': []}
if(len(active_process) > 0):
for key, value in active_process.items():
if(len(value) > 0):
for key2, value2 in value.items():
for process in value2:
try:
user = key
process_name = key2
args, creation_time = process.dump_those_args()
working_directory = process.working_directory
wait_to_finish = process.wait_to_finish
process_hold['active_process'].append({'user': user, 'process_name': process_name, 'args': args, 'working_directory': working_directory, 'wait_to_finish': wait_to_finish})
except Exception as e:
print(f'Could not write the active process to the file. {e}', flush=True)
with open('active_process.json', 'w', encoding='utf-8') as f:
json.dump(process_hold, f)
def load_active_process():
with open('active_process.json', 'r', encoding='utf-8') as f:
try:
data = json.load(f)
except json.JSONDecodeError:
return
if 'active_process' in data:
for process in data['active_process']:
user = process['user']
process_name = process['process_name']
args = process['args']
working_directory = process['working_directory']
wait_to_finish = process['wait_to_finish']
try:
# enhance this part by adding synchronization and also handling the return value
# do not let func call block the main thread - run it in a separate thread
# use a lock to synchronize the access to the active_process dictionary
# use a condition variable to signal the main thread that the process is done
# use a queue to store the return value
# use a separate thread to handle the return value
# TODO: Implement the above v2.0
# for now, just run processes that do not wait for the process to finish and important ones
if process_name in ['spor', 'yht']:
bot.send_message(user, f'{process_name} işlemi kaldığı yerden devam ediyor...')
process_handler(args, wait_to_finish, process_name, user, cwd=working_directory)
except Exception as e:
bot.send_message(user, f'{process_name} işlemi kaldığı yerden devam ederken bir hata oluştu. {e}')
# clear the file
with open('active_process.json', 'w', encoding='utf-8') as f:
f.write('')
try:
load_active_process()
except Exception as e:
print(f'Could not load the active process. {e}', flush=True)
def signal_handler(sig, frame):
# Inform the owner that the program is shutting down
global owner_id
global bot
global active_process
bot.send_message(owner_id, "Program kapatılıyor.")
dump_active_process()
# kill all active processes
if(len(active_process) > 0):
for key, value in active_process.items():
if(len(value) > 0):
for key2, value2 in value.items():
for process in value2:
try:
bot.send_message(key, f'{key2} işlemi kapatılıyor. Görüşürüz...')
if key2 in ['spor', 'yht']:
bot.send_message(key, f'Merak etme, [@atakan](tg://user?id={owner_id}) botu başlattığında __{key2}__ işlemini yeniden çalıştırmaya çalışcağım. Benden haber bekle...', parse_mode='Markdown')
kill_process_tree(process)
except Exception as e:
print(f'Process with pid {process.pid} thrown an exception. Could not kill the process. {e}', flush=True)
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
# some helper functions
def kill_process_tree(process):
# I wish I lived in a world where I could just call process.kill() and be done with it
parent = psutil.Process(process.pid)
for child in parent.children(recursive=True):
child.kill()
process.kill()
## create a message for the user to see the active processes
def create_process_list_message(chat_id):
global active_process
user_jobs = ''
# get keys and their values together
if chat_id not in active_process:
return user_jobs
for key, value in active_process[chat_id].items():
if(len(value) > 0):
user_jobs += f'{key}: adı altında {len(value)} tane işleminiz bulunmaktadır. \n\n'
if(len(user_jobs) > 0):
user_jobs = 'Aşağıda çalışmakta olan tüm işlemlerinizi görebilirsiniz.: \n\n' + user_jobs
return user_jobs
## handle the file and send it to the user
def file_handler(message, output:str, type: str):
global bot
try:
file = open(output, 'rb')
if(type == 'audio'):
bot.send_audio(message.chat.id, audio = file)
elif(type == 'video'):
bot.send_video(message.chat.id, video = file, supports_streaming=True, width=1920, height=1080)
file.close()
except Exception as e:
file.close()
bot.send_message(message.chat.id, f'Dosya boyutu çok büyük. Buluta yükleniyor...')
try:
result = subprocess.run(f'curl -F "file=@{output}" https://temp.sh/upload', shell=True, capture_output=True, text=True)
if result.returncode != 0:
bot.send_message(message.chat.id, f'Dosyayı servera yüklerken bir hata oluştu. {result.stderr}')
else:
bot.send_message(message.chat.id, text= f'Dosyayı indirmek için <a href="{result.stdout}">bu linki</a> kullanabilirsin. Dosya 3 gün sonra silinecektir. Terminal üzerinden indirmek için komut:', parse_mode='HTML')
bot.send_message(message.chat.id, f'curl -X POST {result.stdout} --output {result.stdout.split("/")[-1]}')
except Exception as e:
bot.send_message(message.chat.id, f'Buluta yüklenirken bir hata oluştu. {e}')
finally:
os.remove(output)
# check if the user is in the white list
def access_control(chat_id, admin: bool = False, quiet: bool = False):
global whitelist, bot, owner_id
chat_id = str(chat_id)
if chat_id == owner_id:
return True
elif chat_id in whitelist and not admin:
return True
elif chat_id in whitelist and admin:
if not quiet:
bot.send_message(chat_id, f'Bu işlemi yapmaya yetkiniz yok. Bu işlemi sadece [@atakan](tg://user?id={owner_id}) yapabilir.', parse_mode='Markdown')
return False
else:
if not quiet:
# inline keyboard markup
keyboard = types.InlineKeyboardMarkup(row_width=2)
request_button = types.InlineKeyboardButton("Yetki İste \U0001F6A7", callback_data='request')
cancel_button = types.InlineKeyboardButton("İptal \U0000274C", callback_data='cancel')
keyboard.add(request_button, cancel_button)
bot.send_message(chat_id, f'Bu işlemi yapmaya yetkiniz yok. Botu kullanabilmek için [@atakan](tg://user?id={owner_id}) kullanıcısından yetki isteyebilirsiniz.', parse_mode='Markdown', reply_markup=keyboard)
# handle the callback
@bot.callback_query_handler(func=lambda call: call.data == 'request')
def request(call):
bot.send_message(owner_id, f'[{call.message.chat.username}](tg://user?id={call.message.chat.id}) kullanıcısı yetki istiyor.', parse_mode='Markdown')
# log the request
request_file = os.path.join(os.getcwd(), 'requests', f'{call.message.chat.id}.txt')
f = open(request_file, 'w')
# log first name, last name, username, chat id, date
f.write(f'{call.message.chat.first_name} {call.message.chat.last_name}\n{call.message.chat.username}\n{call.message.chat.id}\n{call.message.date}')
f.close()
bot.send_message(call.message.chat.id, "Yetki isteğiniz gönderildi. Lütfen bekleyin.")
bot.delete_message(call.message.chat.id, call.message.message_id)
@bot.callback_query_handler(func=lambda call: call.data == 'cancel')
def cancel(call):
bot.delete_message(call.message.chat.id, call.message.message_id)
return False
def gramaddict_yaml_file(chat_id):
global usernames
# get the directory for the gramaddict folder
# python -m site --user-site
site = subprocess.run(['python', '-m', 'site', '--user-site'], stdout=subprocess.PIPE)
# ensure the process is completed
site.check_returncode()
# get the site path
site_path = site.stdout.decode('utf-8').strip('\n')
# get the gramaddict folder
gramaddict_folder = os.path.join(site_path, 'GramAddict')
# get the username
username = usernames[str(chat_id)]
yaml_file = os.path.join(gramaddict_folder, 'accounts', username, 'config.yml')
return yaml_file, site_path
def configure_yaml_file(config_file, to_add):
with open(config_file) as f:
config = yaml.safe_load(f)
if 'blogger-followers' in config:
del config['blogger-followers']
if 'blogger-post-likers' in config:
del config['blogger-post-likers']
if 'hashtag-likers-top' in config:
del config['hashtag-likers-top']
if 'unfollow-any' in config:
del config['unfollow-any']
if 'working-hours' in config:
del config['working-hours']
f = open(config_file, 'w')
f.write(yaml.dump(config, default_flow_style=False))
f.write('working-hours: [00.00-23.59]\n')
f.write(to_add)
f.close()
# next step handlers
## youtube
def get_youtube_start_time(message):
global youtube_urls
try:
chat_id = message.chat.id
start_time = message.text.strip()
if start_time == 'cancel':
bot.send_message(chat_id, "İşlem iptal edildi.")
youtube_urls.pop(chat_id)
return
x = start_time.split(':')
if len(x) != 2 or not x[0].isdigit() or not x[1].isdigit():
bot.send_message(chat_id, "Hata: Lütfen başlangıç zamanını örnekteki gibi giriniz. Örnek: 01:15. İşlemi iptal etmek için 'cancel' yazabilirsiniz.")
youtube_urls.pop(chat_id)
bot.register_next_step_handler_by_chat_id(chat_id, get_youtube_start_time)
return
youtube_urls[chat_id].start_time = start_time
bot.send_message(chat_id, "Klip bitiş zamanını giriniz: (Örnek: 01:30) veya 'cancel' yazarak işlemi iptal edebilirsiniz.")
bot.register_next_step_handler_by_chat_id(chat_id, get_youtube_end_time)
except Exception as e:
bot.send_message(chat_id, f'Bu mesajı aldıysan bir şeyler çok yanlış ve büyük ihtimalle benimle ilgili değil. {e}')
def get_youtube_end_time(message):
global youtube_urls
try:
chat_id = message.chat.id
end_time = message.text.strip()
if end_time == 'cancel':
bot.send_message(chat_id, "İşlem iptal edildi.")
youtube_urls.pop(chat_id)
return
x = end_time.split(':')
if len(x) != 2 or not x[0].isdigit() or not x[1].isdigit():
bot.send_message(chat_id, "Hata: Lütfen bitiş zamanını örnekteki gibi giriniz. Örnek: 02:57. İşlemi iptal etmek için 'cancel' yazabilirsiniz.")
youtube_urls.pop(chat_id)
bot.register_next_step_handler_by_chat_id(chat_id, get_youtube_end_time)
return
youtube_urls[chat_id].end_time = end_time
bot.send_message(chat_id, "Klip indiriliyor...\nLütfen bekleyin.")
# call the downloader
executable_file = os.path.join(os.getcwd(), 'youtube', 'executable', 'youtube')
arguments = [youtube_urls[chat_id].url, os.getcwd(), 'clip', youtube_urls[chat_id].start_time, youtube_urls[chat_id].end_time]
out = process_handler([executable_file] + arguments, True, 'youtube', chat_id)
if(not out[0]):
bot.send_message(chat_id, f'Bir sorun oluştu: {out[1]}')
return
youtube_urls.pop(chat_id)
file_handler(message, out[1], type='video')
except Exception as e:
bot.send_message(chat_id, f'Bu mesajı aldıysan bir şeyler çok yanlış ve büyük ihtimalle benimle ilgili değil. {e}')
## yht
def get_yht_departure_station(message):
global train_services
try:
chat_id = message.chat.id
departure_station = message.text.strip()
if departure_station == 'cancel':
bot.send_message(chat_id, "İşlem iptal edildi.")
return
departure_station.replace(' ', '')
stations = get_proper_station(departure_station)
if len(stations) == 0:
bot.send_message(chat_id, "Hata: Lütfen geçerli bir kalkış şehri giriniz. İşlemi iptal etmek için 'cancel' yazabilirsiniz.")
bot.register_next_step_handler_by_chat_id(chat_id, get_yht_departure_station)
return
if len(stations) > 1:
keyboard = types.ReplyKeyboardMarkup(row_width=2)
for i in range(0, len(stations), 2):
button1 = types.KeyboardButton(stations[i])
if i+1 < len(stations):
button2 = types.KeyboardButton(stations[i+1])
keyboard.add(button1, button2)
else:
keyboard.add(button1)
cancel_button = types.KeyboardButton("cancel")
keyboard.add(cancel_button)
bot.send_message(chat_id, "Aşağıdaki istasyonlardan birini seçiniz:", reply_markup=keyboard)
bot.register_next_step_handler_by_chat_id(chat_id, get_yht_departure_station_choice)
else:
train_services[chat_id] = YHTHelper(stations[0])
bot.send_message(chat_id, "Varış şehrini giriniz. (Örnek: İstanbul veya istanbul). Lütfen sadece şehir ismini giriniz. İşlemi iptal etmek için 'cancel' yazabilirsiniz.")
bot.register_next_step_handler_by_chat_id(chat_id, get_yht_arrival_station)
except Exception as e:
bot.send_message(chat_id, f'Bu mesajı aldıysan bir şeyler çok yanlış ve büyük ihtimalle benimle ilgili değil. {e}')
def get_yht_departure_station_choice(message):
global train_services
try:
# remove the reply keyboard
reply_markup = types.ReplyKeyboardRemove()
chat_id = message.chat.id
departure_station = message.text.strip()
if departure_station == 'cancel':
bot.send_message(chat_id, "İşlem iptal edildi.", reply_markup=reply_markup)
return
train_services[chat_id] = YHTHelper(departure_station)
bot.send_message(chat_id, "Varış şehrini giriniz. (Örnek: İstanbul veya istanbul). Lütfen sadece şehir ismini giriniz.. İşlemi iptal etmek için 'cancel' yazabilirsiniz.", reply_markup=reply_markup)
bot.register_next_step_handler_by_chat_id(chat_id, get_yht_arrival_station)
except Exception as e:
bot.send_message(chat_id, f'Bu mesajı aldıysan bir şeyler çok yanlış ve büyük ihtimalle benimle ilgili değil. {e}', reply_markup=reply_markup)
def get_yht_arrival_station(message):
global train_services
reply_markup = types.ReplyKeyboardRemove()
try:
chat_id = message.chat.id
arrival_station = message.text.strip()
if arrival_station == 'cancel':
bot.send_message(chat_id, "İşlem iptal edildi.", reply_markup=reply_markup)
train_services.pop(chat_id)
return
arrival_station.replace(' ', '')
stations = get_proper_station(arrival_station)
if len(stations) == 0:
bot.send_message(chat_id, "Hata: Lütfen geçerli bir varış şehri giriniz. İşlemi iptal etmek için 'cancel' yazabilirsiniz.", reply_markup=reply_markup)
bot.register_next_step_handler_by_chat_id(chat_id, get_yht_arrival_station)
return
if len(stations) > 1:
keyboard = types.ReplyKeyboardMarkup(row_width=2)
for i in range(0, len(stations), 2):
button1 = types.KeyboardButton(stations[i])
if i+1 < len(stations):
button2 = types.KeyboardButton(stations[i+1])
keyboard.add(button1, button2)
else:
keyboard.add(button1)
cancel_button = types.KeyboardButton("cancel")
keyboard.add(cancel_button)
bot.send_message(chat_id, "Aşağıdaki istasyonlardan birini seçiniz:", reply_markup=keyboard)
bot.register_next_step_handler_by_chat_id(chat_id, get_yht_arrival_station_choice)
else:
train_services[chat_id].arrival_station = stations[0]
bot.send_message(chat_id, "Tarih bilgisini giriniz: (Örnek: 13.04.2024). İşlemi iptal etmek için 'cancel' yazabilirsiniz.", reply_markup=reply_markup)
bot.register_next_step_handler_by_chat_id(chat_id, get_yht_date)
except Exception as e:
bot.send_message(chat_id, f'Bu mesajı aldıysan bir şeyler çok yanlış ve büyük ihtimalle benimle ilgili değil. {e}', reply_markup=reply_markup)
def get_yht_arrival_station_choice(message):
global train_services
try:
# remove the reply keyboard
reply_markup = types.ReplyKeyboardRemove()
chat_id = message.chat.id
arrival_station = message.text.strip()
if arrival_station == 'cancel':
bot.send_message(chat_id, "İşlem iptal edildi.", reply_markup=reply_markup)
return
train_services[chat_id].arrival_station = arrival_station
bot.send_message(chat_id, "Tarih bilgisini giriniz: (Örnek: 13.04.2024). İşlemi iptal etmek için 'cancel' yazabilirsiniz.", reply_markup=reply_markup)
bot.register_next_step_handler_by_chat_id(chat_id, get_yht_date)
except Exception as e:
bot.send_message(chat_id, f'Bu mesajı aldıysan bir şeyler çok yanlış ve büyük ihtimalle benimle ilgili değil. {e}', reply_markup=reply_markup)
def get_yht_date(message):
global train_services, bot
reply_markup = types.ReplyKeyboardRemove()
try:
chat_id = message.chat.id
date = message.text.strip()
if date == 'cancel':
bot.send_message(chat_id, "İşlem iptal edildi.", reply_markup=reply_markup)
train_services.pop(chat_id)
return
# check if date is past
user_date_obj = datetime.datetime.strptime(date, "%d.%m.%Y")
if user_date_obj < datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0):
bot.send_message(chat_id, "Hata: Lütfen geçerli bir tarih giriniz. İşlemi iptal etmek için 'cancel' yazabilirsiniz.", reply_markup=reply_markup)
bot.register_next_step_handler_by_chat_id(chat_id, get_yht_date)
return
train_services[chat_id].date = date
hour_list = yht_hour_helper(train_services[chat_id].departure_station, train_services[chat_id].arrival_station, train_services[chat_id].date)
if len(hour_list) == 0:
bot.send_message(chat_id, "Sefer bulunamadı. Lütfen başka bir tarih deneyin.", reply_markup=reply_markup)
return
keyboard = types.ReplyKeyboardMarkup(row_width=2)
for i in range(0, len(hour_list), 2):
button1 = types.KeyboardButton(hour_list[i])
if i+1 < len(hour_list):
button2 = types.KeyboardButton(hour_list[i+1])
keyboard.add(button1, button2)
else:
keyboard.add(button1)
cancel_button = types.KeyboardButton("cancel")
keyboard.add(cancel_button)
bot.send_message(chat_id, "Aşağıdaki saatlerden birini seçiniz:", reply_markup=keyboard)
bot.register_next_step_handler_by_chat_id(chat_id, callback_yht_hour)
return
except Exception as e:
bot.send_message(chat_id, f'Bu mesajı aldıysan bir şeyler çok yanlış ve büyük ihtimalle benimle ilgili değil. {e}', reply_markup=reply_markup)
def callback_yht_hour(message):
global train_services, bot
chat_id = message.chat.id
# remove the reply keyboard
reply_markup = types.ReplyKeyboardRemove()
if message.text == 'cancel':
bot.send_message(chat_id, "İşlem iptal edildi.", reply_markup=reply_markup)
train_services.pop(chat_id)
return
train_services[chat_id].hour = message.text
bot.send_message(chat_id, "İşlem başlatılıyor...\nLütfen bekleyin.", reply_markup=reply_markup)
bot.send_message(chat_id, 'Arama işlemini durdurmak istediğinde /yhtcancel komutunu kullanabilirsin.')
# call the reservation
python_file = os.path.join(os.getcwd(), 'yht', 'yht_v3.py')
arguments = [token, str(chat_id), train_services[chat_id].departure_station, train_services[chat_id].arrival_station, train_services[chat_id].date, train_services[chat_id].hour]
process_handler(['python', python_file] + arguments, False, 'yht', chat_id)
return
def yht_release_choice(message):
global bot, active_process
try:
# remove the reply keyboard
reply_markup = types.ReplyKeyboardRemove()
chat_id = message.chat.id
process_id = message.text.strip()
if process_id == 'cancel':
bot.send_message(chat_id, "İşlem iptal edildi.", reply_markup=reply_markup)
return
process_id = int(process_id)
if chat_id not in active_process or 'yht' not in active_process[chat_id]:
bot.send_message(chat_id, "Hata: Aktif bir işlem bulunamadı.", reply_markup=reply_markup)
return
for process in active_process[chat_id]['yht']:
bot.send_message(chat_id, f'Koltuk salınıyor...', reply_markup=reply_markup)
if process_id == process.pid:
try:
process.stdin.write(b'release\n')
process.stdin.flush()
process.communicate()
time.sleep(10)
bot.send_message(message.chat.id, "Hayır dualarınızı [buradan](https://buymeacoffee.com/atakanakin) kabul ediyorum.", parse_mode='Markdown')
except Exception as e:
bot.send_message(chat_id, f'Bir hata oluştu: {e}', reply_markup=reply_markup)
# delete the process from the active process list
active_process[chat_id]['yht'].remove(process)
if len(active_process[chat_id]['yht']) == 0:
del active_process[chat_id]['yht']
if len(active_process[chat_id]) == 0:
del active_process[chat_id]
return
except Exception as e:
bot.send_message(chat_id, f'Bu mesajı aldıysan bir şeyler çok yanlış ve büyük ihtimalle benimle ilgili değil. {e}', reply_markup=reply_markup)
## spor
def get_spor_username(message):
try:
chat_id = message.chat.id
username = message.text.strip()
if username == 'cancel':
bot.send_message(chat_id, "İşlem iptal edildi.")
return
user_credential_path = os.path.join(os.getcwd(), 'credentials', 'rezmetu', f'{chat_id}.json')
with open(user_credential_path, 'w') as f:
json.dump({'username': username}, f)
bot.send_message(chat_id, "Şifrenizi giriniz: , İşlemi iptal etmek için 'cancel' yazabilirsiniz.")
bot.register_next_step_handler_by_chat_id(chat_id, get_spor_password)
except Exception as e:
bot.send_message(chat_id, f'Bu mesajı aldıysan bir şeyler çok yanlış ve büyük ihtimalle benimle ilgili değil. {e}')
def get_spor_password(message):
try:
chat_id = message.chat.id
password = message.text.strip()
if password == 'cancel':
bot.send_message(chat_id, "İşlem iptal edildi.")
return
user_credential_path = os.path.join(os.getcwd(), 'credentials', 'rezmetu', f'{chat_id}.json')
with open(user_credential_path, 'r+') as f:
config = json.load(f)
config['password'] = password
f.seek(0)
f.write(json.dumps(config))
bot.send_message(chat_id, "Kullanıcı bilgileriniz kaydedildi.")
bot.send_message(message.chat.id, "Lütfen seans başlangıç saatini giriniz: (Örnek: 19:35). İşlemi iptal etmek için 'cancel' yazabilirsiniz.")
bot.register_next_step_handler_by_chat_id(message.chat.id, get_spor_time)
except Exception as e:
bot.send_message(chat_id, f'Bu mesajı aldıysan bir şeyler çok yanlış ve büyük ihtimalle benimle ilgili değil. {e}')
def get_spor_time(message):
try:
chat_id = message.chat.id
desired_time = message.text.strip()
if desired_time == 'cancel':
bot.send_message(chat_id, "İşlem iptal edildi.")
return
bot.send_message(chat_id, "Program başlatılıyor...\nLütfen bekleyin.")
bot.send_message(chat_id, 'Arama işlemini durdurmak istediğinde /sporcancel komutunu kullanabilirsin.')
# call the reservation
python_file = os.path.join(os.getcwd(), 'spor', 'spor_v2.py')
arguments = [str(chat_id), token, desired_time]
process_handler(['python', python_file] + arguments, False, 'spor', chat_id)
except Exception as e:
bot.send_message(chat_id, f'Bu mesajı aldıysan bir şeyler çok yanlış ve büyük ihtimalle benimle ilgili değil. {e}')
## broadcast
def get_broadcast_message(message):
# get the media type and file id from the message
global whitelist
white_list_temp = whitelist.copy()
white_list_temp.append(owner_id)
if message.content_type == 'video':
file_id = message.video.file_id
for user in white_list_temp:
bot.send_video(int(user), file_id, caption=f'[@atakan](tg://user?id={owner_id}) bu videoyu herkesin izlemesi gerektiğini düşünüyor.', parse_mode='Markdown', supports_streaming=True)
elif message.content_type == 'photo':
file_id = None
size_temp = 0
for photo in message.photo:
if photo.file_size > size_temp:
file_id = photo.file_id
size_temp = photo.file_size
for user in white_list_temp:
bot.send_photo(int(user), file_id, caption=f'[@atakan](tg://user?id={owner_id}) bu fotoğrafı herkesin görmesi gerektiğini düşünüyor.', parse_mode='Markdown')
elif message.content_type == 'audio':
file_id = message.audio.file_id
for user in white_list_temp:
bot.send_audio(int(user), file_id, caption=f'[@atakan](tg://user?id={owner_id}) bu ses dosyasını herkesin dinlemesi gerektiğini düşünüyor.', parse_mode='Markdown')
elif message.content_type == 'document':
file_id = message.document.file_id
for user in white_list_temp:
bot.send_document(int(user), file_id, caption=f'[@atakan](tg://user?id={owner_id}) bu dosyayı herkesin görmesi gerektiğini düşünüyor.', parse_mode='Markdown')
elif message.content_type == 'text':
message_text = message.text
if message_text == 'cancel':
return
elif message_text == "":
return
for user in white_list_temp:
bot.send_message(int(user), message_text, parse_mode='html')
## instagram
def get_instagram_download_info(message):
global usernames, instagram_command_flags, token
try:
chat_id = message.chat.id
user_input = message.text.strip()
if user_input == 'cancel':
bot.send_message(chat_id, "İşlem iptal edildi.")
return
bot.send_message(chat_id, "Lütfen bekleyin.")
# call the instagram
mode = instagram_command_flags[str(chat_id)]
python_file = os.path.join(os.getcwd(), 'instagram', 'instagram.py')
arguments = [
"--mode", "download_reel",
"--download_mode", mode,
"--username", usernames[str(chat_id)],
"--chat_id", str(chat_id),
"--token", token,
"--directory", os.path.join(os.getcwd(), 'credentials', 'instagram'),
]
if mode == 'user':
arguments += ["--download_user", user_input]
else:
arguments += ["--download_hashtag", user_input]
process_handler(['python', python_file] + arguments, False, 'instagram', chat_id)
except Exception as e:
bot.send_message(chat_id, f'Bu mesajı aldıysan bir şeyler çok yanlış ve büyük ihtimalle benimle ilgili değil. {e}')
def get_instagram_follow_info(message):
global usernames, instagram_command_flags
try:
chat_id = message.chat.id
user_input = message.text.strip()
if user_input == 'cancel':
bot.send_message(chat_id, "İşlem iptal edildi.")
return
mode = instagram_command_flags[str(chat_id)]
bot.send_message(message.chat.id, f"İşlem başlatılıyor...")
yaml_file, site_path = gramaddict_yaml_file(message.chat.id)
# edit the yaml file
configure_yaml_file(yaml_file, f'{mode}[{user_input}]')
# run the bot
arguments = [
'gramaddict', 'run',
"--config", f'accounts/{usernames[str(message.chat.id)]}/config.yml',
]
process_handler(arguments, False, 'gramaddict', message.chat.id, cwd=f'{site_path}/GramAddict')
except Exception as e:
bot.send_message(chat_id, f'Bu mesajı aldıysan bir şeyler çok yanlış ve büyük ihtimalle benimle ilgili değil. {e}')
def get_instagram_username(message):
try:
chat_id = message.chat.id
username = message.text.strip()
if username == 'cancel':
bot.send_message(chat_id, "İşlem iptal edildi.")
return
with open(f'{chat_id}_instagram_temp.json', 'w') as f:
json.dump({'username': username}, f)
bot.send_message(chat_id, "Şifrenizi giriniz: , işlemi iptal etmek için 'cancel' yazabilirsiniz.")
bot.register_next_step_handler_by_chat_id(chat_id, get_instagram_password)
except Exception as e:
bot.send_message(chat_id, f'Bu mesajı aldıysan bir şeyler çok yanlış ve büyük ihtimalle benimle ilgili değil. {e}')
def get_instagram_password(message):
try:
chat_id = message.chat.id
password = message.text.strip()
if password == 'cancel':
bot.send_message(chat_id, "İşlem iptal edildi.")
return
with open(f'{chat_id}_instagram_temp.json', 'r') as f:
data = json.load(f)
username = data['username']
os.remove(f'{chat_id}_instagram_temp.json')
instagram_path = os.path.join(os.getcwd(), 'credentials', 'instagram')
bot.send_message(message.chat.id, f'{username} kullanıcısı ekleniyor.')
python_file = os.path.join(os.getcwd(), 'instagram', 'instagram.py')
arguments = [
"--mode", "add_account",
"--username", username,
"--password", password,
"--chat_id", str(chat_id),
"--token", token,
"--directory", instagram_path,
]
out = process_handler(['python', python_file] + arguments, True, 'instagram', message.chat.id)
if(not out[0]):
bot.send_message(chat_id, f'Bir sorun oluştu: {out[1]}')
return
except Exception as e:
bot.send_message(chat_id, f'Bu mesajı aldıysan bir şeyler çok yanlış ve büyük ihtimalle benimle ilgili değil. {e}')
# tesseract ocr
def get_tesseract_image(message):
try:
chat_id = message.chat.id
if message.content_type != 'photo':
bot.send_message(chat_id, "Hata: Lütfen bir fotoğraf gönderiniz. İşlem iptal edildi.")
return
file_id = message.photo[-1].file_id
file_info = bot.get_file(file_id)
downloaded_file = bot.download_file(file_info.file_path)
with open(f'temp_content/{chat_id}_ocr_temp.jpg', 'wb') as new_file:
new_file.write(downloaded_file)
result_raw = subprocess.run(f'tesseract temp_content/{chat_id}_ocr_temp.jpg temp_content/{chat_id}_ocr_temp', shell=True, capture_output=True, text=True)
if result_raw.returncode != 0:
raise Exception(result_raw.stderr)
with open(f'temp_content/{chat_id}_ocr_temp.txt', 'r') as f:
temp_result = f.read()
# remove the temp file
os.remove(f'temp_content/{chat_id}_ocr_temp.txt')
detected_lang = detect(temp_result) # Detect language
lang = Language.get(detected_lang).to_alpha3() # Convert to 3-char code
bot.send_message(chat_id, f"Algılanan dil: {lang}")
final_result = subprocess.run(f'tesseract temp_content/{chat_id}_ocr_temp.jpg temp_content/{chat_id}_ocr -l {lang}', shell=True, capture_output=True, text=True)
if final_result.returncode != 0:
raise Exception(final_result.stderr)
os.remove(f'temp_content/{chat_id}_ocr_temp.jpg')
# send file to the user
bot.send_document(chat_id, open(f'temp_content/{chat_id}_ocr.txt', 'rb'))
os.remove(f'temp_content/{chat_id}_ocr.txt')
except Exception as e:
# remove temp files if exists
if os.path.exists(f'temp_content/{chat_id}_ocr_temp.jpg'):
os.remove(f'temp_content/{chat_id}_ocr_temp.jpg')
if os.path.exists(f'temp_content/{chat_id}_ocr_temp.txt'):
os.remove(f'temp_content/{chat_id}_ocr_temp.txt')
if os.path.exists(f'temp_content/{chat_id}_ocr.txt'):
os.remove(f'temp_content/{chat_id}_ocr.txt')
bot.send_message(chat_id, f'Bu mesajı aldıysan bir şeyler çok yanlış ve büyük ihtimalle benimle ilgili değil. {e}')
# command handlers
## start, help, info
@bot.message_handler(commands=['start', 'help', 'info'])
def start(message):
# open the welcome message file
# create reply markup
keyboard = types.InlineKeyboardMarkup(row_width=2)
whoami_button = types.InlineKeyboardButton("Ben Kimim? \U0001F464", callback_data='whoami')
howtowork_button = types.InlineKeyboardButton("Nasıl Çalışır? \U0001F4BB", callback_data='howtowork')
contact_button = types.InlineKeyboardButton("İletişim \U0001F4E9", callback_data='contact')
keyboard.add(whoami_button, howtowork_button, contact_button)
start = open('info/start.txt', 'r', encoding='utf-8')
start_message = start.read()
start.close()
bot.send_message(message.chat.id, start_message, reply_markup=keyboard)
@bot.callback_query_handler(func=lambda call: call.data == 'whoami')
def whoami(call):
whoami = open('info/whoami.txt', 'r', encoding='utf-8')
whoami_message = whoami.read()
whoami.close()
bot.send_message(call.message.chat.id, whoami_message)
bot.send_photo(call.message.chat.id, photo = 'AgACAgQAAxkDAAIEgWYkV3BKtaeqtdZQLXC4NSB_LF7LAALtwTEbjY8gUYKMYUIbPb_0AQADAgADeQADNAQ', caption='Gerçekte ben.')
@bot.callback_query_handler(func=lambda call: call.data == 'howtowork')
def howtowork(call):
howtowork = open('info/howtowork.txt', 'r', encoding='utf-8')
howtowork_message = howtowork.read()
howtowork.close()
bot.send_message(call.message.chat.id, howtowork_message, parse_mode='HTML')
@bot.callback_query_handler(func=lambda call: call.data == 'contact')
def contact(call):
contact = open('info/contact.txt', 'r', encoding='utf-8')
contact_message = contact.read()
contact.close()
bot.send_message(call.message.chat.id, contact_message)
## youtube
@bot.message_handler(commands=['youtube'])
def youtube_handler(message):
if not access_control(message.chat.id):
return
# Extract the YouTube URL from the message text
try:
youtube_url = message.text.split(' ', 1)[1]
youtube_urls[message.chat.id] = YoutubeHelper(youtube_url)
except IndexError:
bot.reply_to(message, "Hata: youtube komutu kullanımı '/youtube video_link' olacak şekildedir daha fazla detay için '/help' komutunu kullanabilirsiniz.")
return
# Create inline keyboard markup
keyboard = types.InlineKeyboardMarkup(row_width=2)
full_video_button = types.InlineKeyboardButton("Full Video \U0001F517", callback_data='full_video')
extract_clip_button = types.InlineKeyboardButton("Klip \U0001F3AC", callback_data='extract_clip')
only_audio_button = types.InlineKeyboardButton("Sadece Ses \U0001F50A", callback_data='only_audio')
cancel_button = types.InlineKeyboardButton("İptal \U0000274C", callback_data='cancel')
keyboard.add(full_video_button, extract_clip_button, only_audio_button, cancel_button)
bot.reply_to(message, "Lütfen bir seçenek seçiniz.", reply_markup=keyboard)
@bot.callback_query_handler(func=lambda call: call.data == 'full_video')
def full_video(call):
global youtube_urls
youtube_url = youtube_urls[call.message.chat.id].url
bot.delete_message(call.message.chat.id, call.message.message_id)
bot.send_message(call.message.chat.id, "Video indiriliyor...\nLütfen bekleyin.")
# call the downloader
executable_file = os.path.join(os.getcwd(), 'youtube', 'executable', 'youtube')
arguments = [youtube_url, os.getcwd(), 'full_video']
out = process_handler([executable_file] + arguments, True, 'youtube', call.message.chat.id)
if(not out[0]):
bot.send_message(call.message.chat.id, f'Bir sorun oluştu: {out[1]}')
return
file_handler(call.message, out[1], type='video')
return
@bot.callback_query_handler(func=lambda call: call.data == 'extract_clip')
def extract_clip(call):
bot.delete_message(call.message.chat.id, call.message.message_id)
# ask for the start and end time
bot.send_message(call.message.chat.id, "Klip başlangıç zamanını giriniz: (Örnek: 00:00). İşlemi iptal etmek için 'cancel' yazabilirsiniz.")
bot.register_next_step_handler_by_chat_id(call.message.chat.id, get_youtube_start_time)
@bot.callback_query_handler(func=lambda call: call.data == 'only_audio')
def only_audio(call):
global youtube_urls
youtube_url = youtube_urls[call.message.chat.id]
bot.delete_message(call.message.chat.id, call.message.message_id)
bot.send_message(call.message.chat.id, "Ses indiriliyor...\nLütfen bekleyin.")
# call the downloader
executable_file = os.path.join(os.getcwd(), 'youtube', 'executable', 'youtube')
arguments = [youtube_url.url , os.getcwd(), 'audio']
out = process_handler([executable_file] + arguments, True, 'youtube', call.message.chat.id)
if(not out[0]):
bot.send_message(call.message.chat.id, f'Bir sorun oluştu: {out[1]}')
return
file_handler(call.message, out[1], type='audio')
return
@bot.callback_query_handler(func=lambda call: call.data == 'cancel')
def cancel(call):
bot.delete_message(call.message.chat.id, call.message.message_id)
bot.send_message(call.message.chat.id, "İşlem iptal edildi.")
return
# ## twitter
# @bot.message_handler(commands=['twitter'])
# def twitter_handler(message):
# if not access_control(message.chat.id):
# return
# # if user has credentials
# credentials = None
# user_credential_path = os.path.join(os.getcwd(), 'credentials', 'twitter', f'{message.chat.id}.json')
# if(os.path.exists(user_credential_path)):
# with open(user_credential_path) as f:
# credentials = json.load(f)
# bot.send_message(message.chat.id, f'{credentials["username"]} kullanıcısı ile giriş yapıldı.')
# else:
# # ask for credentials
# bot.send_message(message.chat.id, "Twitter kullanıcı adınızı giriniz:")