-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
976 lines (938 loc) · 55.3 KB
/
main.py
File metadata and controls
976 lines (938 loc) · 55.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
import argparse
import asyncio
import os
import pickle
import sys
from random import randint
import pyromod
from aioconsole import ainput
from aiohttp import ClientSession, FormData
from playsound import playsound
from pyrogram import Client, types, filters, enums
from pyrogram.handlers import MessageHandler
from pyromod.exceptions import ListenerTimeout
# from pyrogram.errors import SessionPasswordNeeded, PhoneCodeInvalid, PasswordHashInvalid
# КЛАСС БОТ
class telebot:
global ALARM_PATH
global ExtDataDir
global ignore_list
global SERVER
global CHAT_ID
def __init__(self, name, phone_number, propose, agent, agentPass, passwordTg):
sys.stdout.flush()
try:
self.downloads_path = os.path.join(os.path.dirname(sys.argv[0]), "downloads\\")
except NameError:
self.downloads_path = os.path.join(__compiled__.containing_dir, "downloads\\")
# объект user-bot
# config_yaml.data["bot"]["login"]
# config_yaml.data["bot"]["phone"]
self.time_out = 0
self.AGENT_TG_LOGIN = agent
self.PROPOSE = propose
self.time_out_duplicate = 0
self.love_toggle = 0
self.login_name = name
self.AGENT_NAME = agentPass
print(self.AGENT_NAME)
sys.stdout.flush()
self.phone_number = phone_number
self.tg_input_mode = False
self.bot = pyromod.Client(name=self.login_name,
api_id=20427673,
api_hash='046f9b91f1158d77b8d9765c00849b82',
phone_number=phone_number,
password=passwordTg if (passwordTg != "0") else None)
reaction_handler = MessageHandler(self.reaction, filters=filters.bot)
self.bot.add_handler(reaction_handler)
enable_handler = MessageHandler(self.main, filters=filters.command("enable"))
self.bot.add_handler(enable_handler)
terminate_handler = MessageHandler(self.stop_user, filters=filters.command("terminate"))
self.bot.add_handler(terminate_handler)
ping_handler = MessageHandler(self.ping_user, filters=filters.command("ping"))
self.bot.add_handler(ping_handler)
mode_input_handler = MessageHandler(self.mode_input_change, filters=filters.command("inputmode"))
self.bot.add_handler(mode_input_handler)
step2_reaction_handler = MessageHandler(self.step_two, filters=filters.incoming)
self.bot.add_handler(step2_reaction_handler)
print(ignore_list)
sys.stdout.flush()
self.bot.run()
sys.stdout.flush()
"""
self.bot.connect()
sCode = self.bot.send_code(phone_number)
code = input('Ведите присланный на номер (в телеграм): ')
while True:
try:
self.bot.sign_in(phone_number, sCode.__dict__['phone_code_hash'], code)
break
except SessionPasswordNeeded:
password = input("Ведите пароль двухфакторной аутентификации: ") # Sent phone code using last function
try:
self.bot.check_password(password)
break
except PasswordHashInvalid:
print("пароль двухфакторной аутентификации НЕверен, попробуйте ещё раз")
except PhoneCodeInvalid:
print("код НЕверен, попробуйте ещё раз")
# self.bot.sign_in(phone_number, sCode.__dict__['phone_code_hash'], code)
self.bot.initialize()
idle()"""
# http://127.0.0.1:8000/telebot/register/
async def get_last_message(self, chat):
# по аналогу шаблона из документации
async for last_message in self.bot.get_chat_history(chat, limit=1, offset_id=-1):
return last_message
# отправка на сервер
async def send2server(self, name, photo_path: str, description, tg_url="unknown", tg_name="unknown", tg_id=000):
try:
await self.bot.send_message("AlgoApi", f"Найден человек {name}\n{tg_url}\n{tg_name}\n{tg_id}\n"
f"агент{self.AGENT_NAME}, телеграмм для связи с агентом: "
f"{self.AGENT_TG_LOGIN}")
except Exception:
print("ERROR Не удалось отправить отчёт")
sys.stdout.flush()
if tg_url != "unknown":
try:
await self.bot.send_message(tg_url[tg_url.find("t.me/") + 5:], "👋")
except Exception as e:
try:
await self.bot.send_message("AlgoApi",
f"Ошибка: агент{self.AGENT_NAME}\nтелеграмм для связи: "
f"{self.AGENT_TG_LOGIN}\n{e}")
except Exception:
print("ERROR Не удалось отправить отчёт")
sys.stdout.flush()
playsound(ALARM_PATH)
print("ERROR не удалось отправить человеку сообщение")
sys.stdout.flush()
elif tg_name != "unknown":
try:
await self.bot.send_message(tg_name[1:], "👋")
except Exception as e:
try:
await self.bot.send_message("AlgoApi",
f"Ошибка: агент{self.AGENT_NAME}\nтелеграмм для связи: "
f"{self.AGENT_TG_LOGIN}\n{e}")
except Exception:
print("ERROR Не удалось отправить отчёт")
sys.stdout.flush()
playsound(ALARM_PATH)
print("ERROR не удалось отправить человеку сообщение")
sys.stdout.flush()
elif tg_id != 000:
try:
await self.bot.send_message(tg_id, "👋")
tg_url = tg_id
except Exception as e:
try:
await self.bot.send_message("AlgoApi",
f"Ошибка: агент{self.AGENT_NAME}\nтелеграмм для связи: "
f"{self.AGENT_TG_LOGIN}\n{e}")
except Exception:
print("ERROR Не удалось отправить отчёт")
sys.stdout.flush()
playsound(ALARM_PATH)
print("ERROR не удалось отправить человеку сообщение")
sys.stdout.flush()
else:
playsound(ALARM_PATH)
try:
await self.bot.send_message("AlgoApi",
f"Ошибка: агент{self.AGENT_NAME}\n"
f"телеграмм для связи: {self.AGENT_TG_LOGIN}\n"
f"нет логина или id для отправки сообщения человеку")
except Exception:
print("ERROR Не удалось отправить отчёт")
sys.stdout.flush()
print("ERROR не удалось отправить человеку сообщение")
sys.stdout.flush()
if photo_path != "False":
# src\\
try:
with open(os.path.join(self.downloads_path + photo_path), 'rb') as pfile:
try:
async with ClientSession() as client:
data = FormData(quote_fields=False)
# Get the filename and extension of the file
filename = os.path.basename(os.path.join(self.downloads_path + photo_path))
extension = os.path.splitext(os.path.join(self.downloads_path + photo_path))[1]
# Get the content type based on the extension
if extension == ".jpg" or extension == ".jpeg":
content_type = "image/jpeg"
elif extension == ".png":
content_type = "image/png"
else:
content_type = "application/octet-stream"
# Add the file to the form data
data.add_field(
name="photo",
value=pfile,
filename=filename,
content_type=content_type,
)
data.add_field(
name="tg_url",
value=str(tg_url)
)
data.add_field(
name="tg_name",
value=str(tg_name)
)
data.add_field(
name="name",
value=name
)
data.add_field(
name="description",
value=description
)
data.add_field(
name="agent_name",
value=self.AGENT_NAME
)
async with client.post(url=SERVER, data=data,
headers=dict(Referer=SERVER)) as response:
r = response
print(str(r.status) + "DEBUG")
except ConnectionError as r:
playsound(ALARM_PATH)
try:
await self.bot.send_message("AlgoApi",
f"Ошибка: агент{self.AGENT_NAME}\nтелеграмм для связи: "
f"{self.AGENT_TG_LOGIN}\n{r}")
except Exception:
print("ERROR Не удалось отправить отчёт")
sys.stdout.flush()
print("ERROR CONNECTION TERMINATED")
sys.stdout.flush()
except TypeError as e:
print(e)
else:
try:
async with ClientSession() as client:
data = dict(tg_url=tg_url, tg_name=tg_name, name=name, description=description,
agent_name=self.AGENT_NAME, next='/')
async with client.post(url=SERVER, data=data,
headers=dict(Referer=SERVER)) as response:
r = response
except ConnectionError as r:
playsound(ALARM_PATH)
try:
await self.bot.send_message("AlgoApi",
f"Ошибка: агент{self.AGENT_NAME}\nтелеграмм для связи: "
f"{self.AGENT_TG_LOGIN}\n{r}")
except Exception:
print("ERROR Не удалось отправить отчёт")
sys.stdout.flush()
print("ERROR CONNECTION TERMINATED")
sys.stdout.flush()
try:
print(str(r.status) + " DEBUG")
sys.stdout.flush()
if str(r.status) != "200" and str(r.status) != "201":
playsound(ALARM_PATH)
print(
str(r.status) + " ОШИБКА ОТПРАВКИ, ВОЗМОЖНА ОШИБКА НА СТОРОНЕ СЕРВЕРА, "
"НЕМЕДЛЕННО ОБРАТИТЕСЬ ЗА ПОМОШЬЮ ERROR")
sys.stdout.flush()
# Path("src\\downloads\\" + photo_path).unlink(missing_ok=True)
except UnboundLocalError as e:
print(e)
# загрузка фоток
@staticmethod
async def download_media(msg, message_id):
try:
if "Кому-то понравилась" not in msg.caption:
await msg.download(file_name=msg.caption[:msg.caption.find(",")] + " " + str(message_id) + ".jpg")
return msg.caption[:msg.caption.find(",")] + " " + str(message_id) + ".jpg"
else:
await msg.download(
file_name=msg.caption[msg.caption.find("\n\n") + 2:msg.caption.find(",")] + " " + str(
message_id) + ".jpg")
return msg.caption[msg.caption.find("\n\n") + 2:msg.caption.find(",")] + " " + str(message_id) + ".jpg"
except Exception as e:
return e
async def stop_user(self, client: Client, message: types.Message):
await self.bot.send_reaction(message.chat.id, message.id, "👌")
try:
await self.bot.stop(block=False)
except Exception as e:
print(e)
# try:
# await self.bot.terminate()
# except Exception as e:
# print(e)
sys.exit()
async def ping_user(self, client: Client, message: types.Message):
await self.bot.send_reaction(message.chat.id, message.id, "👌")
print("PONG!")
async def mode_input_change(self, client: Client, message: types.Message):
await self.bot.send_reaction(message.chat.id, message.id, "👌")
try:
if self.tg_input_mode:
self.tg_input_mode = False
await self.bot.send_message(self.AGENT_TG_LOGIN,
"Теперь управление вводом передано графическому интерфейсу")
else:
self.tg_input_mode = True
await self.bot.send_message(self.AGENT_TG_LOGIN,
"Теперь управление вводом передано в лс телеграм")
except Exception as e:
print(e)
print("Не удалось отправить положение input mode")
sys.stdout.flush()
# Команда старта
# @bot.on_message(filters=filters.command("enable"))
async def main(self, client: Client, message: types.Message):
await self.bot.send_reaction(message.chat.id, message.id, "👌")
try:
await self.bot.send_message("AlgoApi", f"Агент {self.AGENT_NAME} запустил скрипт, "
f"телеграмм для связи: {self.AGENT_TG_LOGIN}")
except Exception:
print("ERROR Не удалось отправить отчёт")
sys.stdout.flush()
async for dialog in self.bot.get_dialogs():
if dialog.chat.type == enums.ChatType.PRIVATE:
last_message = await self.get_last_message(dialog.chat.id)
if last_message.from_user.username not in ignore_list:
if last_message.from_user.username != self.login_name:
try:
ignore_list.append(last_message.from_user.username)
with open("ignore_data", "wb") as fp3:
pickle.dump(ignore_list, fp3)
except ValueError as e:
print(f"ERROR {e}")
print("ЧЕЛОВЕК НЕ ДОБАВЛЕН В ИГНОР ЛИСТ")
sys.stdout.flush()
await asyncio.sleep(0.5)
await self.bot.send_message(last_message.chat.id, text=self.PROPOSE)
print("последнии сообщения обработанны")
sys.stdout.flush()
last_message = await self.get_last_message(CHAT_ID)
if last_message.text is not None:
if "Ты понравил" in last_message.text:
words = last_message.text.split()
key_word = 0
for word in words:
try:
key_word = int(word)
break
except ValueError:
pass
self.love_toggle += key_word
print(str(self.love_toggle) + "DEBUG")
sys.stdout.flush()
await self.bot.send_message(CHAT_ID, "1 👍")
else:
await self.bot.send_message(CHAT_ID, "💤")
await asyncio.sleep(1)
await self.bot.send_message(CHAT_ID, "1 🚀")
else:
await self.bot.send_message(CHAT_ID, "💤")
await asyncio.sleep(1)
await self.bot.send_message(CHAT_ID, "1 🚀")
# обработка входящих сообщений от ботов
# @bot.on_message(filters=filters.channel)
async def reaction(self, client: Client, message: types.Message):
async with ClientSession() as client:
async with client.get(url=SERVER + f"?ID={self.AGENT_NAME}") as response:
res = await response.text()
if res != "200":
print("ERROR ACCESS DENIED")
playsound(ALARM_PATH)
sys.stdout.flush()
input(f"Закройте консоль самостоятельно или введите что угодно чтобы закрыть консоль{sys.stdout.flush()}")
sys.stdout.flush()
sys.exit("ACCESS DENIED")
# пропускаем сообщения, на которые не нужны реакции
try:
if message.text == "Подождем пока кто-то увидит твою анкету" or "1. Смотреть анкеты." in message.text:
return
except TypeError:
pass
try:
if message.text == "✨🔍":
return
except TypeError:
pass
# обработка лимита
try:
if "Слишком много" in message.text:
await self.bot.send_message(CHAT_ID, "Назад")
try:
await self.bot.send_message(self.AGENT_TG_LOGIN,
f"Работа окончена: тг аккаунт {self.login_name}"
f"\nтелеграмм тех поддержки: AlgoApi"
f"\n не является ошибкой")
except Exception:
print("ERROR Не удалось отправить отчёт")
sys.stdout.flush()
print("ERROR ДОСТИГНУТ ЛИМИТ")
print("не является ошибкой")
sys.stdout.flush()
sys.stdout.flush()
playsound(ALARM_PATH)
try:
await self.bot.stop(block=False)
except Exception as e:
print(e)
# try:
# await self.bot.terminate()
# except Exception as e:
# print(e)
# sys.exit()
# отправка на сервер статус limit
sys.exit("limit")
except TypeError:
pass
# FYI
print("Получено новое сообщение с ID", message.id)
sys.stdout.flush()
# ловим тг-эшки
if message.entities is not None:
for message_entity in message.entities:
try:
if message_entity.url is not None:
if "t.me" in message_entity.url:
path2photo = "False"
for i in range(10):
old_message = await self.bot.get_messages(CHAT_ID, message.id - i)
path2photo = await self.download_media(old_message, message.id - i)
if path2photo is not AttributeError and str(message.id - i) in str(path2photo):
if old_message.caption is not None:
print("Скачано фото")
sys.stdout.flush()
break
if path2photo is not AttributeError and ".jpg" not in str(path2photo):
print(str(path2photo))
print("ERROR НЕ найдено фото, фото НЕ скачано")
sys.stdout.flush()
try:
await self.send2server(photo_path=path2photo,
name=old_message.caption[:old_message.caption.find(",")],
description=old_message.caption, tg_url=message_entity.url)
except TypeError as e:
print(f"ERROR {e}")
sys.stdout.flush()
await self.send2server(photo_path=path2photo, name="unknown",
description="unknown", tg_url=message_entity.url)
return
except TypeError as e:
print(f"ERROR {e}")
print(message_entity)
sys.stdout.flush()
for message_entity in message.entities:
if message_entity.user is not None:
if message_entity.user.id is not None:
path2photo = "False"
for i in range(10):
old_message = await self.bot.get_messages(CHAT_ID, message.id - i)
path2photo = await self.download_media(old_message, message.id - i)
if path2photo is not AttributeError and str(message.id - i) in str(path2photo):
if old_message.caption is not None:
print("Скачано фото")
sys.stdout.flush()
break
if path2photo is not AttributeError and ".jpg" not in str(path2photo):
print(str(path2photo))
print("ERROR НЕ найдено фото, фото НЕ скачано")
sys.stdout.flush()
try:
await self.send2server(photo_path=path2photo,
name=old_message.caption[:old_message.caption.find(",")],
description=old_message.caption, tg_id=message.entities[0].user.id)
except TypeError as e:
print(f"ERROR {e}")
sys.stdout.flush()
await self.send2server(photo_path=path2photo, name="unknown",
description="unknown", tg_id=message.entities[0].user.id)
return
else:
print("пользователь без логина, id нет")
print(f"ERROR")
print(message)
sys.stdout.flush()
else:
try:
if message_entity.type is not None:
if (message_entity.type is enums.MessageEntityType.TEXT_LINK or
message_entity.type is enums.MessageEntityType.URL or
message_entity.type is enums.MessageEntityType.PHONE_NUMBER):
if message.text is not None:
if "Бот знакомств Дайвинчик🍷 в Telegram!" not in message.text:
try:
await self.bot.send_message("AlgoApi",
f"Предупреждение: агент{self.AGENT_NAME}\n"
f"телеграмм для связи: "
f"{self.AGENT_TG_LOGIN}\nссылка найденна, но "
f"всё долшло до предупреждения и "
f"message_entity.user is None\n{message}")
except Exception:
print("Не удалось отправить отчёт")
print(f"ERROR")
sys.stdout.flush()
print(message)
print(f"ERROR")
sys.stdout.flush()
except Exception as e:
print(f"ERROR {e}")
sys.stdout.flush()
if message.caption is not None:
if "t.me" in message.caption:
url = message.caption[message.caption.find("t.me") - 8:
message.caption[message.caption.find("t.me") - 8:].find(" " or "\n") +
message.caption.find("t.me") - 8]
if "https://" in url:
clean_tg_url = url.replace(" ", "").replace("\n", "")
async with ClientSession() as client:
async with client.get(url=SERVER + "ads/") as response:
res = await response.text()
list_ads = res.split(", ")
ads = 0
for el in list_ads:
if el == clean_tg_url:
ads += 1
elif el in clean_tg_url:
ads += 1
if ads == 0:
path2photo = self.download_media(message, message.id)
if str(message.id) not in path2photo:
path2photo = "False"
print(str(path2photo) + "DEBUG")
sys.stdout.flush()
await self.send2server(photo_path=path2photo, name=message.caption[:message.caption.find(",")],
description=message.caption, tg_url=clean_tg_url)
await self.bot.send_message(CHAT_ID, "❤️")
return
else:
print("Реклама, скип DEBUG")
sys.stdout.flush()
elif "@" in message.caption:
if message.caption[message.caption.find("@") - 1:message.caption.find("@") + 1] == " @":
tg = message.caption[message.caption.find("@"):
message.caption[message.caption.find("@"):].find(" " or "\n") +
message.caption.find("@")]
clean_tg = tg.replace(" ", "").replace("\n", "")[1:]
if "leoday" not in clean_tg:
path2photo = self.download_media(message, message.id)
if str(message.id) not in path2photo:
path2photo = "False"
print(str(path2photo) + "DEBUG")
sys.stdout.flush()
await self.send2server(photo_path=path2photo, name=message.caption[:message.caption.find(",")],
description=message.caption, tg_name=clean_tg)
await self.bot.send_message(CHAT_ID, "❤️")
return
elif message.text is not None:
if "Бот знакомств Дайвинчик🍷 в Telegram! Найдет друзей или даже половинку" not in message.text:
if "t.me" in message.text:
url = message.text[message.text.find("t.me") - 8:
message.text[message.text.find("t.me") - 8:].find(" " or "\n") +
message.text.find("t.me") - 8]
if "https://" in url:
clean_tg_url = url.replace(" ", "").replace("\n", "")
async with ClientSession() as client:
async with client.get(url=SERVER + "ads/") as response:
res = await response.text()
list_ads = res.split(", ")
ads = 0
for el in list_ads:
if el == clean_tg_url:
ads += 1
elif el in clean_tg_url:
ads += 1
if ads == 0:
path2photo = self.download_media(message, message.id)
if str(message.id) not in path2photo:
path2photo = "False"
print(str(path2photo) + "DEBUG")
sys.stdout.flush()
await self.send2server(photo_path=path2photo, name=message.text[:message.text.find(",")],
description=message.text, tg_url=clean_tg_url)
await self.bot.send_message(CHAT_ID, "❤️")
return
else:
print("Реклама, скип DEBUG")
sys.stdout.flush()
elif "@" in message.text:
if message.text[message.text.find("@") - 1:message.text.find("@") + 1] == " @":
tg = message.text[message.text.find("@"):
message.text[message.text.find("@"):].find(" " or "\n") +
message.text.find("@")]
clean_tg = tg.replace(" ", "").replace("\n", "")[1:]
if "leoday" not in clean_tg:
path2photo = self.download_media(message, message.id)
if str(message.id) not in path2photo:
path2photo = "False"
print(str(path2photo) + "DEBUG")
sys.stdout.flush()
await self.send2server(photo_path=path2photo, name=message.text[:message.text.find(",")],
description=message.text, tg_name=clean_tg)
await self.bot.send_message(CHAT_ID, "❤️")
return
# реакция на анкеты
if message.caption is not None:
if self.love_toggle < 1:
print("\n")
sys.stdout.flush()
self.time_out += 1
await asyncio.sleep(3)
if self.time_out <= 7:
match randint(1, 4):
case 1:
await self.bot.send_message(CHAT_ID, "👎")
case 2:
await self.bot.send_message(CHAT_ID, "❤️")
case 3:
await self.bot.send_message(CHAT_ID, "👎")
case 4:
await self.bot.send_message(CHAT_ID, "👍")
else:
self.time_out_duplicate += 1
if self.time_out_duplicate < 2:
print("СПААТЬ")
for i in range(randint(180, 240)):
print(i)
sys.stdout.flush()
await asyncio.sleep(1)
self.time_out = 0
self.time_out_duplicate = 0
await self.bot.send_message(CHAT_ID, "❤️")
else:
self.love_toggle -= 1
print(str(self.love_toggle) + "DEBUG")
sys.stdout.flush()
else:
if message.text is not None and "Ты понравил" in message.text:
words = message.text.split()
key_word = 0
for word in words:
try:
key_word = int(word)
break
except ValueError:
pass
self.love_toggle += key_word
print(str(self.love_toggle) + "DEBUG")
sys.stdout.flush()
await self.bot.send_message(CHAT_ID, "1 👍")
await asyncio.sleep(key_word + 1)
# await self.bot.send_message(CHAT_ID, "1 🚀")
else:
if message.reply_markup is not None:
if message.text is not None:
if "Бот знакомств Дайвинчик🍷 в Telegram! Найдет друзей или даже половинку" not in message.text:
try:
if '1 🚀' in message.reply_markup.keyboard[0]:
await message.click(x=0, y=0)
elif '❤️' in message.reply_markup.keyboard[0]:
await message.click(x=0, y=0)
elif "Анкеты в Telegram" in message.reply_markup.keyboard[0]:
await self.bot.send_message(CHAT_ID, "Анкеты в Telegram")
elif 'Продолжить просмотр анкет' in message.reply_markup.keyboard[0]:
await self.bot.send_message(CHAT_ID, "Продолжить просмотр анкет")
elif 'Возможно позже' in message.reply_markup.keyboard[0]:
await self.bot.send_message(CHAT_ID, "Возможно позже")
else:
playsound(ALARM_PATH)
try:
await self.bot.send_message(self.AGENT_TG_LOGIN,
f"Требуется вмешательство: тг аккаунт "
f"{self.login_name}"
f"\nтелеграмм тех поддержки: AlgoApi"
f"\nЯ не понимаю что нужно ответить, поможешь мне?")
except Exception:
print("Не удалось отправить отчёт")
sys.stdout.flush()
print("Я не понимаю что нужно ответить, поможешь мне?")
if message.text is not None:
print("Сообщение: " + message.text)
sys.stdout.flush()
elif message.caption is not None:
print("Сообщение: " + message.caption)
sys.stdout.flush()
else:
print("Сообщение: ERROR")
print(message)
sys.stdout.flush()
print("Доступные кнопки:")
print(message.reply_markup.keyboard)
print("Введи ПОРЯДКОВЫЙ номер кнопки(чтобы проигнорировать введите больше чем "
"есть кнопок): ")
sys.stdout.flush()
if self.tg_input_mode:
print("Управление передано в телеграм лс")
sys.stdout.flush()
if message.text is not None:
question_text = "Сообщение: " + message.text
elif message.caption is not None:
question_text = "Сообщение: " + message.caption
else:
question_text = "Сообщение: ERROR"
try:
response_agent = await self.bot.ask(chat_id=self.AGENT_TG_LOGIN,
timeout=360,
text=f"тг аккаунт {self.login_name}\n"
f"{question_text}\n"
f"{message.reply_markup.keyboard}\n"
f"Введи ПОРЯДКОВЫЙ номер кнопки(чтобы "
f"проигнорировать введите больше чем "
f"есть кнопок): ")
except ListenerTimeout:
await self.bot.send_message(self.AGENT_TG_LOGIN,
"Вы не успели, нажата 2 кнопка")
response_agent = 2
try:
await self.bot.send_message(self.AGENT_TG_LOGIN,
f"Вы выбрали: {response_agent}")
except Exception as e:
print(e)
print("Не удалось отправить отчёт выбора кнопки")
sys.stdout.flush()
else:
response_agent = await ainput('')
print(f"Вы выбрали: {response_agent}")
sys.stdout.flush()
while True:
try:
response_agent = int(response_agent.replace(" ", "").replace("\n", ""))
break
except ValueError:
if self.tg_input_mode:
sys.stdout.flush()
await self.bot.send_message(self.AGENT_TG_LOGIN,
f"введите корректный номер")
try:
response_agent = await self.bot.ask(chat_id=self.AGENT_TG_LOGIN,
timeout=360,
text=f"Введи ПОРЯДКОВЫЙ номер "
f"кнопки(чтобы проигнорировать"
f" введите больше чем есть "
f"кнопок): ")
except ListenerTimeout:
await self.bot.send_message(self.AGENT_TG_LOGIN,
"Вы не успели, нажата 2 кнопка")
response_agent = 2
try:
await self.bot.send_message(self.AGENT_TG_LOGIN,
f"Вы выбрали: {response_agent}")
except Exception as e:
print(e)
print("Не удалось отправить отчёт выбора кнопки")
sys.stdout.flush()
else:
print("введите корректный номер")
sys.stdout.flush()
response_agent = await ainput('')
print(f"Вы выбрали: {response_agent}")
sys.stdout.flush()
if response_agent - 1 <= len(message.reply_markup.keyboard[0]):
await message.click(x=response_agent - 1, y=0)
print("\n")
sys.stdout.flush()
except AttributeError:
playsound(ALARM_PATH)
if message.text is not None:
print(message.text)
sys.stdout.flush()
elif message.caption is not None:
print(message.caption)
sys.stdout.flush()
else:
print(message)
sys.stdout.flush()
try:
await self.bot.send_message(self.AGENT_TG_LOGIN,
f"Предупреждение: тг аккаунт {self.login_name}"
f"\nтелеграмм тех поддержки: AlgoApi"
f"\n Доступных кнопок нет и я не понимаю "
f"что нужно и нужно ли ответить")
except Exception:
print("ERROR Не удалось отправить отчёт")
sys.stdout.flush()
print("Доступных кнопок нет, рекомендуется проигнорировать или "
"зайди в рабочий аккаунт телеграмм и сделать необходимые действия Дайвинчика")
print("\n")
sys.stdout.flush()
else:
if message.photo is None:
playsound(ALARM_PATH)
if message.text is not None:
print(message.text)
sys.stdout.flush()
elif message.caption is not None:
print(message.caption)
sys.stdout.flush()
else:
print(message)
sys.stdout.flush()
print("Доступных кнопок нет, рекомендуется зайди в аккаунт телеграмм и "
"сделать необходимые действия Дайвинчика")
print("\n")
sys.stdout.flush()
return
# @bot.on_message(filters=filters.incoming)
async def step_two(self, client: Client, message: types.Message):
if message.from_user.username not in ignore_list and message.from_user.username != "leomatchbot":
if message.text is not None and "/enable" not in message.text:
username = "empty"
first_name = "empty"
last_name = "empty"
if message.from_user is not None:
if message.from_user.username is not None:
username = message.from_user.username
if message.from_user.first_name is not None:
first_name = message.from_user.first_name
if message.from_user.last_name is not None:
last_name = message.from_user.last_name
try:
ignore_list.append(username)
with open("ignore_data", "wb") as fp1:
pickle.dump(ignore_list, fp1)
except ValueError as e:
print(f"ERROR {e}")
print("ЧЕЛОВЕК НЕ ДОБАВЛЕН В ИГНОР ЛИСТ")
sys.stdout.flush()
await self.bot.send_message(self.AGENT_TG_LOGIN,
text=f"Юзернэйм: {username}\nимя: {first_name} {last_name}\nОТКЛИК")
await message.reply_text(text=self.PROPOSE, quote=True)
elif message.caption is not None and "/enable" not in message.caption:
username = "empty"
first_name = "empty"
last_name = "empty"
if message.from_user is not None:
if message.from_user.username is not None:
username = message.from_user.username
if message.from_user.first_name is not None:
first_name = message.from_user.first_name
if message.from_user.last_name is not None:
last_name = message.from_user.last_name
try:
ignore_list.append(username)
with open("ignore_data", "wb") as fp2:
pickle.dump(ignore_list, fp2)
except ValueError as e:
print(f"ERROR {e}")
print("ЧЕЛОВЕК НЕ ДОБАВЛЕН В ИГНОР ЛИСТ")
sys.stdout.flush()
await self.bot.send_message(self.AGENT_TG_LOGIN,
text=f"Юзернэйм: {username}\nимя: {first_name} {last_name}\nОТКЛИК")
await message.reply_text(text=self.PROPOSE, quote=True)
if __name__ == "__main__":
# запуск user-bot
print(r"""
______ __ ________ __ __
/ \ | \ | \ | \ | \
| $$$$$$\| $$ ______ ______\$$$$$$$$______ | $$ | $$ _______ ______ ______
| $$__| $$| $$ / \ / \ | $$ / \ | $$ | $$ / \ / \ / \
| $$ $$| $$| $$$$$$\| $$$$$$\| $$ | $$$$$$\| $$ | $$| $$$$$$$| $$$$$$\| $$$$$$\
| $$$$$$$$| $$| $$ | $$| $$ | $$| $$ | $$ | $$| $$ | $$ \$$ \ | $$ $$| $$ \$$
| $$ | $$| $$| $$__| $$| $$__/ $$| $$ | $$__| $$| $$__/ $$ _\$$$$$$\| $$$$$$$$| $$
| $$ | $$| $$ \$$ $$ \$$ $$| $$ \$$ $$ \$$ $$| $$ \$$ \| $$
\$$ \$$ \$$ _\$$$$$$$ \$$$$$$ \$$ _\$$$$$$$ \$$$$$$ \$$$$$$$ \$$$$$$$ \$$
| \__| $$ | \__| $$
\$$ $$ \$$ $$
\$$$$$$ \$$$$$$ """)
print("сделано @AlgoApi для @Griffit1771")
print("Версия 2.0.7 от 28.11.2024")
print("\n")
CHAT_ID = "leomatchbot"
# CHAT_ID = "-1002249904247"
# 1234060895
# -1002249904247
SERVER = 'https://algoapirubin.eu.pythonanywhere.com/telebot/'
# self.AGENT_TG_LOGIN = config_yaml.data["agent"]["login"]
try:
with open("ignore_data", "rb") as fp:
try:
ignore_list = pickle.load(fp)
except EOFError:
ignore_list = list()
except FileNotFoundError:
with open("ignore_data", "w+") as f1:
pass
try:
with open("ignore_data", "rb") as fp:
ignore_list = pickle.load(fp)
except EOFError:
ignore_list = list()
ExtDataDir = os.getcwd()
if getattr(sys, 'frozen', False):
ExtDataDir = sys._MEIPASS
ALARM_PATH = r'alarm.wav'
print("Для запуска напишите аккаунту с которым работает скрипт /enable")
print("Чтобы остановить просто закройте консоль")
print("")
print("Если есть ошибки и скрипт не предложил способ их устранения, которые вы не можете самостоятельно решить, "
"то обязательно сообщите")
print("")
print("Если скрипт не реагирует и(или) не приходят новые сообщения, то попробуйте запустить скрипт заново")
print("Если ничего не изменилось, то зайдите на аккаунт с которым работает скрипт и перейдите к общению с "
"дайвинчиком, возможно он требует нажать кнопку в зависимости от его сообщения, после запустите "
"скрипт заново")
print("Если не помогло, то обязательно сообщите")
print("")
sys.stdout.flush()
parser = argparse.ArgumentParser(description='login, phone, text, agent, agentPass')
parser.add_argument("--login")
parser.add_argument("--phone")
parser.add_argument("--text")
parser.add_argument("--agent")
parser.add_argument("--agentPass")
parser.add_argument("--passwordTg")
args = parser.parse_args()
if args.login is None or args.login == "":
print("ERROR Вы забыли заполнить конфиг, а именно login")
print("Закройте консоль самостоятельно или введите что угодно чтобы закрыть консоль")
sys.stdout.flush()
input()
sys.stdout.flush()
sys.exit("the config is not filled in")
if args.phone is None or args.phone == "":
print("ERROR Вы забыли заполнить конфиг, а именно phone")
print("Закройте консоль самостоятельно или введите что угодно чтобы закрыть консоль")
sys.stdout.flush()
input()
sys.stdout.flush()
sys.exit("the config is not filled in")
if args.text is None or args.text == "":
print("ERROR Вы забыли заполнить конфиг, а именно text")
print("Закройте консоль самостоятельно или введите что угодно чтобы закрыть консоль")
sys.stdout.flush()
input()
sys.stdout.flush()
sys.exit("the config is not filled in")
if args.agent is None or args.agent == "":
print("ERROR Вы забыли заполнить конфиг, а именно ваш основной логин в тг без '@'")
print("Закройте консоль самостоятельно или введите что угодно чтобы закрыть консоль")
sys.stdout.flush()
input()
sys.stdout.flush()
sys.exit("the config is not filled in")
if args.agentPass is None or args.agentPass == "":
print("ERROR Вы забыли заполнить конфиг, а именно ваш пароль агента")
print("Закройте консоль самостоятельно или введите что угодно чтобы закрыть консоль")
sys.stdout.flush()
input()
sys.stdout.flush()
sys.exit("the config is not filled in")
if args.passwordTg is None or args.passwordTg == "":
print("ERROR Вы забыли заполнить конфиг, а именно пароль двухфакторной аутентификации")
print("Закройте консоль самостоятельно или введите что угодно чтобы закрыть консоль")
sys.stdout.flush()
input()
sys.stdout.flush()
sys.exit("the config is not filled in")
telebot(name=args.login, phone_number=args.phone, propose=args.text, agent=args.agent, agentPass=args.agentPass,
passwordTg=args.passwordTg)
print("Если есть ошибки попробуйте запустить скрипт заново и только после пожалуйста сообщите")
print("Закройте консоль самостоятельно или введите что угодно чтобы закрыть консоль")
sys.stdout.flush()
sys.stdout.flush()
sys.exit()
# telebot(name="AlisLovvee", phone_number="+79966752732", propose="args.text", agent="args.agent",
# agentPass="args.agentPass", passwordTg="passwordTg")
#