· 5 years ago · May 30, 2020, 04:36 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: # Обновление ивентаря и включение продаж каждые 3 минуты
121 settingSteamApi()
122 ping()
123 inventUpdate()
124 sleep(120)
125 except:
126 sleep(15)
127 pass
128
129
130def ping():
131 try:
132 status = 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 status = 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('176 json')
177 pass
178
179
180def setprices(bestOffer_price, item_price, x, item_name):
181 try:
182 maxbest = int(item_price) * 1.1
183 minbest = int(item_price) * 0.9
184 if int(bestOffer_price) > 5000000:
185 setPrice_end(item_price, x, item_name)
186
187 elif int(maxbest) > int(bestOffer_price) > int(minbest):
188 setPrice_end(bestOffer_price, x, item_name)
189
190 elif int(maxbest) < int(bestOffer_price) > int(minbest):
191 setPrice_end(item_price, x, item_name)
192
193 elif int(maxbest) < int(bestOffer_price) < int(minbest):
194 setPrice_end(minbest, x, item_name)
195
196 elif int(maxbest) > int(bestOffer_price) < int(minbest):
197 setPrice_end(bestOffer_price, x, item_name)
198
199 else:
200 setPrice_end(price2, x, item_name)
201
202 except json.decoder.JSONDecodeError:
203 print('203 error json')
204 pass
205
206
207def best_offer(name):
208 global price2
209 try:
210 data = (requests.get(
211 'https://market.csgo.com/api/v2/search-list-items-by-hash-name-all?key=' + api + '&list_hash_name[]=' + name).json())
212 prices = data['data'][name]
213 best_price = data['data'][name][0]['price']
214 price2 = data['data'][name][2]['price']
215 for price in prices:
216 offer = (price['price'])
217 if offer < best_price:
218 best_price = offer
219 return best_price
220 except:
221 print('223 error')
222 best_offer(name)
223
224
225def getBestPrice(items_sale):
226 global avg
227 for x in items_sale['items']:
228 try:
229 hashed_name = x['market_hash_name']
230 try:
231 global history
232 history = requests.get(
233 'https://market.csgo.com/api/v2/get-list-items-info?key=' + f'{api}' + '&list_hash_name[]=' + f'{hashed_name}').json()[
234 'data'][hashed_name]['history']
235 except:
236 print('238 error json')
237 getBestPrice(items_sale)
238 try:
239 item_name = x['market_hash_name']
240 item_price = (calc() / 40) * 100
241 item_price = int(round(item_price, 0))
242 best_price = best_offer(item_name)
243 setprices(best_price, item_price, x, item_name)
244
245 except json.decoder.JSONDecodeError:
246 print('248 error json')
247 avg = 0
248 sleep(1)
249 itemsOnSale()
250 except json.decoder.JSONDecodeError:
251 print('253 error json')
252 avg = 0
253 sleep(1)
254 itemsOnSale()
255
256
257def itemsOnSale():
258 global avg
259 try:
260 status = requests.get('https://market.csgo.com/api/v2/my-inventory/?key=' + f'{api}').json()['success']
261 if status == True:
262 items_sale = requests.get('https://market.csgo.com/api/v2/my-inventory/?key=' + f'{api}').json()
263 getBestPrice(items_sale)
264 else:
265 sleep(1)
266
267 except json.decoder.JSONDecodeError:
268 print('270 error json')
269 avg = 0
270 sleep(5)
271 itemsOnSale()
272
273
274def price_offers():
275 global item
276 try:
277 MySellOffers = requests.get('https://market.csgo.com/api/GetMySellOffers/?key=' + f'{api}').json()
278 if MySellOffers['success'] == True:
279 list_items = MySellOffers['offers']
280 for x in list_items:
281 name = x['i_market_hash_name']
282 start_price = int(x['ui_price']) * 100
283 classid = x['i_classid']
284 instanceid = x['i_instanceid']
285 end_price = int(start_price * 0.97)
286 end_price = round(end_price, 1)
287 userData = json.load((open('position.json')))
288 userData["items"].append({'start_price': f'{start_price}',
289 'end_price': f'{end_price}',
290 'classid': f'{classid}',
291 'instanceid': f'{instanceid}',
292 'name': f'{name}'})
293
294 ChangeFile('position.json', userData)
295 sleep(1)
296 startDump()
297
298 else:
299 print('Sales is empty! Time to put up some items..')
300 inventUpdate()
301 sleep(60)
302 price_offers()
303 except:
304 print('Error with getting price offers! I will try again after 5 seconds')
305 sleep(1)
306 price_offers()
307
308
309def startDump():
310 print('Function "price dumping" was successfully turned on! log off')
311 while i > 1:
312 sleep(1)
313 try:
314 ds = json.load((open('position.json')))
315 output_data = [v for v in {inp['name']: inp for inp in ds['items']}.values()]
316 json_str = {"items": output_data}
317 ChangeFile('position.json', json_str)
318 sleep(5)
319 dataFor_dump = json.load((open('position.json')))['items']
320 for x in dataFor_dump:
321 try:
322 classid = x['classid']
323 instanceid = x['instanceid']
324 end_price = x['end_price']
325 start_price = round(int(x['start_price']) * 1.05, 1)
326 bestOffer = requests.get(
327 'https://market.csgo.com/api/BestSellOffer/' + f'{classid}' + '_' + f'{instanceid}' + '/?key=' + f'{api}').json()[
328 'best_offer']
329 if int(start_price) > int(bestOffer) > int(end_price):
330 price = int(bestOffer) - 1
331 requests.get(
332 'https://market.csgo.com/api/MassSetPrice/' + f'{classid}' + '_' + f'{instanceid}' + '/' + f'{price}' + '/?key=' + f'{api}').json()
333 else:
334 pass
335 except:
336 sleep(1)
337 pass
338 except:
339 sleep(1)
340 startDump()
341
342
343def sumItems():
344 try:
345 items = (requests.get('https://market.csgo.com/api/Trades/?key=' + f'{api}').json())
346 totalPrice = 0
347 for item in items:
348 price = item['ui_price']
349 totalPrice = int(totalPrice) + int(price)
350 balance = requests.get('https://market.csgo.com/api/GetMoney/?key=' + f'{api}').json()['money'] / 100
351 full = str(float(totalPrice * 0.9) + float(balance))
352 print('On sales: ' + str(round(totalPrice * 0.9)) + ' rub')
353 print('Balance: ' + str(round(balance, 1)) + ' rub')
354 return full
355 except:
356 sumItems()
357
358
359def steam_login():
360 global steam_client
361 try:
362 print('Logging to steam account..')
363 steam_client = sc(api)
364 print('юзаю ' + str(proxy))
365 steam_client._session.proxies = {'https': str(proxy)}
366 steam_client.login(login, pswd, steamguard)
367 print('Successfully logged in!')
368 except requests.exceptions.ConnectionError:
369 print('Bad proxy')
370 steam_login()
371 except steampy.exceptions.InvalidCredentials:
372 sleep(3)
373 steam_login()
374
375
376def del_position():
377 jsonUpd = {"items": []}
378 ChangeFile('position.json', jsonUpd)
379
380
381def setNewMafile(mafileId64, mafilePathclear):
382 global login
383 Mafile = json.load((open(mafileId64)))
384 steamid = Mafile['Session'].get('SteamID')
385 shared_secret = Mafile.get('shared_secret')
386 identity_secret = Mafile.get('identity_secret')
387 login = Mafile.get('account_name')
388 new_mafile_path = 'new_mafile.maFile'
389 dump_newMafile(mafilePathclear, steamid, shared_secret, new_mafile_path, identity_secret)
390
391
392def dump_newMafile(mafilePathclear, steamid, shared_secret, new_mafile_path, identity_secret):
393 global pswd
394 dataPath = str(mafilePathclear) + str(login) + '.txt'
395 file = open(dataPath)
396 log_pass = file.readline()
397 password = str(log_pass).split(':', maxsplit=2)
398 password2 = str(password[2]).split('\n')
399 pswd = (password2[0])
400 new_mafile = {"steamid": str(steamid),
401 "shared_secret": str(shared_secret),
402 "identity_secret": str(identity_secret)}
403
404 ChangeFile(new_mafile_path, new_mafile)
405
406
407def new_mafile():
408 global pswd, login
409 mafilePath = (os.getcwd())
410 mafileId64 = (os.listdir(path=os.getcwd())[0]) # Получаем мафайл (он должен быть 1 в списке!)
411 mafilePathclear = str(mafilePath).split('maFiles', maxsplit=1)[0] # Получаем путь к папке с данными
412 setNewMafile(mafileId64, mafilePathclear)
413
414
415def getProxy():
416 number_proxy = input('Введите номер прокси(коммент): ')
417 data = (requests.get('https://proxy-store.com/api/' + api_key + '/getproxy/comment').json())
418 ChangeFile('json.json', data)
419 for proxy in data['list']:
420 comment = data['list'][proxy]['comment']
421 if comment == number_proxy:
422 proxy = 'https://' + str(data['list'][proxy]['user']) + ':' + str(data['list'][proxy]['pass']) + '@' + str(
423 data['list'][proxy]['ip']) \
424 + ':' + str(data['list'][proxy]['port'])
425 return proxy
426
427
428def getMinPrice(items_sale):
429 global avg
430 for x in items_sale['items']:
431 try:
432 item_name = x['market_hash_name']
433 item_price = best_offer(item_name)
434 setPrice_end(item_price, x, item_name)
435
436 except json.decoder.JSONDecodeError:
437 print('448 error json')
438 avg = 0
439 sleep(1)
440 minimalPrice()
441
442
443def minimalPrice():
444 global avg
445 try:
446 status = requests.get('https://market.csgo.com/api/v2/my-inventory/?key=' + f'{api}').json()['success']
447 if status == True:
448 items_sale = requests.get('https://market.csgo.com/api/v2/my-inventory/?key=' + f'{api}').json()
449 getMinPrice(items_sale)
450 else:
451 sleep(1)
452
453 except json.decoder.JSONDecodeError:
454 print('250 error json')
455 avg = 0
456 sleep(5)
457 minimalPrice()
458
459
460proxy = getProxy()
461new_mafile()
462
463bot_action = input(
464 '"0" - Включить обновление' + '\n'
465 + '"1" - Выставить все на продажу, включить трейды' + '\n'
466 + '"2" - Выставить предметы по оптимальной цене' + '\n'
467 + '"3" - Включить автодамп и трейды' + '\n'
468 + '"4" - Аолучить баланс' + '\n'
469 + '"5" - Включить все' + '\n'
470 + '"6" - Выставить предметы по минимальной цене' + '\n'
471 + 'Write number: ')
472
473if bot_action == '0':
474 Thread(target=updating).start()
475
476if bot_action == '1':
477 steam_login()
478 del_position()
479 Thread(target=updating).start()
480 Thread(target=Trades).start()
481
482if bot_action == '2':
483 itemsOnSale()
484
485if bot_action == '3':
486 del_position()
487 steam_login()
488 Thread(target=Trades).start()
489 Thread(target=price_offers).start()
490 Thread(target=updating).start()
491
492if bot_action == '4':
493 print('All balance: ' + str(sumItems()) + ' rub')
494
495if bot_action == '5':
496 itemsOnSale()
497 print('All balance: ' + str(sumItems()) + ' rub')
498 del_position()
499 steam_login()
500 Thread(target=Trades).start()
501 Thread(target=price_offers).start()
502 Thread(target=updating).start()
503
504if bot_action == '6':
505 minimalPrice()