Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- import json
- import urllib
- import random
- import mimetypes
- from hashlib import md5
- import time
- # https://oauth.vk.com/authorize?client_id=5019010&display=page&redirect_uri=https://oauth.vk.com/blank.html&scope=groups,offline,photos,audio,video,wall&response_type=token&v=5.35
- access_token = "f2c976ab21588ba826350d04abf3736cf97c5778afab0ac5341c5072d77551074eb2f9e51dd95089e8c88"
- tags = "#tag #tag #tag"
- # main_group_id = "-56116141"
- main_group_id = "-99485452"
- post_ids = [x.strip() for x in open('post_ids.txt', 'r') if x.strip()]
- grab_group_ids = ["-41670861", "-55664616", "-79965314", "-58966378"]
- captcha_file = None
- captcha_request_file = None
- class ApiError(Exception):
- def __init__(self, value):
- self.value = value
- def __str__(self):
- return repr(self.value)
- def api(method_name, args, method="POST", timeout=10):
- args = dict(args)
- link = "https://api.vk.com/method/" + request.quote(method_name)
- if access_token and 'access_token' not in args:
- args['access_token'] = access_token
- if 'v' not in args:
- args['v'] = '5.34'
- params = ''
- for key, data in args.items():
- if isinstance(data, (list, tuple)):
- data = ','.join(str(x) for x in data)
- else:
- data = str(data)
- params += request.quote(key) + '=' + request.quote(data) + '&'
- params = params[:-1]
- if method == "GET":
- link += "?" + params
- if method == "POST":
- data = params.encode('utf-8')
- else:
- data = None
- answer = ""
- try:
- answer = json.loads(urlopen(link, data, timeout).read().decode('utf-8'))
- except KeyboardInterrupt:
- raise
- except SystemExit:
- raise
- except:
- raise ApiError
- if "error" in answer:
- raise ApiError(answer.get('error'))
- return answer
- def get_photo_url(photo, max_level='photo_2560', levels=('photo_2560', 'photo_1280', 'photo_807', 'photo_604', 'photo_130', 'photo_75')):
- try: pos = levels.index(max_level)
- except: return
- for x in levels[pos:]:
- url = photo.get(x)
- if url: return url
- def encode_multipart_formdata(fields, files):
- boundary = b'----------' + md5((str(int(time.time())) + str(random.randrange(1000))).encode('utf-8')).hexdigest().encode('utf-8')
- L = []
- for (key, value) in fields:
- key = key.encode('utf-8')
- if not isinstance(value, bytes):
- raise ValueError('Value should be bytes, not %s' % type(value))
- L.append(b'--' + boundary)
- L.append(('Content-Disposition: form-data; name="%s"' % key.decode('utf-8')).encode('utf-8'))
- L.append(b'')
- L.append(value)
- for (key, filename, value) in files:
- key = key.encode('utf-8')
- filename = filename.encode('utf-8')
- if not isinstance(value, bytes):
- raise ValueError('Value should be bytes, not %s' % type(value))
- L.append(b'--' + boundary)
- L.append((
- 'Content-Disposition: form-data; name="%s"; filename="%s"' % (key.decode('utf-8'), filename.decode('utf-8'))
- ).encode('utf-8'))
- content_type = str(mimetypes.guess_type(filename.decode('utf-8'))[0] or 'application/octet-stream')
- L.append(('Content-Type: %s' % content_type).encode('utf-8'))
- L.append(b'')
- L.append(value)
- L.append(b'--' + boundary + b'--')
- L.append(b'')
- body = b'\r\n'.join(L)
- content_type = 'multipart/form-data; boundary=%s' % boundary.decode('utf-8')
- return content_type, body
- def post_request(link, fields, files=(), timeout=10):
- # fields - [('поле1', b'значение'), ('поле2', b'значение')]
- # files - [('поле1', 'имя файла', b'значение'), ('поле2', 'имя файла', b'значение')]
- req = Request(link)
- content_type, body = encode_multipart_formdata(fields, files)
- req.data = body
- req.add_header('Content-Type', content_type)
- return urlopen(req, timeout=timeout)
- def get_grab_group_last_post(group_number):
- last_post = api("wall.get", {'owner_id': grab_group_ids[group_number], "count": "2"})
- if "error" in last_post:
- return last_post
- elif last_post['response']['items'][0].get('is_pinned'):
- return last_post['response']['items'][1]
- else:
- return last_post['response']['items'][0]
- def post_new_post(post):
- attachments = [""]
- for a in post["attachments"]:
- if a["type"] == "photo":
- try: photo = urlopen(get_photo_url(a["photo"]), timeout=5).read()
- except IOError: continue
- photo_server_upload = api("photos.getWallUploadServer", {"group_id": main_group_id[1:]})
- photo_server_upload = photo_server_upload['response']
- try: photo_upload = post_request(photo_server_upload["upload_url"], [], [('photo', 'photo.jpg', photo)]).read()
- except IOError: continue
- photo_upload = json.loads(photo_upload.decode('utf-8'))
- params = {"group_id": main_group_id[1:] }
- params.update(photo_upload)
- saved_photo = api("photos.saveWallPhoto", params)
- saved_photo = saved_photo['response'][0]
- attachments.append('photo' + str(saved_photo['owner_id']) + '_' + str(saved_photo['id']))
- if not attachments:
- post_ids_file = open('post_ids.txt', 'a')
- post_ids_file.write(str(grab_group_ids[i]) + "_" + str(post["id"]) + "\n")
- return False
- final_post = api("wall.post", {"owner_id": main_group_id, "attachments": ",".join(attachments), "from_group": "1"})
- return True
- while True:
- try:
- for i in range(len(grab_group_ids)):
- post_ids = [x.strip() for x in open('post_ids.txt', 'r') if x.strip()]
- last_post = get_grab_group_last_post(i)
- if not "copy_history" in last_post:
- print("Пост является правильным. Начинаем проверку на совпадения.")
- if str(grab_group_ids[i]) + "_" + str(last_post["id"]) in post_ids:
- print("Этот пост уже был запосчен.")
- time.sleep(0.4)
- continue
- if post_new_post(last_post):
- post_ids_file = open('post_ids.txt', 'a')
- post_ids_file.write(str(grab_group_ids[i]) + "_" + str(last_post["id"]) + "\n")
- post_ids_file.close()
- print("Пост запосчен!")
- time.sleep(0.4)
- else:
- print("Ошибка! post_new_post() вернула значение, эквивалентное False.")
- time.sleep(0.4)
- else:
- print("Пост оказался репостом.")
- continue
- except ApiError as exc:
- print("Ошибка! ВК глюк.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement