-
Notifications
You must be signed in to change notification settings - Fork 1
/
core.py
128 lines (96 loc) · 3.26 KB
/
core.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
import os
from datetime import datetime
import vk_api
from dotenv import load_dotenv
from vk_api.exceptions import ApiError
load_dotenv()
access_token = os.getenv('access_token')
my_id = os.getenv('my_id')
class VkTools():
def __init__(self, access_token):
self.vkapi = vk_api.VkApi(token=access_token)
def _bdate_to_age(self, bdate: str):
user_birth_year = bdate.split('.')[2]
now = datetime.now().year
return (now - int(user_birth_year))
def get_profile_info(self, user_id):
try:
info, = self.vkapi.method(
'users.get',
{
'user_id': user_id,
'fields': 'city, sex, bdate',
}
)
except ApiError as e:
info = {}
print(f'error = {e}')
result = {
'user_id': info.get('id'),
'name': (info['first_name'] + ' ' + info['last_name']) if
'first_name' in info and 'last_name' in info else None,
'sex': info.get('sex') if 'sex' in info else None,
'city': (info.get('city')['title'] if
info.get('city') is not None else None),
'age': (self._bdate_to_age(info.get('bdate')) if
'bdate' in info else None),
}
# result = {
# 'user_id': info.get('id'),
# 'name': (info['first_name'] + ' ' + info['last_name']) if
# 'first_name' in info and 'last_name' in info else None,
# 'sex': None,
# 'city': None,
# 'age': None,
# }
return result
def search_worksheet(self, params, offset):
try:
users = self.vkapi.method(
'users.search',
{
'count': 50,
'offset': offset,
'hometown': params.get('city'),
'sex': 1 if params.get('sex') == 2 else 2,
'has_photo': True,
'age_from': params['age'] - 3,
'age_to': params['age'] + 3,
'status': 1 or 6,
}
)
except ApiError as e:
users = []
print(f' error = {e}')
result = [
{
'id': item['id'],
'name': item['first_name'] + ' ' + item['last_name'],
} for item in users['items'] if item['is_closed'] is False
]
return result
def get_photos(self, id):
try:
photos = self.vkapi.method(
'photos.get',
{
'owner_id': id,
'album_id': 'profile',
'extended': 1,
}
)
except ApiError as e:
photos = {}
print(f'error = {e}')
result = [
{
'owner_id': item['owner_id'],
'id': item['id'],
'likes': item['likes']['count'],
'comments': item['comments']['count'],
} for item in photos['items']
]
result.sort(key=lambda x: (x['likes'], x['comments']), reverse=False)
return result[:3]
if __name__ == '__main__':
tools = VkTools(access_token)