forked from placeDE/Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
placedebot.user.js
356 lines (319 loc) · 9.51 KB
/
placedebot.user.js
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
// ==UserScript==
// @name PlaceDE Bot
// @namespace https://github.com/PlaceDE/Bot
// @version 17
// @description /r/place bot
// @author NoahvdAa, reckter, SgtChrome, nama17
// @match https://www.reddit.com/r/place/*
// @match https://new.reddit.com/r/place/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=reddit.com
// @require https://cdn.jsdelivr.net/npm/toastify-js
// @resource TOASTIFY_CSS https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css
// @updateURL https://github.com/PlaceDE/Bot/raw/main/placedebot.user.js
// @downloadURL https://github.com/PlaceDE/Bot/raw/main/placedebot.user.js
// @grant GM_getResourceText
// @grant GM_addStyle
// ==/UserScript==
// Sorry voor de rommelige code, haast en clean gaatn iet altijd samen ;)
var placeOrders = [];
var accessToken;
var canvas = document.createElement('canvas');
const VERSION = 17
var UPDATE_PENDING = false;
const COLOR_MAPPINGS = {
'#6D001A': 0,
'#BE0039': 1,
'#FF4500': 2,
'#FFA800': 3,
'#FFD635': 4,
'#FFF8B8': 5,
'#00A368': 6,
'#00CC78': 7,
'#7EED56': 8,
'#00756F': 9,
'#009EAA': 10,
'#00CCC0': 11,
'#2450A4': 12,
'#3690EA': 13,
'#51E9F4': 14,
'#493AC1': 15,
'#6A5CFF': 16,
'#94B3FF': 17,
'#811E9F': 18,
'#B44AC0': 19,
'#E4ABFF': 20,
'#DE107F': 21,
'#FF3881': 22,
'#FF99AA': 23,
'#6D482F': 24,
'#9C6926': 25,
'#FFB470': 26,
'#000000': 27,
'#515252': 28,
'#898D90': 29,
'#D4D7D9': 30,
'#FFFFFF': 31
};
(async function () {
GM_addStyle(GM_getResourceText('TOASTIFY_CSS'));
canvas.width = 2000;
canvas.height = 2000;
canvas = document.body.appendChild(canvas);
Toastify({
text: 'Abfrage des Zugriffstokens...',
duration: 10000
}).showToast();
accessToken = await getAccessToken();
Toastify({
text: 'Zugriffstoken eingesammelt!',
duration: 10000
}).showToast();
setInterval(updateOrders, 5 * 60 * 1000); // Update orders elke vijf minuten.
await updateOrders();
attemptPlace();
})();
function shuffleWeighted(array) {
for (const item of array) {
item.rndPriority = Math.round(placeOrders.priorities[item.priority] * Math.random());
}
array.sort((a, b) => b.rndPriority - a.rndPriority);
}
function getPixelList() {
const structures = [];
for (const structureName in placeOrders.structures) {
shuffleWeighted(placeOrders.structures[structureName].pixels);
structures.push(placeOrders.structures[structureName]);
}
shuffleWeighted(structures);
return structures.map(structure => structure.pixels).flat();
}
async function attemptPlace() {
var ctx;
try {
ctx = await getCanvasFromUrl(await getCurrentImageUrl('0'), canvas, 0, 0);
ctx = await getCanvasFromUrl(await getCurrentImageUrl('1'), canvas, 1000, 0)
ctx = await getCanvasFromUrl(await getCurrentImageUrl('2'), canvas, 0, 1000)
ctx = await getCanvasFromUrl(await getCurrentImageUrl('3'), canvas, 1000, 1000)
} catch (e) {
console.warn('Fehler beim Abrufen der Zeichenfläche:', e);
Toastify({
text: 'Fehler beim Abrufen der Zeichenfläche. Neuer Versuch in 15 Sekunden...',
duration: 10000
}).showToast();
setTimeout(attemptPlace, 15000); // probeer opnieuw in 15sec.
return;
}
const pixelList = getPixelList();
for (const order of pixelList) {
const x = order.x;
const y = order.y;
const colorId = COLOR_MAPPINGS[order.color] ?? order.color;
const rgbaAtLocation = ctx.getImageData(x, y, 1, 1).data;
const hex = rgbToHex(rgbaAtLocation[0], rgbaAtLocation[1], rgbaAtLocation[2]);
const currentColorId = COLOR_MAPPINGS[hex];
// Pixel already set
if (currentColorId == colorId) continue;
Toastify({
text: `Pixel wird gesetzt auf ${x}, ${y}...`,
duration: 10000
}).showToast();
const time = new Date().getTime();
let nextAvailablePixelTimestamp = await place(x, y, colorId) ?? new Date(time + 1000 * 60 * 5 + 1000 * 15)
// Sanity check timestamp
if (nextAvailablePixelTimestamp < time || nextAvailablePixelTimestamp > time + 1000 * 60 * 5 + 1000 * 15) {
nextAvailablePixelTimestamp = time + 1000 * 60 * 5 + 1000 * 15;
}
// Add a few random seconds to the next available pixel timestamp
const waitFor = nextAvailablePixelTimestamp - time + (Math.random() * 1000 * 15);
const minutes = Math.floor(waitFor / (1000 * 60))
const seconds = Math.floor((waitFor / 1000) % 60)
Toastify({
text: `Warten auf Abkühlzeit ${minutes}:${seconds} bis ${new Date(nextAvailablePixelTimestamp).toLocaleTimeString()}`,
duration: waitFor
}).showToast();
setTimeout(attemptPlace, waitFor);
return;
}
setTimeout(attemptPlace, 30000); // probeer opnieuw in 30sec.
}
function updateOrders() {
fetch(`https://placede.github.io/pixel/pixel.json`, {cache: "no-store"}).then(async (response) => {
if (!response.ok) return console.warn('Bestellungen können nicht geladen werden!');
const data = await response.json();
if (JSON.stringify(data) !== JSON.stringify(placeOrders)) {
const structureCount = Object.keys(data.structures).length;
let pixelCount = 0;
for (const structureName in data.structures) {
pixelCount += data.structures[structureName].pixels.length;
}
Toastify({
text: `Neue Strukturen geladen. Bilder: ${structureCount} - Pixels: ${pixelCount}.`,
duration: 10000
}).showToast();
}
if (data?.version !== VERSION && !UPDATE_PENDING) {
UPDATE_PENDING = true
Toastify({
text: `NEUE VERSION VERFÜGBAR! Aktualisiere hier https://github.com/placeDE/Bot/raw/main/placedebot.user.js`,
duration: -1,
onClick: () => {
// Tapermonkey captures this and opens a new tab
window.location = 'https://github.com/placeDE/Bot/raw/main/placedebot.user.js'
}
}).showToast();
}
placeOrders = data;
}).catch((e) => console.warn('Bestellungen können nicht geladen werden!', e));
}
function getCanvasId(x,y) {
return (x > 1000) + (y > 1000)*2
}
/**
* Places a pixel on the canvas, returns the "nextAvailablePixelTimestamp", if succesfull
* @param x
* @param y
* @param color
* @returns {Promise<number>}
*/
async function place(x, y, color) {
const response = await fetch('https://gql-realtime-2.reddit.com/query', {
method: 'POST',
body: JSON.stringify({
'operationName': 'setPixel',
'variables': {
'input': {
'actionName': 'r/replace:set_pixel',
'PixelMessageData': {
'coordinate': {
'x': x % 1000,
'y': y % 1000
},
'colorIndex': color,
'canvasIndex': getCanvasId(x,y)
}
}
},
'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
}
}
`
}),
headers: {
'origin': 'https://hot-potato.reddit.com',
'referer': 'https://hot-potato.reddit.com/',
'apollographql-client-name': 'mona-lisa',
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
}
});
const data = await response.json()
if (data.errors != undefined) {
Toastify({
text: 'Fehler beim Platzieren des Pixels, warte auf Abkühlzeit...',
duration: 10000
}).showToast();
return data.errors[0].extensions?.nextAvailablePixelTs
}
return data?.data?.act?.data?.[0]?.data?.nextAvailablePixelTimestamp
}
async function getAccessToken() {
const usingOldReddit = window.location.href.includes('new.reddit.com');
const url = usingOldReddit ? 'https://new.reddit.com/r/place/' : 'https://www.reddit.com/r/place/';
const response = await fetch(url);
const responseText = await response.text();
// TODO: ew
return responseText.split('\"accessToken\":\"')[1].split('"')[0];
}
async function getCurrentImageUrl(id = '0') {
return new Promise((resolve, reject) => {
const ws = new WebSocket('wss://gql-realtime-2.reddit.com/query', 'graphql-ws');
ws.onopen = () => {
ws.send(JSON.stringify({
'type': 'connection_init',
'payload': {
'Authorization': `Bearer ${accessToken}`
}
}));
ws.send(JSON.stringify({
'id': '1',
'type': 'start',
'payload': {
'variables': {
'input': {
'channel': {
'teamOwner': 'AFD2022',
'category': 'CANVAS',
'tag': id
}
}
},
'extensions': {},
'operationName': 'replace',
'query': `subscription replace($input: SubscribeInput!) {
subscribe(input: $input) {
id
... on BasicMessage {
data {
__typename
... on FullFrameMessageData {
__typename
name
timestamp
}
}
__typename
}
__typename
}
}
`
}
}));
};
ws.onmessage = (message) => {
const { data } = message;
const parsed = JSON.parse(data);
// TODO: ew
if (!parsed.payload || !parsed.payload.data || !parsed.payload.data.subscribe || !parsed.payload.data.subscribe.data) return;
ws.close();
resolve(parsed.payload.data.subscribe.data.name + `?noCache=${Date.now() * Math.random()}`);
}
ws.onerror = reject;
});
}
function getCanvasFromUrl(url, canvas, x = 0, y = 0) {
return new Promise((resolve, reject) => {
var ctx = canvas.getContext('2d');
var img = new Image();
img.crossOrigin = 'anonymous';
img.onload = () => {
ctx.drawImage(img, x, y);
resolve(ctx);
};
img.onerror = reject;
img.src = url;
});
}
function rgbToHex(r, g, b) {
return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1).toUpperCase();
}