-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.py
303 lines (280 loc) · 13.3 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
from config import user_token, comm_token, offset, line
import vk_api
import requests
import datetime
from vk_api.longpoll import VkLongPoll, VkEventType
from random import randrange
from database import *
class VKBot:
def __init__(self):
print('Bot was created')
self.vk = vk_api.VkApi(token=comm_token) # АВТОРИЗАЦИЯ СООБЩЕСТВА
self.longpoll = VkLongPoll(self.vk) # РАБОТА С СООБЩЕНИЯМИ
def write_msg(self, user_id, message):
"""МЕТОД ДЛЯ ОТПРАВКИ СООБЩЕНИЙ"""
self.vk.method('messages.send', {'user_id': user_id,
'message': message,
'random_id': randrange(10 ** 7)})
def name(self, user_id):
"""ПОЛУЧЕНИЕ ИМЕНИ ПОЛЬЗОВАТЕЛЯ, КОТОРЫЙ НАПИСАЛ БОТУ"""
url = f'https://api.vk.com/method/users.get'
params = {'access_token': user_token,
'user_ids': user_id,
'v': '5.131'}
repl = requests.get(url, params=params)
response = repl.json()
try:
information_dict = response['response']
for i in information_dict:
for key, value in i.items():
first_name = i.get('first_name')
return first_name
except KeyError:
self.write_msg(user_id, 'Ошибка получения токена, введите токен в переменную - user_token')
def get_sex(self, user_id):
"""ПОЛУЧЕНИЕ ПОЛА ПОЛЬЗОВАТЕЛЯ, МЕНЯЕТ НА ПРОТИВОПОЛОЖНЫЙ"""
url = f'https://api.vk.com/method/users.get'
params = {'access_token': user_token,
'user_ids': user_id,
'fields': 'sex',
'v': '5.131'}
repl = requests.get(url, params=params)
response = repl.json()
try:
information_list = response['response']
for i in information_list:
if i.get('sex') == 2:
find_sex = 1
return find_sex
elif i.get('sex') == 1:
find_sex = 2
return find_sex
except KeyError:
self.write_msg(user_id, 'Ошибка получения токена, введите токен в переменную - user_token')
def get_age_low(self, user_id):
"""ПОЛУЧЕНИЕ ВОЗРАСТА ПОЛЬЗОВАТЕЛЯ ИЛИ НИЖНЕЙ ГРАНИЦЫ ДЛЯ ПОИСКА"""
url = url = f'https://api.vk.com/method/users.get'
params = {'access_token': user_token,
'user_ids': user_id,
'fields': 'bdate',
'v': '5.131'}
repl = requests.get(url, params=params)
response = repl.json()
try:
information_list = response['response']
for i in information_list:
date = i.get('bdate')
date_list = date.split('.')
if len(date_list) == 3:
year = int(date_list[2])
year_now = int(datetime.date.today().year)
return year_now - year
elif len(date_list) == 2 or date not in information_list:
self.write_msg(user_id, 'Введите нижний порог возраста (min - 16): ')
for event in self.longpoll.listen():
if event.type == VkEventType.MESSAGE_NEW and event.to_me:
age = event.text
return age
except KeyError:
self.write_msg(user_id, 'Ошибка получения токена')
def get_age_high(self, user_id):
"""ПОЛУЧЕНИЕ ВОЗРАСТА ПОЛЬЗОВАТЕЛЯ ИЛИ ВЕРХНЕЙ ГРАНИЦЫ ДЛЯ ПОИСКА"""
url = url = f'https://api.vk.com/method/users.get'
params = {'access_token': user_token,
'user_ids': user_id,
'fields': 'bdate',
'v': '5.131'}
repl = requests.get(url, params=params)
response = repl.json()
try:
information_list = response['response']
for i in information_list:
date = i.get('bdate')
date_list = date.split('.')
if len(date_list) == 3:
year = int(date_list[2])
year_now = int(datetime.date.today().year)
return year_now - year
elif len(date_list) == 2 or date not in information_list:
self.write_msg(user_id, 'Введите верхний порог возраста (max - 65): ')
for event in self.longpoll.listen():
if event.type == VkEventType.MESSAGE_NEW and event.to_me:
age = event.text
return age
except KeyError:
self.write_msg(user_id, 'Ошибка получения токена, введите токен в переменную - user_token')
# @staticmethod
def cities(self, user_id, city_name):
"""ПОЛУЧЕНИЕ ID ГОРОДА ПОЛЬЗОВАТЕЛЯ ПО НАЗВАНИЮ"""
url = url = f'https://api.vk.com/method/database.getCities'
params = {'access_token': user_token,
'country_id': 1,
'q': f'{city_name}',
'need_all': 0,
'count': 1000,
'v': '5.131'}
repl = requests.get(url, params=params)
response = repl.json()
try:
information_list = response['response']
list_cities = information_list['items']
for i in list_cities:
found_city_name = i.get('title')
if found_city_name == city_name:
found_city_id = i.get('id')
return int(found_city_id)
except KeyError:
self.write_msg(user_id, 'Ошибка получения токена')
def find_city(self, user_id):
"""ПОЛУЧЕНИЕ ИНФОРМАЦИИ О ГОРОДЕ ПОЛЬЗОВАТЕЛЯ"""
url = f'https://api.vk.com/method/users.get'
params = {'access_token': user_token,
'fields': 'city',
'user_ids': user_id,
'v': '5.131'}
repl = requests.get(url, params=params)
response = repl.json()
try:
information_dict = response['response']
for i in information_dict:
if 'city' in i:
city = i.get('city')
id = str(city.get('id'))
return id
elif 'city' not in i:
self.write_msg(user_id, 'Введите название вашего города: ')
for event in self.longpoll.listen():
if event.type == VkEventType.MESSAGE_NEW and event.to_me:
city_name = event.text
id_city = self.cities(user_id, city_name)
if id_city != '' or id_city != None:
return str(id_city)
else:
break
except KeyError:
self.write_msg(user_id, 'Ошибка получения токена')
def find_user(self, user_id):
"""ПОИСК ЧЕЛОВЕКА ПО ПОЛУЧЕННЫМ ДАННЫМ"""
url = f'https://api.vk.com/method/users.search'
params = {'access_token': user_token,
'v': '5.131',
'sex': self.get_sex(user_id),
'age_from': self.get_age_low(user_id),
'age_to': self.get_age_high(user_id),
'city': self.find_city(user_id),
'fields': 'is_closed, id, first_name, last_name',
'status': '1' or '6',
'count': 500}
resp = requests.get(url, params=params)
resp_json = resp.json()
try:
dict_1 = resp_json['response']
list_1 = dict_1['items']
for person_dict in list_1:
if person_dict.get('is_closed') == False:
first_name = person_dict.get('first_name')
last_name = person_dict.get('last_name')
vk_id = str(person_dict.get('id'))
vk_link = 'vk.com/id' + str(person_dict.get('id'))
insert_data_users(first_name, last_name, vk_id, vk_link)
else:
continue
return f'Поиск завершён'
except KeyError:
self.write_msg(user_id, 'Ошибка получения токена')
def get_photos_id(self, user_id):
"""ПОЛУЧЕНИЕ ID ФОТОГРАФИЙ С РАНЖИРОВАНИЕМ В ОБРАТНОМ ПОРЯДКЕ"""
url = 'https://api.vk.com/method/photos.getAll'
params = {'access_token': user_token,
'type': 'album',
'owner_id': user_id,
'extended': 1,
'count': 25,
'v': '5.131'}
resp = requests.get(url, params=params)
dict_photos = dict()
resp_json = resp.json()
try:
dict_1 = resp_json['response']
list_1 = dict_1['items']
for i in list_1:
photo_id = str(i.get('id'))
i_likes = i.get('likes')
if i_likes.get('count'):
likes = i_likes.get('count')
dict_photos[likes] = photo_id
list_of_ids = sorted(dict_photos.items(), reverse=True)
return list_of_ids
except KeyError:
self.write_msg(user_id, 'Ошибка получения токена')
def get_photo_1(self, user_id):
"""ПОЛУЧЕНИЕ ID ФОТОГРАФИИ № 1"""
list = self.get_photos_id(user_id)
count = 0
for i in list:
count += 1
if count == 1:
return i[1]
def get_photo_2(self, user_id):
"""ПОЛУЧЕНИЕ ID ФОТОГРАФИИ № 2"""
list = self.get_photos_id(user_id)
count = 0
for i in list:
count += 1
if count == 2:
return i[1]
def get_photo_3(self, user_id):
"""ПОЛУЧЕНИЕ ID ФОТОГРАФИИ № 3"""
list = self.get_photos_id(user_id)
count = 0
for i in list:
count += 1
if count == 3:
return i[1]
def send_photo_1(self, user_id, message, offset):
"""ОТПРАВКА ПЕРВОЙ ФОТОГРАФИИ"""
self.vk.method('messages.send', {'user_id': user_id,
'access_token': user_token,
'message': message,
'attachment': f'photo{self.person_id(offset)}_{self.get_photo_1(self.person_id(offset))}',
'random_id': 0})
def send_photo_2(self, user_id, message, offset):
"""ОТПРАВКА ВТОРОЙ ФОТОГРАФИИ"""
self.vk.method('messages.send', {'user_id': user_id,
'access_token': user_token,
'message': message,
'attachment': f'photo{self.person_id(offset)}_{self.get_photo_2(self.person_id(offset))}',
'random_id': 0})
def send_photo_3(self, user_id, message, offset):
"""ОТПРАВКА ТРЕТЬЕЙ ФОТОГРАФИИ"""
self.vk.method('messages.send', {'user_id': user_id,
'access_token': user_token,
'message': message,
'attachment': f'photo{self.person_id(offset)}_{self.get_photo_3(self.person_id(offset))}',
'random_id': 0})
def find_persons(self, user_id, offset):
self.write_msg(user_id, self.found_person_info(offset))
self.person_id(offset)
insert_data_seen_users(self.person_id(offset), offset) #offset
self.get_photos_id(self.person_id(offset))
self.send_photo_1(user_id, 'Фото номер 1', offset)
if self.get_photo_2(self.person_id(offset)) != None:
self.send_photo_2(user_id, 'Фото номер 2', offset)
self.send_photo_3(user_id, 'Фото номер 3', offset)
else:
self.write_msg(user_id, f'Больше фотографий нет')
def found_person_info(self, offset):
"""ВЫВОД ИНФОРМАЦИИ О НАЙДЕННОМ ПОЛЬЗОВАТЕЛИ"""
tuple_person = select(offset)
list_person = []
for i in tuple_person:
list_person.append(i)
return f'{list_person[0]} {list_person[1]}, ссылка - {list_person[3]}'
def person_id(self, offset):
"""ВЫВОД ID НАЙДЕННОГО ПОЛЬЗОВАТЕЛЯ"""
tuple_person = select(offset)
list_person = []
for i in tuple_person:
list_person.append(i)
return str(list_person[2])
bot = VKBot()