Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import requests
- from time import sleep
- from random import randrange
- import argparse
- import getpass
- from PIL import Image
- import numpy as np
- import math
- palette = ([
- (255, 255, 255),
- (228, 228, 228),
- (136, 136, 136),
- (34, 34, 34),
- (255, 167, 209),
- (229, 0, 0),
- (229, 149, 0),
- (160, 106, 66),
- (229, 217, 0),
- (148, 224, 68),
- (2, 190, 1),
- (0, 211, 221),
- (0, 131, 199),
- (0, 0, 234),
- (207, 110, 228),
- (130, 0, 128)
- ])
- def main():
- parser = argparse.ArgumentParser(description='Draw an image on Reddit\'s Place canvas.')
- parser.add_argument('--user', help='Reddit username')
- parser.add_argument('--passwd', help='Reddit password')
- parser.add_argument('--image', help='Image file to draw')
- parser.add_argument('-x', help='X position of the upper left corner of where to draw', type=int)
- parser.add_argument('-y', help='Y position of the upper left corner of where to draw', type=int)
- args = parser.parse_args()
- if args.user is None:
- args.user = input("Enter Reddit Username: ")
- if args.passwd is None:
- args.passwd = getpass.getpass()
- place = Place(args.user, args.passwd, greedy=True)
- image = Image.open(args.image)
- try:
- while True:
- draw_image(place, image, (args.x, args.y), palette)
- except KeyboardInterrupt:
- print("Exiting")
- def draw_image(place, image, position, palette):
- """Draws an image on the Place canvas.
- place: Place object
- image: image to draw
- position: upper left corner of where to draw on the canvas
- palette: list of tuples of allowed colors
- """
- pixels = image_to_index_array(image, palette)
- x = randrange(0, image.width)
- y = randrange(0, image.height)
- place_x = position[0] + x
- place_y = position[1] + y
- place_pixel = place.get(place_x, place_y)
- if "color" in place_pixel and place_pixel["color"] != pixels[x, y]:
- print(f"Draw color {pixels[x, y]} at position ({place_x}, {place_y})")
- place.draw(place_x, place_y, pixels[x, y])
- def get_closest_color_index(color, color_list):
- """"Finds the index in the color list that closest matches the color"""
- def dist(a, b):
- """Euclidian distance in RGB space. Could probably be better."""
- return math.sqrt((a[0] - b[0]) ** 2 +
- (a[1] - b[1]) ** 2 +
- (a[2] - b[2]) ** 2)
- closest_color = min(color_list, key=lambda x: dist(x, color))
- return color_list.index(closest_color)
- def image_to_index_array(image, palette):
- original = image.convert("RGB")
- out = np.zeros(original.size, dtype=np.int8)
- for y in range(original.height):
- for x in range(original.width):
- original_clr = original.getpixel((x, y))
- new_clr_num = get_closest_color_index(original_clr, palette)
- out[x, y] = new_clr_num
- return out
- # https://www.reddit.com/r/Python/comments/62ph3u/python_rplace_module/
- class Place(object):
- def __init__(self, user, passwd, greedy=False):
- """
- user: reddit username
- pass: reddit password
- greedy: keep trying to perform request
- """
- self.session = requests.session()
- self.session.headers.update({"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 OPR/43.0.2442.1144"})
- self.greedy = greedy
- payload= {'op': 'login',
- 'user': user,
- 'passwd': passwd}
- self.session.post("https://www.reddit.com/post/login", data=payload)
- sleep(1)
- self.last = self.session.get("https://reddit.com/api/me.json")
- self.modhash = self.last.json()["data"]["modhash"]
- self.session.headers.update({"x-modhash": self.modhash})
- def _get(self, x, y):
- payload = {"x": x,
- "y": y}
- return self.session.get("https://www.reddit.com/api/place/pixel.json", params=payload)
- def get(self, x=0, y=0):
- """get the color information at a given pixel
- x: x-coordinates
- y: y-coordinates
- """
- self.last = self._get(x,y)
- if self.greedy:
- while self.last.status_code == 429:
- sleep(1)
- self.last = self._get(x,y)
- return self.last.json()
- def _draw(self, x=0, y=0, color=0):
- payload = {"x": x,
- "y": y,
- "color": color}
- return self.session.post("https://www.reddit.com/api/place/draw.json", data=payload)
- def draw(self, x=0, y=0, color=0):
- """draw a color at given coordinates
- x: x-coordinates
- y: y-coordinates
- color: color to draw at coordinates
- """
- self.last = self._draw(x,y, color)
- if self.greedy:
- while self.last.status_code == 429:
- json = self.last.json()
- if "wait_seconds" in json:
- wait=json["wait_seconds"]
- print("Waiting: {}s".format(wait))
- sleep(wait)
- else:
- sleep(1)
- self.last = self._draw(x,y, color)
- return self.last.json()
- if __name__ == '__main__':
- main()
Add Comment
Please, Sign In to add comment