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