-
Notifications
You must be signed in to change notification settings - Fork 31
/
vk_messages.py
1187 lines (970 loc) · 50.2 KB
/
vk_messages.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import urllib
from concurrent.futures._base import CancelledError, TimeoutError
from aiogram.utils.markdown import quote_html, hlink
from aiovk.longpoll import LongPoll
from aiogram.utils.exceptions import MessageError
from bot import *
log = logging.getLogger('vk_messages')
inline_link_re = re.compile('\[([a-zA-Z0-9_]*)\|(.*?)\]', re.MULTILINE)
################### Честно взято по лицензии https://github.com/vk-brain/sketal/blob/master/LICENSE ###################
def parse_msg_flags(bitmask, keys=('unread', 'outbox', 'replied', 'important', 'chat',
'friends', 'spam', 'deleted', 'fixed', 'media', 'hidden')):
"""Функция для чтения битовой маски и возврата словаря значений"""
start = 1
values = []
for _ in range(1, 12):
result = bitmask & start
start *= 2
values.append(bool(result))
return dict(zip(keys, values))
from enum import Enum
class Wait(Enum):
NO = 0
YES = 1
CUSTOM = 2
class EventType(Enum):
Longpoll = 0
ChatChange = 1
Callback = 2
class Event:
__slots__ = ("api", "type", "reserved_by", "occupied_by", "meta")
def __init__(self, api, evnt_type):
self.api = api
self.type = evnt_type
self.meta = {}
self.reserved_by = []
self.occupied_by = []
# https://vk.com/dev/using_longpoll
class LongpollEvent(Event):
__slots__ = ("evnt_data", "id")
def __init__(self, api, evnt_id, evnt_data):
super().__init__(api, EventType.Longpoll)
self.id = evnt_id
self.evnt_data = evnt_data
def __str__(self):
return f"LongpollEvent ({self.id}, {self.evnt_data[1] if len(self.evnt_data) > 1 else '_'})"
class MessageEventData(object):
__slots__ = ("is_multichat", "user_id", "full_text", "full_message_data",
"time", "msg_id", "attaches", "is_out", "forwarded", "chat_id",
"true_user_id", "is_forwarded", "true_msg_id")
@staticmethod
def from_message_body(obj):
data = MessageEventData()
data.attaches = {}
data.forwarded = []
c = 0
for a in obj.get("attachments", []):
c += 1
data.attaches[f'attach{c}_type'] = a['type']
try:
data.attaches[f'attach{c}'] = f'{a[a["type"]]["owner_id"]}_{a[a["type"]]["id"]}'
except KeyError:
data.attaches[f'attach{c}'] = ""
if 'fwd_messages' in obj:
data.forwarded = MessageEventData.parse_brief_forwarded_messages(obj)
if "chat_id" in obj:
data.is_multichat = True
data.chat_id = int(obj["chat_id"])
if "id" in obj:
data.msg_id = obj["id"]
data.true_msg_id = obj["id"]
data.user_id = int(obj['user_id'])
data.true_user_id = int(obj['user_id'])
data.full_text = obj['text']
data.time = int(obj['date'])
data.is_out = obj.get('out', False)
data.is_forwarded = False
data.full_message_data = obj
return data
@staticmethod
def parse_brief_forwarded_messages(obj):
if 'fwd_messages' not in obj:
return ()
result = []
for mes in obj['fwd_messages']:
result.append((mes.get('id', None), MessageEventData.parse_brief_forwarded_messages(mes)))
return tuple(result)
@staticmethod
def parse_brief_forwarded_messages_from_lp(data):
result = []
token = ""
i = -1
while True:
i += 1
if i >= len(data):
if token:
result.append((token, ()))
break
if data[i] in "1234567890_-":
token += data[i]
continue
if data[i] in (",", ")"):
if not token:
continue
result.append((token, ()))
token = ""
continue
if data[i] == ":":
stack = 1
for j in range(i + 2, len(data)):
if data[j] == "(":
stack += 1
elif data[j] == ")":
stack -= 1
if stack == 0:
jump_to_i = j
break
sub_data = data[i + 2: jump_to_i]
result.append((token, MessageEventData.parse_brief_forwarded_messages_from_lp(sub_data)))
i = jump_to_i + 1
token = ""
continue
return tuple(result)
def __init__(self):
self.is_multichat = False
self.is_forwarded = False
self.is_out = False
self.chat_id = 0
self.user_id = 0
self.true_user_id = 0
self.full_text = ""
self.time = ""
self.msg_id = 0
self.true_msg_id = 0
self.attaches = None
self.forwarded = None
self.full_message_data = None
class Attachment(object):
__slots__ = ('type', 'owner_id', 'id', 'access_key', 'url', 'ext')
def __init__(self, attach_type, owner_id, aid, access_key=None, url=None, ext=None):
self.type = attach_type
self.owner_id = owner_id
self.id = aid
self.access_key = access_key
self.url = url
self.ext = ext
@staticmethod
def from_upload_result(result, attach_type="photo"):
url = None
for k in result:
if "photo_" in k:
url = result[k]
elif "link_" in k:
url = result[k]
elif "url" == k:
url = result[k]
return Attachment(attach_type, result["owner_id"], result["id"], url=url, ext=result.get("ext"))
@staticmethod
def from_raw(raw_attach):
a_type = raw_attach['type']
attach = raw_attach[a_type]
url = None
for k, v in attach.items():
if "photo_" in k:
url = v
elif "link_" in k:
url = v
elif "url" == k:
url = v
return Attachment(a_type, attach.get('owner_id', ''), attach.get('id', ''), attach.get('access_key'), url,
ext=attach.get("ext"))
def value(self):
if self.access_key:
return f'{self.type}{self.owner_id}_{self.id}_{self.access_key}'
return f'{self.type}{self.owner_id}_{self.id}'
def __str__(self):
return self.value()
MAX_LENGHT = 4000
from math import ceil
class LPMessage(object):
"""Класс, объект которого передаётся в плагин для упрощённого ответа"""
__slots__ = ('message_data', 'api', 'is_multichat', 'chat_id', 'user_id', 'is_out', 'true_user_id',
'timestamp', 'answer_values', 'msg_id', 'text', 'full_text', 'meta', 'is_event',
'brief_attaches', 'brief_forwarded', '_full_attaches', '_full_forwarded',
'reserved_by', 'occupied_by', 'peer_id', "is_forwarded", 'true_msg_id')
def __init__(self, vk_api_object, message_data):
self.message_data = message_data
self.api = vk_api_object
self.reserved_by = []
self.occupied_by = []
self.meta = {}
self.is_event = False
self.is_multichat = message_data.is_multichat
self.is_forwarded = message_data.is_forwarded
self.user_id = message_data.user_id
self.true_user_id = message_data.true_user_id
self.chat_id = message_data.chat_id
self.peer_id = (message_data.chat_id or message_data.user_id) + self.is_multichat * 2000000000
self.full_text = message_data.full_text
self.text = self.full_text.replace(""", "\"") # Not need .lower() there # edited by @Kylmakalle
self.msg_id = message_data.msg_id
self.true_msg_id = message_data.true_msg_id
self.is_out = message_data.is_out
self.timestamp = message_data.time
self.brief_forwarded = message_data.forwarded
self._full_forwarded = None
self.brief_attaches = message_data.attaches
self._full_attaches = None
if self.is_multichat:
self.answer_values = {'chat_id': self.chat_id}
else:
self.answer_values = {'user_id': self.user_id}
async def get_full_attaches(self):
"""Get list of all attachments as `Attachment` for this message"""
if self._full_attaches is None:
await self.get_full_data()
return self._full_attaches
async def get_full_forwarded(self):
"""Get list of all forwarded messages as `LPMessage` for this message"""
if self._full_forwarded is None:
await self.get_full_data()
return self._full_forwarded
async def get_full_data(self, message_data=None):
"""Update lists of all forwarded messages and all attachments for this message"""
self._full_attaches = []
self._full_forwarded = []
if not message_data:
values = {'message_ids': self.msg_id}
full_message_data = await self.api.messages.getById(**values)
if not full_message_data or not full_message_data['items']: # Если пришёл пустой ответ от VK API
return
message = full_message_data['items'][0]
else:
message = message_data
if "attachments" in message:
for raw_attach in message["attachments"]:
attach = Attachment.from_raw(raw_attach) # Создаём аттач
self._full_attaches.append(attach) # Добавляем к нашему внутреннему списку аттачей
if 'fwd_messages' in message:
self._full_forwarded, self.brief_forwarded = await self.parse_forwarded_messages(message)
async def parse_forwarded_messages(self, im):
if 'fwd_messages' not in im:
return (), ()
result = []
brief_result = []
for mes in im['fwd_messages']:
obj = MessageEventData.from_message_body(mes)
obj.msg_id = self.msg_id
obj.chat_id = self.chat_id
obj.user_id = self.user_id
obj.is_multichat = self.is_multichat
obj.is_out = self.is_out
obj.is_forwarded = True
m = await LPMessage.create(self.api, obj)
big_result, small_result = await self.parse_forwarded_messages(mes)
result.append((m, big_result))
brief_result.append((m.msg_id, small_result))
return tuple(result), tuple(brief_result)
@staticmethod
def prepare_message(message):
"""Split message to parts that can be send by `messages.send`"""
message_length = len(message)
if message_length <= MAX_LENGHT:
return [message]
def fit_parts(sep):
current_length = 0
current_message = ""
sep_length = len(sep)
parts = message.split(sep)
length = len(parts)
for j in range(length):
m = parts[j]
temp_length = len(m)
if temp_length > MAX_LENGHT:
return
if j != length - 1 and current_length + temp_length + sep_length <= MAX_LENGHT:
current_message += m + sep
current_length += temp_length + sep_length
elif current_length + temp_length <= MAX_LENGHT:
current_message += m
current_length += temp_length
elif current_length + temp_length > MAX_LENGHT:
yield current_message
current_length = temp_length
current_message = m
if j != length - 1 and current_length + sep_length < MAX_LENGHT:
current_message += sep
current_length += sep_length
if current_message:
yield current_message
result = list(fit_parts("\n"))
if not result:
result = list(fit_parts(" "))
if not result:
result = []
for i in range(int(ceil(message_length / MAX_LENGHT))):
result.append(message[i * MAX_LENGHT: (i + 1) * MAX_LENGHT])
return result
return result
@staticmethod
async def create(vk_api_object, data):
msg = LPMessage(vk_api_object, data)
if data.full_message_data:
await msg.get_full_data(data.full_message_data)
return msg
class ChatChangeEvent(Event):
__slots__ = ("source_act", "source_mid", "chat_id", "new_title",
"old_title", "changer", "chat_id", "new_cover", "user_id")
def __init__(self, api, user_id, chat_id, source_act, source_mid, new_title, old_title, new_cover, changer):
super().__init__(api, EventType.ChatChange)
self.chat_id = chat_id
self.user_id = user_id
self.source_act = source_act
self.source_mid = source_mid
self.new_cover = new_cover
self.new_title = new_title
self.old_title = old_title
self.changer = changer
async def check_event(api, user_id, chat_id, attaches):
if chat_id != 0 and "source_act" in attaches:
photo = attaches.get("attach1_type") + attaches.get("attach1") if "attach1" in attaches else None
evnt = ChatChangeEvent(api, user_id, chat_id, attaches.get("source_act"),
int(attaches.get("source_mid", 0)), attaches.get("source_text"),
attaches.get("source_old_text"), photo, int(attaches.get("from", 0)))
await process_event(evnt)
return True
return False
async def process_longpoll_event(api, new_event):
if not new_event:
return
event_id = new_event[0]
if event_id != 4 and event_id != 5:
evnt = LongpollEvent(api, event_id, new_event)
return # await process_event(evnt)
data = MessageEventData()
data.msg_id = new_event[1]
data.attaches = new_event[6]
data.time = int(new_event[4])
try:
data.user_id = int(data.attaches['from'])
data.chat_id = int(new_event[3]) - 2000000000
data.is_multichat = True
del data.attaches['from']
except KeyError:
data.user_id = int(new_event[3])
data.is_multichat = False
# https://vk.com/dev/using_longpoll_2
flags = parse_msg_flags(new_event[2])
if flags['outbox']:
return
data.is_out = True
data.full_text = new_event[5].replace('<br>', '\n')
if "fwd" in data.attaches:
data.forwarded = MessageEventData.parse_brief_forwarded_messages_from_lp(data.attaches["fwd"])
del data.attaches["fwd"]
else:
data.forwarded = []
msg = LPMessage(api, data)
if await check_event(api, data.user_id, data.chat_id, data.attaches):
msg.is_event = True
await process_message(msg)
#######################################################################################################################
async def process_message(msg, token=None, is_multichat=None, vk_chat_id=None, user_id=None, forward_settings=None,
vkchat=None,
full_msg=None, forwarded=False, vk_msg_id=None, main_message=None, known_users=None,
force_disable_notify=None, full_chat=None):
token = token or msg.api._session.access_token
is_multichat = is_multichat or msg.is_multichat
vk_msg_id = vk_msg_id or msg.msg_id
user_id = user_id or msg.user_id
known_users = known_users or {}
header_message = None
vkuser = VkUser.objects.filter(token=token).first()
if not vkuser:
return
if user_id not in known_users or {}:
peer_id, first_name, last_name = await get_name(user_id, msg.api)
known_users[user_id] = (peer_id, first_name, last_name)
else:
peer_id, first_name, last_name = known_users[user_id]
if is_multichat:
vk_chat_id = vk_chat_id or msg.peer_id
else:
vk_chat_id = vk_chat_id or peer_id
if not vkchat:
vkchat, created_vkchat = await get_vk_chat(vk_chat_id)
forward_setting = forward_settings or Forward.objects.filter(owner=vkuser.owner, vkchat=vkchat).first()
full_msg = full_msg or await msg.api('messages.getById', message_ids=', '.join(str(x) for x in [vk_msg_id]))
# Узнаем title чата
if is_multichat:
full_chat = await msg.api('messages.getChat', chat_id=vk_chat_id - 2000000000)
if full_msg.get('items'):
for vk_msg in full_msg['items']:
# Формируем ссылку на сообщение на случай ошибки
# message id
vk_msg_url_chat_id = None
if vk_msg.get("peer_id"):
try:
if int(vk_msg.get("peer_id")) >= 2000000000:
vk_msg_url_chat_id = f"c{int(vk_msg.get('peer_id')) - 2000000000}"
except:
pass
if not vk_msg_url_chat_id:
vk_msg_url_chat_id = vk_msg.get("from_id") or ""
#
vk_msg_url_msg_id = vk_msg.get("id") or vk_msg.get("conversation_message_id") or ""
vk_msg_url = f'https://vk.com/im?msgid={vk_msg_url_msg_id}&sel={vk_msg_url_chat_id}'
disable_notify = force_disable_notify or bool(vk_msg.get('push_settings', False))
attaches_scheme = []
if vk_msg.get('attachments'):
attaches_scheme = [await process_attachment(attachment, token, vk_msg_url) for attachment in
vk_msg['attachments']]
if vk_msg.get('geo'):
location = vk_msg['geo']['coordinates']['latitude'], vk_msg['geo']['coordinates']['longitude']
is_venue = vk_msg['geo'].get('place')
if is_venue:
attaches_scheme.append({'content': [location[0], location[1], is_venue.get('title', 'Место'),
is_venue.get('city', 'Город')], 'type': 'venue'})
else:
attaches_scheme.append({'content': [location[0], location[1]], 'type': 'location'})
name = first_name + ((' ' + last_name) if last_name else '')
if forward_setting:
if forwarded or is_multichat:
header = f'<b>{name}</b>' + '\n'
elif not forwarded:
header = ''
to_tg_chat = forward_setting.tgchat.cid
else:
if forwarded or not is_multichat:
header = f'<b>{name}</b>' + '\n'
elif is_multichat:
header = f'<b>{name} @ {quote_html(full_chat["title"])}</b>' + '\n'
to_tg_chat = vkuser.owner.uid
# Логика реплая на сообщение, которое уже есть в чате
if not main_message:
if vk_msg.get('reply_message'):
reply_msg_in_db = Message.objects.filter(
vk_chat=vk_chat_id,
vk_id=vk_msg['reply_message'].get('id') or vk_msg['reply_message'].get(
'conversation_message_id'),
tg_chat=to_tg_chat
).first()
if reply_msg_in_db:
main_message = reply_msg_in_db.tg_id
body_parts = []
body = quote_html(vk_msg.get('text', ''))
if body:
if (len(header) + len(body)) > MAX_MESSAGE_LENGTH:
body_parts = safe_split_text(header + body, MAX_MESSAGE_LENGTH)
body_parts[-1] = body_parts[-1] + '\n'
else:
body += '\n'
if attaches_scheme:
first_text_attach = next((attach for attach in attaches_scheme if attach and attach['type'] == 'text'),
None)
if first_text_attach:
if body_parts and (len(first_text_attach) + len(body_parts[-1])) > MAX_MESSAGE_LENGTH:
body_parts.append(first_text_attach['content'])
else:
body += first_text_attach['content']
attaches_scheme.remove(first_text_attach)
# ТК у некоторых войсов транскрипт не происходит, то мы можем их потерять. Так делать больше не будем.
# first_voice_attach = next(
# (attach for attach in attaches_scheme if attach and attach['type'] == 'audio_message'),
# None)
# if first_voice_attach:
# # Будем отправлять только те войсы, в которых завершен транскрипт сообщений
# if first_voice_attach.get('transcript_state') != 'done':
# return
if body_parts:
for body_part in range(len(body_parts)):
m = inline_link_re.finditer(body_parts[body_part])
for i in m:
vk_url = f'https://vk.com/{i.group(1)}'
check_url = await check_vk_url(vk_url)
if check_url:
body_parts[body_part] = body_parts[body_part].replace(i.group(0),
hlink(f'{i.group(2)}', url=vk_url))
try:
await bot.send_chat_action(to_tg_chat, ChatActions.TYPING)
except:
return
try: # Чтобы не падало при реплае на сообщение из чата внутри ТГ
tg_message = await bot.send_message(vkuser.owner.uid, body_parts[body_part],
parse_mode=ParseMode.HTML,
reply_to_message_id=main_message,
disable_notification=disable_notify)
except MessageError: # Надо бы обновить aiogram, чтобы можно было ловить MessageToReplyNotFound
tg_message = await bot.send_message(vkuser.owner.uid, body_parts[body_part],
parse_mode=ParseMode.HTML,
reply_to_message_id=None,
disable_notification=disable_notify)
if body_part == 0:
header_message = tg_message
if forwarded:
main_message = header_message.message_id
Message.objects.create(
vk_chat=vk_chat_id,
vk_id=vk_msg_id,
tg_chat=tg_message.chat.id,
tg_id=tg_message.message_id
)
elif not body_parts and (header + body):
m = inline_link_re.finditer(body)
for i in m:
vk_url = f'https://vk.com/{i.group(1)}'
check_url = await check_vk_url(vk_url)
if check_url:
body = body.replace(i.group(0), hlink(f'{i.group(2)}', url=vk_url))
try:
await bot.send_chat_action(to_tg_chat, ChatActions.TYPING)
except:
return
try: # Чтобы не падало при реплае на сообщение из чата внутри ТГ
header_message = tg_message = await bot.send_message(to_tg_chat, header + body,
parse_mode=ParseMode.HTML,
reply_to_message_id=main_message,
disable_notification=disable_notify)
except MessageError: # Надо бы обновить aiogram, чтобы можно было ловить MessageToReplyNotFound
header_message = tg_message = await bot.send_message(to_tg_chat, header + body,
parse_mode=ParseMode.HTML,
reply_to_message_id=None,
disable_notification=disable_notify)
if forwarded:
main_message = header_message.message_id
Message.objects.create(
vk_chat=vk_chat_id,
vk_id=vk_msg_id,
tg_chat=tg_message.chat.id,
tg_id=tg_message.message_id
)
photo_attachments = [attach for attach in attaches_scheme if attach and attach['type'] == 'photo']
if len(photo_attachments) > 1:
media = MediaGroup()
for photo in photo_attachments:
media.attach_photo(photo['content'])
tg_messages = await tgsend(bot.send_media_group, to_tg_chat, media, reply_to_message_id=main_message,
disable_notification=disable_notify, vk_msg_url=vk_msg_url)
for tg_message in tg_messages:
Message.objects.create(
vk_chat=vk_chat_id,
vk_id=vk_msg_id,
tg_chat=tg_message.chat.id,
tg_id=tg_message.message_id
)
for attachment in attaches_scheme:
if attachment:
tg_message = None
if attachment['type'] == 'text':
await bot.send_chat_action(to_tg_chat, ChatActions.TYPING)
tg_message = await tgsend(bot.send_message, to_tg_chat, attachment['content'],
parse_mode=ParseMode.HTML, reply_to_message_id=main_message,
disable_notification=disable_notify, vk_msg_url=vk_msg_url)
elif attachment['type'] == 'photo' and len(photo_attachments) == 1:
await bot.send_chat_action(to_tg_chat, ChatActions.UPLOAD_PHOTO)
tg_message = await tgsend(bot.send_photo, to_tg_chat, attachment['content'],
reply_to_message_id=main_message,
disable_notification=disable_notify, vk_msg_url=vk_msg_url)
elif attachment['type'] == 'document':
await bot.send_chat_action(to_tg_chat, ChatActions.UPLOAD_DOCUMENT)
tg_message = await tgsend(bot.send_document, to_tg_chat,
attachment.get('content', '') or attachment.get('url'),
reply_to_message_id=main_message, disable_notification=disable_notify,
vk_msg_url=vk_msg_url)
if 'content' in attachment:
try:
# Иногда тут появляется url, лень проверять откуда растут ноги
attachment['content'].close()
except:
pass
try:
# Тут вообще не оч понятно, почему не удаляет
os.remove(os.path.join(attachment['temp_path'],
attachment['file_name'] + attachment['custom_ext']))
except:
pass
elif attachment['type'] == 'video':
await bot.send_chat_action(to_tg_chat, ChatActions.UPLOAD_VIDEO)
tg_message = await tgsend(bot.send_video, to_tg_chat, attachment['content'],
reply_to_message_id=main_message, disable_notification=disable_notify,
vk_msg_url=vk_msg_url)
elif attachment['type'] == 'sticker':
await bot.send_chat_action(to_tg_chat, ChatActions.TYPING)
tg_message = await tgsend(bot.send_sticker, to_tg_chat, attachment['content'],
reply_to_message_id=main_message, disable_notification=disable_notify,
vk_msg_url=vk_msg_url)
elif attachment['type'] == 'location':
await bot.send_chat_action(to_tg_chat, ChatActions.FIND_LOCATION)
tg_message = await tgsend(bot.send_location, to_tg_chat, *attachment['content'],
reply_to_message_id=main_message, disable_notification=disable_notify,
vk_msg_url=vk_msg_url)
elif attachment['type'] == 'venue':
await bot.send_chat_action(to_tg_chat, ChatActions.FIND_LOCATION)
tg_message = await tgsend(bot.send_venue, to_tg_chat, *attachment['content'],
reply_to_message_id=main_message, disable_notification=disable_notify,
vk_msg_url=vk_msg_url)
elif attachment['type'] == 'audio':
await bot.send_chat_action(to_tg_chat, ChatActions.UPLOAD_DOCUMENT)
tg_message = await tgsend(bot.send_audio, to_tg_chat, audio=attachment['content'],
caption=attachment.get('caption', None),
performer=attachment.get('artist', None),
title=attachment.get('title', None),
reply_to_message_id=main_message, disable_notification=disable_notify,
vk_msg_url=vk_msg_url,
parse_mode='HTML')
elif attachment['type'] == 'audio_message':
await bot.send_chat_action(to_tg_chat, ChatActions.RECORD_AUDIO)
tg_message = await tgsend(bot.send_voice, to_tg_chat, voice=attachment['content'])
# Надо бы делать по-умнее, но очень лень.
# if attachment.get('transcript'):
# transcript_text = '<i>Войс:</i> ' + attachment['transcript']
# transcript_message = await tgsend(bot.send_message, to_tg_chat, text=transcript_text,
# reply_to_message_id=tg_message.message_id,
# parse_mode=ParseMode.HTML)
# Message.objects.create(
# vk_chat=vk_chat_id,
# vk_id=vk_msg_id,
# tg_chat=transcript_message.chat.id,
# tg_id=transcript_message.message_id
# )
if tg_message:
Message.objects.create(
vk_chat=vk_chat_id,
vk_id=vk_msg_id,
tg_chat=tg_message.chat.id,
tg_id=tg_message.message_id
)
if vk_msg.get('fwd_messages'):
await bot.send_chat_action(to_tg_chat, ChatActions.TYPING)
for fwd_message in vk_msg['fwd_messages']:
# Не у всех сообщений есть уникальный id, похоже надо сохранять conversation_message_id в том числе
# И делать миграции
if fwd_message.get('id'):
fwd_msgs_in_db = Message.objects.filter(
vk_chat=vk_chat_id,
vk_id=fwd_message['id'],
tg_chat=to_tg_chat
)
else:
fwd_msgs_in_db = None
if fwd_msgs_in_db:
for fwd_msg_in_db in fwd_msgs_in_db:
try:
await bot.forward_message(to_tg_chat, to_tg_chat, fwd_msg_in_db.tg_id,
disable_notification=disable_notify, vk_msg_url=vk_msg_url)
except:
await process_message(msg, token=token, is_multichat=is_multichat,
vk_chat_id=vk_chat_id,
user_id=fwd_message['from_id'],
forward_settings=forward_settings, vk_msg_id=vk_msg_id,
vkchat=vkchat,
full_msg={'items': [fwd_message]}, forwarded=True,
main_message=header_message.message_id if header_message else None,
known_users=known_users, force_disable_notify=disable_notify)
else:
await process_message(msg, token=token, is_multichat=is_multichat, vk_chat_id=vk_chat_id,
user_id=fwd_message['from_id'],
forward_settings=forward_settings, vk_msg_id=vk_msg_id, vkchat=vkchat,
full_msg={'items': [fwd_message]}, forwarded=True,
main_message=header_message.message_id if header_message else None,
known_users=known_users, force_disable_notify=disable_notify)
async def get_name(identifier, api):
if identifier > 0:
peer = await api('users.get', user_ids=identifier)
first_name = peer[0]['first_name']
last_name = peer[0]['last_name'] or ''
else:
peer = await api('groups.getById', group_ids=abs(identifier))
first_name = peer[0]['name']
last_name = ''
peer[0]['id'] = -peer[0]['id']
return peer[0]['id'], first_name, last_name
async def tgsend(method, *args, **kwargs):
vk_msg_url = kwargs.pop('vk_msg_url', 0)
try:
tg_message = await method(*args, **kwargs)
return tg_message
except RetryAfter as e:
await asyncio.sleep(e.timeout)
await tgsend(method, *args, **kwargs)
except Exception:
log.exception(msg='Error in message sending', exc_info=True)
await tgsend_error_report(args[0], vk_msg_url)
async def tgsend_error_report(chat_id, vk_msg_url):
try:
text = '<i>Ошибка отправки сообщения VK → Telegram</i>'
if vk_msg_url:
text += '\n' + f'<a href="{vk_msg_url}">Сообщение</a>'
await bot.send_message(chat_id, text=text, parse_mode='HTML')
except RetryAfter as e:
await asyncio.sleep(e.timeout)
await tgsend_error_report(chat_id, vk_msg_url)
except Exception:
log.exception(msg='Error in message sending report', exc_info=True)
pass
async def process_event(msg):
pass
async def check_vk_url(url):
try:
with aiohttp.ClientSession(conn_timeout=5) as session:
r = await session.request('GET', url)
if r.status == 200:
return True
return False
except:
return False
def form_audio_title(data: dict, delimer=' '):
result = data.get('artist')
if result:
if 'title' in data:
result += delimer + data['title']
else:
if 'title' in data:
result = data['title']
else:
return
return result
def search_max_vk_photo_size(sizes: list) -> dict:
return list(sorted(sizes, key=lambda x: (int(x.get('width', 0)), int(x.get('height', 0))), reverse=True))[0]
async def process_attachment(attachment, token=None, vk_msg_url=None):
atype = attachment.get('type')
if atype == 'photo':
photo_url = search_max_vk_photo_size(attachment[atype]['sizes'])['url']
return {'content': photo_url, 'type': 'photo'}
elif atype == 'audio_message':
voice_url = attachment[atype]['link_ogg']
res = {'content': voice_url, 'type': 'audio_message'}
if attachment[atype].get('transcript'):
return {'content': f'<i>Войс:</i>{attachment[atype]["transcript"]}', 'type': 'text'}
return res
elif atype == 'audio':
if attachment[atype].get('url') and AUDIO_PROXY_URL:
try:
with aiohttp.ClientSession() as session:
r = await session.request('GET', AUDIO_PROXY_URL,
params={'url': urllib.parse.quote(attachment[atype]['url']),
'artist': urllib.parse.quote(attachment[atype].get('artist', '')),
'title': urllib.parse.quote(attachment[atype].get('title', ''))},
headers=CHROME_HEADERS)
if r.status != 200:
raise Exception
audio = await r.read()
audio = io.BytesIO(audio)
return {'content': audio, 'type': 'audio'}
except:
pass
if AUDIO_ACCESS_URL:
if token:
try:
with aiohttp.ClientSession() as session:
r = await session.request('GET', AUDIO_ACCESS_URL.format(token=token,
owner_id=attachment[atype]['owner_id'],
audio_id=attachment[atype]['id'],
access_key=attachment[atype].get(
'access_key', '')))
if r.status != 200:
raise Exception
audio = await r.read()
audio = io.BytesIO(audio)
return {'content': audio, 'type': 'audio'}
except:
pass
if AUDIO_URL:
try:
with aiohttp.ClientSession() as session:
r = await session.request('GET', AUDIO_URL.format(owner_id=attachment[atype]['owner_id'],
audio_id=attachment[atype]['id']))
if r.status != 200:
raise Exception
audio = await r.read()
audio = io.BytesIO(audio)
return {'content': audio, 'type': 'audio'}
except:
pass
if AUDIO_SEARCH_URL:
try:
search = form_audio_title(attachment[atype])
if not search:
raise Exception
with aiohttp.ClientSession() as session:
r = await session.request('GET', AUDIO_SEARCH_URL, params={'q': urllib.parse.quote(search)})
if r.status != 200:
raise Exception
audios = await r.json()
if audios['success'] and audios['data']:
if attachment[atype]['duration']:
audio = min(audios['data'],
key=lambda x: abs(x['duration'] - attachment[atype]['duration']))
else:
audio = audios['data'][0]
else:
raise Exception
with aiohttp.ClientSession() as session:
r = await session.request('GET', audio["download"])
if r.status != 200:
raise Exception
audio = await r.read()
audio = io.BytesIO(audio)
# search = form_audio_title(attachment[atype], ' - ')