Guest User

Reddit Placer

a guest
Apr 2nd, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.63 KB | None | 0 0
  1. import math
  2. import sys
  3. import time
  4. import random
  5.  
  6. import requests
  7. from PIL import Image
  8. from requests.adapters import HTTPAdapter
  9.  
  10. img = Image.open(sys.argv[1])
  11. origin = (int(sys.argv[2]), int(sys.argv[3]))
  12. username = sys.argv[4]
  13. password = sys.argv[5]
  14. percent = 0
  15.  
  16. def find_palette(point):
  17.     rgb_code_dictionary = {
  18.         (255, 255, 255): 0,
  19.         (228, 228, 228): 1,
  20.         (136, 136, 136): 2,
  21.         (34, 34, 34): 3,
  22.         (255, 167, 209): 4,
  23.         (229, 0, 0): 5,
  24.         (229, 149, 0): 6,
  25.         (160, 106, 66): 7,
  26.         (229, 217, 0): 8,
  27.         (148, 224, 68): 9,
  28.         (2, 190, 1): 10,
  29.         (0, 211, 211): 11,
  30.         (0, 131, 199): 12,
  31.         (0, 0, 234): 13,
  32.         (207, 110, 228): 14,
  33.         (130, 0, 128): 15
  34.     }
  35.  
  36.     def distance(c1, c2):
  37.         (r1, g1, b1) = c1
  38.         (r2, g2, b2) = c2
  39.         return math.sqrt((r1 - r2) ** 2 + (g1 - g2) ** 2 + (b1 - b2) ** 2)
  40.  
  41.     colors = list(rgb_code_dictionary.keys())
  42.     closest_colors = sorted(colors, key=lambda color: distance(color, point))
  43.     closest_color = closest_colors[0]
  44.     code = rgb_code_dictionary[closest_color]
  45.     return code
  46.  
  47.  
  48. s = requests.Session()
  49. s.mount('https://www.reddit.com', HTTPAdapter(max_retries=5))
  50. s.headers["User-Agent"] = "PlacePlacer"
  51. r = s.post("https://www.reddit.com/api/login/{}".format(username),
  52.            data={"user": username, "passwd": password, "api_type": "json"})
  53. s.headers['x-modhash'] = r.json()["json"]["data"]["modhash"]
  54.  
  55.  
  56. def place_pixel(ax, ay, new_color):
  57.     message = "Probing absolute pixel {},{}".format(ax, ay)
  58.  
  59.     while True:
  60.         r = s.get("http://reddit.com/api/place/pixel.json?x={}&y={}".format(ax, ay), timeout=5)
  61.         if r.status_code == 200:
  62.             data = r.json()
  63.             break
  64.         else:
  65.             print("ERROR: ", r, r.text)
  66.         time.sleep(5)
  67.  
  68.     old_color = data["color"] if "color" in data else 0
  69.     if old_color == new_color:
  70.         print("{}: skipping, color #{} set by {}".format(message, new_color, data[
  71.             "user_name"] if "user_name" in data else "<nobody>"))
  72.         time.sleep(.25)
  73.     else:
  74.         print("{}: Placing color #{}".format(message, new_color, ax, ay))
  75.         r = s.post("https://www.reddit.com/api/place/draw.json",
  76.                    data={"x": str(ax), "y": str(ay), "color": str(new_color)})
  77.  
  78.         try:
  79.             secs = float(r.json()["wait_seconds"])
  80.             if "error" not in r.json():
  81.                 message = "Placed color, waiting {} seconds. {}% complete."
  82.             else:
  83.                 message = "Cooldown already active - waiting {} seconds. {}% complete."
  84.             err = False
  85.         except Exception as e:
  86.             err = True
  87.             message = "Got exception. Waiting {} seconds. {}% complete"
  88.             secs = 30
  89.  
  90.         waitTime = int(secs) + 2
  91.         while(waitTime > 0):
  92.             m = message.format(waitTime, percent)
  93.             time.sleep(1)
  94.             waitTime -= 1
  95.             if waitTime > 0:
  96.                 print(m, end="              \r")
  97.             else:
  98.                 print(m)
  99.  
  100.         if err or "error" in r.json():
  101.             place_pixel(ax, ay, new_color)
  102.  
  103. # From: http://stackoverflow.com/questions/27337784/how-do-i-shuffle-a-multidimensional-list-in-python
  104. def shuffle2d(arr2d, rand=random):
  105.     """Shuffes entries of 2-d array arr2d, preserving shape."""
  106.     reshape = []
  107.     data = []
  108.     iend = 0
  109.     for row in arr2d:
  110.         data.extend(row)
  111.         istart, iend = iend, iend+len(row)
  112.         reshape.append((istart, iend))
  113.     rand.shuffle(data)
  114.     return [data[istart:iend] for (istart,iend) in reshape]
  115.  
  116. while True:
  117.     print("starting image placement for img height: {}, width: {}".format(img.height, img.width))
  118.     arr2d = shuffle2d([[[i,j] for i in range(img.width)] for j in range(img.height)])
  119.     total = img.width * img.height
  120.     checked = 0
  121.     for y in range(img.width ):
  122.         for x in range(img.height ):
  123.             xx = arr2d[x][y]
  124.             pixel = img.getpixel((xx[0], xx[1]))
  125.  
  126.             if len(pixel) < 4 or pixel[3] > 0:
  127.                 pal = find_palette((pixel[0], pixel[1], pixel[2]))
  128.  
  129.                 ax = xx[0] + origin[0]
  130.                 ay = xx[1] + origin[1]
  131.  
  132.                 place_pixel(ax, ay, pal)
  133.                 checked += 1
  134.                 percent = round((checked/total) * 100, 2)
  135.     message = "All pixels placed, sleeping {}s..."
  136.     waitTime = 10
  137.     while(waitTime > 0):
  138.         m = message.format(waitTime)
  139.         time.sleep(1)
  140.         waitTime -= 1
  141.         if waitTime > 0:
  142.             print(m, end="              \r")
  143.         else:
  144.             print(m)
Add Comment
Please, Sign In to add comment