This repository has been archived by the owner on May 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__main__.py
1021 lines (899 loc) · 41.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Основной модуль бота.
"""
import io
import logging
import os
import pickle
import random
import re
import signal
import string
import sys
import traceback
import typing
from datetime import datetime
import pkg_resources
import requests
import telebot
from telebot import util
from telebot.types import Message, User, Chat, PhotoSize, File, Document, \
ForceReply, InlineQuery, InlineQueryResultVoice
from vk_api import vk_api, VkTools
from vk_api.vk_api import VkApiMethod
try:
from . import config
from .tgdata import vk_group, chat_state
from .external_api import whatanime_ga
from .external_api import iqdb_org
from .tgdata.inline_sound import InlineSound
except ImportError:
from tgdata import chat_state, vk_group
from tgdata.inline_sound import InlineSound
from external_api import whatanime_ga, iqdb_org
import config
users_dict: typing.Dict[str, int] = {}
"""
Словарь id пользователей.
user.username <-> user.id
"""
chat_states: typing.Dict[int, chat_state.ChatState] = {}
"""
Словарь состояня чатов.
msg.chat.id <-> ChatState
"""
soundboard_sounds: typing.List[InlineSound] = []
"""
Список звуков soundboard для inline-бота.
"""
inline_disabled = True
messages_log_files: typing.Dict[int, io.StringIO] = {}
"""
Словарь файлов для полного логгирования чатов.
msg.chat.id <-> file stream (io.StringIO)
"""
log: logging.Logger = None
logs_path = os.path.join(config.BOT_HOME, "logs")
saves_path = os.path.join(config.BOT_HOME, "saves")
tmp_path = os.path.join(config.BOT_HOME, "tmp")
bot = telebot.TeleBot(config.BOT_TOKEN, num_threads=config.NUM_THREADS)
iqdb: iqdb_org.IqdbClient = None
iqdb_disabled = True
whatanime: whatanime_ga.WhatAnimeClient = None
whatanime_disabled = True
vk: VkApiMethod = None
vk_tools: VkTools = None
vk_disabled = True
VK_VER = 5.69
VK_PHOTO_ATTACH_REGEX = re.compile(r"photo_(\d+)")
VK_GROUP_REGEX = re.compile(r".*vk\.com/(.+?)(\?.+)?$", re.MULTILINE)
HTML_ANEK_REGEX = re.compile(r"<meta name=\"description\" content=\"(.*?)\">", re.DOTALL)
EXIT_SUCCESS = 0
EXIT_UNKNOWN = -256
# status emoji
ready = "\u2705 "
pending = "\u2747\ufe0f "
not_ready = "\u274e "
error = "\u203c\ufe0f "
def download_and_report_progress(msg: Message, max_file_size: int
) -> typing.Optional[typing.Tuple[str, Message]]:
"""
Загружает файл и сообщает об этом в указанном чате.
:param Message msg: сообщение-источник
:param int max_file_size: максимальный размер для загрузки
:return: путь до скачанного файла И
:rtype: typing.Optional[typing.Tuple[str, Message]]
"""
chat_id = msg.chat.id
msg_text = msg.text
if (msg.photo is None and msg.document is None) and not msg_text.startswith(("http://", "https://",)):
log.debug("not link, skipping: {}".format(msg.text))
return None
# Prepare URL
status_msg = bot.send_message(chat_id, pending + "Подготовка ссылки\n" +
not_ready + "Загрузка\n" +
not_ready + "Поиск\n" +
not_ready + "Результат\n" +
not_ready + "Превью\n")
if msg.photo is not None: # Фото, .jpg
photos: typing.List[PhotoSize] = msg.photo
file: File = bot.get_file(photos[-1].file_id) # Biggest resolution
download_url = "https://api.telegram.org/file/bot{}/{}".format(config.BOT_TOKEN, file.file_path)
log.debug("pic")
elif msg.document is not None: # Документ, any!
document: Document = msg.document
file: File = bot.get_file(document.file_id)
download_url = "https://api.telegram.org/file/bot{}/{}".format(config.BOT_TOKEN, file.file_path)
log.debug("doc")
else: # Ссылка, any!
download_url = msg_text
log.debug("text")
if download_url is None:
bot.edit_message_text(error + "Подготовка ссылки\n" +
not_ready + "Загрузка\n" +
not_ready + "Поиск\n" +
not_ready + "Результат\n" +
not_ready + "Превью\n",
chat_id, status_msg.message_id)
bot.send_message(chat_id, "Не смог получить ссылку для загрузки. Жду еще одного сообщения или /abort!")
return None
log.debug("ready to download input, url: {}".format(download_url))
# Download!
try:
status_msg = bot.edit_message_text(ready + "Подготовка ссылки\n" +
pending + "Загрузка\n" +
not_ready + "Поиск\n" +
not_ready + "Результат\n" +
not_ready + "Превью\n",
chat_id, status_msg.message_id)
response = requests.get(download_url, timeout=4, stream=True)
data = response.raw.read(max_file_size + 1, decode_content=True)
if len(data) > max_file_size: # 2MB
response.close()
bot.edit_message_text(ready + "Подготовка ссылки\n" +
error + "Загрузка\n" +
not_ready + "Поиск\n" +
not_ready + "Результат\n" +
not_ready + "Превью\n",
chat_id, status_msg.message_id)
bot.send_message(chat_id, "Объем данных превышает 2МБ, отменено. Жду еще одного сообщения или /abort!")
return None
# noinspection PyUnusedLocal
rand = "".join(random.choice(string.ascii_letters + string.digits) for x in range(
random.randint(16, 32)))
search_file_path = os.path.join(tmp_path, "search_{}_{}".format(msg.message_id, rand))
with open(search_file_path, mode="wb") as file:
file.write(data)
except Exception as exc:
bot.edit_message_text(ready + "Подготовка ссылки\n" +
error + "Загрузка\n" +
not_ready + "Поиск\n" +
not_ready + "Результат\n" +
not_ready + "Превью\n",
chat_id, status_msg.message_id)
bot.send_message(chat_id, "Ошибка при загрузке. Жду еще одного сообщения или /abort!\n"
"Подробнее: {}".format(exc))
log.debug("{}".format(traceback.format_exc()))
# noinspection PyBroadException
try:
# noinspection PyUnboundLocalVariable
os.remove(os.path.realpath(search_file_path))
except:
pass
return None
status_msg = bot.edit_message_text(ready + "Подготовка ссылки\n" +
ready + "Загрузка\n" +
pending + "Поиск\n" +
not_ready + "Результат\n" +
not_ready + "Превью\n",
chat_id, status_msg.message_id)
return search_file_path, status_msg
def chat_in_state(chat_msg: Message, state_name: str) -> bool:
"""
Проверяет состояние указанного чата.
:param Message chat_msg: сообщение из чата
:param str state_name: название состояния
:return: ``True``, если чат в указанном состоянии
:rtype: bool
"""
chat_id = chat_msg.chat.id
if chat_id in chat_states and chat_states[chat_id].state_name == state_name:
return True
else:
return False
def is_admin(chat_msg: Message) -> bool:
"""
Проверяет, отправлено ли сообщение администратором бота.
:param Message chat_msg: сообщение из чата
:return: ``True``, если отправитель является администратором
:rtype: bool
"""
if config.ADMIN_USERNAME is None:
return False
sender: User = chat_msg.from_user
log.debug("{} admin check...".format(sender.username))
return True if sender.username == config.ADMIN_USERNAME else False
@bot.message_handler(commands=["abort", ])
def bot_cmd_abort(msg: Message):
"""
Отменяет выполняемую команду.
:param Message msg: сообщение
"""
bot_all_messages(msg)
chat_id = msg.chat.id
if not chat_in_state(msg, chat_state.NONE):
chat_states[chat_id].state_name = chat_state.NONE
bot.send_message(chat_id, "Отменено.")
else:
bot.send_message(chat_id, "Я ничем не занят!")
@bot.message_handler(commands=["eval", ], func=is_admin)
def bot_cmd_eval(msg: Message):
"""
Позволяет запустить любой кусок Python кода на сервере.
Доступно только администратору.
:param Message msg: сообщение
"""
bot_all_messages(msg)
chat_id = msg.chat.id
if len(msg.text.split()) <= 1:
bot.send_message(chat_id, "Укажите строчку кода после команды!")
return
cmd: str = msg.text.split(' ', 1)[1]
try:
cmd = "cmd_result = " + cmd
log.debug("compiling {}...".format(cmd))
cmd_compiled = compile(cmd, "<string>", "exec")
exec(cmd_compiled, globals(), locals())
result = locals().get("cmd_result")
except Exception as exc:
result = "Exception: {}\n{}".format(exc, traceback.format_exc())
for splitted in util.split_string(str(result), 2000):
bot.send_message(chat_id, splitted)
@bot.message_handler(commands=["list_chats", ], func=is_admin)
def bot_cmd_list_chats(msg: Message):
"""
Возвращает список чатов и их состояние.
Доступно только администратору.
:param Message msg: сообщение
"""
bot_all_messages(msg)
chat_id = msg.chat.id
result = ""
for other_chat_id, other_chat_state in chat_states.items():
if hasattr(other_chat_state, "title"):
result += "<code>{}</code>: {}, state <code>{}</code>\n" \
.format(other_chat_id, other_chat_state.title, other_chat_state.state_name)
else:
result += "<code>{}</code>: state <code>{}</code>\n" \
.format(other_chat_id, other_chat_state.state_name)
bot.send_message(chat_id, result, parse_mode="HTML")
@bot.message_handler(commands=["send_msg", ], func=is_admin)
def bot_cmd_send_msg(msg: Message):
"""
Отправляет собщение на указанный ``chat_id``.
Доступно только администратору.
:param Message msg: сообщение
"""
bot_all_messages(msg)
chat_id = msg.chat.id
in_text = msg.text
if len(in_text.split()) < 3:
bot.send_message(chat_id, "Команда работает в следующем формате:\n"
"<code>/send_msg chat_id msg</code>", parse_mode="HTML")
return
_, out_chat_id, out_text = in_text.split(' ', 2)
try:
bot.send_message(int(out_chat_id), out_text, parse_mode="HTML")
bot.send_message(chat_id, "Выполнено.")
except Exception as exc:
bot.send_message(chat_id, "Exception: {}\n{}".format(exc, traceback.format_exc()))
@bot.message_handler(commands=["info", ])
def bot_cmd_info(msg: Message):
"""
Информация о боте и чате.
:param Message msg: сообщение
"""
bot_all_messages(msg)
# TODO
@bot.message_handler(func=lambda msg: chat_in_state(msg, chat_state.IQDB),
content_types=["text", "document", "photo"])
def bot_process_iqdb(msg: Message):
"""
Ищет арт на бурах с помощью `iqdb.org`.
:param Message msg: сообщение
"""
bot_all_messages(msg)
chat_id = msg.chat.id
try:
search_file_path, status_msg = download_and_report_progress(msg, iqdb_org.MAX_SIZE)
except TypeError:
return
try:
results: typing.List[iqdb_org.IqdbResult] = iqdb.search(search_file_path)
result = results[0]
bot.edit_message_text(ready + "Подготовка ссылки\n" +
ready + "Загрузка\n" +
ready + "Поиск\n" +
ready + "Результат\n" +
ready + "Превью\n",
chat_id, status_msg.message_id)
out_msg = "{type} ({sim}%): {rat}, {res}\n" \
"Preview: {prev}\n" \
"Sauce: {sauce}".format(
type=result.match_type,
sim=result.similarity,
rat=result.rating,
res=result.resolution,
prev=result.preview_link,
sauce=result.source_link
)
if result.tags is not None:
out_msg += "\n\nTags: "
for tag in result.tags:
out_msg += "<code>{}</code> ".format(tag)
bot.send_message(chat_id, out_msg, parse_mode="HTML")
chat_states[chat_id].state_name = chat_state.NONE
except Exception as exc:
bot.edit_message_text(ready + "Подготовка ссылки\n" +
ready + "Загрузка\n" +
error + "Поиск\n" +
not_ready + "Результат\n" +
not_ready + "Превью\n",
chat_id, status_msg.message_id)
bot.send_message(chat_id, "Ошибка при поиске. Жду еще одного сообщения или /abort!\n"
"Подробнее: {}".format(exc))
log.debug("{}".format(traceback.format_exc()))
# noinspection PyBroadException
try:
os.remove(os.path.realpath(search_file_path))
except:
pass
@bot.message_handler(func=lambda msg: chat_in_state(msg, chat_state.WHATANIME),
content_types=["text", "document", "photo"])
def bot_process_whatanime(msg: Message):
"""
Ищет скриншот из аниме с помощью `whatanime.ga`.
:param Message msg: сообщение
"""
bot_all_messages(msg)
chat_id = msg.chat.id
try:
search_file_path, status_msg = download_and_report_progress(msg, 2097152)
except TypeError:
return
# Search!
try:
results: typing.List[whatanime_ga.WhatAnimeResult] = whatanime.search(search_file_path)
status_msg = bot.edit_message_text(ready + "Подготовка ссылки\n" +
ready + "Загрузка\n" +
ready + "Поиск\n" +
pending + "Результат\n" +
not_ready + "Превью\n",
chat_id, status_msg.message_id)
# Вообще-то, результатов обычно несколько. Но мне слишком лень писать сложную обработку, поэтому довольствуемся
# самым подходящим.
result = results[0]
result.load_thumbnail()
bot.send_message(chat_id, "<code>{}</code>".format(result.title_romaji), parse_mode="HTML")
status_msg = bot.edit_message_text(ready + "Подготовка ссылки\n" +
ready + "Загрузка\n" +
ready + "Поиск\n" +
ready + "Результат\n" +
pending + "Превью\n"
"Осталось {} запросов за {} секунд."
.format(whatanime.now_quota,
whatanime.quota_expire),
chat_id, status_msg.message_id)
match = "Совпадение" if result.similarity > 0.80 else "Низкая вероятность! Совпадение"
out_msg = "{0}: {1:.1f}%\n" \
"{2} (EP#{3}, в {4:.2f} мин)\n" \
"{5}".format(match, result.similarity * 100, result.title, result.episode,
result.at / 60, result.title_english)
with open(result.thumb_path, mode="rb") as file:
bot.send_photo(chat_id, file, out_msg)
os.remove(result.thumb_path)
except Exception as exc:
bot.edit_message_text(ready + "Подготовка ссылки\n" +
ready + "Загрузка\n" +
error + "Поиск\n" +
not_ready + "Результат\n" +
not_ready + "Превью\n",
chat_id, status_msg.message_id)
bot.send_message(chat_id, "Ошибка при поиске. Жду еще одного сообщения или /abort!\n"
"Подробнее: {}".format(exc))
log.debug("{}".format(traceback.format_exc()))
os.remove(os.path.realpath(search_file_path))
return
# Preview!
try:
result.load_preview()
out_msg = "{0:.2f} - {1:.2f}".format(result.__dict__["from"] / 60, result.to / 60)
bot.send_chat_action(chat_id, "record_video")
with open(result.preview_path, mode="rb") as file:
bot.send_video(chat_id, file, caption=out_msg)
os.remove(result.preview_path)
bot.edit_message_text(ready + "Подготовка ссылки\n" +
ready + "Загрузка\n" +
ready + "Поиск\n" +
ready + "Результат\n" +
ready + "Превью\n"
"Осталось {} запросов за {} секунд."
.format(whatanime.now_quota, whatanime.quota_expire),
chat_id, status_msg.message_id)
except Exception as exc:
bot.edit_message_text(ready + "Подготовка ссылки\n" +
ready + "Загрузка\n" +
ready + "Поиск\n" +
ready + "Результат\n" +
error + "Превью ({})\n"
"Осталось {} запросов за {} секунд."
.format(exc, whatanime.now_quota, whatanime.quota_expire),
chat_id, status_msg.message_id)
log.debug("{}".format(traceback.format_exc()))
os.remove(os.path.realpath(search_file_path))
chat_states[chat_id].state_name = chat_state.NONE
@bot.message_handler(func=lambda msg: chat_in_state(msg, chat_state.CONFIGURE_VK_GROUPS_ADD))
def bot_process_configuration_vk(msg: Message):
"""
Проверяет адреса и добавляет их в список групп ВК.
:param Message msg: сообщение
"""
bot_all_messages(msg)
this_chat: chat_state.ChatState = chat_states[msg.chat.id]
if (msg.reply_to_message is not None and this_chat.message_id_to_reply is not None) \
and (msg.reply_to_message.message_id == this_chat.message_id_to_reply):
text: str = msg.text
dead_links: list = []
vk_groups = this_chat.vk_groups
for line in text.splitlines():
log.debug("line {}".format(line))
if not VK_GROUP_REGEX.match(line):
dead_links.append(line)
break
group_name: str = re.sub(VK_GROUP_REGEX, r"\1", line)
log.debug("got group \"{}\"...".format(group_name))
try:
response = vk.groups.getById(group_id=group_name, fields="id", version=VK_VER)
except (vk_api.ApiError, vk_api.ApiHttpError) as err:
log.info("...but request failed ({})".format(err))
dead_links.append(line)
break
log.debug("...and vk response:\n"
"{}".format(response))
group_dict: dict = response[0]
group = vk_group.VkGroup(group_dict["id"], group_dict["name"], group_dict["screen_name"])
log.info("finally, our group: {}".format(group))
vk_groups.append(group)
success_grps = ""
for entry in vk_groups:
success_grps += entry.__str__() + "\n"
fail_grps = ""
for entry in dead_links:
fail_grps += entry + "\n"
out_msg = "<b>Попытка добавления!</b>\n" \
"Для остановки напиши /abort\n\n" \
"Сейчас в списке:\n" \
"<code>{}</code>\n" \
"Не добавлено:\n" \
"<code>{}</code>".format(success_grps, fail_grps if (len(fail_grps) != 0) else "Ничего!")
bot.send_message(msg.chat.id, out_msg, parse_mode="HTML")
@bot.message_handler(commands=['add', ])
def bot_cmd_configuration_vk_add(msg: Message):
"""
Переводит бота в режим добавления групп ВК, если находится в правильном состоянии.
:param Message msg: сообщение
"""
bot_all_messages(msg)
if chat_in_state(msg, chat_state.CONFIGURE_VK_GROUPS):
out_msg = "<b>Reply`ем на это сообщение</b> напишите адреса <b>публичных</b> сообществ ВК, " \
"по одному на строку.\n" \
"<i>Желательно без мусорных знаков...</i>"
chat_id = msg.chat.id
sent_msg = bot.send_message(chat_id, out_msg, reply_markup=ForceReply(), parse_mode="HTML")
chat_states[chat_id].state_name = chat_state.CONFIGURE_VK_GROUPS_ADD
chat_states[chat_id].message_id_to_reply = sent_msg.message_id
@bot.message_handler(commands=["clear", ])
def bot_cmd_configuration_vk_clear(msg: Message):
"""
Очищает список групп ВК, если находится в правильном состоянии.
:param Message msg: сообщение
"""
bot_all_messages(msg)
if chat_in_state(msg, chat_state.CONFIGURE_VK_GROUPS):
chat_id = msg.chat.id
chat_states[chat_id].vk_groups.clear()
bot.send_message(chat_id, "Выполнено.")
@bot.message_handler(commands=["config_vk", ])
def bot_cmd_configuration_vk(msg: Message):
"""
Запускает настройку сообществ `vk.com`.
:param Message msg: сообщение
"""
bot_all_messages(msg)
chat_id = msg.chat.id
if vk_disabled:
bot.send_message(chat_id, "Модуль ВКонтакте отключен.")
return
grps_str = ""
chat_states[chat_id].state_name = chat_state.CONFIGURE_VK_GROUPS
grps = chat_states[chat_id].vk_groups
for entry in grps:
grps_str += entry.__str__() + "\n"
out_msg = "Вошел в режим <b>Конфигурация модуля ВКонтакте</b>!\n" \
"/add — добавление групп\n" \
"/clear — очистка списка\n" \
"/abort — отмена\n\n" \
"Сейчас в списке:\n" \
"<code>{}</code>\n".format(grps_str)
bot.send_message(chat_id, out_msg, parse_mode="HTML")
@bot.message_handler(commands=["vk_pic", ])
def bot_cmd_vk_pic(msg: Message):
"""
Посылает рандомную картинку из списка сообществ.
:param Message msg: сообщение
"""
bot_all_messages(msg)
chat_id = msg.chat.id
if vk_disabled:
bot.send_message(chat_id, "Модуль ВКонтакте отключен.")
return
if len(chat_states[chat_id].vk_groups) == 0:
bot.send_message(chat_id, "Сначала настройте группы с помощью /config_vk")
return
bot.send_chat_action(chat_id, "upload_photo")
chosen_group: vk_group.VkGroup = random.choice(chat_states[chat_id].vk_groups)
log.debug("selected {} as source".format(chosen_group))
response = vk_tools.get_all("wall.get", max_count=config.VK_ITEMS_PER_REQUEST, values={
"domain": chosen_group.url_name,
"fields": "attachments",
"version": VK_VER,
}, limit=config.VK_ITEMS_PER_REQUEST * 25) # 275 постов по умолчанию
max_size_url = "ERROR"
log.debug("items count: {}".format(len(response["items"])))
chosen = False
while not chosen:
chosen_post: dict = random.choice(response["items"])
if chosen_post["marked_as_ads"] == 1:
log.debug("skip (ad)")
continue
if "attachments" not in chosen_post:
log.debug("skip (attach)")
continue
for attach in chosen_post["attachments"]:
if "photo" in attach:
log.debug("found photo!")
photo_attach = attach["photo"]
log.debug("attach {}".format(photo_attach))
max_size = 75
for key in photo_attach: # Аццкий костыль для выбора фото максимального разрешения
value = photo_attach[key]
log.debug("<{}> -> {}".format(key, value))
if VK_PHOTO_ATTACH_REGEX.match(key): # Ключ типа ``photo_<res>``, где 25 <= <res> <= inf
size = int(re.sub(VK_PHOTO_ATTACH_REGEX, r"\1", key))
if size > max_size:
max_size = size
max_size_url = photo_attach["photo_" + str(max_size)]
chosen = True
break
elif "doc" in attach:
log.debug("photo not found, found doc!")
doc_attach = attach["doc"]
if doc_attach["ext"] != "gif":
log.debug("but it isn\'t gif...")
continue
max_size_url = doc_attach["url"]
chosen = True
break
else:
log.debug("not found!")
bot.send_message(chat_id, "{}\n"
"Из https://vk.com/{}".format(max_size_url, chosen_group.url_name))
@bot.message_handler(commands=["whatanime", ])
def bot_cmd_whatanime(msg: Message):
"""
Входит в режим поиска аниме по скриншоту (спасибо whatanime.ga за API).
:param Message msg: сообщение
"""
bot_all_messages(msg)
chat_id = msg.chat.id
if whatanime_disabled:
bot.send_message(chat_id, "Модуль whatanime.ga отключен.")
return
chat_states[chat_id].state_name = chat_state.WHATANIME
out_msg = "Вошел в режим <b>whatanime.ga: поиск аниме</b>!\n" \
"Напиши /abort для выхода.\n\n" \
"Для поиска отправь картинку или <b>прямую</b> ссылку (должна начинаться с http/https)."
bot.send_message(chat_id, out_msg, parse_mode="HTML")
@bot.message_handler(commands=["iqdb", ])
def bot_cmd_iqdb(msg: Message):
"""
Входит в режим поиска соуса арта (не спасибо iqdb.org за отсутствие API).
:param Message msg: сообщение
"""
bot_all_messages(msg)
chat_id = msg.chat.id
if iqdb_disabled:
bot.send_message(chat_id, "Модуль iqdb.org отключен.")
return
chat_states[chat_id].state_name = chat_state.IQDB
out_msg = "Вошел в режим <b>iqdb.org: multi-service image search</b>!\n" \
"Напиши /abort для выхода.\n\n" \
"Для поиска отправь картинку или <b>прямую</b> ссылку (должна начинаться с http/https)."
bot.send_message(chat_id, out_msg, parse_mode="HTML")
@bot.message_handler(commands=["codfish", ])
def bot_cmd_codfish(msg: Message):
"""
Бьет треской, теперь с видео.
:param Message msg: сообщение
"""
bot_all_messages(msg)
chat_id = msg.chat.id
text = msg.text.replace("@", "") # Sometimes `lolbot` is written as `@lolbot`
words = text.split()
username = words[-1] # Get username from orig. message
bot.send_chat_action(chat_id, "record_video")
codfish_video = pkg_resources.resource_stream(config.VIDEOS, config.CODFISH) # Our codfish video
if len(words) <= 1: # No username
bot.send_message(chat_id, "Укажи юзернейм кого бить!")
elif username == bot.get_me().username: # Himself
bot.send_video(chat_id, codfish_video, caption="Хорошенько шлепнул себя треской.")
elif username in users_dict: # Search in our users dict (user_id's are unique?)
raw = requests.get("https://api.telegram.org:443/bot{}/getChatMember?chat_id={}&user_id={}"
.format(config.BOT_TOKEN, chat_id, users_dict[username])) # Get user first name
response_json: tuple = raw.json()
# noinspection PyTypeChecker
user_first_name = response_json["result"]["user"]["first_name"]
log.debug("user first name is {}".format(user_first_name))
bot.send_video(chat_id, codfish_video, caption="Хорошенько шлепнул {} треской."
.format(user_first_name))
else: # Unknown
bot.send_message(chat_id, "Извини, пока не знаю <b>{}</b>...".format(username), parse_mode="HTML")
@bot.message_handler(commands=["quote", ])
def bot_cmd_quote(msg: Message):
"""
Посылает рандомную цитату с `tproger.ru`.
:param Message msg: сообщение
"""
bot_all_messages(msg)
quote = requests.get("https://tproger.ru/wp-content/plugins/citation-widget/getQuotes.php").text
bot.send_message(msg.chat.id, "<code>{}</code>".format(quote), parse_mode="HTML")
@bot.message_handler(commands=["anek", ])
def bot_cmd_anek(msg: Message):
"""
Посылает рандомный анекдот с `baneks.ru`.
:param Message msg: сообщение
"""
bot_all_messages(msg)
request = requests.get("https://baneks.ru/{}".format(random.randrange(1, 1142)))
request.encoding = "utf-8"
html_text = request.text
# Да, это парсинг регексами: сервер отдает данные без экранирования кавычек...
result = HTML_ANEK_REGEX.search(html_text)
out_msg = result.group(1) if result else "ERROR"
bot.send_message(msg.chat.id, "<code>{}</code>".format(out_msg), parse_mode="HTML")
@bot.inline_handler(lambda a: True)
def bot_inline_handler(inline_query: InlineQuery):
"""
Отвечает на inline списокм звуков, полученных с указанного в config сервера.
:param InlineQuery inline_query: inline запрос
"""
if inline_disabled:
log.info("tried inline, disabled")
return
log.debug("got inline {}".format(inline_query.query))
results = []
id_counter = 0
for sound in soundboard_sounds:
if sound.pretty_name.find(inline_query.query) != -1 or sound.category.find(inline_query.query) != -1:
if id_counter > 20:
break # Display only 20
id_counter += 1
results.append(InlineQueryResultVoice(id_counter, config.SERVER_ADDRESS + sound.full_url,
title=sound.pretty_name, performer=sound.category))
bot.answer_inline_query(inline_query.id, results)
@bot.message_handler(func=lambda msg: True,
content_types=["text", "audio", "document", "photo", "sticker", "video", "video_note", "voice",
"location", "contact", "new_chat_members", "left_chat_member", "new_chat_title",
"new_chat_photo", "delete_chat_photo", "group_chat_created",
"supergroup_chat_created", "channel_chat_created", "migrate_to_chat_id",
"migrate_from_chat_id", "pinned_message", ])
def bot_all_messages(msg: Message):
"""
Метод для заполнения :var:`users_dict` и инициализации состояния чатов.
Обрабатывает любые сообщения.
:param Message msg: сообщение
"""
user: User = msg.from_user
chat: Chat = msg.chat
if user.username not in users_dict:
log.debug("user not known")
users_dict[user.username] = user.id
else:
log.debug("user known")
chat_id = msg.chat.id
chat_title = chat.title if chat.title is not None else chat.username
if chat_id not in chat_states:
log.debug("chat not known")
chat_states[chat_id] = chat_state.ChatState(chat_state.NONE, chat_title)
else:
log.debug("chat known")
if not hasattr(chat_states[chat_id], "title"):
chat_states[chat_id].title = chat_title
if config.LOG_INPUT:
global messages_log_files
if chat_id not in messages_log_files:
base_name = "chat_{}.log".format(chat_title)
log_path = os.path.join(logs_path, base_name)
messages_log_files[chat_id] \
= open(log_path, mode="at", buffering=1, encoding="utf-8", errors="backslashreplace")
messages_log_files[chat_id].write("with id: {}\n".format(chat_id))
file_instance: io.StringIO = messages_log_files[chat_id]
dtime = datetime.fromtimestamp(msg.date).strftime('%Y-%m-%d %H:%M:%S')
if msg.text is not None:
out_str = "({}) {}:\n" \
"{}\n\n".format(dtime, user.username, msg.text)
else:
out_str = "({}) {}:\n" \
"*{}* {}\n\n".format(dtime, user.username, msg.content_type, msg.caption)
file_instance.write(out_str)
file_instance.flush()
def prepare_logger() -> logging.Logger:
"""
Готовит логгер к использованию.
:return: готовый экземпляр логгера
:rtype: logging.Logger
"""
formatter = logging.Formatter(config.LOG_FORMAT)
loglevel = config.LOG_LEVEL
l_log = logging.getLogger()
l_log.setLevel(loglevel)
if config.LOG_TO_STDOUT:
ch = logging.StreamHandler()
ch.setFormatter(formatter)
ch.setLevel(loglevel)
l_log.addHandler(ch)
if config.LOG_TO_FILE:
fh = logging.FileHandler(os.path.join(logs_path, "main.log"))
fh.setFormatter(formatter)
fh.setLevel(loglevel)
l_log.addHandler(fh)
l_log.info("Logs path: {}".format(os.path.join(logs_path, "main.log")))
return l_log
def save_chat_states():
"""
Сохряняет состояние чатов и пользователей в ``.pkl``-файл.
"""
states_save_path = os.path.join(saves_path, "states.pkl")
users_save_path = os.path.join(saves_path, "users.pkl")
global log
if log is None:
log = prepare_logger()
log.info("saving info to {}...".format(saves_path))
try:
with open(states_save_path, "w+b") as states_file:
pickle.dump(chat_states, states_file, pickle.HIGHEST_PROTOCOL)
with open(users_save_path, "w+b") as users_file:
pickle.dump(users_dict, users_file, pickle.HIGHEST_PROTOCOL)
log.info("...success!")
except Exception as exc:
log.warning("can\'t save info: {}".format(exc))
# noinspection PyUnusedLocal
def exit_handler(sig, frame):
"""
Обработчик ``^C``.
"""
save_chat_states()
bot.stop_polling()
for file in messages_log_files.values():
if not file.closed:
file.close()
log.info("-=-=-= EXIT =-=-=-")
sys.exit(EXIT_SUCCESS)
def main() -> int:
"""
Точка входа.
:return: код выхода (сейчас не используется)
:rtype: int
"""
# Prepare home dir
if not os.path.exists(config.BOT_HOME):
os.makedirs(config.BOT_HOME)
os.makedirs(logs_path)
os.makedirs(saves_path)
os.makedirs(tmp_path)
elif not os.path.isdir(config.BOT_HOME):
os.remove(config.BOT_HOME)
os.makedirs(config.BOT_HOME)
os.makedirs(logs_path)
os.makedirs(saves_path)
os.makedirs(tmp_path)
# Prepare logger
global log
log = prepare_logger()
log.info("-=-=-= NEW LAUNCH =-=-=-")
# Init inline queries
try:
log.info("inline init...")
global soundboard_sounds
response = requests.get(config.SERVER_ADDRESS + "/index.json")
json_arr = response.json()
for sound in json_arr:
soundboard_sounds.append(InlineSound(sound))
global inline_disabled
inline_disabled = False
log.info("...success!")
except Exception as exc:
log.error("...failure! Reason: {}, inline disabled".format(exc))
log.debug("With trace:\n{}".format(traceback.format_exc()))
# Init VK API
try:
log.info("vk init...")
vk_session = vk_api.VkApi(login=config.VK_LOGIN, password=config.VK_PASSWORD,
config_filename=os.path.join(saves_path, 'vk_config.v2.json'),
api_version=str(VK_VER))
vk_session.auth()
global vk
vk = vk_session.get_api()
log.info("...success!")
log.info("vk tools init...")
global vk_tools
vk_tools = VkTools(vk_session)
log.info("...success!")
log.info("vk test...")
response = vk.groups.getById(group_id="team", fields="id", version=VK_VER)
log.info("...success!")
log.debug("With response: {}".format(response))
global vk_disabled
vk_disabled = False
except Exception as exc:
log.error("...failure! Reason: {}, VK disabled".format(exc))
log.debug("With trace:\n{}".format(traceback.format_exc()))
# Init whatanime.ga API
try:
log.info("whatanime init...")
global whatanime
whatanime = whatanime_ga.WhatAnimeClient(config.WHATANIME_TOKEN)
log.info("...success! UID: {}".format(whatanime.user_id))
global whatanime_disabled
whatanime_disabled = False
except Exception as exc:
log.error("...failure! Reason: {}, whatanime disabled".format(exc))
log.debug("With trace:\n{}".format(traceback.format_exc()))
# Init iqdb.org API
try:
log.info("iqdb init...")
global iqdb
iqdb = iqdb_org.IqdbClient()
log.info("...success! Boorus:\n{}".format(iqdb.boorus_status))
global iqdb_disabled
iqdb_disabled = False
except Exception as exc:
log.error("...failure! Reason: {}, iqdb disabled".format(exc))
log.debug("With trace:\n{}".format(traceback.format_exc()))
# Load info from disk
states_save_path = os.path.join(saves_path, "states.pkl")
users_save_path = os.path.join(saves_path, "users.pkl")
log.info("loading info from {}...".format(saves_path))
try:
with open(states_save_path, "rb") as states_file:
global chat_states
chat_states = pickle.load(states_file)
with open(users_save_path, "rb") as users_file:
global users_dict
users_dict = pickle.load(users_file)
log.info("...success!")
except Exception as exc:
log.warning("can\'t load info: {}".format(exc))
log.debug("With trace:\n"
"{}".format(traceback.format_exc()))
# Start
log.info("Starting polling")
bot.polling(none_stop=True)
# Block thread!
log.info("Stopped!")
return EXIT_SUCCESS
if __name__ == '__main__':
"""