This repository has been archived by the owner on Mar 31, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
automaton.py
438 lines (287 loc) · 11 KB
/
automaton.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
428
429
430
431
432
433
434
435
436
437
438
import os.path
import sys
import enum
import json
import time
import random
import getpass
import logging
import threading
logging.basicConfig(format='[%(asctime)s] %(name)s: %(levelname)s: %(message)s', level=logging.INFO)
try:
import requests
except ImportError:
logging.error("Package `requests` is required.")
sys.exit(1)
class TaskType(enum.Enum):
BUY = 1
CHAIN = 2
class Task:
def __init__(self, type, *args):
self.type = type
self.args = args
class SlavesGame:
def __init__(self, login=None, password=None, token=None):
self.GAME_SERVER_URL = "https://pixel.w84.vkforms.ru/HappySanta/slaves/1.0.0"
if login is None and token is None:
raise Exception()
self.access_token = self.auth(login, password) if token is None else token
self.application_url, self.authorization_data = self.get_auth_data()
self.mobile_iframe_url = f"{self.application_url}?{self.authorization_data}"
self.application_url = self.application_url[:-11]
self.headers = {
"Authorization": f"Bearer {self.authorization_data}",
"User-Agent": "Mozilla/5.0 (Linux; arm_64; Android 10; MIX 2S) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Mobile Safari/537.36",
"Referer": self.mobile_iframe_url,
"Origin": self.application_url,
}
def auth(self, login, password):
url = f"https://oauth.vk.com/token?grant_type=password&client_id=2274003&client_secret=hHbZxrka2uZ6jB1inYsH&username={login}&password={password}"
response = requests.get(url).json()
return response["access_token"]
def get_auth_data(self):
url = f"https://api.vk.com/method/execute.resolveScreenName?access_token={self.access_token}&v=5.55&screen_name=app7794757_522020267&owner_id=-176897109&func_v=3"
response = requests.get(url).json()
return response["response"]["object"]["mobile_iframe_url"].split("?")
def get(self, data):
url = f"{self.GAME_SERVER_URL}/{data}"
response = requests.get(url, headers=self.headers).json()
return response
def post(self, method, data={}):
url = f"{self.GAME_SERVER_URL}/{method}"
response = requests.post(url, json=data, headers=self.headers).json()
return response
def start(self):
return self.get("start")
def users(self, ids):
return self.post("user", {"ids": ids})
def top_users(self):
return self.get("topUsers")
def buy_slave(self, id):
return self.post("buySlave", {"slave_id": id})
def set_job(self, id, job):
return self.post("jobSlave", {"slave_id": id, "name": job})
def user_info(self, id):
return self.get(f"user?id={id}")
def buy_fetter(self, id):
return self.post("buyFetter", {"slave_id": id})
def sell_slave(self, id):
return self.post("saleSlave", {"slave_id": id})
class Automaton:
def __init__(self, credentials):
logging.info("Creating a new Game instance.")
if type(credentials) is str:
self.game = SlavesGame(token=credentials)
else:
self.game = SlavesGame(login=credentials[0], password=credentials[1])
logging.info("Game instance created.")
self.ids = []
self.balance = []
self.my_id = 0
self.tasks = []
self.busy = threading.Event()
self.interval = 30
self.cooldown = 1.5
self.attempts = 3
self.max_ids = 25000
self.job = "Ave SPAM!"
if os.path.isfile("./config.json"):
logging.info("Found `config.json` file. Loading settings...")
try:
with open("./config.json", "r") as config_file:
config = json.load(config_file)
self.interval = int(config["interval"])
self.cooldown = float(config["cooldown"])
self.attempts = int(config["attempts"])
self.max_ids = int(config["max_ids"])
self.job = str(config["job"])
logging.info("Loaded settings from `config.json`!")
except:
logging.error("Can't load `config.json`. Reverting to default settings!")
@property
def is_busy(self):
return self.busy.is_set()
def get_friends(self, id):
ids = []
offset = 0
while offset < self.max_ids:
response = requests.get(f"https://api.vk.com/method/friends.get?user_id={id}&offset={offset if offset != 0 else 1}&order=random&access_token={self.game.access_token}&v=5.130").json()
if "error" in response:
logging.error(response["error"]["error_msg"])
break
items = response["response"]["items"]
ids.extend(items)
if len(items) < 5000:
break
offset += 5000
offset = 0
while offset < self.max_ids:
response = requests.get(f"https://api.vk.com/method/users.getFollowers?user_id={id}&offset={offset if offset != 0 else 1}&count=1000&access_token={self.game.access_token}&v=5.130").json()
if "error" in response:
logging.error(response["error"]["error_msg"])
break
items = response["response"]["items"]
ids.extend(items)
if len(items) < 1000:
break
offset += 1000
return ids
def fetch_ids(self):
logging.info("Fetching some ids...")
ids = self.get_friends(self.my_id)
self.ids.extend(ids)
for id in ids:
if id == self.my_id:
continue
if len(self.ids) >= self.max_ids:
break
new_ids = self.get_friends(id)
self.ids.extend(new_ids)
logging.info(f"{len(self.ids)} (max. {self.max_ids}) id(s) fetched!")
logging.info(f"Fetched {len(self.ids)} id(s).")
def task_generator(self):
logging.info("Starting task generator!")
while True:
if self.is_busy:
logging.info(f"Main thread is busy, so task generator is sleeping for {self.interval} second(s)...")
time.sleep(self.interval)
continue
logging.info("Updating game statistics...")
data = self.game.start()
balance = data["me"]["balance"]
my_slaves = data["slaves"]
logging.info(f"Balance: {balance}.")
logging.info(f"Slaves count: {len(my_slaves)}.")
logging.info("Searching for slaves which should be chained again...")
count = 0
total_price = 0
for slave in sorted(filter(lambda slave: slave["fetter_to"] == 0 and slave["master_id"] == self.my_id, my_slaves), key=lambda slave: slave["fetter_price"]):
if total_price >= balance:
break
if slave["fetter_price"] < balance:
fetter_price = slave["fetter_price"]
task = Task(TaskType.CHAIN, slave["id"], fetter_price)
self.tasks.append(task)
total_price += fetter_price
count += 1
logging.info(f"Found {count} slave(s).")
logging.info("Searching for slaves to purchase...")
try:
ids = random.sample(self.ids, 100)
except ValueError:
ids = self.ids
logging.warning("Count of users is below 100.")
users = self.game.users(ids)["users"]
logging.info(f"Fetched {len(users)} user(s).")
count = 0
total_price = 0
for slave in sorted(filter(lambda slave: slave["price"] + slave["fetter_price"] < balance and slave["master_id"] != self.my_id, users), key=lambda slave: slave["price"] + slave["fetter_price"]):
if total_price >= balance:
break
if slave["price"] + slave["fetter_price"] < balance:
slave_price = slave["price"] + slave["fetter_price"]
task = Task(TaskType.BUY, slave["id"], slave_price)
self.tasks.append(task)
total_price += slave_price
count += 1
logging.info(f"Found {count} user(s).")
random.shuffle(self.tasks)
logging.info(f"Task generator is sleeping for {self.interval} second(s)...")
time.sleep(self.interval)
def chain(self, id):
logging.info(f"Chaining id{id}!")
attempts = 0
while attempts < self.attempts:
if "error" in self.game.buy_fetter(id):
logging.error(f"Can't chain id{id}! :(")
logging.info(f"Attempt {attempts+1} / {self.attempts}!")
attempts += 1
if attempts == self.attempts:
logging.error("Maximum count of attempts reached.")
return
time.sleep(self.cooldown)
continue
break
logging.info(f"Chained id{id}!")
time.sleep(self.cooldown)
def set_job(self, id, job):
logging.info(f"Setting job for id{id} to `{job}`!")
attempts = 0
while attempts < self.attempts:
if "error" in self.game.set_job(id, job):
logging.error(f"Can't set job for id{id}! :(")
logging.info(f"Attempt {attempts+1} / {self.attempts}!")
attempts += 1
if attempts == self.attempts:
logging.error("Maximum count of attempts reached.")
return
time.sleep(self.cooldown)
continue
break
logging.info(f"Job was set for id{id}!")
time.sleep(self.cooldown)
def buy(self, id):
logging.info(f"Buying id{id}!")
attempts = 0
while attempts < self.attempts:
if "error" in self.game.buy_slave(id):
logging.error(f"Can't buy id{id}! :(")
logging.info(f"Attempt {attempts+1} / {self.attempts}!")
attempts += 1
if attempts == self.attempts:
logging.error("Maximum count of attempts reached.")
return
time.sleep(self.cooldown)
continue
break
logging.info(f"Bought id{id}!")
time.sleep(self.cooldown)
def start(self):
logging.info("Starting!")
logging.info("Fetching my id...")
response = requests.get(f"https://api.vk.com/method/users.get?access_token={self.game.access_token}&v=5.130").json()
self.my_id = response["response"][0]["id"]
logging.info(f"My id: {self.my_id}.")
self.fetch_ids()
task_generator = threading.Thread(target=self.task_generator)
task_generator.daemon = True
task_generator.start()
while True:
if len(self.tasks) < 1:
continue
task = self.tasks.pop()
logging.info(f"There are/is {len(self.tasks)} task(s) pending.")
self.busy.set()
if task.type == TaskType.CHAIN:
self.chain(task.args[0])
elif task.type == TaskType.BUY:
id = task.args[0]
self.buy(id)
self.set_job(id, self.job)
self.chain(id)
self.busy.clear()
print("Automaton | made by @txlyre, www: txlyre.website")
print("GitHub: github.com/txlyre/automaton\n\n")
logging.info("Authorization!")
if os.path.isfile("./.token"):
logging.info("Reading credentials from `.token` file.")
with open("./.token", "r") as token_file:
credentials = token_file.read()
else:
logging.info("No `.token` file found. Give your credentials.")
login = input("login: ")
password = getpass.getpass("password: ")
credentials = (login, password)
try:
automaton = Automaton(credentials)
except:
logging.error("Failed to perform authorization.")
sys.exit(1)
logging.info("Saving token to `.token` file...")
with open("./.token", "w") as token_file:
token_file.write(automaton.game.access_token)
try:
automaton.start()
except KeyboardInterrupt:
logging.info("Interrupted by user.")
sys.exit(0)