forked from CloudburstSys/PonyPixel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
executable file
·427 lines (348 loc) · 13.9 KB
/
bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
#!/usr/bin/env python3
import math
from enum import Enum
import time
import json
import os
import sys
import requests
from bs4 import BeautifulSoup
import urllib
from io import BytesIO
from websocket import create_connection
from websocket import WebSocketConnectionClosedException
from PIL import ImageColor
from PIL import Image
import random
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("username", nargs="?")
parser.add_argument("password", nargs="?")
args = parser.parse_args()
if args.username is None or args.password is None:
import botConfig
else:
botConfig = args
SET_PIXEL_QUERY = \
"""mutation setPixel($input: ActInput!) {
act(input: $input) {
data {
... on BasicMessage {
id
data {
... on GetUserCooldownResponseMessageData {
nextAvailablePixelTimestamp
__typename
}
... on SetPixelResponseMessageData {
timestamp
__typename
}
__typename
}
__typename
}
__typename
}
__typename
}
}
"""
def rgb_to_hex(rgb):
return ("#%02x%02x%02x%02x" % rgb).upper()
# function to find the closest rgb color from palette to a target rgb color
def closest_color(target_rgb, rgb_colors_array_in):
r, g, b, a = target_rgb
color_diffs = []
for color in rgb_colors_array_in:
cr, cg, cb, ca = color
color_diff = math.sqrt((r - cr)**2 + (g - cg)**2 + (b - cb)**2 + (a - ca)**2)
color_diffs.append((color_diff, color))
return min(color_diffs)[1]
rgb_colors_array = []
class Color(Enum):
BLACK = 27
WHITE = 31
class Placer:
REDDIT_URL = "https://www.reddit.com"
LOGIN_URL = REDDIT_URL + "/login"
INITIAL_HEADERS = {
"accept":
"*/*",
"accept-encoding":
"gzip, deflate, br",
"accept-language":
"en-US,en;q=0.9",
"content-type":
"application/x-www-form-urlencoded",
"origin":
REDDIT_URL,
"sec-ch-ua":
'" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
"sec-ch-ua-mobile":
"?0",
"sec-ch-ua-platform":
'"Windows"',
"sec-fetch-dest":
"empty",
"sec-fetch-mode":
"cors",
"sec-fetch-site":
"same-origin",
"user-agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36"
}
def __init__(self):
self.client = requests.session()
self.client.headers.update(self.INITIAL_HEADERS)
self.token = None
def login(self, username: str, password: str):
# get the csrf token
r = self.client.get(self.LOGIN_URL)
time.sleep(1)
login_get_soup = BeautifulSoup(r.content, "html.parser")
csrf_token = login_get_soup.find("input",
{"name": "csrf_token"})["value"]
# authenticate
r = self.client.post(self.LOGIN_URL,
data={
"username": username,
"password": password,
"dest": self.REDDIT_URL,
"csrf_token": csrf_token
})
time.sleep(1)
print(r.content)
assert r.status_code == 200
# get the new access token
r = self.client.get(self.REDDIT_URL)
data_str = BeautifulSoup(r.content, features="html5lib").find(
"script", {
"id": "data"
}).contents[0][len("window.__r = "):-1]
data = json.loads(data_str)
self.token = data["user"]["session"]["accessToken"]
def get_board(self, canvas):
print("Getting board")
ws = create_connection("wss://gql-realtime-2.reddit.com/query", origin="https://hot-potato.reddit.com")
ws.send(
json.dumps({
"type": "connection_init",
"payload": {
"Authorization": "Bearer " + self.token
},
}))
ws.recv()
ws.send(
json.dumps({
"id": "1",
"type": "start",
"payload": {
"variables": {
"input": {
"channel": {
"teamOwner": "AFD2022",
"category": "CONFIG",
}
}
},
"extensions": {},
"operationName":
"configuration",
"query":
"subscription configuration($input: SubscribeInput!) {\n subscribe(input: $input) {\n id\n ... on BasicMessage {\n data {\n __typename\n ... on ConfigurationMessageData {\n colorPalette {\n colors {\n hex\n index\n __typename\n }\n __typename\n }\n canvasConfigurations {\n index\n dx\n dy\n __typename\n }\n canvasWidth\n canvasHeight\n __typename\n }\n }\n __typename\n }\n __typename\n }\n}\n",
},
}))
ws.recv()
ws.send(
json.dumps({
"id": "2",
"type": "start",
"payload": {
"variables": {
"input": {
"channel": {
"teamOwner": "AFD2022",
"category": "CANVAS",
"tag": str(canvas),
}
}
},
"extensions": {},
"operationName":
"replace",
"query":
"subscription replace($input: SubscribeInput!) {\n subscribe(input: $input) {\n id\n ... on BasicMessage {\n data {\n __typename\n ... on FullFrameMessageData {\n __typename\n name\n timestamp\n }\n ... on DiffFrameMessageData {\n __typename\n name\n currentTimestamp\n previousTimestamp\n }\n }\n __typename\n }\n __typename\n }\n}\n",
},
}))
file = ""
while True:
temp = json.loads(ws.recv())
if temp["type"] == "data":
msg = temp["payload"]["data"]["subscribe"]
if msg["data"]["__typename"] == "FullFrameMessageData":
file = msg["data"]["name"]
break
ws.close()
boardimg = BytesIO(requests.get(file, stream=True).content)
print("Got image:", file)
return boardimg
def place_tile(self, canvas: int, x: int, y: int, color: int):
headers = self.INITIAL_HEADERS.copy()
headers.update({
"apollographql-client-name": "mona-lisa",
"apollographql-client-version": "0.0.1",
"content-type": "application/json",
"origin": "https://hot-potato.reddit.com",
"referer": "https://hot-potato.reddit.com/",
"sec-fetch-site": "same-site",
"authorization": "Bearer " + self.token
})
r = requests.post("https://gql-realtime-2.reddit.com/query",
json={
"operationName": "setPixel",
"query": SET_PIXEL_QUERY,
"variables": {
"input": {
"PixelMessageData": {
"canvasIndex": canvas,
"colorIndex": color,
"coordinate": {
"x": x,
"y": y
}
},
"actionName": "r/replace:set_pixel"
}
}
},
headers=headers)
if r.json()["data"] == None:
try:
waitTime = math.floor(
r.json()["errors"][0]["extensions"]["nextAvailablePixelTs"])
print("placing failed: rate limited")
except:
waitTime = 10000
else:
waitTime = math.floor(r.json()["data"]["act"]["data"][0]["data"]
["nextAvailablePixelTimestamp"])
print("placing succeeded")
return waitTime / 1000
color_map = {
"#BE0039FF": 1,
"#FF4500FF": 2, # bright red
"#FFA800FF": 3, # orange
"#FFD635FF": 4, # yellow
"#00A368FF": 6, # darker green
"#00CC78FF": 7,
"#7EED56FF": 8, # lighter green
"#00756FFF": 9,
"#009EAAFF": 10,
"#2450A4FF": 12, # darkest blue
"#3690EAFF": 13, # medium normal blue
"#51E9F4FF": 14, # cyan
"#493AC1FF": 15,
"#6A5CFFFF": 16,
"#811E9FFF": 18, # darkest purple
"#B44AC0FF": 19, # normal purple
"#FF3881FF": 22,
"#FF99AAFF": 23, # pink
"#6D482FFF": 24,
"#9C6926FF": 25, # brown
"#000000FF": 27, # black
"#898D90FF": 29, # grey
"#D4D7D9FF": 30, # light grey
"#FFFFFFFF": 31, # white
}
def init_rgb_colors_array():
global rgb_colors_array
# generate array of available rgb colors we can use
for color_hex, color_index in color_map.items():
rgb_array = ImageColor.getcolor(color_hex, "RGBA")
rgb_colors_array.append(rgb_array)
print("available colors for palette (rgba): ", rgb_colors_array)
init_rgb_colors_array()
place = Placer()
version = "Derpy0.4.2"
def trigger():
# Behold, the dirtiest code I ever wrote
# This hacky hack serves as a bridge for urllib in Python 2 and Python 3
try:
urllib.urlopen
except:
urllib.urlopen = urllib.request.urlopen
def getData():
im = urllib.urlopen('https://raw.githubusercontent.com/Cantersoft/PonyPixel/master/template.png').read()
img = Image.open(BytesIO(im)).convert("RGBA").load()
new_origin = urllib.urlopen('https://raw.githubusercontent.com/Cantersoft/PonyPixel/master/coordinates.txt?t={}'.format(time.time())).read().decode("utf-8").replace("\n", "").split(',')
origin = (int(new_origin[0]), int(new_origin[1]))
size = (int(new_origin[2]), int(new_origin[3]))
canvas = int(new_origin[4])
#ver = urllib.urlopen('https://raw.githubusercontent.com/CloudburstSys/place.conep.one/master/version.txt').read().decode("utf-8").replace("\n", "")
#print("LOCAL VERSION: {}".format(version))
#print("UPSTREAM VERSION: {}".format(ver))
#if(ver != version):
# print("VERSION OUT OF DATE!")
# print("PLEASE RUN 'git pull https://github.com/CloudburstSys/PonyPixel.git' TO UPDATE")
# return (None, (None, None), (None, None), None)
return (img, origin, size, canvas)
(img, origin, size, canvas) = getData()
if(img == None):
exit()
return
(ox, oy) = origin
(sx, sy) = size
pix2 = Image.open(place.get_board(canvas)).convert("RGBA").load()
rows = []
thisRow = []
totalPixels = sx*sy
correctPixels = 0
wrongPixels = 0
wrongPixelsArray = []
for i in range(sx*sy):
x = (i % sx) + ox
y = math.floor(i / sx) + oy
(red, green, blue, alpha) = img[x-ox, y-oy]
if(color_map[rgb_to_hex(closest_color(pix2[x, y], rgb_colors_array))] == color_map[rgb_to_hex(closest_color(img[x-ox, y-oy],rgb_colors_array))]):
# Great! They're equal!
correctPixels += 1
elif(alpha == 0):
# Blank pixel. we ignore it
totalPixels = totalPixels - 1
else:
#print("Pixel at ({},{}) damaged: Expected: {}, got {}".format(x,y, color_text_map[color_map[rgb_to_hex(closest_color(img[x-ox, y-oy],rgb_colors_array))]], color_text_map[color_map[rgb_to_hex(closest_color(pix2[x, y], rgb_colors_array))]]))
wrongPixels += 1
wrongPixelsArray.append((x,y,rgb_to_hex(closest_color(img[x-ox, y-oy],rgb_colors_array))))
print("{}% correct ({} out of {}), {} wrong pixels".format(math.floor((correctPixels/totalPixels)*100),correctPixels,totalPixels,wrongPixels))
if(len(wrongPixelsArray) == 0):
print("nothing to do!")
return time.time() + random.randint(5,30)
else:
(x,y,expected) = random.choice(wrongPixelsArray)
print("Fixing pixel at ({},{}) on canvas id {}... Replacing with {}".format(x,y,canvas,expected))
timestampOfSafePlace = place.place_tile(int(canvas),x,y,color_map[expected]) + random.randint(5,30)
print("Done. Can next place at {} seconds from now".format(timestampOfSafePlace - time.time()))
return timestampOfSafePlace
timestampOfPlaceAttempt = 0
place.login(botConfig.username, botConfig.password)
while True:
if timestampOfPlaceAttempt > time.time():
time.sleep(5)
continue
try:
timestampOfPlaceAttempt = trigger()
if((timestampOfPlaceAttempt - time.time()) > 86400):
print(" ")
print(" ")
print("-------------------------------")
print("BOT BANNED FROM R/PLACE")
print("Please generate a new account and rerun.")
quit()
except WebSocketConnectionClosedException:
print("WebSocket connection refused. Auth issue. Reload.")
os.execv(sys.argv[0], sys.argv)
exit()
except:
print("????????")
time.sleep(5)