def handle_address(og_group, new_group, token): addresses = [] r_addresses = vk_request('get', 'groups.getAddresses', { 'group_id': og_group}, token, '5.126') for a in r_addresses['response']['items']: a['group_id'] = new_group add_r = vk_request('get', 'groups.addAddress', a, token, '5.126')
def addSavedPost(request): if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) user_id = data.get('user_id', None) post_link = data.get('post_link', None) if user_id is not None and post_link is not None: user = VkUser.objects.all().get(pk=user_id) if 'wall' in post_link: if '-' in post_link: splitted = post_link.split('-') post_id = splitted[1] post_id = "-" + post_id else: splitted = post_link.split('wall')[1] post_id = splitted.split('?')[0] else: return {'error': True, 'message': 'link'} wall_data = vk_request('get', 'wall.getById', {'posts': post_id}, user.token, '5.124')['response'][0] print(wall_data) new_post = SavedPost(user=user, message=wall_data['text'], attachments=json.dumps( wall_data.get('attachments', ''))) new_post.save() return JsonResponse(model_to_dict(new_post), safe=False) return HttpResponse('Wrong request')
def remove_from_vk(post, now): from think_bank.views import vk_request from .models import AvailableGroup groups = json.loads(post.target_groups_id) try: for g_id in groups: target_group = AvailableGroup.objects.all().get(pk=g_id) current_ids = json.loads(post.posted_vk_ids) post_id = current_ids[str(g_id)] props = { 'owner_id': "-" + target_group.group_id, 'post_id': post_id, } d = vk_request('get', 'wall.delete', props, post.post.user.post_token, '5.124') print('Deleted', d, post_id) post.posted_vk_ids = json.dumps({}) post.last_day_deleted = now.weekday() post.on_delete = False post.save() except: print('Error') post.delete()
def addAvailableGroup(request): if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) user_id = data.get('user_id', None) group_url = data.get('group_url', None) if user_id is not None and group_url is not None: user = VkUser.objects.get(pk=user_id) if 'https://vk.com/' in group_url: processed_url = group_url.replace('https://vk.com/', '') if 'public' in processed_url: processed_url = processed_url.replace('public', '') else: return {'error': True, 'message': 'not_url'} if AvailableGroup.objects.all().filter( Q(user=user) & Q(group_id=processed_url)).count() == 0: group = vk_request('get', 'groups.getById', {'group_ids': processed_url}, user.token, '5.124')['response'][0] new_group = AvailableGroup(group_id=group['id'], name=group['name'], group_img=group['photo_50'], user=user) new_group.save() return JsonResponse(model_to_dict(new_group), safe=False) return HttpResponse('Wrong request')
def send_message(message, user_id): community_token = 'b80859e3d19b51d9c172b0b51c68f6824ee392617640be2f827ba1929f85d4c0ffe876e55e5f5d1dcbfb8' rand = int(random.randint(-30000, 30000)) answer = vk_request('post', 'messages.send', { 'peer_id': user_id, 'message': message, 'random_id': rand }, community_token, '5.131') print(answer)
def send_message(message, user_id): community_token = 'ec944a7cbd5b2bd0f86a5b5096782dd0ada66e6d8dbb0903a3321dfd8787ee1849385d2b5126d5df28b62' rand = int(random.randint(-30000, 30000)) answer = vk_request('post', 'messages.send', { 'peer_id': user_id, 'message': message, 'random_id': rand }, community_token, '5.131') print(answer)
def handle_posts(og_group, new_group, token): posts = [] wall = vk_request('get', 'wall.get', { 'owner_id': og_group * -1, 'count': 100}, token, '5.126')['response']['items'] for post in reversed(wall): close_comments = post['comments']['can_post'] * -1 attachments = getAttachments(post) text = post['text'] rand = random.randint(-32768, 32767) props = { 'owner_id': "-" + str(new_group), 'from_group': 1, 'message': text, 'attachments': attachments, 'guid': rand, 'close_comments': close_comments, 'mute_notifications': 1 } posted_vk_id = vk_request( 'post', 'wall.post', props, token, '5.124')
def handle_edit(g_id, access, desc, website, subject, phone, public_cat, public_sub_cat, country, city, age_limits, addresses, token): settings = vk_request('get', 'groups.setSettings', { 'messages': 1, 'group_id': int(g_id)}, token, '5.126') props = {} assign(props, 'description', desc) assign(props, 'website', website) assign(props, 'group_id', g_id) assign(props, 'access', access) assign(props, 'subject', subject) assign(props, 'phone', phone) assign(props, 'public_category', public_cat) assign(props, 'public_subcategory', public_sub_cat) assign(props, 'country', country) assign(props, 'city', city) assign(props, 'age_limits', age_limits) assign(props, 'addresses', addresses) edit = vk_request('get', 'groups.edit', props, token, '5.126') return 1
def handle_create(title, desc, g_type, public_cat, public_subcategory, subtype, token): created_group_info = vk_request('get', 'groups.create', { 'title': title, 'description': desc, 'type': 'public' if g_type == 'page' else g_type, 'public_category': public_cat, 'public_subcategory': public_subcategory, 'subtype': subtype }, token, '5.126') print(created_group_info) return created_group_info['response']['id']
def handle_photos(created_group_id, g_cover, g_photo, token): photo_url = vk_request('get', 'photos.getOwnerPhotoUploadServer', { 'owner_id': created_group_id * -1}, token, '5.126') photo_url = photo_url['response']['upload_url'] cover_url = vk_request('get', 'photos.getOwnerCoverPhotoUploadServer', { 'group_id': created_group_id, 'crop_y2': g_cover['images'][-1]['height'], 'crop_x2': g_cover['images'][-1]['width']}, token, '5.126') cover_url = cover_url['response']['upload_url'] urllib.request.urlretrieve(g_photo, "logo.png") photo_server = requests.post( photo_url, files={'photo': open("logo.png", 'rb')}).json() urllib.request.urlretrieve(g_cover['images'][-1]['url'], "cover.png") photo_cover = requests.post( cover_url, files={'photo': open("cover.png", 'rb')}).json() photo_answer = vk_request('post', 'photos.saveOwnerPhoto', { 'server': photo_server['server'], 'hash': photo_server['hash'], 'photo': photo_server['photo']}, token, '5.126') cover_answer = vk_request('post', 'photos.saveOwnerCoverPhoto', { 'hash': photo_cover['hash'], 'photo': photo_cover['photo']}, token, '5.126') return 1
def getVkUserInfo(user_id): try: user_data = vk_request( 'get', 'users.get', { 'user_ids': user_id, 'fields': 'photo_200' }, 'ec944a7cbd5b2bd0f86a5b5096782dd0ada66e6d8dbb0903a3321dfd8787ee1849385d2b5126d5df28b62', '5.124')['response'][0] result = {} result['vk_id'] = user_data['id'] result['photo'] = user_data['photo_200'] result['name'] = user_data['first_name'] + ' ' + user_data['last_name'] return result except: return -1
def login(request): if request.method == 'POST': user = json.loads(request.body.decode('utf-8')) user_id = user.get('user_id', None) token = user.get('access_token', None) # redirect_url = user.get('url', None) if token is not None: # r = requests.get( # 'https://oauth.vk.com/access_token?client_id='+client_id+'&client_secret='+client_secret+'&redirect_uri='+redirect_url+'&code=' + code) # result = json.loads(r.content.decode('utf-8')) # token = result['access_token'] # user_id = result['user_id'] users = VkUser.objects.all().filter(user_id=user_id) if not users: user_data = vk_request('get', 'users.get', { 'user_ids': user_id, 'fields': 'photo_200' }, token, '5.124')['response'][0] new_user = VkUser(user_id=user_data['id'], user_img=user_data['photo_200'], user_name=user_data['first_name'] + ' ' + user_data['last_name'], token=token, post_token='') new_user.save() new_user.post_token = '' new_user.shutterstock_token = '' result = model_to_dict(new_user) result['medals'] = json.loads(new_user.medals) return JsonResponse(result, safe=False) else: old_user = users.first() old_user.token = token old_user.save() result = model_to_dict(old_user) result['medals'] = json.loads(old_user.medals) return JsonResponse(result, safe=False) return HttpResponse('Wrong request')
def handle_contacts(contacts, og_group_id, g_id, token, created_group, created_group_url): cont = [] for i in contacts: cont.append(i['user_id']) managers = vk_request('get', 'groups.getMembers', { 'group_id': og_group_id, 'filter': 'managers'}, token, '5.126') for m in managers['response']['items']: contact_flag = 1 if m['id'] in cont else 0 moderators_count = 0 if m['role'] != 'creator': new_future_moderator = FutureModerator( role=m['role'], is_contact=contact_flag, vk_id=m['id'], group_id=g_id) new_future_moderator.save() moderators_count += 1 # send_message(m['role'], m['id'], # created_group_url, message_token, g_id) # r = vk_request('get', 'groups.editManager', { # 'group_id': g_id, 'user_id': m['id'], 'role': m['role'], 'is_contact': contact_flag}, token, '5.126') created_group.number_of_moderators = moderators_count created_group.save()
def post_to_vk(post, now): import random from think_bank.views import vk_request from .models import AvailableGroup groups = json.loads(post.target_groups_id) new_ids = {} try: for g_id in groups: target_group = AvailableGroup.objects.all().get(pk=g_id) rand = random.randint(-32768, 32767) props = { 'owner_id': "-" + target_group.group_id, 'from_group': post.from_group, 'message': post.post.message, 'attachments': getAttachments(post), 'guid': rand, 'mark_as_ads': post.mark_as_ads, 'close_comments': post.close_comments, 'mute_notifications': post.mute_notifications } posted_vk_id = '' posted_vk_id = vk_request('post', 'wall.post', props, post.post.user.post_token, '5.124') print(posted_vk_id) pid = posted_vk_id['response']['post_id'] print('Post added', posted_vk_id) new_ids[g_id] = pid post.posted_vk_ids = json.dumps(new_ids) post.last_day_added = now.weekday() post.on_delete = True post.save() except: print('Error') post.delete()
def search_people(job): user_id = job.owner.user_id token = job.owner.token def compare_images(img_link1, img_link2): hash0 = imagehash.average_hash(Image.open( requests.get(img_link1, stream=True).raw)) hash1 = imagehash.average_hash(Image.open( requests.get(img_link2, stream=True).raw)) cutoff = 5 # maximum bits that could be different between the hashes. if hash0 - hash1 < cutoff: return True else: return False def compare(o, o2): if o['has_photo'] != o2['has_photo']: return False index = 0 index = index + \ 1 if o.get('sex', None) == o2.get('sex', None) else index index = index + \ 10 if o.get('bdate', None) == o2.get('bdate', None) else index index = index + 3 if o.get('country', None) == o2.get('country', None) else index index = index + 1 if o.get('timezone', None) == o2.get('timezone', None) else index index = index + \ 1 if o.get('about', None) == o2.get('about', None) else index index = index + \ 1 if o.get('activities', None) == o2.get( 'activities', None) else index index = index + \ 1 if o.get('books', None) == o2.get('books', None) else index index = index + \ 10 if o.get('career', None) == o2.get('career', None)else index index = index + 1 if o.get('faculty', None) == o2.get('faculty', None) else index index = index + \ 1 if o.get('faculty_name', None) == o2.get( 'faculty_name', None) else index index = index + \ 1 if o.get('graduation', None) == o2.get( 'graduation', None) else index index = index + \ 1 if o.get('home_phone', None) == o2.get( 'home_phone', None) else index index = index + 1 if o.get('home_town', None) == o2.get('home_town', None) else index index = index + \ 10 if o.get('interests', None) == o2.get( 'interests', None) else index index = index + 1 if o.get('military', None) == o2.get('military', None) else index index = index + 1 if o.get('nickname', None) == o2.get('nickname', None) else index index = index + \ 1 if o.get('occupation', None) == o2.get( 'occupation', None) else index index = index + 1 if o.get('personal', None) == o2.get('personal', None) else index index = index + \ 10 if o.get('quotes', None) == o2.get('quotes', None) else index index = index + 1 if o.get('relation', None) == o2.get('relation', None) else index index = index + 1 if o.get('relatives', None) == o2.get('relatives', None) else index index = index + 1 if o.get('schools', None) == o2.get('schools', None) else index index = index + \ 1 if o.get('site', None) == o2.get('site', None) else index index = index + 40 if o.get('status', None) == o2.get( 'status', None) and o.get('status', None) != '' else index index = index + \ 1 if o.get('universities', None) == o2.get( 'universities', None) else index index = index + \ 1 if o.get('university', None) == o2.get( 'university', None) else index index = index + \ 1 if o.get('university_name', None) == o2.get( 'university_name', None) else index # 31 if index > 20: return compare_images(o['photo_max'], o2['photo_max']) return False fields = ' photo_id, sex, bdate, city, country, home_town, has_photo, photo_max, has_mobile, contacts, site, education, universities, schools, status, last_seen, followers_count, common_count, occupation, nickname, relatives, relation, personal, connections, exports, activities, interests, music, movies, tv, books, games, about, quotes, timezone, screen_name, maiden_name, crop_photo, career, military, blacklisted, blacklisted_by_me' current_user_params = {'user_ids': [user_id], 'fields': fields} current_user_response = vk_request( 'post', 'users.get', current_user_params, token, '5.131') current_user_obj = current_user_response['response'][0] search_params = {'q': current_user_obj['first_name'] + ' ' + current_user_obj['last_name'], 'fields': fields, 'sort': 0, 'count': 1000} search_response = vk_request( 'post', 'users.search', search_params, token, '5.131') search_list = search_response['response']['items'] result = [] count = search_response['response']['count'] i = 0 for item in search_list: i += 1 if compare(current_user_obj, item): result.append(item) if i % 10 == 0: print(count) job.progress = str(int(i) / int(count)) job.save() job.progress = '1' job.in_progress = False job.data = json.dumps(result) job.save()
def send_message(role, user_id, group_url, token, group_id): message = 'Здравствуйте, была созданна новая группа, в которой вам нужно получить управляющую должность ' + \ str(role) + '. Пожалуйста, вступите в группу по ссылке: ' + str(group_url) rand = random.randint(-32768, 32767) answer = vk_request('post', 'messages.send', { 'peer_id': int(user_id), 'message': message, 'random_id ': rand, 'group_id': int(group_id)}, token, '5.45')
def copy_group(id, post_token): def assign(dics, key, value): if value is None: return dics dics[key] = value return dics def send_message(role, user_id, group_url, token, group_id): message = 'Здравствуйте, была созданна новая группа, в которой вам нужно получить управляющую должность ' + \ str(role) + '. Пожалуйста, вступите в группу по ссылке: ' + str(group_url) rand = random.randint(-32768, 32767) answer = vk_request('post', 'messages.send', { 'peer_id': int(user_id), 'message': message, 'random_id ': rand, 'group_id': int(group_id)}, token, '5.45') def getAttachments(post): attachments = post['attachments'] final_attachments = '' if len(attachments) != 0: for item in attachments: type = item['type'] print(item) if type == 'link': link_url = item[type]['url'] # photo_id = item[type]['photo']['id'] # photo_owner = item[type]['photo']['owner_id'] # final_attachments += 'photo' + \ # str(photo_owner) + '_' + \ # str(photo_id) + ',' + str(link_url) final_attachments += link_url else: owner_id = str(item[type]['owner_id']) media_id = str(item[type]['id']) final_attachments += type+owner_id + '_' + media_id + ',' return final_attachments def handle_contacts(contacts, og_group_id, g_id, token, created_group, created_group_url): cont = [] for i in contacts: cont.append(i['user_id']) managers = vk_request('get', 'groups.getMembers', { 'group_id': og_group_id, 'filter': 'managers'}, token, '5.126') for m in managers['response']['items']: contact_flag = 1 if m['id'] in cont else 0 moderators_count = 0 if m['role'] != 'creator': new_future_moderator = FutureModerator( role=m['role'], is_contact=contact_flag, vk_id=m['id'], group_id=g_id) new_future_moderator.save() moderators_count += 1 # send_message(m['role'], m['id'], # created_group_url, message_token, g_id) # r = vk_request('get', 'groups.editManager', { # 'group_id': g_id, 'user_id': m['id'], 'role': m['role'], 'is_contact': contact_flag}, token, '5.126') created_group.number_of_moderators = moderators_count created_group.save() def handle_posts(og_group, new_group, token): posts = [] wall = vk_request('get', 'wall.get', { 'owner_id': og_group * -1, 'count': 100}, token, '5.126')['response']['items'] for post in reversed(wall): close_comments = post['comments']['can_post'] * -1 attachments = getAttachments(post) text = post['text'] rand = random.randint(-32768, 32767) props = { 'owner_id': "-" + str(new_group), 'from_group': 1, 'message': text, 'attachments': attachments, 'guid': rand, 'close_comments': close_comments, 'mute_notifications': 1 } posted_vk_id = vk_request( 'post', 'wall.post', props, token, '5.124') def handle_create(title, desc, g_type, public_cat, public_subcategory, subtype, token): created_group_info = vk_request('get', 'groups.create', { 'title': title, 'description': desc, 'type': 'public' if g_type == 'page' else g_type, 'public_category': public_cat, 'public_subcategory': public_subcategory, 'subtype': subtype }, token, '5.126') print(created_group_info) return created_group_info['response']['id'] def handle_edit(g_id, access, desc, website, subject, phone, public_cat, public_sub_cat, country, city, age_limits, addresses, token): settings = vk_request('get', 'groups.setSettings', { 'messages': 1, 'group_id': int(g_id)}, token, '5.126') props = {} assign(props, 'description', desc) assign(props, 'website', website) assign(props, 'group_id', g_id) assign(props, 'access', access) assign(props, 'subject', subject) assign(props, 'phone', phone) assign(props, 'public_category', public_cat) assign(props, 'public_subcategory', public_sub_cat) assign(props, 'country', country) assign(props, 'city', city) assign(props, 'age_limits', age_limits) assign(props, 'addresses', addresses) edit = vk_request('get', 'groups.edit', props, token, '5.126') return 1 def handle_photos(created_group_id, g_cover, g_photo, token): photo_url = vk_request('get', 'photos.getOwnerPhotoUploadServer', { 'owner_id': created_group_id * -1}, token, '5.126') photo_url = photo_url['response']['upload_url'] cover_url = vk_request('get', 'photos.getOwnerCoverPhotoUploadServer', { 'group_id': created_group_id, 'crop_y2': g_cover['images'][-1]['height'], 'crop_x2': g_cover['images'][-1]['width']}, token, '5.126') cover_url = cover_url['response']['upload_url'] urllib.request.urlretrieve(g_photo, "logo.png") photo_server = requests.post( photo_url, files={'photo': open("logo.png", 'rb')}).json() urllib.request.urlretrieve(g_cover['images'][-1]['url'], "cover.png") photo_cover = requests.post( cover_url, files={'photo': open("cover.png", 'rb')}).json() photo_answer = vk_request('post', 'photos.saveOwnerPhoto', { 'server': photo_server['server'], 'hash': photo_server['hash'], 'photo': photo_server['photo']}, token, '5.126') cover_answer = vk_request('post', 'photos.saveOwnerCoverPhoto', { 'hash': photo_cover['hash'], 'photo': photo_cover['photo']}, token, '5.126') return 1 def handle_address(og_group, new_group, token): addresses = [] r_addresses = vk_request('get', 'groups.getAddresses', { 'group_id': og_group}, token, '5.126') for a in r_addresses['response']['items']: a['group_id'] = new_group add_r = vk_request('get', 'groups.addAddress', a, token, '5.126') def handle_code(created_group, token): code = vk_request('get', 'groups.getCallbackConfirmationCode', { 'group_id': created_group.group_id}, token, '5.126')['response']['code'] # print(code) created_group.code = code created_group.save() def handle_callback_server(created_group, token): server_id = vk_request('get', 'groups.addCallbackServer', { 'group_id': created_group.group_id, 'url': 'https://vtarget-backend.herokuapp.com/bot-moderators', 'title': 'Managers'}, token, '5.126')['response']['server_id'] # print(server_id) d = vk_request('get', 'groups.setCallbackSettings', { 'group_id': created_group.group_id, 'server_id': server_id, 'group_join': 1}, token, '5.126') # print(d) # CODE ---------------------------------------------------------------------------- # # # CODE ---------------------------------------------------------------------------- group_id = id group = vk_request('get', 'groups.getById', { 'group_id': group_id, 'fields': 'activity,addresses,city,contacts,country,cover,crop_photo,screen_name,type'}, post_token, '5.126') print(group) group = group['response'][0] g_screen_name = group['screen_name'] group_id = group['id'] g_activity = group.get('activity', None) g_contacts = group.get('contacts', None) g_addresses = group.get('addresses', None) g_city = group.get('city', None) if g_city is not None: g_city = g_city['id'] g_country = group.get('country', None) if g_country is not None: g_country = g_country['id'] g_cover = group.get('cover', None) g_type = group.get('type', None) g_photo = group['photo_200'] current_setting = vk_request('get', 'groups.getSettings', { 'group_id': group_id}, post_token, '5.126') print(current_setting) current_setting = current_setting['response'] g_title = current_setting.get('title', None) g_website = current_setting.get('website', None) g_public_category = current_setting.get('public_category', None) g_description = current_setting.get('description', None) g_phone = current_setting.get('phone', None) g_public_subcategory = current_setting.get('public_subcategory', None) g_age_limits = current_setting.get('age_limits', None) # posts = [] # wall = vk_request('get', 'wall.get', { # 'owner_id': group_id * -1, 'count': 100}, post_token, '5.126')['response']['items'] # for post in wall: # close_comments = post['comments']['can_post'] * -1 # attachments = getAttachments(post) # text = post['text'] # posts.append({'text': text, 'attachments': attachments, # 'close_comments': close_comments}) created_group_id = handle_create( g_title, g_description, g_type, g_public_category, g_public_subcategory, 2, post_token) url_type = 'public' if g_type == 'page' else g_type created_group_url = 'https://vk.com/' + \ str(url_type) + str(created_group_id) created_group = CreatedGroup( group_id=created_group_id, number_of_moderators=0) subject = 8 # настраиваемое поле access = 0 # настраиваемое поле try: edit_result = handle_edit(created_group_id, access, g_description, g_website, subject, g_phone, g_public_category, g_public_subcategory, g_country, g_city, g_age_limits, group['addresses']['is_enabled'], post_token) except: pass try: photo_result = handle_photos( created_group_id, g_cover, g_photo, post_token) except: pass try: handle_address(group_id, created_group_id, post_token) except: pass try: handle_posts(group_id, created_group_id, post_token) except: pass try: handle_contacts(g_contacts, group_id, created_group_id, post_token, created_group, created_group_url) except: pass handle_code(created_group, post_token) handle_callback_server(created_group, post_token) return created_group_url
def handle_callback_server(created_group, token): server_id = vk_request('get', 'groups.addCallbackServer', { 'group_id': created_group.group_id, 'url': 'https://vtarget-backend.herokuapp.com/bot-moderators', 'title': 'Managers'}, token, '5.126')['response']['server_id'] # print(server_id) d = vk_request('get', 'groups.setCallbackSettings', { 'group_id': created_group.group_id, 'server_id': server_id, 'group_join': 1}, token, '5.126')
def handle_code(created_group, token): code = vk_request('get', 'groups.getCallbackConfirmationCode', { 'group_id': created_group.group_id}, token, '5.126')['response']['code'] # print(code) created_group.code = code created_group.save()
def get_app_info(id, token): return vk_request('get', 'apps.get', {'app_id': id}, token, '5.21')['response']