· 5 years ago · Jun 01, 2020, 12:16 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 elif tradeOffer['success'] == False:
97 error = tradeOffer['error']
98 if error == 'Error creating request: Failed to load your inventory. Please refresh it':
99 print('Ошибка обновления инвенторя! Обновляю...')
100 inventUpdate()
101 else:
102 pass
103 else:
104 print('nothing')
105 datajson = {}
106 ChangeFile('data.json', datajson)
107 sleep(30)
108 except:
109 sleep(10)
110 print('Ошибка 80 trades')
111 jsonstr = {}
112 ChangeFile('data.json', jsonstr)
113 assetid = ''
114 Trades()
115
116
117def updating():
118 i = 10
119 try:
120 while i > 1: # Обновление ивентаря и включение продаж каждые 2 минуты
121 settingSteamApi()
122 ping()
123 inventUpdate()
124 sleep(120)
125 except:
126 sleep(15)
127 pass
128
129
130def ping():
131 try:
132 requests.get('https://market.csgo.com/api/v2/ping?key=' + f'{api}')
133 except:
134 sleep(5)
135 pass
136
137
138def inventUpdate():
139 try:
140 requests.get('https://market.csgo.com/api/v2/update-inventory/?key=' + f'{api}').json()
141 except:
142 sleep(5)
143 pass
144
145
146def settingSteamApi():
147 try:
148 requests.get('https://market.csgo.com/api/SetSteamAPIKey/' + apikey + '/?key=' + api).json()
149 except:
150 sleep(5)
151 pass
152
153
154def calc():
155 global history, avg
156 try:
157 for x in history[:40]:
158 avg = avg + x[1]
159 avg = round(avg, 0)
160 return avg
161 except:
162 avg = 0
163 sleep(1)
164 calc()
165
166
167def setPrice_end(price, x, item_name):
168 global avg, price2
169 try:
170 requests.get('https://market.csgo.com/api/SetPrice/new_' + x['classid'] + '_' + x[
171 'instanceid'] + '/' + f'{price}' + '/?key=' + f'{api}').json()
172 print(f'{item_name}' + ' with price ' + f'{int(price) / 100}' + ' rub' + ' successfully was added on sale')
173 avg = 0
174 price2 = 0
175 except json.decoder.JSONDecodeError:
176 print('169 json')
177 pass
178
179
180def setprices(bestOffer_price, item_price, x, item_name):
181 try:
182 print('ITEM BEST OFFER IS 117= ' + str(bestOffer_price))
183 maxbest = int(item_price) * 1.1
184 minbest = int(item_price) * 0.9
185 if int(bestOffer_price) > 5000000:
186 setPrice_end(item_price, x, item_name)
187
188 elif int(maxbest) > int(bestOffer_price) > int(minbest):
189 setPrice_end(bestOffer_price, x, item_name)
190
191 elif int(maxbest) < int(bestOffer_price) > int(minbest):
192 setPrice_end(item_price, x, item_name)
193
194 elif int(maxbest) < int(bestOffer_price) < int(minbest):
195 setPrice_end(minbest, x, item_name)
196
197 elif int(maxbest) > int(bestOffer_price) < int(minbest):
198 setPrice_end(bestOffer_price, x, item_name)
199
200 else:
201 setPrice_end(price2, x, item_name)
202
203 except json.decoder.JSONDecodeError:
204 print('184 error json')
205 pass
206
207
208def best_offer(name):
209 global price2
210 try:
211 data = (requests.get(
212 'https://market.csgo.com/api/v2/search-list-items-by-hash-name-all?key=' + api + '&list_hash_name[]=' + name).json())
213 prices = data['data'][name]
214 best_price = data['data'][name][0]['price']
215 price2 = data['data'][name][2]['price']
216 print('now best: ' + str(best_price))
217 for price in prices:
218 offer = (price['price'])
219 if offer < best_price:
220 best_price = offer
221 print('best= ' + str(best_price))
222 return best_price
223 except TypeError:
224 print('207 error')
225 best_offer(name)
226
227
228def getBestPrice(items_sale):
229 global avg
230 for x in items_sale['items']:
231 try:
232 hashed_name = x['market_hash_name']
233 try:
234 global history
235 history = requests.get(
236 'https://market.csgo.com/api/v2/get-list-items-info?key=' + f'{api}' + '&list_hash_name[]=' + f'{hashed_name}').json()[
237 'data'][hashed_name]['history']
238 except:
239 print('222 error json')
240 getBestPrice(items_sale)
241 try:
242 item_name = x['market_hash_name']
243 item_price = (calc() / 40) * 100
244 item_price = int(round(item_price, 0))
245 print('ITEM AVG= ' + str(item_price))
246
247 best_price = best_offer(item_name)
248 setprices(best_price, item_price, x, item_name)
249
250 except json.decoder.JSONDecodeError:
251 print('224 error json')
252 avg = 0
253 sleep(1)
254 itemsOnSale()
255 except json.decoder.JSONDecodeError:
256 print('229 error json')
257 avg = 0
258 sleep(1)
259 itemsOnSale()
260
261
262def itemsOnSale():
263 global avg
264 try:
265 status = requests.get('https://market.csgo.com/api/v2/my-inventory/?key=' + f'{api}').json()['success']
266 if status == True:
267 items_sale = requests.get('https://market.csgo.com/api/v2/my-inventory/?key=' + f'{api}').json()
268 getBestPrice(items_sale)
269 else:
270 sleep(1)
271
272 except json.decoder.JSONDecodeError:
273 print('250 error json')
274 avg = 0
275 sleep(5)
276 itemsOnSale()
277
278
279def price_offers():
280 global item
281 try:
282 MySellOffers = requests.get('https://market.csgo.com/api/GetMySellOffers/?key=' + f'{api}').json()
283 if MySellOffers['success'] == True:
284 list_items = MySellOffers['offers']
285 for x in list_items:
286 name = x['i_market_hash_name']
287 start_price = int(x['ui_price']) * 100
288 classid = x['i_classid']
289 instanceid = x['i_instanceid']
290 end_price = int(start_price * 0.97)
291 end_price = round(end_price, 1)
292 userData = json.load((open('position.json')))
293 userData["items"].append({'start_price': f'{start_price}',
294 'end_price': f'{end_price}',
295 'classid': f'{classid}',
296 'instanceid': f'{instanceid}',
297 'name': f'{name}'})
298
299 ChangeFile('position.json', userData)
300 sleep(1)
301 startDump()
302
303 else:
304 print('Sales is empty! Time to put up some items..')
305 inventUpdate()
306 sleep(60)
307 price_offers()
308 except:
309 print('Error with getting price offers! I will try again after 5 seconds')
310 sleep(1)
311 price_offers()
312
313
314def startDump():
315 print('Function "price dumping" was successfully turned on! log off')
316 while i > 1:
317 sleep(1)
318 try:
319 ds = json.load((open('position.json')))
320 output_data = [v for v in {inp['name']: inp for inp in ds['items']}.values()]
321 json_str = {"items": output_data}
322 ChangeFile('position.json', json_str)
323 sleep(5)
324 dataFor_dump = json.load((open('position.json')))['items']
325 for x in dataFor_dump:
326 try:
327 classid = x['classid']
328 instanceid = x['instanceid']
329 end_price = x['end_price']
330 start_price = round(int(x['start_price']) * 1.05, 1)
331 bestOffer = requests.get(
332 'https://market.csgo.com/api/BestSellOffer/' + f'{classid}' + '_' + f'{instanceid}' + '/?key=' + f'{api}').json()[
333 'best_offer']
334 if int(start_price) > int(bestOffer) > int(end_price):
335 price = int(bestOffer) - 1
336 requests.get(
337 'https://market.csgo.com/api/MassSetPrice/' + f'{classid}' + '_' + f'{instanceid}' + '/' + f'{price}' + '/?key=' + f'{api}').json()
338 else:
339 pass
340 except:
341 sleep(1)
342 pass
343 except:
344 sleep(1)
345 startDump()
346
347
348def sumItems():
349 try:
350 items = (requests.get('https://market.csgo.com/api/Trades/?key=' + f'{api}').json())
351 totalPrice = 0
352 for item in items:
353 price = item['ui_price']
354 totalPrice = int(totalPrice) + int(price)
355 balance = requests.get('https://market.csgo.com/api/GetMoney/?key=' + f'{api}').json()['money'] / 100
356 full = str(float(totalPrice * 0.9) + float(balance))
357 print('On sales: ' + str(round(totalPrice * 0.9)) + ' rub')
358 print('Balance: ' + str(round(balance, 1)) + ' rub')
359 return full
360 except:
361 sumItems()
362
363
364def steam_login():
365 global steam_client
366 try:
367 print('Logging to steam account..')
368 steam_client = sc(api)
369 print('юзаю ' + str(proxy))
370 steam_client._session.proxies = {'https': str(proxy)}
371 steam_client.login(login, pswd, steamguard)
372 print('Successfully logged in!')
373 except requests.exceptions.ConnectionError:
374 print('Bad proxy')
375 sleep(10)
376 steam_login()
377 except steampy.exceptions.InvalidCredentials:
378 print('Bad proxy')
379 sleep(10)
380 steam_login()
381
382
383def del_position():
384 jsonUpd = {"items": []}
385 ChangeFile('position.json', jsonUpd)
386
387
388def setNewMafile(mafileId64, mafilePathclear):
389 global login
390 Mafile = json.load((open(mafileId64)))
391 steamid = Mafile['Session'].get('SteamID')
392 shared_secret = Mafile.get('shared_secret')
393 identity_secret = Mafile.get('identity_secret')
394 login = Mafile.get('account_name')
395 new_mafile_path = 'new_mafile.maFile'
396 dump_newMafile(mafilePathclear, steamid, shared_secret, new_mafile_path, identity_secret)
397
398
399def dump_newMafile(mafilePathclear, steamid, shared_secret, new_mafile_path, identity_secret):
400 global pswd
401 dataPath = str(mafilePathclear) + str(login) + '.txt'
402 file = open(dataPath)
403 log_pass = file.readline()
404 password = str(log_pass).split(':', maxsplit=2)
405 password2 = str(password[2]).split('\n')
406 pswd = (password2[0])
407 new_mafile = {"steamid": str(steamid),
408 "shared_secret": str(shared_secret),
409 "identity_secret": str(identity_secret)}
410
411 ChangeFile(new_mafile_path, new_mafile)
412
413
414def new_mafile():
415 global pswd, login
416 mafilePath = (os.getcwd())
417 mafileId64 = (os.listdir(path=os.getcwd())[0]) # Получаем мафайл (он должен быть 1 в списке!)
418 mafilePathclear = str(mafilePath).split('maFiles', maxsplit=1)[0] # Получаем путь к папке с данными
419 setNewMafile(mafileId64, mafilePathclear)
420
421
422def getProxy():
423 number_proxy = input('Введите номер прокси(коммент): ')
424 data = (requests.get('https://proxy-store.com/api/' + api_key + '/getproxy/comment').json())
425 ChangeFile('json.json', data)
426 for proxy in data['list']:
427 comment = data['list'][proxy]['comment']
428 if comment == number_proxy:
429 proxy = 'https://' + str(data['list'][proxy]['user']) + ':' + str(data['list'][proxy]['pass']) + '@' + str(
430 data['list'][proxy]['ip']) \
431 + ':' + str(data['list'][proxy]['port'])
432 return proxy
433
434
435def getMinPrice(items_sale):
436 global avg
437 for x in items_sale['items']:
438 try:
439 item_name = x['market_hash_name']
440 item_price = best_offer(item_name)
441 setPrice_end(item_price, x, item_name)
442
443 except json.decoder.JSONDecodeError:
444 print('448 error json')
445 avg = 0
446 sleep(1)
447 minimalPrice()
448
449
450def getid():
451 try:
452 MySellOffers = requests.get('https://market.csgo.com/api/GetMySellOffers/?key=' + f'{api}').json()
453 if MySellOffers['success'] == True:
454 list_items = MySellOffers['offers']
455 for x in list_items:
456 name = x['i_market_hash_name']
457 start_price = int(x['ui_price']) * 100
458 classid = x['i_classid']
459 instanceid = x['i_instanceid']
460 end_price = int(start_price * 0.97)
461 end_price = round(end_price, 1)
462 userData = json.load((open('edit.json')))
463 userData["items"].append({'start_price': f'{start_price}',
464 'end_price': f'{end_price}',
465 'classid': f'{classid}',
466 'instanceid': f'{instanceid}',
467 'name': f'{name}'})
468
469 ChangeFile('edit.json', userData)
470 sleep(1)
471
472 else:
473 print('Sales is empty! Time to put up some items..')
474 sleep(60)
475 getid()
476 except:
477 print('ОШИБКА')
478 getid()
479
480
481def del_id():
482 jsonUpd = {"items": []}
483 ChangeFile('edit.json', jsonUpd)
484
485
486def set_some_item():
487 name = input('Введите имя:')
488 price = input('Введите цену в рублях:')
489 price = int(price) * 100
490 del_id()
491 getid()
492 data = json.load((open('edit.json')))
493 for item in data['items']:
494 if item['name'] == name:
495 classid = item['classid']
496 instanceid = item['instanceid']
497 try:
498 requests.get(
499 'https://market.csgo.com/api/MassSetPrice/' + f'{classid}' + '_' + f'{instanceid}' + '/' + f'{price}' + '/?key=' + f'{api}').json()
500 except:
501 print('Ошшшшшибка')
502 mes = input('еще?')
503 if mes == '+':
504 set_some_item()
505 mes = input('еще?')
506 if mes == '+':
507 set_some_item()
508
509
510def minimalPrice():
511 global avg
512 try:
513 status = requests.get('https://market.csgo.com/api/v2/my-inventory/?key=' + f'{api}').json()['success']
514 if status == True:
515 items_sale = requests.get('https://market.csgo.com/api/v2/my-inventory/?key=' + f'{api}').json()
516 getMinPrice(items_sale)
517 else:
518 sleep(1)
519
520 except json.decoder.JSONDecodeError:
521 print('250 error json')
522 avg = 0
523 sleep(5)
524 minimalPrice()
525
526
527proxy = getProxy()
528new_mafile()
529
530bot_action = input(
531 '"0" - Включить обновление' + '\n'
532 + '"1" - Выставить все на продажу, включить трейды' + '\n'
533 + '"2" - Выставить предметы по оптимальной цене' + '\n'
534 + '"3" - Включить автодамп и трейды' + '\n'
535 + '"4" - Аолучить баланс' + '\n'
536 + '"5" - Включить все' + '\n'
537 + '"6" - Выставить предметы по минимальной цене' + '\n'
538 + 'Write number: ')
539
540if bot_action == '0':
541 Thread(target=updating).start()
542
543if bot_action == '1':
544 steam_login()
545 del_position()
546 Thread(target=updating).start()
547 Thread(target=Trades).start()
548
549if bot_action == '2':
550 itemsOnSale()
551
552if bot_action == '3':
553 del_position()
554 steam_login()
555 Thread(target=Trades).start()
556 Thread(target=price_offers).start()
557 Thread(target=updating).start()
558
559if bot_action == '4':
560 print('All balance: ' + str(sumItems()) + ' rub')
561
562if bot_action == '5':
563 itemsOnSale()
564 print('All balance: ' + str(sumItems()) + ' rub')
565 del_position()
566 steam_login()
567 Thread(target=Trades).start()
568 Thread(target=price_offers).start()
569 Thread(target=updating).start()
570
571if bot_action == '6':
572 minimalPrice()
573
574if bot_action == '7':
575 set_some_item()