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