forked from Kylmakalle/tgvkbot
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbot.py
executable file
·3298 lines (3058 loc) · 138 KB
/
bot.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 -*-
# A simple chat client for matrix.
# This sample will allow you to connect to a room, and send/recieve messages.
# Args: host:port username password room
# Error Codes:
# 1 - Unknown problem has occured
# 2 - Could not find the server.
# 3 - Bad URL Format.
# 4 - Bad username/password.
# 11 - Wrong room format.
# 12 - Couldn't find room.
import sys
import logging
import time
import datetime
import json
import os
import pickle
import re
import threading
import random
import requests
import traceback
import vk
import ujson
import wget
import uuid
from PIL import Image
from matrix_client.client import MatrixClient
from matrix_client.api import MatrixRequestError
from requests.exceptions import MissingSchema
from requests import exceptions
import config as conf
client = None
log = None
data={}
lock = None
vk_threads = {}
vk_dialogs = {}
VK_API_VERSION = '5.95'
VK_POLLING_VERSION = '3'
currentchat = {}
def process_command(user,room,cmd,formated_message=None,format_type=None,reply_to_id=None,file_url=None,file_type=None):
global client
global log
global data
try:
log.debug("=start function=")
answer=None
session_data_room=None
session_data_vk=None
session_data_user=None
if reply_to_id!=None and format_type=="org.matrix.custom.html" and formated_message!=None:
# разбираем, чтобы получить исходное сообщение и ответ
log.debug("formated_message=%s"%formated_message)
source_message=re.sub('<mx-reply><blockquote>.*<\/a><br>','', formated_message)
source_message=re.sub('<mx-reply><blockquote>.*<\/a><br />','', source_message)
source_message=re.sub('</blockquote></mx-reply>.*','', source_message)
source_cmd=re.sub(r'.*</blockquote></mx-reply>','', formated_message.replace('\n',''))
log.debug("source=%s"%source_message)
log.debug("cmd=%s"%source_cmd)
cmd="> %s\n\n%s"%(source_message,source_cmd)
if re.search('^@%s:.*'%conf.username, user.lower()) is not None:
# отправленное нами же сообщение - пропускаем:
log.debug("skip our message")
return True
if user not in data["users"]:
data["users"][user]={}
if "rooms" not in data["users"][user]:
data["users"][user]["rooms"]={}
if "vk" not in data["users"][user]:
data["users"][user]["vk"]={}
data["users"][user]["vk"]["exit"]=False
data["users"][user]["vk"]["ts"]=0
data["users"][user]["vk"]["pts"]=0
data["users"][user]["vk"]["ts_check_poll"]=0
if room not in data["users"][user]["rooms"]:
data["users"][user]["rooms"][room]={}
data["users"][user]["rooms"][room]["state"]="listen_command"
session_data_room=data["users"][user]["rooms"][room]
session_data_vk=data["users"][user]["vk"]
session_data_user=data["users"][user]
cur_state=data["users"][user]["rooms"][room]["state"]
log.debug("user=%s send command=%s"%(user,cmd))
log.debug("cur_state=%s"%cur_state)
# комната в режиме диалога - это созданная ботом комната. Она не принимает иных команд. Все команды принимает только комната с ботом
if cur_state == "dialog":
bot_control_room=data["users"][user]["matrix_bot_data"]["control_room"]
dialog=session_data_room["cur_dialog"]
if "pause" in data["users"][user]["rooms"][room]:
if data["users"][user]["rooms"][room]["pause"]==True:
# комната в приостановленном режиме - сообщаем, что пересылка отключена:
if send_notice(room,"Пересылка сообщений из этой комнаты в ВК и обратно приостановлена. Для возобновления используйте команду '!resume %s' в комнате управления ботом\nВаше сообщение не было отправлено в ВК."%room) == False:
log.error("send_notice")
return False
return True
if file_type!=None and file_url!=None:
# отправка файла:
if re.search("^image",file_type)!=None:
# Отправка изображения из матрицы:
photo_data=get_file(file_url)
if photo_data==None:
log.error("error get file by mxurl=%s"%file_url)
bot_system_message(user,'Ошибка: не смог получить вложение из матрицы по mxurl=%s'%file_url)
send_message(room,'Ошибка: не смог получить вложение из матрицы по mxurl=%s'%file_url)
return False
message_id=vk_send_photo(session_data_vk["vk_id"],dialog["id"],cmd,photo_data,dialog["type"])
if message_id == None:
log.error("error vk_send_photo() for user %s"%user)
send_message(room,"не смог отправить фото в ВК - ошибка АПИ")
return False
elif re.search("^video",file_type)!=None:
# Отправка видео из матрицы:
video_data=get_file(file_url)
if video_data==None:
log.error("error get file by mxurl=%s"%file_url)
bot_system_message(user,'Ошибка: не смог получить вложение из матрицы по mxurl=%s'%file_url)
send_message(room,'Ошибка: не смог получить вложение из матрицы по mxurl=%s'%file_url)
return False
message_id=vk_send_video(session_data_vk["vk_id"],dialog["id"],cmd,video_data,dialog["type"])
if message_id == None:
log.error("error vk_send_video() for user %s"%user)
send_message(room,"не смог отправить видео в ВК - ошибка АПИ")
return False
elif re.search("^audio",file_type)!=None:
# Отправка звукового файла из матрицы:
audio_data=get_file(file_url)
if audio_data==None:
log.error("error get file by mxurl=%s"%file_url)
bot_system_message(user,'Ошибка: не смог получить вложение из матрицы по mxurl=%s'%file_url)
send_message(room,'Ошибка: не смог получить вложение из матрицы по mxurl=%s'%file_url)
return False
message_id=vk_send_doc(session_data_vk["vk_id"],dialog["id"],cmd,audio_data,dialog["type"])
if message_id == None:
log.error("error vk_send_doc() for user %s"%user)
send_message(room,"не смог отправить аудио в ВК - ошибка АПИ")
return False
else:
# Отправка простого файла из матрицы:
doc_data=get_file(file_url)
if doc_data==None:
log.error("error get file by mxurl=%s"%file_url)
bot_system_message(user,'Ошибка: не смог получить вложение из матрицы по mxurl=%s'%file_url)
send_message(room,'Ошибка: не смог получить вложение из матрицы по mxurl=%s'%file_url)
return False
message_id=vk_send_doc(session_data_vk["vk_id"],dialog["id"],cmd,doc_data,dialog["type"])
if message_id == None:
log.error("error vk_send_doc() for user %s"%user)
send_message(room,"не смог отправить файл в ВК - ошибка АПИ")
return False
else:
# отправка текста:
message_id=vk_send_text(session_data_vk["vk_id"],dialog["id"],cmd,dialog["type"])
if message_id == None:
log.error("error vk_send_text() for user %s"%user)
send_message(room,"не смог отправить сообщение в ВК - ошибка АПИ")
return False
# Сохраняем message_id, полученный от ВК, когда мы отправили сообщение из матрицы в ВК:
try:
log.debug("add last message id as: %d"%message_id)
except:
log.error("message_id not int!")
log.error("message_id=")
log.error(message_id)
return False
if save_message_id(user,room,message_id) == False:
log.error("save_message_id()")
bot_system_message(user,'Ошибка: не смог сохранить идентификатор отправленного сообщения - внутренняя ошибка бота')
return False
return True
# Комната управления:
# в любом состоянии отмена - всё отменяет:
if re.search('^!stop$', cmd.lower()) is not None or \
re.search('^!стоп$', cmd.lower()) is not None or \
re.search('^!отмена$', cmd.lower()) is not None or \
re.search('^!cancel$', cmd.lower()) is not None:
data["users"][user]["rooms"][room]["state"]="listen_command"
send_message(room,'Отменил текущий режим (%s) и перешёл в начальный режим ожидания команд. Жду команд.'%session_data_room["state"])
# сохраняем на диск:
save_data(data)
return True
elif re.search('^!стат$', cmd.lower()) is not None or \
re.search('^!состояние$', cmd.lower()) is not None or \
re.search('^!stat$', cmd.lower()) is not None:
send_message(room,"Текущее состояние: %s"%session_data_room["state"])
if session_data_room["state"]=="dialog":
send_message(room,'Текущая комната: "%s"'%session_data_room["cur_dialog"]["title"])
return True
elif re.search('^!ping$', cmd.lower()) is not None:
message="==== Состояние связи с VK: ====\n"
message+="Состояние соединения: %s\n"%data["users"][user]["vk"]["connection_status"]
message+="Описание состояния соединения: %s\n"%data["users"][user]["vk"]["connection_status_descr"]
delta_ts = int(time.time())-data["users"][user]["vk"]["ts_check_poll"]
message+="Время прошедшее с предыдущего опроса событий в ВК: %d сек.\n"%delta_ts
send_message(room,message)
return True
elif re.search('^!reconnect$', cmd.lower()) is not None:
data["users"][user]["vk"]["exit"]=True
message="Послал команду на переподключение к ВК.\n"
send_message(room,message)
return True
if cur_state == "listen_command":
if re.search('^!*\?$', cmd.lower()) is not None or \
re.search('^!*h$', cmd.lower()) is not None or \
re.search('^!*помощь', cmd.lower()) is not None or \
re.search('^!*справка', cmd.lower()) is not None or \
re.search('^!*help', cmd.lower()) is not None:
answer="""!login - авторизоваться в ВК
!logout - выйти из ВК (пока не реализовано)
!search - поиск диалогов в ВК (пока не реализовано)
!dialogs - список всех ваших диалогов в ВК. В ответном сообщении Вам потребуется ввести номер диалога, чтобы начать общение в этом диалоге через матрицу.
!rooms - список соответствий диалогов ВК и ваших комнат
!delete room_id - удалить соответствение диалога ВК и комнаты MATRIX. Диалог в ВК останется и если придёт новое сообщение в нём - то бот заново создаст у вас комнту и соответстие. И вы получите сообщение из ВК.
!pause room_id - приостановить пересылку сообщений из ВК в указанную комнату MATRIX. Для включения используейте команду !resume room_id.
!resume room_id - возобновить пересылку сообщений из ВК в указанную комнату MATRIX. Для приостановки используейте команду !pause room_id.
!stat - текущее состояние комнаты
!reconnect - переподключиться к ВК
!ping - текущее состояние соединения с ВК
"""
return send_message(room,answer)
# login
elif re.search('^!login$', cmd.lower()) is not None:
return login_command(user,room,cmd)
# dialogs
elif re.search('^!dialogs$', cmd.lower()) is not None or \
re.search('^!диалоги$', cmd.lower()) is not None or \
re.search('^!d$', cmd.lower()) is not None:
return dialogs_command(user,room,cmd)
elif re.search('^!rooms$', cmd.lower()) is not None or \
re.search('^!комнаты$', cmd.lower()) is not None:
return rooms_command(user,room,cmd)
elif re.search('^!delete .*', cmd.lower()) is not None:
return delete_room_association(user,room,cmd)
elif re.search('^!pause .*', cmd.lower()) is not None:
return bridge_pause_for_room(user,room,cmd)
elif re.search('^!resume .*', cmd.lower()) is not None:
return bridge_resume_for_room(user,room,cmd)
elif re.search('^!rooms$', cmd.lower()) is not None or \
re.search('^!комнаты$', cmd.lower()) is not None:
return rooms_command(user,room,cmd)
elif cur_state == "wait_vk_id":
# парсинг ссылки
m = re.search('https://oauth\.vk\.com/blank\.html#access_token=[a-z0-9]*&expires_in=[0-9]*&user_id=[0-9]*',cmd)
if m:
code = extract_unique_code(m.group(0))
try:
vk_user = verifycode(code)
except:
send_message(room, 'Неверная ссылка, попробуйте ещё раз!')
log.warning("error auth url from user=%s"%user)
return False
send_message(room,'Вход выполнен в аккаунт {} {}!'.format(vk_user['first_name'], vk_user['last_name']))
data["users"][user]["vk"]["vk_id"]=code
data["users"][user]["vk"]["first_name"]=vk_user['first_name']
data["users"][user]["vk"]["last_name"]=vk_user['last_name']
data["users"][user]["rooms"][room]["state"]="listen_command"
# сохраняем на диск:
save_data(data)
elif cur_state == "wait_vk_app_id":
# парсинг ссылки
try:
vk_app_id = int(cmd)
except:
log.warning("error get VK app id from user=%s"%user)
send_message(room, 'Я ожидаю от вас "ID приложения" по ссылке https://vk.com/apps?act=manage в настройках созданного Вами приложения. Код должен быть обычным числом. Или же отмените ожидание с помощью команд: !стоп, !stop, !отмена, !cancel')
return False
data["users"][user]["vk"]["vk_app_id"]=vk_app_id
data["users"][user]["rooms"][room]["state"]="listen_command"
# сохраняем на диск:
save_data(data)
# заново запускаем обработчик логина с уже обновлёнными данными:
return login_command(user,room,cmd)
elif cur_state == "wait_dialog_index":
try:
index=int(cmd)
except:
send_message(room,"пожалуйста, введите номер диалога или команды !stop, !отмена, !cancel")
return True
if index not in session_data_room["dialogs_list"]:
send_message(room,"Неверный номер диалога, введите верный номер диалога или команды !stop, !отмена, !cancel")
return True
cur_dialog=session_data_room["dialogs_list"][index]
found_room=find_bridge_room(user,cur_dialog["id"])
if found_room != None:
# Такая комната уже существует!
log.info("room already exist for user '%s' for vk-dialog with vk-id '%d' ('%s')"%(user,cur_dialog["id"],cur_dialog["title"]))
send_message(room,"У Вас уже есть комната (%s), связанная с этим пользователем - не создаю повторную. Позже будет добавлен функционал по чистке такх комнат."%found_room)
send_message(room,"Перешёл в режим команд")
data["users"][user]["rooms"][room]["state"]="listen_command"
return False
# получаем фото пользователя ВК с которым устанавливаем мост:
room_avatar_mx_url=None
vk_id=data["users"][user]["vk"]["vk_id"]
session = get_session(vk_id)
user_photo_url=vk_get_user_photo_url(session, cur_dialog["id"])
if user_photo_url==None:
log.error("get user vk profile photo for user_id=%d"%cur_dialog["id"])
else:
user_photo_image_data=get_data_from_url(user_photo_url)
if user_photo_image_data==None:
log.error("get image from url: %s"%user_photo_url)
room_id=create_room(user,cur_dialog["title_ext"] + " (VK)",user_photo_image_data)
if room_id==None:
log.error("error create_room() for user '%s' for vk-dialog with vk-id '%d' ('%s')"%(user,cur_dialog["id"],cur_dialog["title"]))
send_message(room,"Не смог создать дополнительную комнату в матрице: '%s' связанную с одноимённым диалогом в ВК"%cur_dialog["title"])
send_message(room,"Перешёл в режим команд")
data["users"][user]["rooms"][room]["state"]="listen_command"
return False
send_message(room,"Создал новую комнату матрицы с именем: '%s (VK)' связанную с одноимённым диалогом в ВК"%cur_dialog["title"])
data["users"][user]["rooms"][room_id]={}
data["users"][user]["rooms"][room_id]["last_matrix_owner_message"]=[]
data["users"][user]["rooms"][room_id]["cur_dialog"]=cur_dialog
data["users"][user]["rooms"][room_id]["state"]="dialog"
# сохраняем на диск:
save_data(data)
send_message(room,"Перешёл в режим команд")
data["users"][user]["rooms"][room]["state"]="listen_command"
return True
except Exception as e:
log.error(get_exception_traceback_descr(e))
log.error("exception at execute process_command()")
bot_system_message(user,"внутренняя ошибка бота при обработке команды в функции process_command()")
return False
# сохраняем message_id в списке отправленных нами сообщений:
def save_message_id(user,room,message_id):
global log
global data
try:
# уточнение типа:
if isinstance(data["users"][user]["rooms"][room]["last_matrix_owner_message"], list) == False:
data["users"][user]["rooms"][room]["last_matrix_owner_message"]=[]
cur_m_list=data["users"][user]["rooms"][room]["last_matrix_owner_message"]
cur_m_list.append(message_id)
# ограничиваем список запомненных сообщений 30-ю:
s=len(cur_m_list)
if s > 30:
delta=s-30
cur_m_list=cur_m_list[delta:]
data["users"][user]["rooms"][room]["last_matrix_owner_message"]=cur_m_list
except:
log.error(get_exception_traceback_descr(e))
log.error("exception at execute save_message_id()")
return False
return True
# проверяем наличие message_id в списке ранее отправленных нами сообщений:
def check_own_message_id(user,room,message_id):
global log
global data
try:
# уточнение типа:
if isinstance(data["users"][user]["rooms"][room]["last_matrix_owner_message"], list) == False:
data["users"][user]["rooms"][room]["last_matrix_owner_message"]=[]
if message_id in data["users"][user]["rooms"][room]["last_matrix_owner_message"]:
return True
else:
return False
except:
log.error(get_exception_traceback_descr(e))
log.error("exception at execute check_own_message_id()")
return False
def update_user_info(user):
global log
global data
found=False
try:
log.debug("=start function=")
#try:
vk_id=data["users"][user]["vk"]["vk_id"]
session = get_session(vk_id)
api = vk.API(session, v=VK_API_VERSION)
user_profile=dict(api.account.getProfileInfo(fields=[]))
data["users"][user]["vk"]["first_name"]=user_profile['first_name']
data["users"][user]["vk"]["last_name"]=user_profile['last_name']
dialogs=get_dialogs(vk_id)
if dialogs == None:
log.error("get_dialogs() for user=%s"%user)
bot_system_message(user,"внутренняя ошибка бота при получении списка диалогов пользователя в функции update_user_info()")
return False
# ищем свой аккаунт по ФИО (иначе пока не знаю как получить свой ID):
for user_id in dialogs["users"]:
item=dialogs["users"][user_id]
if item["last_name"] == data["users"][user]["vk"]["last_name"] and \
item["first_name"] == data["users"][user]["vk"]["first_name"]:
# предполагаем, что у пользователя в контактах не будет человека с таким же ФИО, как и он сам O_o:
found=True
data["users"][user]["vk"]["user_id"]=item["id"]
if found==True:
log.info("определил свой аккаунт как: %s %s, id:%d"%(\
data["users"][user]["vk"]["last_name"],\
data["users"][user]["vk"]["first_name"],\
data["users"][user]["vk"]["user_id"]\
))
save_data(data)
return True
else:
log.warning("не нашли информацию о себе - пропуск")
return False
except Exception as e:
log.error(get_exception_traceback_descr(e))
log.error("exception at execute update_user_info()")
bot_system_message(user,"внутренняя ошибка бота при получении профиля пользователя в функции update_user_info()")
return False
def find_bridge_room(user,vk_room_id):
global log
try:
log.debug("=start function=")
for room in data["users"][user]["rooms"]:
if data["users"][user]["rooms"][room]["state"]=="dialog" and \
data["users"][user]["rooms"][room]["cur_dialog"]["id"]==vk_room_id:
log.info("found bridge for user '%s' with vk_id '%d'"%(user,vk_room_id))
return room;
return None
except Exception as e:
log.error(get_exception_traceback_descr(e))
log.error("exception at execute find_bridge_room()")
bot_system_message(user,"внутренняя ошибка бота в функции find_bridge_room()")
return None
def get_new_vk_messages_v2(user):
global data
global lock
global log
try:
log.debug("=start function=")
if "vk" not in data["users"][user]:
return None
if "vk_id" not in data["users"][user]["vk"]:
return None
server=""
key=""
session=""
ts=0
log.debug("try lock() before access global data()")
with lock:
log.debug("success lock() before access global data")
if "server" in data["users"][user]["vk"]:
server=data["users"][user]["vk"]["server"]
if "ts" in data["users"][user]["vk"]:
ts=data["users"][user]["vk"]["ts"]
if "key" in data["users"][user]["vk"]:
key=data["users"][user]["vk"]["key"]
log.debug("release lock() after access global data")
exit_flag=False
while True:
try:
if server=="" or key=="":
log.warning('Need update server data')
raise Exception('Need update server data')
log.debug("get polling with ts=%d"%ts)
url="https://%(server)s?act=a_check&key=%(key)s&ts=%(ts)s&wait=25&mode=2&version=%(VK_POLLING_VERSION)s"%\
{\
"ts":ts,\
"key":key,\
"server":server,\
"VK_POLLING_VERSION":VK_POLLING_VERSION\
}
log.debug("try exec requests.post(%s)"%url)
r = requests.post(url,timeout=conf.post_timeout)
log.debug("requests.post return: %s"%r.text)
ret=json.loads(r.text)
if "failed" in ret and ( ret["failed"]==2 or ret["failed"]==3):
log.info("need update key or ts")
raise Exception("need update key or ts")
if "updates" not in ret:
log.warning("'No 'updates' in ret'")
raise Exception("No 'updates' in ret")
ts=ret["ts"]
log.debug("try lock() before access global data()")
with lock:
log.debug("success lock() before access global data")
data["users"][user]["vk"]["ts"]=ts
data["users"][user]["vk"]["ts_check_poll"]=int(time.time())
log.debug("release lock() after access global data")
#log.debug("ret=")
#log.debug(json.dumps(ret, indent=4, sort_keys=True,ensure_ascii=False))
except (exceptions.ConnectionError, TimeoutError, exceptions.Timeout, \
exceptions.ConnectTimeout, exceptions.ReadTimeout) as e:
log.debug("except timeout from requests.post(): %s"%e)
# Проверка на необходимость выйти из потока:
exit_flag=False
log.debug("try lock() before access global data()")
with lock:
log.debug("success lock() before access global data")
if "exit" in data["users"][user]["vk"]:
exit_flag=data["users"][user]["vk"]["exit"]
log.debug("release lock() after access global data")
log.debug("thread: exit_flag=%d"%int(exit_flag))
if exit_flag==True:
log.info("get command to close thread for user %s - exit from thread..."%user)
return None
log.debug("try again requests.post()")
continue
except Exception as e:
log.debug("except from requests.post()")
log.debug("e=")
log.debug(e)
# Проверка на необходимость выйти из потока:
exit_flag=False
log.debug("try lock() before access global data()")
with lock:
log.debug("success lock() before access global data")
if "exit" in data["users"][user]["vk"]:
exit_flag=data["users"][user]["vk"]["exit"]
log.debug("release lock() after access global data")
log.debug("thread: exit_flag=%d"%int(exit_flag))
if exit_flag==True:
log.info("get command to close thread for user %s - exit from thread..."%user)
return None
log.warning("error get event updates - try update session info")
session = get_session(data["users"][user]["vk"]["vk_id"])
log.debug("session=")
log.debug(session)
log.debug("try exec get_tses()")
ts,pts,key,server=get_tses(session)
log.debug("end exec get_tses()")
log.debug("try lock() before access global data()")
with lock:
log.debug("success lock() before access global data")
update_vk_tses_data(data,user,ts,pts,key,server)
save_data(data)
log.debug("release lock() after access global data")
# продолжаем попытки получения данных от vk
log.debug("try again requests.post()")
continue
# ищем нужные нам события (новые сообщения), типы всех событий описаны вот тут: https://vk.com/dev/using_longpoll_2
# 4 - Добавление нового сообщения.
# 5 - Редактирование сообщения.
# 51 - Один из параметров (состав, тема) беседы $chat_id были изменены. $self — 1 или 0 (вызваны ли изменения самим пользователем).
# 52 - Изменение информации чата $peer_id с типом $type_id, $info — дополнительная информация об изменениях, зависит от типа события.
# 70 - Пользователь $user_id совершил звонок с идентификатором $call_id.
ts=ret["ts"]
new_events=False
for update in ret["updates"]:
if update[0]==4 \
or update[0]==5 \
or update[0]==51 \
or update[0]==70 \
or update[0]==52:
new_events=True
log.info("getting info about new events - try get events...")
break
if new_events:
# выходим из цикла ожидания событий:
break
# Проверка на необходимость выйти из потока:
exit_flag=False
log.debug("try lock() before access global data()")
with lock:
log.debug("success lock() before access global data")
if "exit" in data["users"][user]["vk"]:
exit_flag=data["users"][user]["vk"]["exit"]
log.debug("release lock() after access global data")
log.debug("thread: exit_flag=%d"%int(exit_flag))
if exit_flag==True:
log.info("get command to close thread for user %s - exit from thread..."%user)
return None
# Проверка на необходимость выйти из потока:
exit_flag=False
log.debug("try lock() before access global data()")
with lock:
log.debug("success lock() before access global data")
if "exit" in data["users"][user]["vk"]:
exit_flag=data["users"][user]["vk"]["exit"]
log.debug("release lock() after access global data")
log.debug("thread: exit_flag=%d"%int(exit_flag))
if exit_flag==True:
log.info("get command to close thread for user %s - exit from thread..."%user)
return None
# получаем данные событий:
log.debug("session=")
log.debug(session)
session = get_session(data["users"][user]["vk"]["vk_id"])
log.debug("session=")
log.debug(session)
api = vk.API(session, v=VK_API_VERSION)
try:
#ts_pts = ujson.dumps({"ts": data["users"][user]["vk"]["ts"], "pts": data["users"][user]["vk"]["pts"]})
#ts_pts = ujson.dumps({"ts": data["users"][user]["vk"]["ts"], "pts": data["users"][user]["vk"]["pts"],"wait":25})
#new = api.execute(code='return API.messages.getLongPollHistory({});'.format(ts_pts))
log.debug("try exec api.messages.getLongPollHistory()")
new = api.messages.getLongPollHistory(
ts=data["users"][user]["vk"]["ts"],\
pts=data["users"][user]["vk"]["pts"],\
lp_version=VK_POLLING_VERSION\
)
log.debug("end exec api.messages.getLongPollHistory()")
except vk.api.VkAPIError:
timeout = 3
log.warning('Retrying getLongPollHistory in {} seconds'.format(timeout))
time.sleep(timeout)
ts,pts,key,server=get_tses(session)
log.debug("try lock() before access global data()")
with lock:
log.debug("success lock() before access global data")
update_vk_tses_data(data,user,ts,pts,key,server)
log.debug("release lock() after access global data")
log.debug("try exec api.messages.getLongPollHistory()")
new = api.messages.getLongPollHistory(
ts=ts,\
pts=pts,\
lp_version=VK_POLLING_VERSION\
)
log.debug("end exec api.messages.getLongPollHistory()")
log.debug("New data from VK:")
log.debug(json.dumps(new, indent=4, sort_keys=True,ensure_ascii=False))
msgs = new['messages']
log.debug("try lock() before access global data()")
with lock:
log.debug("success lock() before access global data")
data["users"][user]["vk"]["pts"] = new["new_pts"]
log.debug("release lock() after access global data")
count = msgs["count"]
res = None
if count == 0:
pass
else:
res={}
res["messages"] = msgs["items"]
# при разговоре с админами иногда может не быть профилей O_o
if "profiles" in new:
res["profiles"] = new["profiles"]
else:
res["profiles"] = []
res["conversations"] = new["conversations"]
return res
except Exception as e:
log.error(get_exception_traceback_descr(e))
log.error("exception at execute get_new_vk_messages_v2()")
bot_system_message(user,"ошибка получения сообщений из ВК. Ошибка работы с ВК-апи в функции get_new_vk_messages_v2()")
return None
def get_new_vk_messages(user):
global data
global lock
global log
try:
log.debug("=start function=")
if "vk" not in data["users"][user]:
return None
if "vk_id" not in data["users"][user]["vk"]:
return None
session = get_session(data["users"][user]["vk"]["vk_id"])
#log.debug("ts=%d, pts=%d"%(data["users"][user]["vk"]["ts"], data["users"][user]["vk"]["pts"]))
api = vk.API(session, v=VK_API_VERSION)
try:
ts_pts = ujson.dumps({"ts": data["users"][user]["vk"]["ts"], "pts": data["users"][user]["vk"]["pts"]})
#ts_pts = ujson.dumps({"ts": data["users"][user]["vk"]["ts"], "pts": data["users"][user]["vk"]["pts"],"wait":25})
new = api.execute(code='return API.messages.getLongPollHistory({});'.format(ts_pts))
except vk.api.VkAPIError:
timeout = 3
log.warning('Retrying getLongPollHistory in {} seconds'.format(timeout))
time.sleep(timeout)
log.debug("try lock() before access global data()")
ts,pts,key,server=get_tses(session)
with lock:
log.debug("success lock() before access global data")
update_vk_tses_data(data,user,ts,pts,key,server)
log.debug("release lock() after access global data")
ts_pts = ujson.dumps({"ts": data["users"][user]["vk"]["ts"], "pts": data["users"][user]["vk"]["pts"]})
new = api.execute(code='return API.messages.getLongPollHistory({});'.format(ts_pts))
log.debug("New data from VK:")
log.debug(json.dumps(new, indent=4, sort_keys=True,ensure_ascii=False))
msgs = new['messages']
log.debug("try lock() before access global data()")
with lock:
log.debug("success lock() before access global data")
data["users"][user]["vk"]["pts"] = new["new_pts"]
log.debug("release lock() after access global data")
count = msgs["count"]
res = None
if count == 0:
pass
else:
res={}
res["messages"] = msgs["items"]
res["profiles"] = new["profiles"]
res["conversations"] = new["conversations"]
return res
except Exception as e:
log.error(get_exception_traceback_descr(e))
log.error("exception at execute get_new_vk_messages()")
bot_system_message(user,"ошибка получения сообщений из ВК. Ошибка работы с ВК-апи в функции get_new_vk_messages()")
return None
def extract_unique_code(text):
global log
log.debug("=start function=")
# Extracts the unique_code from the sent /start command.
try:
return text[45:].split('&')[0]
except Exception as e:
log.error(get_exception_traceback_descr(e))
return None
def get_session(token):
global log
log.debug("=start function=")
return vk.Session(access_token=token)
def update_vk_tses_data(data, user, ts, pts, key, server):
data["users"][user]["vk"]["server"]=server
data["users"][user]["vk"]["key"]=key
data["users"][user]["vk"]["ts"]=ts
data["users"][user]["vk"]["pts"]=pts
def get_tses(session):
global log
try:
log.debug("=start function=")
api = vk.API(session, v=VK_API_VERSION)
ts = api.messages.getLongPollServer(need_pts=1,v=VK_API_VERSION,lp_version=VK_POLLING_VERSION)
return ts['ts'], ts['pts'], ts['key'], ts['server']
except Exception as e:
log.error(get_exception_traceback_descr(e))
log.error("exception at execute get_tses()")
return None
def verifycode(code):
global log
try:
log.debug("=start function=")
session = vk.Session(access_token=code)
api = vk.API(session, v=VK_API_VERSION)
return dict(api.account.getProfileInfo(fields=[]))
except Exception as e:
log.error(get_exception_traceback_descr(e))
log.error("exception at execute get_user_profile_by_uid()()")
return None
def info_extractor(info):
global log
try:
log.debug("=start function=")
info = info[-1].url[8:-1].split('.')
return info
except Exception as e:
log.error(get_exception_traceback_descr(e))
log.error("exception at execute info_extractor()")
return None
def vk_send_text(vk_id, chat_id, message, chat_type="user", forward_messages=None):
global log
message_id=None
try:
log.debug("=start function=")
random_id=random.randint(0,4294967296)
session = get_session(vk_id)
api = vk.API(session, v=VK_API_VERSION)
if chat_type!="user":
message_id=api.messages.send(peer_id=chat_id, random_id=random_id, message=message, forward_messages=forward_messages)
else:
message_id=api.messages.send(user_id=chat_id, random_id=random_id, message=message, forward_messages=forward_messages)
# message_id содержит ID отправленного сообщения
except Exception as e:
log.error(get_exception_traceback_descr(e))
log.error("exception at execute vk_send_text()")
log.error("vk_send_text API or network error")
return None
return message_id
def vk_send_video(vk_id, chat_id, name, video_data, chat_type="user"):
global log
message_id=None
try:
log.debug("=start function=")
random_id=random.randint(0,4294967296)
session = get_session(vk_id)
api = vk.API(session, v=VK_API_VERSION)
# получаем адрес загрузки:
save_response=api.video.save(name=name)
log.debug("api.video.save return:")
log.debug(save_response)
url = save_response['upload_url']
files = {'video_file': (name,video_data,'multipart/form-data')}
r = requests.post(url, files=files, timeout=conf.post_files_timeout)
log.debug("requests.post return: %s"%r.text)
ret=json.loads(r.text)
attachment_str="video%d_%d"%(ret['owner_id'],ret['video_id'])
if chat_type!="user":
message_id=api.messages.send(chat_id=chat_id, random_id=random_id, message=name,attachment=(attachment_str))
else:
message_id=api.messages.send(user_id=chat_id, random_id=random_id, message=name,attachment=(attachment_str))
log.debug("api.messages.send return:")
log.debug(message_id)
except Exception as e:
log.error(get_exception_traceback_descr(e))
log.error("exception at execute vk_send_video()")
log.error("vk_send_video API or network error")
return None
return message_id
def vk_send_audio(vk_id, chat_id, name, audio_data, chat_type="user"):
global log
message_id=None
try:
log.debug("=start function=")
random_id=random.randint(0,4294967296)
session = get_session(vk_id)
api = vk.API(session, v=VK_API_VERSION)
# получаем адрес загрузки:
save_response=api.video.save(name=name)
log.debug("api.video.save return:")
log.debug(save_response)
url = save_response['upload_url']
files = {'video_file': (name,video_data,'multipart/form-data')}
r = requests.post(url, files=files, timeout=conf.post_files_timeout)
log.debug("requests.post return: %s"%r.text)
ret=json.loads(r.text)
attachment_str="video%d_%d"%(ret['owner_id'],ret['video_id'])
if chat_type!="user":
message_id=api.messages.send(chat_id=chat_id, random_id=random_id, message=name,attachment=(attachment_str))
else:
message_id=api.messages.send(user_id=chat_id, random_id=random_id, message=name,attachment=(attachment_str))
log.debug("api.messages.send return:")
log.debug(message_id)
except Exception as e:
log.error(get_exception_traceback_descr(e))
log.error("exception at execute vk_send_audio()")
log.error("vk_send_video API or network error")
return None
return message_id
def vk_send_doc(vk_id, chat_id, name, doc_data, chat_type="user"):
global log
message_id=None
try:
log.debug("=start function=")
random_id=random.randint(0,4294967296)
session = get_session(vk_id)
api = vk.API(session, v=VK_API_VERSION)
# получаем адрес загрузки:
response=api.docs.getMessagesUploadServer()
log.debug("api.docs.getMessagesUploadServer return:")
log.debug(response)
#
url = response['upload_url']
files = {'file': (name,doc_data,'multipart/form-data')}
r = requests.post(url, files=files, timeout=conf.post_files_timeout)
log.debug("requests.post return: %s"%r.text)
ret=json.loads(r.text)
response=api.docs.save(file=ret['file'],title=name)
log.debug("api.docs.save return:")
log.debug(response)
attachment_str="doc%d_%d"%(response['doc']['owner_id'],response['doc']['id'])
if chat_type!="user":
message_id=api.messages.send(chat_id=chat_id,random_id=random_id, message=name,attachment=(attachment_str))
else:
message_id=api.messages.send(user_id=chat_id,random_id=random_id, message=name,attachment=(attachment_str))
log.debug("api..messages.send return:")
log.debug(message_id)
except Exception as e:
log.error(get_exception_traceback_descr(e))
log.error("exception at execute vk_send_doc()")
log.error("vk_send_doc API or network error")
return None
return message_id
def vk_send_photo(vk_id, chat_id, name, photo_data, chat_type="user"):
global log
message_id=None
log.debug("=start function=")
random_id=random.randint(0,4294967296)
try:
session = get_session(vk_id)
api = vk.API(session, v=VK_API_VERSION)
# получаем адрес загрузки:
response=api.photos.getMessagesUploadServer()
log.debug("api.photos.getMessagesUploadServer return:")
log.debug(response)
#
url = response['upload_url']
files = {'photo': ('photo.png',photo_data,'multipart/form-data')}
r = requests.post(url, files=files, timeout=conf.post_files_timeout)
log.debug("requests.post return: %s"%r.text)
ret=json.loads(r.text)
response=api.photos.saveMessagesPhoto(photo=ret['photo'],server=ret['server'],hash=ret['hash'])
log.debug("api.photos.saveMessagesPhoto return:")
log.debug(response)
attachment="photo%(owner_id)d_%(media_id)d"%{"owner_id":response[0]["owner_id"],"media_id":response[0]["id"]}
log.debug("attachment=%s"%attachment)
if chat_type!="user":
message_id=api.messages.send(chat_id=chat_id, random_id=random_id, message=name,attachment=attachment)
else:
message_id=api.messages.send(user_id=chat_id, random_id=random_id, message=name,attachment=attachment)
log.debug("api..messages.send return:")
log.debug(message_id)
except Exception as e:
log.error(get_exception_traceback_descr(e))
log.error("exception at execute vk_send_photo()")
log.error("vk_send_photo API or network error")
return None
return message_id
def bridge_pause_for_room(user,room,cmd):
global log
log.debug("=start function=")
global lock
global data
global client
try:
room_id=cmd.replace("!pause ","").strip()
if room_id in data["users"][user]["rooms"]:
# приостанавливаем пересылку сообщений из ВК в эту комнату:
log.info("!pause for room: '%s' for user '%s'"%(room_id,user))
vk_dialog_title=""
if "cur_dialog" in data["users"][user]["rooms"][room_id] and \
"title" in data["users"][user]["rooms"][room_id]["cur_dialog"]:
vk_dialog_title=data["users"][user]["rooms"][room_id]["cur_dialog"]["title"]
data["users"][user]["rooms"][room_id]["pause"]=True
log.info("save state data on disk")
save_data(data)
bot_system_message(user,"Успешно приостановил пересылку сообщений из ВК в соответствии: %s - %s"%(vk_dialog_title,room_id))
if send_notice(room_id,"Пересылка сообщений из ВК в эту комнату приостановлена. Для возобновления используйте команду '!resume %s' в комнате управления ботом"%room_id) == False:
log.error("send_notice")
else:
bot_system_message(user,"Ошибка! Неизвестная комната: %s"%room_id)
return False
return True
except Exception as e:
log.error(get_exception_traceback_descr(e))
log.error("exception at execute bridge_pause_for_room()")
bot_system_message(user,"внутренняя ошибка бота")
return False
def bridge_resume_for_room(user,room,cmd):
global log
log.debug("=start function=")
global lock
global data
global client
try:
room_id=cmd.replace("!resume ","").strip()
if room_id in data["users"][user]["rooms"]:
# возобновляем пересылку сообщений из ВК в эту комнату: