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