· 5 years ago · May 25, 2020, 01:02 PM
1import requests
2import json
3from time import sleep
4from threading import Thread
5import steampy
6from steampy.client import Asset
7from steampy.utils import GameOptions
8from steampy.client import SteamClient as sc
9import os
10
11game = GameOptions.CS
12
13api = '' # Market API
14apikey = '' # Steam api
15api_key = '' # Proxy store key
16percent = 0.97 # формат 0.n
17
18url = 'https://market.csgo.com/api/Trades/?key=' + api # <= don't change it!
19steamguard = 'new_mafile.maFile' # <= don't change it!
20i = 2 # <= don't change it!
21avg = 0 # <= don't change it!
22assetid = '' # <= don't change it!
23price2 = 0 # <= don't change it!
24
25
26def ChangeFile(fileName, Data):
27 with open(str(fileName), 'w') as file:
28 json.dump(Data, file, indent=4)
29 file.close()
30
31
32def offer(assetid, msg, trade_url):
33 if steam_client.is_session_alive():
34 my_items = steam_client.get_my_inventory(game)
35 items = iter(my_items.values())
36 for i in items:
37 if i['id'] == assetid:
38 item = Asset(i['id'], game)
39 return steam_client.make_offer_with_url([item], [], trade_url, msg, True)
40 else:
41 pass
42 else:
43 steam_login()
44 my_items = steam_client.get_my_inventory(game)
45 items = iter(my_items.values())
46 for i in items:
47 if i['id'] == assetid:
48 item = Asset(i['id'], game)
49 return steam_client.make_offer_with_url([item], [], trade_url, msg, True)
50 else:
51 pass
52
53
54def confirm(tradeid):
55 global assetid
56 try:
57 steam_client._confirm_transaction(tradeid)
58 except:
59 print("---------------------" + '\n' +
60 "Trade offer was confirmed!" + '\n'
61 + '---------------------')
62 userdata = json.load((open('data.json')))
63 userdata.update({str(assetid): 'used'})
64 ChangeFile('data.json', userdata)
65 assetid = ''
66
67
68def dataCheck(data):
69 if data == 'None' or None:
70 print('Не получилось создать трейд оффер')
71 pass
72 else:
73 tradeid = data['tradeofferid']
74 confirm(tradeid)
75
76
77def Trades():
78 global assetid
79 while i > 1:
80 try:
81 tradeOffer = requests.get('https://market.csgo.com/api/ItemRequest/in/1/?key=' + api).json()
82 print(tradeOffer)
83 if tradeOffer['success'] == True:
84 msg = tradeOffer['request']['tradeoffermessage']
85 trade_url = tradeOffer['request']['tradelink']
86 assetid = tradeOffer['request']['items'][0]['assetid']
87 userdata = json.load((open('data.json')))
88 result = userdata.get(str(assetid))
89 if result == None:
90 data = offer(assetid, msg, trade_url)
91 dataCheck(data)
92 else:
93 print('спим')
94 sleep(15)
95 pass
96 else:
97 print('nothing')
98 datajson = {}
99 ChangeFile('data.json', datajson)
100 sleep(30)
101 except:
102 sleep(10)
103 print('Ошибка 80 trades')
104 jsonstr = {}
105 ChangeFile('data.json', jsonstr)
106 assetid = ''
107 Trades()
108
109
110def updating():
111 i = 10
112 try:
113 while i > 1: # Обновление ивентаря и включение продаж каждые 3 минуты
114 settingSteamApi()
115 ping()
116 inventUpdate()
117 sleep(120)
118 except:
119 sleep(15)
120 pass
121
122
123def ping():
124 try:
125 status = requests.get('https://market.csgo.com/api/v2/ping?key=' + f'{api}')
126 status2 = status.json()
127 if status2['success'] == True:
128 pass
129 elif status2['success'] == False and status2['message'] == 'too early for pong':
130 pass
131 else:
132 pass
133 except:
134 sleep(5)
135 pass
136
137
138def inventUpdate():
139 try:
140 status = requests.get('https://market.csgo.com/api/v2/update-inventory/?key=' + f'{api}').json()
141 if status['success'] == True:
142 pass
143 elif status['success'] == False:
144 pass
145 except:
146 sleep(5)
147 pass
148
149
150def settingSteamApi():
151 try:
152 requests.get('https://market.csgo.com/api/SetSteamAPIKey/' + apikey + '/?key=' + api).json()
153 except:
154 sleep(5)
155 pass
156
157
158def calc():
159 global history, avg
160 try:
161 for x in history[:40]:
162 avg = avg + x[1]
163 avg = round(avg, 0)
164 return avg
165 except:
166 avg = 0
167 sleep(1)
168 calc()
169
170
171def setPrice_end(price, x, item_name):
172 global avg, price2
173 try:
174 requests.get('https://market.csgo.com/api/SetPrice/new_' + x['classid'] + '_' + x[
175 'instanceid'] + '/' + f'{price}' + '/?key=' + f'{api}').json()
176 print(f'{item_name}' + ' with price ' + f'{int(price) / 100}' + ' rub' + ' successfully was added on sale')
177 avg = 0
178 price2 = 0
179 except json.decoder.JSONDecodeError:
180 print('169 json')
181 pass
182
183
184def setprices(bestOffer_price, item_price, x, item_name):
185 try:
186 print('ITEM BEST OFFER IS 117= ' + str(bestOffer_price))
187 maxbest = int(item_price) * 1.1
188 minbest = int(item_price) * 0.9
189 if int(bestOffer_price) > 5000000:
190 setPrice_end(item_price, x, item_name)
191
192 elif int(maxbest) > int(bestOffer_price) > int(minbest):
193 setPrice_end(bestOffer_price, x, item_name)
194
195 elif int(maxbest) < int(bestOffer_price) > int(minbest):
196 setPrice_end(item_price, x, item_name)
197
198 elif int(maxbest) < int(bestOffer_price) < int(minbest):
199 setPrice_end(minbest, x, item_name)
200
201 elif int(maxbest) > int(bestOffer_price) < int(minbest):
202 setPrice_end(bestOffer_price, x, item_name)
203
204 else:
205 setPrice_end(price2, x, item_name)
206
207 except json.decoder.JSONDecodeError:
208 print('184 error json')
209 pass
210
211
212def best_offer(name):
213 global price2
214 try:
215 data = (requests.get(
216 'https://market.csgo.com/api/v2/search-list-items-by-hash-name-all?key=' + api + '&list_hash_name[]=' + name).json())
217 prices = data['data'][name]
218 best_price = data['data'][name][0]['price']
219 price2 = data['data'][name][2]['price']
220 print('now best: ' + str(best_price))
221 for price in prices:
222 offer = (price['price'])
223 if offer < best_price:
224 best_price = offer
225 print('best= ' + str(best_price))
226 return best_price
227 except TypeError:
228 print('207 error')
229 best_offer(name)
230
231
232def getBestPrice(items_sale):
233 global avg
234 for x in items_sale['items']:
235 try:
236 hashed_name = x['market_hash_name']
237 try:
238 global history
239 history = requests.get(
240 'https://market.csgo.com/api/v2/get-list-items-info?key=' + f'{api}' + '&list_hash_name[]=' + f'{hashed_name}').json()[
241 'data'][hashed_name]['history']
242 except:
243 print('222 error json')
244 getBestPrice(items_sale)
245 try:
246 item_name = x['market_hash_name']
247 item_price = (calc() / 40) * 100
248 item_price = int(round(item_price, 0))
249 print('ITEM AVG= ' + str(item_price))
250
251 best_price = best_offer(item_name)
252 setprices(best_price, item_price, x, item_name)
253
254 except json.decoder.JSONDecodeError:
255 print('224 error json')
256 avg = 0
257 sleep(1)
258 itemsOnSale()
259 except json.decoder.JSONDecodeError:
260 print('229 error json')
261 avg = 0
262 sleep(1)
263 itemsOnSale()
264
265
266def itemsOnSale():
267 global avg
268 try:
269 status = requests.get('https://market.csgo.com/api/v2/my-inventory/?key=' + f'{api}').json()['success']
270 if status == True:
271 items_sale = requests.get('https://market.csgo.com/api/v2/my-inventory/?key=' + f'{api}').json()
272 getBestPrice(items_sale)
273 else:
274 sleep(1)
275
276 except json.decoder.JSONDecodeError:
277 print('250 error json')
278 avg = 0
279 sleep(5)
280 itemsOnSale()
281
282
283def price_offers():
284 global item
285 try:
286 status = requests.get('https://market.csgo.com/api/GetMySellOffers/?key=' + f'{api}').json()['success']
287 if status == True:
288 sleep(1)
289 list_items = requests.get('https://market.csgo.com/api/GetMySellOffers/?key=' + f'{api}').json()['offers']
290 for x in list_items:
291 name = x['i_market_hash_name']
292 start_price = int(x['ui_price']) * 100
293 classid = x['i_classid']
294 instanceid = x['i_instanceid']
295 end_price = int(start_price * int(percent))
296 end_price = round(end_price, 1)
297 userData = json.load((open('position.json')))
298 userData["items"].append({'start_price': f'{start_price}',
299 'end_price': f'{end_price}',
300 'classid': f'{classid}',
301 'instanceid': f'{instanceid}',
302 'name': f'{name}'})
303
304 ChangeFile('position.json', userData)
305 sleep(5)
306 Thread(target=startDump).start()
307
308 else:
309 print('Sales is empty! Time to put up some items..')
310 inventUpdate()
311 sleep(60)
312 price_offers()
313 except:
314 print('Error with getting price offers! I will try again after 5 seconds')
315 sleep(1)
316 price_offers()
317
318
319def startDump():
320 print('Function "price dumping" was successfully turned on! log off')
321 while i > 1:
322 sleep(1)
323 try:
324 ds = json.load((open('position.json')))
325 output_data = [v for v in {inp['name']: inp for inp in ds['items']}.values()]
326 json_str = {"items": output_data}
327 ChangeFile('position.json', json_str)
328 sleep(5)
329 dataFor_dump = json.load((open('position.json')))['items']
330 for x in dataFor_dump:
331 try:
332 classid = x['classid']
333 instanceid = x['instanceid']
334 end_price = x['end_price']
335 start_price = round(int(x['start_price']) * 1.05, 1)
336 bestOffer = requests.get(
337 'https://market.csgo.com/api/BestSellOffer/' + f'{classid}' + '_' + f'{instanceid}' + '/?key=' + f'{api}').json()[
338 'best_offer']
339 if int(start_price) > int(bestOffer) > int(end_price):
340 price = int(bestOffer) - 1
341 requests.get(
342 'https://market.csgo.com/api/MassSetPrice/' + f'{classid}' + '_' + f'{instanceid}' + '/' + f'{price}' + '/?key=' + f'{api}').json()
343 else:
344 pass
345 except:
346 sleep(1)
347 pass
348 except:
349 sleep(5)
350 Thread(target=startDump).join()
351 price_offers()
352
353
354def sumItems():
355 try:
356 items = (requests.get('https://market.csgo.com/api/Trades/?key=' + f'{api}').json())
357 totalPrice = 0
358 for item in items:
359 price = item['ui_price']
360 totalPrice = int(totalPrice) + int(price)
361 balance = requests.get('https://market.csgo.com/api/GetMoney/?key=' + f'{api}').json()['money'] / 100
362 full = str(float(totalPrice * 0.9) + float(balance))
363 print('On sales: ' + str(round(totalPrice * 0.9)) + ' rub')
364 print('Balance: ' + str(round(balance, 1)) + ' rub')
365 return full
366 except:
367 sumItems()
368
369
370def steam_login():
371 global steam_client
372 try:
373 print('Logging to steam account..')
374 steam_client = sc(api)
375 steam_client._session.proxies = {'https': proxy}
376 steam_client.login(login, pswd, steamguard)
377 print('Successfully logged in!')
378 except requests.exceptions.ConnectionError:
379 print('Bad proxy')
380 except steampy.exceptions.InvalidCredentials:
381 sleep(3)
382 steam_login()
383
384
385def del_position():
386 jsonUpd = {"items": []}
387 ChangeFile('position.json', jsonUpd)
388
389
390def setNewMafile(mafileId64, mafilePathclear):
391 global login
392 Mafile = json.load((open(mafileId64)))
393 steamid = Mafile['Session'].get('SteamID')
394 shared_secret = Mafile.get('shared_secret')
395 identity_secret = Mafile.get('identity_secret')
396 login = Mafile.get('account_name')
397 new_mafile_path = 'new_mafile.maFile'
398 dump_newMafile(mafilePathclear, steamid, shared_secret, new_mafile_path, identity_secret)
399
400
401def dump_newMafile(mafilePathclear, steamid, shared_secret, new_mafile_path, identity_secret):
402 global pswd
403 dataPath = str(mafilePathclear) + str(login) + '.txt'
404 file = open(dataPath)
405 log_pass = file.readline()
406 password = str(log_pass).split(':', maxsplit=2)
407 password2 = str(password[2]).split('\n')
408 pswd = (password2[0])
409 new_mafile = {"steamid": str(steamid),
410 "shared_secret": str(shared_secret),
411 "identity_secret": str(identity_secret)}
412
413 ChangeFile(new_mafile_path, new_mafile)
414
415
416def new_mafile():
417 global pswd, login
418 mafilePath = (os.getcwd())
419 mafileId64 = (os.listdir(path=os.getcwd())[0]) # Получаем мафайл (он должен быть 1 в списке!)
420 mafilePathclear = str(mafilePath).split('maFiles', maxsplit=1)[0] # Получаем путь к папке с данными
421 setNewMafile(mafileId64, mafilePathclear)
422
423
424def getProxy():
425 global proxy
426 number_proxy = input('Введите номер прокси(коммент): ')
427 data = (requests.get('https://proxy-store.com/api/' + api_key + '/getproxy/comment').json())
428 ChangeFile('json.json', data)
429 for proxy in data['list']:
430 comment = data['list'][proxy]['comment']
431 if comment == number_proxy:
432 proxy = 'https://' + str(data['list'][proxy]['user']) + ':' + str(data['list'][proxy]['pass']) + '@' + str(
433 data['list'][proxy]['ip']) \
434 + ':' + str(data['list'][proxy]['port'])
435 print(proxy)
436
437
438def getMinPrice(items_sale):
439 global avg
440 for x in items_sale['items']:
441 try:
442 item_name = x['market_hash_name']
443 item_price = best_offer(item_name)
444 setPrice_end(item_price, x, item_name)
445
446 except json.decoder.JSONDecodeError:
447 print('448 error json')
448 avg = 0
449 sleep(1)
450 minimalPrice()
451
452
453def minimalPrice():
454 global avg
455 try:
456 status = requests.get('https://market.csgo.com/api/v2/my-inventory/?key=' + f'{api}').json()['success']
457 if status == True:
458 items_sale = requests.get('https://market.csgo.com/api/v2/my-inventory/?key=' + f'{api}').json()
459 getMinPrice(items_sale)
460 else:
461 sleep(1)
462
463 except json.decoder.JSONDecodeError:
464 print('250 error json')
465 avg = 0
466 sleep(5)
467 minimalPrice()
468
469
470getProxy()
471new_mafile()
472
473bot_action = input(
474 '"0" - Включить обновление' + '\n'
475 + '"1" - Выставить все на продажу, включить трейды' + '\n'
476 + '"2" - Выставить предметы по оптимальной цене' + '\n'
477 + '"3" - Включить автодамп и трейды' + '\n'
478 + '"4" - Аолучить баланс' + '\n'
479 + '"5" - Включить все' + '\n'
480 + '"6" - Выставить предметы по минимальной цене' + '\n'
481 + 'Write number: ')
482
483if bot_action == '0':
484 Thread(target=updating).start()
485
486if bot_action == '1':
487 steam_login()
488 del_position()
489 Thread(target=updating).start()
490 Thread(target=Trades).start()
491
492if bot_action == '2':
493 itemsOnSale()
494
495if bot_action == '3':
496 del_position()
497 steam_login()
498 Thread(target=Trades).start()
499 Thread(target=price_offers).start()
500 Thread(target=updating).start()
501
502if bot_action == '4':
503 print('All balance: ' + str(sumItems()) + ' rub')
504
505if bot_action == '5':
506 itemsOnSale()
507 print('All balance: ' + str(sumItems()) + ' rub')
508 del_position()
509 steam_login()
510 Thread(target=Trades).start()
511 Thread(target=price_offers).start()
512 Thread(target=updating).start()
513
514if bot_action == '6':
515 minimalPrice()