· 5 years ago · May 24, 2020, 12:34 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
15proxy = ''
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 = ''
23price2 = 0
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 if tradeOffer['success'] == True:
83 msg = tradeOffer['request']['tradeoffermessage']
84 trade_url = tradeOffer['request']['tradelink']
85 assetid = tradeOffer['request']['items'][0]['assetid']
86 userdata = json.load((open('data.json')))
87 result = userdata.get(str(assetid))
88 if result == None:
89 data = offer(assetid, msg, trade_url)
90 dataCheck(data)
91 else:
92 print('спим')
93 sleep(15)
94 pass
95 else:
96 print('nothing')
97 datajson = {}
98 ChangeFile('data.json', datajson)
99 sleep(30)
100 except:
101 print('Ошибка 80 trades')
102 userdata = json.load((open('data.json')))
103 userdata.update({str(assetid): 'used'})
104 ChangeFile('data.json', userdata)
105 assetid = ''
106 Trades()
107
108
109def updating():
110 i = 10
111 try:
112 while i > 1: # Обновление ивентаря и включение продаж каждые 3 минуты
113 settingSteamApi()
114 ping()
115 inventUpdate()
116 sleep(120)
117 except:
118 sleep(15)
119 pass
120
121
122def ping():
123 try:
124 status = requests.get('https://market.csgo.com/api/v2/ping?key=' + f'{api}')
125 status2 = status.json()
126 if status2['success'] == True:
127 pass
128 elif status2['success'] == False and status2['message'] == 'too early for pong':
129 pass
130 else:
131 pass
132 except:
133 sleep(5)
134 pass
135
136
137def inventUpdate():
138 try:
139 status = requests.get('https://market.csgo.com/api/v2/update-inventory/?key=' + f'{api}').json()
140 if status['success'] == True:
141 pass
142 elif status['success'] == False:
143 pass
144 except:
145 sleep(5)
146 pass
147
148
149def settingSteamApi():
150 try:
151 requests.get('https://market.csgo.com/api/SetSteamAPIKey/' + apikey + '/?key=' + api).json()
152 except:
153 sleep(5)
154 pass
155
156
157def calc():
158 global history, avg
159 try:
160 for x in history[:40]:
161 avg = avg + x[1]
162 avg = round(avg, 0)
163 return avg
164 except:
165 avg = 0
166 sleep(1)
167 calc()
168
169
170def setPrice_end(price, x, item_name):
171 global avg, price2
172 try:
173 requests.get('https://market.csgo.com/api/SetPrice/new_' + x['classid'] + '_' + x[
174 'instanceid'] + '/' + f'{price}' + '/?key=' + f'{api}').json()
175 print(f'{item_name}' + ' with price ' + f'{int(price) / 100}' + ' rub' + ' successfully was added on sale')
176 avg = 0
177 price2 = 0
178 except json.decoder.JSONDecodeError:
179 print('169 json')
180 pass
181
182
183def setprices(bestOffer_price, item_price, x, item_name):
184 try:
185 print('ITEM BEST OFFER IS 117= ' + str(bestOffer_price))
186 maxbest = int(item_price) * 1.1
187 minbest = int(item_price) * 0.9
188 if int(bestOffer_price) > 5000000:
189 setPrice_end(item_price, x, item_name)
190
191 elif int(maxbest) > int(bestOffer_price) > int(minbest):
192 setPrice_end(bestOffer_price, x, item_name)
193
194 elif int(maxbest) < int(bestOffer_price) > int(minbest):
195 setPrice_end(item_price, x, item_name)
196
197 elif int(maxbest) < int(bestOffer_price) < int(minbest):
198 setPrice_end(minbest, x, item_name)
199
200 elif int(maxbest) > int(bestOffer_price) < int(minbest):
201 setPrice_end(bestOffer_price, x, item_name)
202
203 else:
204 setPrice_end(price2, x, item_name)
205
206 except json.decoder.JSONDecodeError:
207 print('184 error json')
208 pass
209
210
211def best_offer(name):
212 global price2
213 try:
214 data = (requests.get(
215 'https://market.csgo.com/api/v2/search-list-items-by-hash-name-all?key=' + api + '&list_hash_name[]=' + name).json())
216 prices = data['data'][name]
217 best_price = data['data'][name][0]['price']
218 price2 = data['data'][name][2]['price']
219 print('now best: ' + str(best_price))
220 for price in prices:
221 offer = (price['price'])
222 if offer < best_price:
223 best_price = offer
224 print('best= ' + str(best_price))
225 return best_price
226 except TypeError:
227 print('207 error')
228 best_offer(name)
229
230
231def getBestPrice(items_sale):
232 global avg
233 for x in items_sale['items']:
234 try:
235 hashed_name = x['market_hash_name']
236 try:
237 global history
238 history = requests.get(
239 'https://market.csgo.com/api/v2/get-list-items-info?key=' + f'{api}' + '&list_hash_name[]=' + f'{hashed_name}').json()[
240 'data'][hashed_name]['history']
241 except:
242 print('222 error json')
243 getBestPrice(items_sale)
244 try:
245 item_name = x['market_hash_name']
246 item_price = (calc() / 40) * 100
247 item_price = int(round(item_price, 0))
248 print('ITEM AVG= ' + str(item_price))
249
250 best_price = best_offer(item_name)
251 setprices(best_price, item_price, x, item_name)
252
253 except json.decoder.JSONDecodeError:
254 print('224 error json')
255 avg = 0
256 sleep(1)
257 itemsOnSale()
258 except json.decoder.JSONDecodeError:
259 print('229 error json')
260 avg = 0
261 sleep(1)
262 itemsOnSale()
263
264
265def itemsOnSale():
266 global avg
267 try:
268 status = requests.get('https://market.csgo.com/api/v2/my-inventory/?key=' + f'{api}').json()['success']
269 if status == True:
270 items_sale = requests.get('https://market.csgo.com/api/v2/my-inventory/?key=' + f'{api}').json()
271 getBestPrice(items_sale)
272 else:
273 sleep(1)
274
275 except json.decoder.JSONDecodeError:
276 print('250 error json')
277 avg = 0
278 sleep(5)
279 itemsOnSale()
280
281
282def price_offers():
283 global item
284 try:
285 status = requests.get('https://market.csgo.com/api/GetMySellOffers/?key=' + f'{api}').json()['success']
286 if status == True:
287 sleep(1)
288 list_items = requests.get('https://market.csgo.com/api/GetMySellOffers/?key=' + f'{api}').json()['offers']
289 for x in list_items:
290 name = x['i_market_hash_name']
291 start_price = int(x['ui_price']) * 100
292 classid = x['i_classid']
293 instanceid = x['i_instanceid']
294 end_price = int(start_price * 0.97)
295 end_price = round(end_price, 1)
296 userData = json.load((open('position.json')))
297 userData["items"].append({'start_price': f'{start_price}',
298 'end_price': f'{end_price}',
299 'classid': f'{classid}',
300 'instanceid': f'{instanceid}',
301 'name': f'{name}'})
302
303 ChangeFile('position.json', userData)
304 sleep(5)
305 Thread(target=startDump).start()
306
307 else:
308 print('Sales is empty! Time to put up some items..')
309 inventUpdate()
310 sleep(60)
311 price_offers()
312 except:
313 print('Error with getting price offers! I will try again after 5 seconds')
314 sleep(1)
315 price_offers()
316
317
318def startDump():
319 print('Function "price dumping" was successfully turned on! log off')
320 while i > 1:
321 sleep(1)
322 try:
323 ds = json.load((open('position.json')))
324 output_data = [v for v in {inp['name']: inp for inp in ds['items']}.values()]
325 json_str = {"items": output_data}
326 ChangeFile('position.json', json_str)
327 sleep(5)
328 dataFor_dump = json.load((open('position.json')))['items']
329 for x in dataFor_dump:
330 try:
331 classid = x['classid']
332 instanceid = x['instanceid']
333 end_price = x['end_price']
334 start_price = round(int(x['start_price']) * 1.05, 1)
335 bestOffer = requests.get(
336 'https://market.csgo.com/api/BestSellOffer/' + f'{classid}' + '_' + f'{instanceid}' + '/?key=' + f'{api}').json()[
337 'best_offer']
338 if int(start_price) > int(bestOffer) > int(end_price):
339 price = int(bestOffer) - 1
340 requests.get(
341 'https://market.csgo.com/api/MassSetPrice/' + f'{classid}' + '_' + f'{instanceid}' + '/' + f'{price}' + '/?key=' + f'{api}').json()
342 else:
343 pass
344 except:
345 sleep(1)
346 pass
347 except:
348 sleep(5)
349 Thread(target=startDump).join()
350 price_offers()
351
352
353def sumItems():
354 try:
355 items = (requests.get('https://market.csgo.com/api/Trades/?key=' + f'{api}').json())
356 totalPrice = 0
357 for item in items:
358 price = item['ui_price']
359 totalPrice = int(totalPrice) + int(price)
360 balance = requests.get('https://market.csgo.com/api/GetMoney/?key=' + f'{api}').json()['money'] / 100
361 full = str(float(totalPrice * 0.9) + float(balance))
362 print('On sales: ' + str(round(totalPrice * 0.9)) + ' rub')
363 print('Balance: ' + str(round(balance, 1)) + ' rub')
364 return full
365 except:
366 sumItems()
367
368
369def steam_login():
370 global steam_client
371 try:
372 print('Logging to steam account..')
373 steam_client = sc(api)
374 steam_client._session.proxies = {'https': proxy}
375 steam_client.login(login, pswd, steamguard)
376 print('Successfully logged in!')
377 except requests.exceptions.ConnectionError:
378 print('Bad proxy')
379 except steampy.exceptions.InvalidCredentials:
380 sleep(3)
381 steam_login()
382
383
384def del_position():
385 jsonUpd = {"items": []}
386 ChangeFile('position.json', jsonUpd)
387
388
389def setNewMafile(mafileId64, mafilePathclear):
390 global login
391 Mafile = json.load((open(mafileId64)))
392 steamid = Mafile['Session'].get('SteamID')
393 shared_secret = Mafile.get('shared_secret')
394 identity_secret = Mafile.get('identity_secret')
395 login = Mafile.get('account_name')
396 new_mafile_path = 'new_mafile.maFile'
397 dump_newMafile(mafilePathclear, steamid, shared_secret, new_mafile_path, identity_secret)
398
399
400def dump_newMafile(mafilePathclear, steamid, shared_secret, new_mafile_path, identity_secret):
401 global pswd
402 dataPath = str(mafilePathclear) + str(login) + '.txt'
403 file = open(dataPath)
404 log_pass = file.readline()
405 password = str(log_pass).split(':', maxsplit=2)
406 password2 = str(password[2]).split('\n')
407 pswd = (password2[0])
408 new_mafile = {"steamid": str(steamid),
409 "shared_secret": str(shared_secret),
410 "identity_secret": str(identity_secret)}
411
412 ChangeFile(new_mafile_path, new_mafile)
413
414
415def new_mafile():
416 global pswd, login
417 mafilePath = (os.getcwd())
418 mafileId64 = (os.listdir(path=os.getcwd())[0]) # Получаем мафайл (он должен быть 1 в списке!)
419 mafilePathclear = str(mafilePath).split('maFiles', maxsplit=1)[0] # Получаем путь к папке с данными
420 setNewMafile(mafileId64, mafilePathclear)
421
422
423new_mafile()
424bot_action = input(
425 '"0" - Turn on updating' + '\n'
426 + '"1" - Automatically put up tradable items on sale, turn on updating and trades' + '\n'
427 + '"2" - Automatically put up tradable items on sale' + '\n'
428 + '"3" - Turn on auto dump and trades' + '\n'
429 + '"4" - Get your balance' + '\n'
430 + '"5" - Tern on all' + '\n'
431 + 'Write number: ')
432
433if bot_action == '0':
434 Thread(target=updating).start()
435
436if bot_action == '1':
437 steam_login()
438 del_position()
439 Thread(target=updating).start()
440 Thread(target=Trades).start()
441
442if bot_action == '2':
443 itemsOnSale()
444
445if bot_action == '3':
446 del_position()
447 steam_login()
448 Thread(target=Trades).start()
449 Thread(target=price_offers).start()
450 Thread(target=updating).start()
451
452if bot_action == '4':
453 print('All balance: ' + str(sumItems()) + ' rub')
454
455if bot_action == '5':
456 itemsOnSale()
457 print('All balance: ' + str(sumItems()) + ' rub')
458 del_position()
459 steam_login()
460 Thread(target=Trades).start()
461 Thread(target=price_offers).start()
462 Thread(target=updating).start()