This repository has been archived by the owner on Apr 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconversations_parser.py
105 lines (95 loc) · 5.55 KB
/
conversations_parser.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
from termcolor import colored, cprint
from datetime import datetime
class Parser:
api = None
def __init__(self, api):
self.api = api
@staticmethod
def _find_profile(conversations, peer_id, key='profiles'):
for profile in conversations[key]:
if profile['id'] == abs(peer_id):
return profile
raise LookupError('Неизвестная ошибка')
@staticmethod
def _print_message(message):
if message['text']:
print(message['text'])
if len(message['attachments']):
for attachment in message['attachments']:
print('Дополнительно:', colored(attachment['type'], 'cyan'), end=' ')
print()
def _print_private_message(self, conversations, conversation):
peer_id = conversation['conversation']['peer']['id']
peer_info = self._find_profile(conversations, peer_id)
print('-' * 10, colored('{} {} ({})'.format(peer_info['first_name'], peer_info['last_name'], peer_id), 'red'))
date = datetime.fromtimestamp(conversation['last_message']['date'])
print(date.strftime('%Y-%m-%d %H:%M:%S'))
if conversation['last_message']['out'] and conversation['last_message']['text']:
print('Сообщение', colored('(Вы)' + ':', 'green'), end=' ')
else:
print('Сообщение', colored('(Собеседник)', 'blue') + ':', end=' ')
self._print_message(conversation['last_message'])
def _print_chat_message(self, conversations, conversation):
title = colored(conversation['conversation']['chat_settings']['title'], 'blue')
chat_id = conversation['conversation']['peer']['id']
last_peer = conversation['last_message']['from_id']
print('---------- Чат: {} ({})'.format(title, chat_id))
if last_peer >= 0:
last_peer_info = self._find_profile(conversations, last_peer)
print(
colored(f'Сообщение от: {last_peer_info["first_name"]} \
{last_peer_info["last_name"]} ({last_peer})', "blue"))
else:
last_peer_info = self._find_profile(conversations, last_peer, key='groups')
print(f'Сообщение от: {colored(last_peer_info["name"], "blue")} ({last_peer})')
date = datetime.fromtimestamp(conversation['last_message']['date'])
print(date.strftime('%Y-%m-%d %H:%M:%S'))
if conversation['last_message']['text']:
print('Собщение:', end=' ')
self._print_message(conversation['last_message'])
def _print_group_message(self, conversations, conversation):
group_id = conversation['conversation']['peer']['local_id']
group_info = self._find_profile(conversations, group_id, key='groups')
print('-' * 10 + colored(' {} ({})'.format(group_info['name'], group_id), 'cyan'))
date = datetime.fromtimestamp(conversation['last_message']['date'])
print(date.strftime('%Y-%m-%d %H:%M:%S'))
if conversation['last_message']['out'] and conversation['last_message']['text']:
print('Сообщение', colored('(Вы)' + ':', 'green'), end=' ')
else:
print('Сообщение', colored('(Группа)', 'blue') + ':', end=' ')
self._print_message(conversation['last_message'])
def print_conversations_short(self, count):
dialogs_ids = []
conversations = self.api.messages.getConversations(count=count, extended=True)
for i, conversation in enumerate(conversations['items']):
if conversation['conversation']['peer']['type'] == 'user':
peer_id = conversation['conversation']['peer']['id']
peer_info = self._find_profile(conversations, peer_id)
cprint('№{}:{} {} ({}):'.format(i, peer_info['first_name'], peer_info['last_name'], peer_id),
'red')
dialogs_ids.append(peer_id)
elif conversation['conversation']['peer']['type'] == 'chat':
title = conversation['conversation']['chat_settings']['title']
chat_id = conversation['conversation']['peer']['id']
cprint('№{}:Чат: {} ({})'.format(i, title, chat_id), 'blue')
dialogs_ids.append(chat_id)
elif conversation['conversation']['peer']['type'] == 'group':
group_id = conversation['conversation']['peer']['id']
group_info = self._find_profile(conversations, abs(group_id), key='groups')
cprint('№{}:Группа: {} ({})'.format(i, group_info['name'], group_id), 'cyan')
dialogs_ids.append(group_id)
else:
dialogs_ids.append(None)
print('Peer', conversation['conversation']['peer']['type'], 'is not recognized')
return dialogs_ids
def print_conversations(self, count, filter='all'):
conversations = self.api.messages.getConversations(count=count, filter=filter, extended=True)
for conversation in conversations['items']:
if conversation['conversation']['peer']['type'] == 'user':
self._print_private_message(conversations, conversation)
elif conversation['conversation']['peer']['type'] == 'chat':
self._print_chat_message(conversations, conversation)
elif conversation['conversation']['peer']['type'] == 'group':
self._print_group_message(conversations, conversation)
else:
print('--------\nPeer', conversation['conversation']['peer']['type'], 'is not recognized')