Advertisement
MrDavidBrony

Sunny Pony | pony_factory 1.0

Aug 7th, 2015
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.02 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3.  
  4. import json
  5. import urllib
  6. import random
  7. import mimetypes
  8. from hashlib import md5
  9. import time
  10.  
  11. # 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
  12.  
  13. access_token = "f2c976ab21588ba826350d04abf3736cf97c5778afab0ac5341c5072d77551074eb2f9e51dd95089e8c88"
  14. tags = "#tag #tag #tag"
  15. # main_group_id = "-56116141"
  16. main_group_id = "-99485452"
  17. post_ids = [x.strip() for x in open('post_ids.txt', 'r') if x.strip()]
  18. grab_group_ids = ["-41670861", "-55664616", "-79965314", "-58966378"]
  19. captcha_file = None
  20. captcha_request_file = None
  21.  
  22. class ApiError(Exception):
  23.     def __init__(self, value):
  24.         self.value = value
  25.     def __str__(self):
  26.         return repr(self.value)
  27.  
  28. def api(method_name, args, method="POST", timeout=10):
  29.     args = dict(args)
  30.     link = "https://api.vk.com/method/" + request.quote(method_name)
  31.     if access_token and 'access_token' not in args:
  32.         args['access_token'] = access_token
  33.     if 'v' not in args:
  34.         args['v'] = '5.34'
  35.  
  36.     params = ''
  37.  
  38.     for key, data in args.items():
  39.         if isinstance(data, (list, tuple)):
  40.             data = ','.join(str(x) for x in data)
  41.         else:
  42.             data = str(data)
  43.         params += request.quote(key) + '=' + request.quote(data) + '&'
  44.     params = params[:-1]
  45.  
  46.     if method == "GET":
  47.         link += "?" + params
  48.  
  49.     if method == "POST":
  50.         data = params.encode('utf-8')
  51.     else:
  52.         data = None
  53.  
  54.     answer = ""
  55.  
  56.     try:
  57.         answer = json.loads(urlopen(link, data, timeout).read().decode('utf-8'))
  58.     except KeyboardInterrupt:
  59.         raise
  60.     except SystemExit:
  61.         raise
  62.     except:
  63.         raise ApiError
  64.     if "error" in answer:
  65.         raise ApiError(answer.get('error'))
  66.  
  67.         return answer
  68.  
  69. def get_photo_url(photo, max_level='photo_2560', levels=('photo_2560', 'photo_1280', 'photo_807', 'photo_604', 'photo_130', 'photo_75')):
  70.     try: pos = levels.index(max_level)
  71.     except: return
  72.    
  73.     for x in levels[pos:]:
  74.         url = photo.get(x)
  75.         if url: return url
  76.  
  77. def encode_multipart_formdata(fields, files):
  78.     boundary = b'----------' + md5((str(int(time.time())) + str(random.randrange(1000))).encode('utf-8')).hexdigest().encode('utf-8')
  79.     L = []
  80.  
  81.     for (key, value) in fields:
  82.         key = key.encode('utf-8')
  83.         if not isinstance(value, bytes):
  84.             raise ValueError('Value should be bytes, not %s' % type(value))
  85.         L.append(b'--' + boundary)
  86.         L.append(('Content-Disposition: form-data; name="%s"' % key.decode('utf-8')).encode('utf-8'))
  87.         L.append(b'')
  88.         L.append(value)
  89.  
  90.     for (key, filename, value) in files:
  91.         key = key.encode('utf-8')
  92.         filename = filename.encode('utf-8')
  93.         if not isinstance(value, bytes):
  94.             raise ValueError('Value should be bytes, not %s' % type(value))
  95.         L.append(b'--' + boundary)
  96.         L.append((
  97.             'Content-Disposition: form-data; name="%s"; filename="%s"' % (key.decode('utf-8'), filename.decode('utf-8'))
  98.         ).encode('utf-8'))
  99.         content_type = str(mimetypes.guess_type(filename.decode('utf-8'))[0] or 'application/octet-stream')
  100.         L.append(('Content-Type: %s' % content_type).encode('utf-8'))
  101.         L.append(b'')
  102.         L.append(value)
  103.  
  104.     L.append(b'--' + boundary + b'--')
  105.     L.append(b'')
  106.     body = b'\r\n'.join(L)
  107.     content_type = 'multipart/form-data; boundary=%s' % boundary.decode('utf-8')
  108.     return content_type, body
  109.  
  110.  
  111. def post_request(link, fields, files=(), timeout=10):
  112.     # fields - [('поле1', b'значение'), ('поле2', b'значение')]
  113.     # files - [('поле1', 'имя файла', b'значение'), ('поле2', 'имя файла', b'значение')]
  114.     req = Request(link)
  115.     content_type, body = encode_multipart_formdata(fields, files)
  116.     req.data = body
  117.     req.add_header('Content-Type', content_type)
  118.     return urlopen(req, timeout=timeout)
  119.  
  120. def get_grab_group_last_post(group_number):
  121.     last_post = api("wall.get", {'owner_id': grab_group_ids[group_number], "count": "2"})
  122.     if "error" in last_post:
  123.         return last_post
  124.     elif last_post['response']['items'][0].get('is_pinned'):
  125.         return last_post['response']['items'][1]
  126.     else:
  127.         return last_post['response']['items'][0]
  128.  
  129. def post_new_post(post):
  130.     attachments = [""]
  131.     for a in post["attachments"]:
  132.         if a["type"] == "photo":
  133.             try: photo = urlopen(get_photo_url(a["photo"]), timeout=5).read()
  134.             except IOError: continue
  135.             photo_server_upload = api("photos.getWallUploadServer", {"group_id": main_group_id[1:]})
  136.             photo_server_upload = photo_server_upload['response']
  137.             try: photo_upload = post_request(photo_server_upload["upload_url"], [], [('photo', 'photo.jpg', photo)]).read()
  138.             except IOError: continue
  139.             photo_upload = json.loads(photo_upload.decode('utf-8'))
  140.             params = {"group_id": main_group_id[1:] }
  141.             params.update(photo_upload)
  142.             saved_photo = api("photos.saveWallPhoto", params)
  143.             saved_photo = saved_photo['response'][0]
  144.             attachments.append('photo' + str(saved_photo['owner_id']) + '_' + str(saved_photo['id']))
  145.     if not attachments:
  146.         post_ids_file = open('post_ids.txt', 'a')
  147.         post_ids_file.write(str(grab_group_ids[i]) + "_" + str(post["id"]) + "\n")
  148.         return False
  149.     final_post = api("wall.post", {"owner_id": main_group_id, "attachments": ",".join(attachments), "from_group": "1"})
  150.     return True
  151.  
  152. while True:
  153.     try:
  154.         for i in range(len(grab_group_ids)):
  155.             post_ids = [x.strip() for x in open('post_ids.txt', 'r') if x.strip()]
  156.             last_post = get_grab_group_last_post(i)
  157.             if not "copy_history" in last_post:
  158.                 print("Пост является правильным. Начинаем проверку на совпадения.")            
  159.                 if str(grab_group_ids[i]) + "_" + str(last_post["id"]) in post_ids:
  160.                     print("Этот пост уже был запосчен.")
  161.                     time.sleep(0.4)
  162.                     continue
  163.  
  164.                 if post_new_post(last_post):
  165.                     post_ids_file = open('post_ids.txt', 'a')
  166.                     post_ids_file.write(str(grab_group_ids[i]) + "_" + str(last_post["id"]) + "\n")
  167.                     post_ids_file.close()
  168.                     print("Пост запосчен!")
  169.                     time.sleep(0.4)
  170.                 else:
  171.                     print("Ошибка! post_new_post() вернула значение, эквивалентное False.")
  172.                     time.sleep(0.4)
  173.  
  174.  
  175.             else:
  176.                 print("Пост оказался репостом.")
  177.                 continue
  178.  
  179.     except ApiError as exc:
  180.         print("Ошибка! ВК глюк.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement