· 5 years ago · May 13, 2020, 01:30 PM
1import requests
2import json
3from time import sleep
4from threading import Thread
5from steampy.client import SteamClient, Asset
6from steampy.utils import GameOptions
7
8game = GameOptions.CS
9
10api = ''
11api2 = ''
12i = 2
13avg = 0
14# Set steam API key
15apikey = ''
16# Set path to SteamGuard file
17steamguard = 'C:/pytest/22/maFiles/737.maFile'
18# Steam username
19login = ''
20# Steam password
21pswd = ''
22
23url = 'https://market.csgo.com/api/Trades/?key=' + api
24
25
26def offer(assetid, msg, trade_url):
27 if steam_client.is_session_alive():
28 my_items = steam_client.get_my_inventory(game)
29 items = iter(my_items.values())
30 for i in items:
31 if i['id'] == assetid:
32 item = Asset(i['id'], game)
33 return steam_client.make_offer_with_url([item], [], trade_url, msg, True)
34 else:
35 pass
36 else:
37 steam_client.login(login, pswd, steamguard)
38 my_items = steam_client.get_my_inventory(game)
39 items = iter(my_items.values())
40 for i in items:
41 if i['instanceid'] == assetid:
42 item = Asset(i['id'], game)
43 return steam_client.make_offer_with_url([item], [], trade_url, msg, True)
44 else:
45 pass
46
47
48def confirm(tradeid):
49 try:
50 steam_client._confirm_transaction(tradeid)
51 except:
52 print("trade confirmed!")
53
54
55def Trades():
56 while i > 1:
57 sleep(10)
58 try:
59 itemdata = requests.post(url).json()
60 if itemdata == []:
61 print('На продаже ничего нету! Самое время выставить что-нибудь...')
62 else:
63 try:
64 with open('json.json', 'w') as info:
65 json.dump(itemdata, info)
66 assetid = itemdata[0]['ui_asset']
67
68 if (itemdata[0]['ui_status'] == "1"):
69 pass
70 elif (itemdata[0]['ui_status'] == '2'):
71 tradedata = requests.post("https://market.csgo.com/api/ItemRequest/in/1/?key=" + api).json()
72 print(tradedata)
73 msg = tradedata['request']['tradeoffermessage']
74 trade_url = tradedata['request']['tradelink']
75 data = offer(assetid, msg, trade_url)
76 sleep(5)
77 with open('tradedata.json', 'w') as file:
78 json.dump(tradedata, file, indent=4)
79 tradeid = data['tradeofferid'] # ОШИБКА TypeError: 'NoneType' object is not subscriptable
80 confirm(tradeid)
81 except TypeError:
82 pass
83 except KeyError:
84 pass
85
86 else:
87 sleep(10)
88 print('Wait trade offer...')
89 pass
90 except json.decoder.JSONDecodeError:
91 pass
92 except requests.exceptions.ConnectionError:
93 print('Connection refused')
94 sleep(30)
95 pass
96
97
98def updating():
99 try:
100 i = 2
101 while i > 1: # Обновление ивентаря и включение продаж каждые 3 минуты
102 inventUpdate()
103 ping()
104 settingSteamApi()
105 sleep(160)
106 except json.decoder.JSONDecodeError:
107 print('Вылезла ошибка! Отдыхаю 15 секунд')
108 sleep(15)
109 Thread(target=updating).start()
110 except requests.exceptions.ConnectionError:
111 print('Connection refused')
112 sleep(30)
113 pass
114
115
116def ping():
117 try:
118 status = requests.get('https://market.csgo.com/api/v2/ping?key=' + f'{api2}')
119 status2 = status.json()
120
121 if status2['success'] == True:
122 print('Продажи были успешно включены!')
123
124 elif status2['success'] == False and status2['message'] == 'too early for pong':
125 print('Продажи и так были включены')
126
127 else:
128 print('Ошибка включения продаж! Попробую еще раз через 160 секунд...')
129
130 except Exception:
131 print('Connection refused')
132 sleep(30)
133 pass
134
135
136def inventUpdate():
137 try:
138 status = requests.get('https://market.csgo.com/api/v2/update-inventory/?key=' + f'{api2}').json()
139 if status['success'] == True:
140 print('Инвентарь был успешно обновлен!')
141 elif status['success'] == False:
142 print('Ошибка обновления инвентаря! Попробую еще раз через 160 секунд...')
143
144 except requests.exceptions.ConnectionError:
145 print('Connection refused')
146 sleep(30)
147 pass
148
149
150def settingSteamApi():
151 try:
152 requests.get('https://market.csgo.com/api/SetSteamAPIKey/' + apikey + '/?key=' + api).json()
153
154 except requests.exceptions.ConnectionError:
155 print('Connection refused')
156 sleep(30)
157 pass
158
159
160def itemsOnSale():
161 try:
162 items_sale = requests.get('https://market.csgo.com/api/v2/my-inventory/?key=' + f'{api}').json() ####ОШИБКА
163 for x in items_sale['items']:
164 try:
165 hashed_name = x['market_hash_name']
166 try:
167 history = requests.get(
168 'https://market.csgo.com/api/v2/get-list-items-info?key=' + f'{api}' + '&list_hash_name[]=' + f'{hashed_name}').json()[
169 'data'][hashed_name]['history']
170 except json.decoder.JSONDecodeError:
171 print('Тм лагает, попробуем позже...')
172 itemsOnSale()
173
174 def calc():
175 global avg
176 try:
177 for x in history[:40]:
178 avg = avg + x[1]
179 avg = round(avg, 0)
180 return avg
181 except NameError:
182 print('ТМ лагает!')
183 itemsOnSale()
184
185 try:
186 item_name = x['market_hash_name']
187 item_price = (calc() / 40) * 100
188 item_price = int(round(item_price, 0))
189 bestOffer_status = requests.get(
190 'https://market.csgo.com/api/BestSellOffer/' + x['classid'] + '_' + x[
191 'instanceid'] + '/?key=' + f'{api}').json()['success']
192 bestOffer_price = requests.get(
193 'https://market.csgo.com/api/BestSellOffer/' + x['classid'] + '_' + x[
194 'instanceid'] + '/?key=' + f'{api}').json()['best_offer']
195
196 item = f'{item_name}' + ' по цене ' + f'{item_price / 100}' + ' rub' + ' был успешно выставлен на продажу!'
197 if int(item_price) > 5000000:
198 global avg
199 avg = 0
200 pass
201
202 elif int(bestOffer_price) > 5000000:
203 avg = 0
204 pass
205
206 else:
207 if bestOffer_status == True:
208 if int(bestOffer_price) > 5000000:
209 requests.get('https://market.csgo.com/api/SetPrice/new_' + x['classid'] + '_' + x[
210 'instanceid'] + '/' + f'{item_price}' + '/?key=' + f'{api}')
211 avg = 0
212 print(
213 f'{item_name}' + ' по цене ' + f'{int(item_price) / 100}' + ' rub' + ' был успешно выставлен на продажу!')
214
215 if int(bestOffer_price) > int(item_price):
216 requests.get('https://market.csgo.com/api/SetPrice/new_' + x['classid'] + '_' + x[
217 'instanceid'] + '/' + f'{bestOffer_price}' + '/?key=' + f'{api}')
218 print(
219 f'{item_name}' + ' по цене ' + f'{int(bestOffer_price) / 100}' + ' rub' + ' был успешно выставлен на продажу!')
220 avg = 0
221 else:
222 requests.get('https://market.csgo.com/api/SetPrice/new_' + x['classid'] + '_' + x[
223 'instanceid'] + '/' + f'{item_price}' + '/?key=' + f'{api}')
224 print(item)
225 avg = 0
226 except KeyError:
227 avg = 0
228 pass
229 except json.decoder.JSONDecodeError:
230 avg = 0
231 pass
232
233 except TypeError:
234 avg = 0
235 pass
236 except json.decoder.JSONDecodeError:
237 avg = 0
238 itemsOnSale()
239 except requests.exceptions.ConnectionError:
240 print('Connection refused')
241 sleep(30)
242 avg = 0
243 itemsOnSale()
244
245
246def price_offers():
247 global item
248 try:
249 list_items = requests.get('https://market.csgo.com/api/GetMySellOffers/?key=' + f'{api}').json()['offers']
250 sleep(5)
251 for x in list_items:
252 name = x['i_market_hash_name']
253 start_price = int(x['ui_price']) * 100
254 classid = x['i_classid']
255 instanceid = x['i_instanceid']
256 end_price = int(start_price * 0.97)
257 end_price = round(end_price, 1)
258
259 userData = json.load((open('C:\\pytest\\position.json')))
260
261 userData["items"].append({'start_price': f'{start_price}',
262 'end_price': f'{end_price}',
263 'classid': f'{classid}',
264 'instanceid': f'{instanceid}',
265 'name': f'{name}'})
266
267 with open('C:\\pytest\\position.json', 'w') as file:
268 json.dump(userData, file, indent=4)
269 file.close()
270
271 except TypeError:
272 sleep(1)
273 print('TypeError')
274 pass
275 except json.decoder.JSONDecodeError:
276 sleep(10)
277 price_offers()
278 except KeyError:
279 sleep(1)
280 print('KeyError')
281 pass
282 except requests.exceptions.ConnectionError:
283 print('Connection refused')
284 sleep(30)
285 pass
286
287 Thread(target=startDump).start()
288
289
290def startDump():
291 while i > 1:
292 sleep(5)
293 try:
294 ds = json.load((open('C:\\pytest\\position.json')))
295 output_data = [v for v in {inp['name']: inp for inp in ds['items']}.values()]
296 json_str = {"items": output_data}
297
298 with open('C:\\pytest\\position.json', 'w') as file:
299 json.dump(json_str, file, indent=4)
300 file.close()
301
302 dataFor_dump = json.load((open('C:\\pytest\\position.json')))['items']
303 for x in dataFor_dump:
304 try:
305 classid = x['classid']
306 instanceid = x['instanceid']
307 name = x['name']
308 end_price = x['end_price']
309
310 bestOffer = requests.get(
311 'https://market.csgo.com/api/BestSellOffer/' + f'{classid}' + '_' + f'{instanceid}' + '/?key=' + f'{api}').json()[
312 'best_offer']
313
314 if int(bestOffer) > int(end_price):
315 price = int(bestOffer) - 1
316 if price > 1000000:
317 pass
318 else:
319 status = requests.get(
320 'https://market.csgo.com/api/MassSetPrice/' + f'{classid}' + '_' + f'{instanceid}' + '/' + f'{price}' + '/?key=' + f'{api}').json()
321
322 items = status['items']
323 for item in items:
324 oldPrice = item['oldPrice']
325 newPrice = item['newPrice']
326 if oldPrice == newPrice:
327 pass
328 else:
329 print('Цена на ' + str(name) + ' : ' + str(newPrice / 100) + ' рублей')
330
331 else:
332 pass
333
334 except KeyError:
335 pass
336 except json.decoder.JSONDecodeError:
337 sleep(10)
338 startDump()
339
340
341 except json.decoder.JSONDecodeError:
342 sleep(10)
343 startDump()
344
345 except requests.exceptions.ConnectionError:
346 print('Connection refused')
347 sleep(30)
348 startDump()
349
350
351def sumItems():
352 try:
353 items = (requests.get('https://market.csgo.com/api/Trades/?key=' + f'{api}').json())
354 totalPrice = 0
355 for item in items:
356 price = item['ui_price']
357 totalPrice = int(totalPrice) + int(price)
358
359 print('На продаже: ' + str(totalPrice * 0.9) + ' рублей')
360 print('Баланс: ' + str(
361 requests.get('https://market.csgo.com/api/GetMoney/?key=' + f'{api}').json()['money'] / 100))
362 full = str(float(totalPrice * 0.9) + float(
363 requests.get('https://market.csgo.com/api/GetMoney/?key=' + f'{api}').json()['money'] / 100))
364 return full
365
366 except json.decoder.JSONDecodeError:
367 sumItems()
368
369 except requests.exceptions.ConnectionError:
370 print('Connection refused')
371 sleep(30)
372 pass
373
374
375bot_action = input(
376 '"0" - включить продажи и обновление инвентаря' + '\n'
377 + '"1" - автоматичестки выставить все предметы по минимальной цене, включить передачу и продажи' + '\n'
378 + '"2" - выставить предметы на продажу по минимальной цене' + '\n'
379 + '"3" - включить автодамп цен + продажи (beta)' + '\n'
380 + '"4" - узнать баланс предметов на продаже' + '\n'
381 + 'Что нужно сделать?: ')
382
383if bot_action == '0':
384 Thread(target=updating).start()
385
386if bot_action == '1':
387 jsonUpd = {"items": []}
388 with open('C:\\pytest\\position.json', 'w') as file:
389 json.dump(jsonUpd, file, indent=4)
390 file.close()
391 Thread(target=updating).start()
392 Thread(target=Trades).start()
393 itemsOnSale()
394 price_offers()
395
396if bot_action == '2':
397 itemsOnSale()
398
399if bot_action == '3':
400 jsonUpd = {"items": []}
401 with open('C:\\pytest\\position.json', 'w') as file:
402 json.dump(jsonUpd, file, indent=4)
403 file.close()
404 print('Входим в стим')
405 steam_client = SteamClient(api)
406 steam_client.login(login, pswd, steamguard)
407 print('Вошли в стим')
408 Thread(target=price_offers).start()
409 Thread(target=updating).start()
410 Thread(target=Trades).start()
411 price_offers()
412
413if bot_action == '4':
414 print('В общем: ' + str(sumItems()) + ' рублей')