CatmanIX

r/place bot

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