-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsoft.py
More file actions
905 lines (765 loc) · 42.4 KB
/
soft.py
File metadata and controls
905 lines (765 loc) · 42.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
import asyncio
import csv
import random
import re
from tkinter import Tk, Button, Label, Listbox, Scrollbar, Entry, Toplevel, IntVar, StringVar, END, Text, Radiobutton, Frame
from tkinter import ttk
from tkinter.font import Font
from telethon import TelegramClient
from telethon.errors import (
FloodWaitError, UserDeactivatedBanError, UserPrivacyRestrictedError,
ChannelInvalidError, InviteHashInvalidError,
InviteRequestSentError, UserAlreadyParticipantError, SessionPasswordNeededError
)
from telethon.tl.functions.channels import JoinChannelRequest, LeaveChannelRequest
from telethon.tl.functions.messages import ImportChatInviteRequest, GetMessagesViewsRequest
from telethon.tl.functions.account import UpdateStatusRequest
from datetime import datetime, timedelta
# Цветовая схема
DARK_BG = "#1a1a2e"
DARK_FG = "#e6e6e6"
ACCENT_COLOR = "#4cc9f0"
SECONDARY_ACCENT = "#4361ee"
BUTTON_COLOR = "#3a3a5e"
ENTRY_COLOR = "#2d2d44"
LISTBOX_COLOR = "#252538"
HIGHLIGHT_COLOR = "#3a3a5e"
ERROR_COLOR = "#f72585"
SUCCESS_COLOR = "#4cc9f0"
FONT = ("Segoe UI", 10)
TITLE_FONT = ("Segoe UI", 12, "bold")
ACCOUNTS_FILE = 'accounts.csv'
CHANNELS_FILE = 'channels.txt'
OUTPUT_DELAY = 0.1
WAIT_TIME = 1
CODE_TIMEOUT = 30 # Таймаут для ввода кода в секундах
RETRY_DELAY = 5 # Задержка перед повторной попыткой при ошибке базы данных
class SubscriptionBot:
def __init__(self):
self.accounts = self.load_accounts(ACCOUNTS_FILE)
self.channels = self.load_channels(CHANNELS_FILE)
self.current_account_index = 0
self.is_paused = True
self.stop_flag = True
self.wait_time_min = 1
self.wait_time_max = 10
self.unsubscribe_to_subscribe_delay = 1
self.loop = asyncio.new_event_loop()
self.post_link = None
self.start_date = None # Для хранения даты начала анализа постов
asyncio.set_event_loop(self.loop)
self.root = Tk()
self.root.title("Telegram")
self.root.config(bg=DARK_BG)
self.root.geometry("600x700")
self.root.minsize(550, 650)
self.mode = StringVar(value="subscribe")
self.setup_styles()
self.create_ui()
if self.channels:
self.current_channel_var.set(f"Текущий канал: {self.channels[0]}")
self.resume_time = None
self.open_start_date_window() # Открываем окно для выбора даты начала анализа
def setup_styles(self):
self.style = ttk.Style()
self.style.theme_use('clam')
self.style.configure('.', background=DARK_BG, foreground=DARK_FG, font=FONT)
self.style.configure('TButton',
font=FONT,
background=BUTTON_COLOR,
foreground=DARK_FG,
borderwidth=0,
relief='flat',
padding=6)
self.style.map('TButton',
background=[('active', SECONDARY_ACCENT), ('pressed', '#3a5f8a')],
foreground=[('active', DARK_FG), ('pressed', DARK_FG)])
self.style.configure('Accent.TButton',
background=ACCENT_COLOR,
foreground="#000000",
font=("Segoe UI", 10, "bold"))
self.style.map('Accent.TButton',
background=[('active', SECONDARY_ACCENT), ('pressed', '#3a5f8a')])
self.style.configure('TLabel',
font=FONT,
background=DARK_BG,
foreground=DARK_FG)
self.style.configure('Title.TLabel',
font=TITLE_FONT,
background=DARK_BG,
foreground=ACCENT_COLOR)
self.style.configure('TEntry',
fieldbackground=ENTRY_COLOR,
foreground=DARK_FG,
insertcolor=DARK_FG,
borderwidth=1,
relief='flat',
padding=5)
self.style.configure('TRadiobutton',
background=DARK_BG,
foreground=DARK_FG,
indicatorcolor=DARK_BG,
selectcolor=ACCENT_COLOR)
self.style.configure('TListbox',
background=LISTBOX_COLOR,
foreground=DARK_FG,
selectbackground=HIGHLIGHT_COLOR,
borderwidth=0,
relief='flat')
self.style.configure('TFrame',
background=DARK_BG)
def create_ui(self):
main_container = ttk.Frame(self.root)
main_container.pack(fill='both', expand=True, padx=10, pady=10)
title_frame = ttk.Frame(main_container)
title_frame.pack(fill='x', pady=(0, 10))
ttk.Label(title_frame,
text="Telegram checker post",
style='Title.TLabel').pack()
self.create_control_panel(main_container)
self.create_mode_selector(main_container)
self.create_input_fields(main_container)
self.create_status_display(main_container)
self.create_completed_list(main_container)
self.create_current_channel_display(main_container)
self.create_bottom_panel(main_container)
def create_control_panel(self, parent):
control_frame = ttk.Frame(parent)
control_frame.pack(fill='x', pady=(0, 10))
button_frame = ttk.Frame(control_frame)
button_frame.pack(fill='x')
self.start_button = ttk.Button(button_frame,
text="▶ Старт",
command=self.start_subscription)
self.start_button.pack(side='left', padx=2, expand=True, fill='x')
self.pause_button = ttk.Button(button_frame,
text="⏸ Пауза",
command=self.pause_subscription)
self.pause_button.pack(side='left', padx=2, expand=True, fill='x')
self.resume_button = ttk.Button(button_frame,
text="⏵ Продолжить",
command=self.resume_subscription)
self.resume_button.pack(side='left', padx=2, expand=True, fill='x')
def create_mode_selector(self, parent):
mode_frame = ttk.Frame(parent)
mode_frame.pack(fill='x', pady=(10, 5))
ttk.Label(mode_frame, text="Режим работы:").pack(side='left', padx=(0, 10))
ttk.Radiobutton(mode_frame,
text="Подписка",
variable=self.mode,
value="subscribe").pack(side='left', padx=5)
ttk.Radiobutton(mode_frame,
text="Просмотр поста",
variable=self.mode,
value="view").pack(side='left', padx=5)
def create_input_fields(self, parent):
input_frame = ttk.Frame(parent)
input_frame.pack(fill='x', pady=5)
post_frame = ttk.Frame(input_frame)
post_frame.pack(fill='x', pady=2)
ttk.Label(post_frame, text="Ссылка на пост:").pack(side='left', padx=(0, 10))
self.post_entry = ttk.Entry(post_frame)
self.post_entry.pack(side='left', expand=True, fill='x')
current_frame = ttk.Frame(input_frame)
current_frame.pack(fill='x', pady=2)
ttk.Label(current_frame, text="Текущий номер:").pack(side='left', padx=(0, 10))
self.current_entry = ttk.Entry(current_frame)
self.current_entry.pack(side='left', expand=True, fill='x')
def create_status_display(self, parent):
status_frame = ttk.Frame(parent)
status_frame.pack(fill='x', pady=5)
self.main_timer_var = StringVar(value="⏱ Ожидание между аккаунтами: 0 сек")
self.main_timer_label = ttk.Label(status_frame, textvariable=self.main_timer_var)
self.main_timer_label.pack(fill='x')
self.unsubscribe_timer_var = StringVar(value="⏱ Ожидание между отпиской и подпиской: 0 сек")
self.unsubscribe_timer_label = ttk.Label(status_frame, textvariable=self.unsubscribe_timer_var)
self.unsubscribe_timer_label.pack(fill='x')
self.status_var = StringVar(value="🟡 Статус: Ожидание")
self.status_label = ttk.Label(status_frame, textvariable=self.status_var)
self.status_label.pack(fill='x')
self.timing_var = StringVar(value=f"⏱ Тайминг: {self.wait_time_min}-{self.wait_time_max} минут")
self.timing_label = ttk.Label(status_frame, textvariable=self.timing_var)
self.timing_label.pack(fill='x')
def create_completed_list(self, parent):
list_frame = ttk.Frame(parent)
list_frame.pack(fill='both', expand=True, pady=5)
ttk.Label(list_frame, text="Выполненные операции:").pack(anchor='w')
list_container = ttk.Frame(list_frame)
list_container.pack(fill='both', expand=True)
self.completed_list = Listbox(list_container,
bg=LISTBOX_COLOR,
fg=DARK_FG,
selectbackground=HIGHLIGHT_COLOR,
font=FONT,
borderwidth=0,
highlightthickness=0)
self.completed_list.pack(side='left', fill='both', expand=True)
scrollbar = ttk.Scrollbar(list_container, command=self.completed_list.yview)
scrollbar.pack(side='right', fill='y')
self.completed_list.config(yscrollcommand=scrollbar.set)
def create_current_channel_display(self, parent):
self.current_channel_var = StringVar(value="🔗 Текущий канал: не указан")
self.current_channel_label = ttk.Label(parent,
textvariable=self.current_channel_var,
font=("Segoe UI", 9, "italic"))
self.current_channel_label.pack(fill='x', pady=(5, 0))
def create_bottom_panel(self, parent):
bottom_frame = ttk.Frame(parent)
bottom_frame.pack(fill='x', pady=(5, 0))
self.resume_time_button = ttk.Button(bottom_frame,
text="⏰ Время старта",
command=self.open_resume_time_window)
self.resume_time_button.pack(side='left', padx=2, expand=True, fill='x')
self.stop_button = ttk.Button(bottom_frame,
text="⏹ Стоп",
command=self.stop_subscription,
style='Accent.TButton')
self.stop_button.pack(side='left', padx=2, expand=True, fill='x')
self.time_button = ttk.Button(bottom_frame,
text="⚙️ Тайминг",
command=self.open_time_window)
self.time_button.pack(side='left', padx=2, expand=True, fill='x')
self.links_button = ttk.Button(bottom_frame,
text="🔗 Ссылки",
command=self.change_links)
self.links_button.pack(side='left', padx=2, expand=True, fill='x')
def load_accounts(self, filename):
accounts = []
try:
with open(filename, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
accounts.append((row['phone'], int(row['api_id']), row['api_hash']))
random.shuffle(accounts)
except FileNotFoundError:
print(f"Ошибка: Файл {filename} не найден")
except Exception as e:
print(f"Ошибка при загрузке аккаунтов: {e}")
return accounts
def load_channels(self, filename):
channels = []
try:
with open(filename, 'r') as f:
channels = [line.strip() for line in f.readlines() if line.strip()]
except FileNotFoundError:
print(f"Ошибка: Файл {filename} не найден")
except Exception as e:
print(f"Ошибка при загрузке каналов: {e}")
return channels
def change_links(self):
link_window = Toplevel(self.root)
link_window.title("Редактирование ссылок")
link_window.config(bg=DARK_BG)
link_window.resizable(False, False)
link_window.option_add('*Background', DARK_BG)
link_window.option_add('*Foreground', DARK_FG)
link_window.option_add('*Font', FONT)
container = ttk.Frame(link_window)
container.pack(padx=15, pady=15)
ttk.Label(container,
text="Введите ссылки канала (по одной на строку):",
style='Title.TLabel').grid(row=0, column=0, columnspan=2, pady=10)
text_box = Text(container,
height=10,
width=50,
bg=ENTRY_COLOR,
fg=DARK_FG,
selectbackground=HIGHLIGHT_COLOR,
insertbackground=DARK_FG,
font=FONT,
relief='flat',
padx=5,
pady=5)
text_box.grid(row=1, column=0, columnspan=2, pady=5)
for channel in self.channels:
text_box.insert(END, channel + "\n")
def save_links():
new_links = text_box.get("1.0", END).strip().split("\n")
new_links = [link for link in new_links if link.strip()]
if new_links:
try:
with open(CHANNELS_FILE, 'w') as file:
for link in new_links:
file.write(link + "\n")
self.channels = new_links
self.current_channel_var.set(f"🔗 Текущий канал: {self.channels[0] if self.channels else 'не указан'}")
link_window.destroy()
except Exception as e:
print(f"Ошибка при сохранении ссылок: {e}")
save_button = ttk.Button(container,
text="Сохранить",
command=save_links,
style='Accent.TButton')
save_button.grid(row=2, column=0, columnspan=2, pady=10, sticky='ew')
def open_time_window(self):
time_window = Toplevel(self.root)
time_window.title("Настройка времени")
time_window.config(bg=DARK_BG)
time_window.resizable(False, False)
time_window.option_add('*Background', DARK_BG)
time_window.option_add('*Foreground', DARK_FG)
time_window.option_add('*Font', FONT)
container = ttk.Frame(time_window)
container.pack(padx=15, pady=15)
ttk.Label(container,
text="Настройка временных интервалов",
style='Title.TLabel').grid(row=0, column=0, columnspan=2, pady=10)
min_time_var = IntVar(value=self.wait_time_min)
max_time_var = IntVar(value=self.wait_time_max)
delay_var = IntVar(value=self.unsubscribe_to_subscribe_delay)
ttk.Label(container, text="Минимальное время между подписками (мин):").grid(row=1, column=0, sticky='w', pady=2)
min_entry = ttk.Entry(container, textvariable=min_time_var)
min_entry.grid(row=1, column=1, pady=2, padx=5)
ttk.Label(container, text="Максимальное время между подписками (мин):").grid(row=2, column=0, sticky='w', pady=2)
max_entry = ttk.Entry(container, textvariable=max_time_var)
max_entry.grid(row=2, column=1, pady=2, padx=5)
ttk.Label(container, text="Время между отпиской и подпиской (сек):").grid(row=3, column=0, sticky='w', pady=2)
delay_entry = ttk.Entry(container, textvariable=delay_var)
delay_entry.grid(row=3, column=1, pady=2, padx=5)
def save_time_settings():
try:
self.wait_time_min = min_time_var.get()
self.wait_time_max = max_time_var.get()
self.unsubscribe_to_subscribe_delay = delay_var.get()
if self.wait_time_min <= 0 or self.wait_time_max <= 0 or self.unsubscribe_to_subscribe_delay < 0:
raise ValueError("Временные интервалы должны быть положительными")
self.timing_var.set(f"⏱ Тайминг: {self.wait_time_min}-{self.wait_time_max} минут")
time_window.destroy()
except Exception as e:
print(f"Ошибка при сохранении настроек времени: {e}")
save_button = ttk.Button(container,
text="Сохранить настройки",
command=save_time_settings,
style='Accent.TButton')
save_button.grid(row=4, column=0, columnspan=2, pady=10, sticky='ew')
def open_resume_time_window(self):
time_window = Toplevel(self.root)
time_window.title("Настройка времени старта")
time_window.config(bg=DARK_BG)
time_window.resizable(False, False)
time_window.option_add('*Background', DARK_BG)
time_window.option_add('*Foreground', DARK_FG)
time_window.option_add('*Font', FONT)
container = ttk.Frame(time_window)
container.pack(padx=15, pady=15)
ttk.Label(container,
text="Установите время старта",
style='Title.TLabel').grid(row=0, column=0, columnspan=2, pady=10)
resume_hour_var = IntVar()
resume_minute_var = IntVar()
ttk.Label(container, text="Часы (0-23):").grid(row=1, column=0, sticky='w', pady=2)
hour_entry = ttk.Entry(container, textvariable=resume_hour_var, width=5)
hour_entry.grid(row=1, column=1, pady=2, padx=5, sticky='w')
ttk.Label(container, text="Минуты (0-59):").grid(row=2, column=0, sticky='w', pady=2)
minute_entry = ttk.Entry(container, textvariable=resume_minute_var, width=5)
minute_entry.grid(row=2, column=1, pady=2, padx=5, sticky='w')
def save_resume_time():
try:
hour = resume_hour_var.get()
minute = resume_minute_var.get()
if 0 <= hour <= 23 and 0 <= minute <= 59:
self.resume_time = datetime.strptime(f"{hour}:{minute}", "%H:%M").time()
time_window.destroy()
else:
self.status_var.set("🔴 Ошибка: неверное время")
except ValueError:
self.status_var.set("🔴 Ошибка: неверный формат времени")
save_button = ttk.Button(container,
text="Установить время",
command=save_resume_time,
style='Accent.TButton')
save_button.grid(row=3, column=0, columnspan=2, pady=10, sticky='ew')
def open_start_date_window(self):
date_window = Toplevel(self.root)
date_window.title("Выбор даты начала анализа")
date_window.config(bg=DARK_BG)
date_window.resizable(False, False)
date_window.option_add('*Background', DARK_BG)
date_window.option_add('*Foreground', DARK_FG)
date_window.option_add('*Font', FONT)
container = ttk.Frame(date_window)
container.pack(padx=15, pady=15)
ttk.Label(container,
text="Укажите дату и время начала анализа постов",
style='Title.TLabel').grid(row=0, column=0, columnspan=2, pady=10)
# Поля для ввода даты и времени
ttk.Label(container, text="День (1-31):").grid(row=1, column=0, sticky='w', pady=2)
day_var = IntVar(value=datetime.now().day)
day_entry = ttk.Entry(container, textvariable=day_var, width=5)
day_entry.grid(row=1, column=1, pady=2, padx=5, sticky='w')
ttk.Label(container, text="Месяц (1-12):").grid(row=2, column=0, sticky='w', pady=2)
month_var = IntVar(value=datetime.now().month)
month_entry = ttk.Entry(container, textvariable=month_var, width=5)
month_entry.grid(row=2, column=1, pady=2, padx=5, sticky='w')
ttk.Label(container, text="Год (например, 2025):").grid(row=3, column=0, sticky='w', pady=2)
year_var = IntVar(value=datetime.now().year)
year_entry = ttk.Entry(container, textvariable=year_var, width=5)
year_entry.grid(row=3, column=1, pady=2, padx=5, sticky='w')
ttk.Label(container, text="Часы (0-23):").grid(row=4, column=0, sticky='w', pady=2)
hour_var = IntVar(value=0)
hour_entry = ttk.Entry(container, textvariable=hour_var, width=5)
hour_entry.grid(row=4, column=1, pady=2, padx=5, sticky='w')
ttk.Label(container, text="Минуты (0-59):").grid(row=5, column=0, sticky='w', pady=2)
minute_var = IntVar(value=0)
minute_entry = ttk.Entry(container, textvariable=minute_var, width=5)
minute_entry.grid(row=5, column=1, pady=2, padx=5, sticky='w')
def save_start_date():
try:
day = day_var.get()
month = month_var.get()
year = year_var.get()
hour = hour_var.get()
minute = minute_var.get()
# Проверка корректности введенных значений
if (1 <= day <= 31 and 1 <= month <= 12 and year >= 2000 and
0 <= hour <= 23 and 0 <= minute <= 59):
self.start_date = datetime(year, month, day, hour, minute)
print(f"Дата начала анализа установлена: {self.start_date}")
date_window.destroy()
else:
print("Ошибка: Неверные значения даты или времени")
except ValueError:
print("Ошибка: Неверный формат даты или времени")
save_button = ttk.Button(container,
text="Установить дату",
command=save_start_date,
style='Accent.TButton')
save_button.grid(row=6, column=0, columnspan=2, pady=10, sticky='ew')
# Если окно закрывается без сохранения, используем начало текущего дня
date_window.protocol("WM_DELETE_WINDOW", lambda: self.set_default_start_date(date_window))
def set_default_start_date(self, window):
# Устанавливаем начало текущего дня (00:00) как дату начала анализа
self.start_date = datetime.combine(datetime.today(), datetime.min.time())
print(f"Дата начала анализа не указана, используется начало текущего дня: {self.start_date}")
window.destroy()
def parse_post_link(self, link):
try:
pattern = r"https://t\.me/c/(\d+)/(\d+)"
match = re.match(pattern, link)
if match:
channel_id = int(match.group(1))
return channel_id
raise ValueError("Неверный формат ссылки. Ожидается: https://t.me/c/<channel_id>/<message_id>")
except Exception as e:
print(f"Ошибка при разборе ссылки {link}: {e}")
return None
async def view_post(self, client, link):
try:
channel_id = self.parse_post_link(link)
if channel_id is None:
return False
# Попробуем получить сущность канала
try:
channel_id = int(f"-100{channel_id}")
peer = await client.get_entity(channel_id)
print(f"Получен peer для канала {link}: {peer.id}, тип: {type(peer).__name__}")
except (ValueError, ChannelInvalidError):
try:
peer = await client.get_entity(-1000000000000 + channel_id)
print(f"Получен peer через альтернативный ID для {link}")
except Exception as e:
print(f"Не удалось получить сущность канала для {link}: {e}")
return False
# Проверяем тип объекта
if not type(peer).__name__ == 'Channel' or not (peer.broadcast or peer.megagroup):
print(f"Ошибка: {link} указывает на неподдерживаемый тип объекта ({type(peer).__name__}).")
return False
# Подписываемся на канал, если нет доступа
try:
await client(JoinChannelRequest(peer))
print(f"Подписался на канал для просмотра {link}")
except UserAlreadyParticipantError:
print(f"Уже участник канала {link}")
except Exception as e:
print(f"Не удалось подписаться на канал {link}: {e}")
return False
# Получаем сообщения начиная с указанной даты (self.start_date)
if not self.start_date:
self.start_date = datetime.combine(datetime.today(), datetime.min.time())
print(f"Дата начала анализа не указана, используется начало текущего дня: {self.start_date}")
print(f"Получение сообщений начиная с {self.start_date}")
# Получаем последние 200 сообщений без ограничения по offset_date
messages = await client.get_messages(peer, limit=200)
# Фильтруем сообщения, оставляя только те, что позже self.start_date
message_ids = [msg.id for msg in messages if msg.date.replace(tzinfo=None) >= self.start_date]
total_messages = len(messages)
print(f"Получено {total_messages} сообщений, из них {len(message_ids)} начиная с {self.start_date}")
if message_ids:
await client(GetMessagesViewsRequest(
peer=peer,
id=message_ids,
increment=True
))
print(f"Просмотрено {len(message_ids)} постов начиная с {self.start_date}")
return True
else:
print(f"Нет постов начиная с {self.start_date}. Всего сообщений: {total_messages}")
# Проверяем, есть ли вообще сообщения
recent_messages = await client.get_messages(peer, limit=10)
if recent_messages:
print(f"Самое новое сообщение от {recent_messages[0].date}")
for msg in recent_messages:
print(f"Сообщение ID {msg.id}: {msg.text[:50]}...")
else:
print("Канал пуст или сообщения недоступны")
return False
except ChannelInvalidError:
print(f"Ошибка: Аккаунт не имеет доступа к каналу {link} после попытки подписки.")
return False
except Exception as e:
print(f"Ошибка при просмотре постов {link}: {e}")
return False
def pause_subscription(self):
self.is_paused = True
self.status_var.set("Статус: На паузе")
def resume_subscription(self):
self.is_paused = False
self.status_var.set("Статус: В работе")
def stop_subscription(self):
self.start_button.config(state="normal")
self.stop_flag = True
def start_subscription(self):
self.start_button.config(state="disabled")
self.stop_flag = False
self.post_link = self.post_entry.get() if self.mode.get() == "view" else None
if self.mode.get() == "view" and not self.post_link:
print("Ошибка: Не указана ссылка на пост")
self.start_button.config(state="normal")
return
# Принудительный старт, если время старта не указано
if not self.resume_time:
print("Время старта не указано, начинаем работу немедленно...")
self.loop.create_task(self.run_process())
else:
current_time = datetime.now().time()
time_difference = self.calculate_time_difference(current_time, self.resume_time)
if time_difference > 0:
print(f"Ожидание до {self.resume_time}...")
self.loop.create_task(self.wait_until_start(time_difference))
else:
self.loop.create_task(self.run_process())
def calculate_time_difference(self, current_time, resume_time):
try:
current_dt = datetime.combine(datetime.today(), current_time)
future_dt = datetime.combine(datetime.today(), resume_time)
return (future_dt - current_dt).seconds
except Exception as e:
print(f"Ошибка при вычислении разницы времени: {e}")
return 0
async def wait_until_start(self, time_difference):
await asyncio.sleep(time_difference)
print("Время старта наступило, начинаем работу...")
self.loop.create_task(self.run_process())
async def run_process(self):
if self.mode.get() == "subscribe":
await self.run_subscription()
else:
await self.run_view_post()
async def run_subscription(self):
for idx, (phone, api_id, api_hash) in enumerate(self.accounts):
if self.stop_flag:
break
if self.is_paused:
while self.is_paused:
if self.resume_time:
now = datetime.now().time()
if now >= self.resume_time:
self.is_paused = False
print("Продолжаем работу.")
break
await asyncio.sleep(0.1)
client = TelegramClient(f'session_{phone}', api_id, api_hash)
self.current_account_index = idx
self.update_current_account(phone)
try:
await client.connect()
if not await client.is_user_authorized():
try:
await client.send_code_request(phone)
code = await self.get_code_with_timeout(phone)
if code:
try:
await client.sign_in(phone, code)
except SessionPasswordNeededError:
password = await self.get_password(phone)
if password:
await client.sign_in(password=password)
else:
print(f"Пароль не введен для {phone}, пропускаем аккаунт.")
continue
else:
print(f"Код не введен для {phone} в течение 30 секунд, пропускаем аккаунт.")
continue
except FloodWaitError as e:
print(f"Слишком много запросов для {phone}, ожидание {e.seconds} секунд.")
await asyncio.sleep(e.seconds)
continue
except Exception as e:
print(f"Ошибка авторизации для {phone}: {e}")
continue
await client(UpdateStatusRequest(offline=False))
await self.subscribe_to_channels(client, self.channels)
self.add_to_completed(phone)
sleep_time = random.randint(self.wait_time_min * 60, self.wait_time_max * 60) # Конвертация минут в секунды
await self.update_main_timer(sleep_time)
except Exception as e:
print(f"Ошибка с {phone}: {e}")
if "database is locked" in str(e):
print(f"База данных заблокирована, ожидание {RETRY_DELAY} секунд перед повторной попыткой...")
await asyncio.sleep(RETRY_DELAY)
finally:
await self.safe_disconnect(client)
async def run_view_post(self):
for idx, (phone, api_id, api_hash) in enumerate(self.accounts):
if self.stop_flag:
break
if self.is_paused:
while self.is_paused:
if self.resume_time:
now = datetime.now().time()
if now >= self.resume_time:
self.is_paused = False
print("Продолжаем работу.")
break
await asyncio.sleep(0.1)
client = TelegramClient(f'session_{phone}', api_id, api_hash)
self.current_account_index = idx
self.update_current_account(phone)
try:
await client.connect()
if not await client.is_user_authorized():
try:
await client.send_code_request(phone)
code = await self.get_code_with_timeout(phone)
if code:
try:
await client.sign_in(phone, code)
except SessionPasswordNeededError:
password = await self.get_password(phone)
if password:
await client.sign_in(password=password)
else:
print(f"Пароль не введен для {phone}, пропускаем аккаунт.")
continue
else:
print(f"Код не введен для {phone} в течение 30 секунд, пропускаем аккаунт.")
continue
except FloodWaitError as e:
print(f"Слишком много запросов для {phone}, ожидание {e.seconds} секунд.")
await asyncio.sleep(e.seconds)
continue
except Exception as e:
print(f"Ошибка авторизации для {phone}: {e}")
continue
success = await self.view_post(client, self.post_link)
if success:
self.add_to_completed(phone)
await asyncio.sleep(1)
except Exception as e:
print(f"Ошибка с {phone}: {e}")
if "database is locked" in str(e):
print(f"База данных заблокирована, ожидание {RETRY_DELAY} секунд перед повторной попыткой...")
await asyncio.sleep(RETRY_DELAY)
finally:
await self.safe_disconnect(client)
async def safe_disconnect(self, client):
try:
await client.disconnect()
except Exception as e:
print(f"Ошибка при отключении клиента: {e}")
if "database is locked" in str(e):
print(f"База данных заблокирована, повторная попытка через {RETRY_DELAY} секунд...")
await asyncio.sleep(RETRY_DELAY)
await client.disconnect()
def update_current_account(self, phone):
self.current_entry.delete(0, END)
self.current_entry.insert(0, phone)
def add_to_completed(self, phone):
index = self.completed_list.size() + 1
self.completed_list.insert(END, f"{index}. {phone}")
async def get_code_with_timeout(self, phone):
print(f'Ожидание кода для {phone} (30 секунд)...')
try:
code = await asyncio.wait_for(
self.loop.run_in_executor(None, lambda: input(f'Введите код для {phone}: ')),
timeout=CODE_TIMEOUT
)
return code.strip()
except asyncio.TimeoutError:
print(f"Таймаут: код для {phone} не введен в течение 30 секунд")
return None
except asyncio.CancelledError:
return None
async def get_password(self, phone):
print(f'Требуется пароль для {phone} (двухфакторная аутентификация)...')
try:
password = await self.loop.run_in_executor(None, lambda: input(f'Введите пароль для {phone}: '))
return password
except asyncio.CancelledError:
return None
async def unsubscribe_from_channel(self, client, channel):
try:
entity = await self.get_channel_entity(client, channel)
if not entity:
print(f'Не удалось получить сущность канала для {channel}')
return False
print(f'Отписываюсь от {channel}...')
await client(LeaveChannelRequest(entity))
return True
except Exception as e:
print(f'Ошибка при отписке от канала {channel}: {e}')
return False
async def subscribe_to_channels(self, client, channels):
for channel in channels:
self.current_channel_var.set(f"Текущая ссылка: {channel}")
try:
await asyncio.sleep(OUTPUT_DELAY)
was_unsubscribed = await self.unsubscribe_from_channel(client, channel)
if was_unsubscribed:
await self.update_unsubscribe_timer(self.unsubscribe_to_subscribe_delay)
print(f'Подписываю на {channel}')
entity = await self.get_channel_entity(client, channel)
if entity:
await client(JoinChannelRequest(entity))
print(f'Успешно подписался на {channel}')
else:
print(f'Не удалось получить сущность для канала {channel}')
except FloodWaitError as e:
print(f'Ошибка ожидания: {e.seconds} секунд. Пропускаем {channel}.')
except Exception as e:
print(f'Ошибка при подписке на {channel}: {e}')
async def get_channel_entity(self, client, channel):
try:
if "joinchat" in channel or "+" in channel:
hash_part = channel.split('/')[-1].replace('+', '')
try:
invite = await client(ImportChatInviteRequest(hash_part))
return invite.chats[0]
except UserAlreadyParticipantError:
print(f'Пользователь уже участник {channel}. Используем get_entity для отписки.')
return await client.get_entity(channel)
else:
return await client.get_entity(channel)
except Exception as e:
print(f'Ошибка при получении сущности канала для {channel}: {e}')
return None
async def update_main_timer(self, seconds):
for remaining in range(seconds, 0, -1):
self.main_timer_var.set(f"Ожидание между аккаунтами: {remaining} сек")
await asyncio.sleep(1)
self.main_timer_var.set("Готово к следующему аккаунту...")
async def update_unsubscribe_timer(self, seconds):
for remaining in range(seconds, 0, -1):
self.unsubscribe_timer_var.set(f"Ожидание между отпиской и подпиской: {remaining} сек")
await asyncio.sleep(1)
self.unsubscribe_timer_var.set("")
def run(self):
self.root.after(20, self.check_asyncio_loop)
self.root.mainloop()
def check_asyncio_loop(self):
self.loop.call_soon(self.loop.stop)
self.loop.run_forever()
self.root.after(100, self.check_asyncio_loop)
if __name__ == '__main__':
bot = SubscriptionBot()
bot.run()