· 5 years ago · May 12, 2020, 05:24 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 = '' # Cs go tm api
11api2 = ''
12i = 2
13avg = 0
14# Set steam API key
15apikey = ''
16# Set path to SteamGuard file
17steamguard = 'C:/pytest/20/maFiles/.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 print(' ')
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 print(item)
44 print(steam_client.make_offer_with_url([item], [], trade_url, msg, True))
45 return steam_client.make_offer_with_url([item], [], trade_url, msg, True)
46 else:
47 print(' ')
48
49
50def confirm(tradeid):
51 try:
52 steam_client._confirm_transaction(tradeid)
53 except:
54 print("trade confirmed!")
55
56
57def Trades():
58 while i > 1:
59 sleep(10)
60 try:
61 itemdata = requests.post(url).json()
62 if itemdata == []:
63 print('На продаже ничего нету! Самое время выставить что-нибудь...')
64 else:
65 try:
66 with open('json.json', 'w') as info:
67 json.dump(itemdata, info)
68 assetid = itemdata[0]['ui_asset']
69
70 if (itemdata[0]['ui_status'] == "1"):
71 print('ui == 1')
72 elif (itemdata[0]['ui_status'] == '2'):
73 tradedata = requests.post("https://market.csgo.com/api/ItemRequest/in/1/?key=" + api).json()
74 print(tradedata)
75
76 msg = tradedata['request']['tradeoffermessage']
77 trade_url = tradedata['request']['tradelink']
78 data = offer(assetid, msg, trade_url)
79 sleep(5)
80 with open('tradedata.json', 'w') as file:
81 json.dump(tradedata, file, indent=4)
82 tradeid = data['tradeofferid'] # ОШИБКА TypeError: 'NoneType' object is not subscriptable
83 confirm(tradeid)
84 except TypeError:
85 pass
86 except KeyError:
87 pass
88
89 else:
90 sleep(10)
91 print('Wait trade offer...')
92 pass
93 except json.decoder.JSONDecodeError:
94 pass
95 except requests.exceptions.ConnectionError:
96 print('Connection refused')
97 sleep(30)
98 pass
99
100
101def updating():
102 try:
103 i = 2
104 while i > 1: # Обновление ивентаря и включение продаж каждые 3 минуты
105 inventUpdate()
106 ping()
107 sleep(160)
108 except json.decoder.JSONDecodeError:
109 print('Вылезла ошибка! Отдыхаю 15 секунд')
110 sleep(15)
111 Thread(target=updating).start()
112 except requests.exceptions.ConnectionError:
113 print('Connection refused')
114 sleep(30)
115 pass
116
117
118def ping():
119 try:
120 status = requests.get('https://market.csgo.com/api/v2/ping?key=' + f'{api2}')
121 status2 = status.json()
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 requests.exceptions.ConnectionError:
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 itemsOnSale():
152 try:
153 items_sale = requests.get('https://market.csgo.com/api/v2/my-inventory/?key=' + f'{api}').json() ####ОШИБКА
154 for x in items_sale['items']:
155 try:
156 hashed_name = x['market_hash_name']
157 try:
158 history = requests.get(
159 'https://market.csgo.com/api/v2/get-list-items-info?key=' + f'{api}' + '&list_hash_name[]=' + f'{hashed_name}').json()[
160 'data'][hashed_name]['history']
161 except json.decoder.JSONDecodeError:
162 print('Тм лагает, попробуем позже...')
163 itemsOnSale()
164
165 def calc():
166 global avg
167 try:
168 for x in history[:40]:
169 avg = avg + x[1]
170 avg = round(avg, 0)
171 return avg
172 except NameError:
173 print('ТМ лагает!')
174 itemsOnSale()
175
176 try:
177 item_name = x['market_hash_name']
178 item_price = (calc() / 40) * 100
179 item_price = int(round(item_price, 0))
180 bestOffer_status = requests.get(
181 'https://market.csgo.com/api/BestSellOffer/' + x['classid'] + '_' + x[
182 'instanceid'] + '/?key=' + f'{api}').json()['success']
183 bestOffer_price = requests.get(
184 'https://market.csgo.com/api/BestSellOffer/' + x['classid'] + '_' + x[
185 'instanceid'] + '/?key=' + f'{api}').json()['best_offer']
186
187 item = f'{item_name}' + ' по цене ' + f'{item_price / 100}' + ' rub' + ' был успешно выставлен на продажу!'
188 if int(item_price) > 1000000:
189 global avg
190 avg = 0
191 pass
192 else:
193 if bestOffer_status == True:
194 if int(bestOffer_price) > int(item_price):
195 requests.get('https://market.csgo.com/api/SetPrice/new_' + x['classid'] + '_' + x[
196 'instanceid'] + '/' + f'{bestOffer_price}' + '/?key=' + f'{api}')
197 print(
198 f'{item_name}' + ' по цене ' + f'{int(bestOffer_price) / 100}' + ' rub' + ' был успешно выставлен на продажу!')
199 avg = 0
200 else:
201 requests.get('https://market.csgo.com/api/SetPrice/new_' + x['classid'] + '_' + x[
202 'instanceid'] + '/' + f'{item_price}' + '/?key=' + f'{api}')
203 print(item)
204 avg = 0
205 except KeyError:
206 avg = 0
207 pass
208 except json.decoder.JSONDecodeError:
209 avg = 0
210 pass
211
212 except TypeError:
213 avg = 0
214 pass
215 except json.decoder.JSONDecodeError:
216 avg = 0
217 itemsOnSale()
218 except requests.exceptions.ConnectionError:
219 print('Connection refused')
220 sleep(30)
221 avg = 0
222 itemsOnSale()
223
224def price_offers():
225 global item
226 try:
227 list_items = requests.get('https://market.csgo.com/api/GetMySellOffers/?key=' + f'{api}').json()['offers']
228
229 for x in list_items:
230 name = x['i_market_hash_name']
231 start_price = int(x['ui_price']) * 100
232 classid = x['i_classid']
233 instanceid = x['i_instanceid']
234 end_price = int(start_price * 0.97)
235 end_price = round(end_price, 1)
236
237 userData = json.load((open('C:\\pytest\\position.json')))
238
239 userData["items"].append({'start_price': f'{start_price}',
240 'end_price': f'{end_price}',
241 'classid': f'{classid}',
242 'instanceid': f'{instanceid}',
243 'name': f'{name}'})
244
245 with open('C:\\pytest\\position.json', 'w') as file:
246 json.dump(userData, file, indent=4)
247 file.close()
248
249 except TypeError:
250 sleep(1)
251 price_offers()
252 except json.decoder.JSONDecodeError:
253 sleep(1)
254 price_offers()
255 except KeyError:
256 sleep(1)
257 price_offers()
258 except requests.exceptions.ConnectionError:
259 print('Connection refused')
260 sleep(30)
261 price_offers()
262
263 Thread(target=startDump).start()
264
265
266def startDump():
267 while i > 1:
268 sleep(5)
269 try:
270 ds = json.load((open('C:\\pytest\\position.json')))
271 output_data = [v for v in {inp['name']: inp for inp in ds['items']}.values()]
272 json_str = {"items": output_data}
273
274 with open('C:\\pytest\\position.json', 'w') as file:
275 json.dump(json_str, file, indent=4)
276 file.close()
277
278 dataFor_dump = json.load((open('C:\\pytest\\position.json')))['items']
279 for x in dataFor_dump:
280 try:
281 classid = x['classid']
282 instanceid = x['instanceid']
283 name = x['name']
284 end_price = x['end_price']
285
286 bestOffer = requests.get(
287 'https://market.csgo.com/api/BestSellOffer/' + f'{classid}' + '_' + f'{instanceid}' + '/?key=' + f'{api}').json()[
288 'best_offer']
289
290 if int(bestOffer) > int(end_price):
291 price = int(bestOffer) - 1
292
293 requests.get(
294 'https://market.csgo.com/api/MassSetPrice/' + f'{classid}' + '_' + f'{instanceid}' + '/' + f'{price}' + '/?key=' + f'{api}').json()
295 print('ЦЕНА НА ' + str(name) + ' ' + str(price / 100))
296 else:
297 pass
298
299 except json.decoder.JSONDecodeError:
300 startDump()
301 except KeyError:
302 pass
303 except json.decoder.JSONDecodeError:
304 sleep(10)
305 price_offers()
306
307 except requests.exceptions.ConnectionError:
308 print('Connection refused')
309 sleep(30)
310 price_offers()
311
312
313def sumItems():
314 try:
315 items = (requests.get('https://market.csgo.com/api/Trades/?key=' + f'{api}').json())
316 totalPrice = 0
317 for item in items:
318 price = item['ui_price']
319 totalPrice = int(totalPrice) + int(price)
320
321 print('На продаже: ' + str(totalPrice * 0.9) + ' рублей')
322 print('Баланс: ' + str(
323 requests.get('https://market.csgo.com/api/GetMoney/?key=' + f'{api}').json()['money'] / 100))
324 full = str(float(totalPrice * 0.9) + float(
325 requests.get('https://market.csgo.com/api/GetMoney/?key=' + f'{api}').json()['money'] / 100))
326 return full
327
328 except json.decoder.JSONDecodeError:
329 sumItems()
330
331 except requests.exceptions.ConnectionError:
332 print('Connection refused')
333 sleep(30)
334 pass
335
336
337bot_action = input(
338 '"0" - включить продажи и обновление инвентаря' + '\n'
339 + '"1" - автоматичестки выставить все предметы по минимальной цене, включить передачу и продажи' + '\n'
340 + '"2" - выставить предметы на продажу по минимальной цене' + '\n'
341 + '"3" - включить автодамп цен + продажи (beta)' + '\n'
342 + '"4" - узнать баланс предметов на продаже' + '\n'
343 + 'Что нужно сделать?: ')
344
345if bot_action == '0':
346 Thread(target=updating).start()
347
348if bot_action == '1':
349 Thread(target=updating).start()
350 Thread(target=Trades).start()
351 itemsOnSale()
352 jsonUpd = {"items": []}
353 with open('C:\\pytest\\position.json', 'w') as file:
354 json.dump(jsonUpd, file, indent=4)
355 file.close()
356
357 price_offers()
358
359if bot_action == '2':
360 itemsOnSale()
361
362if bot_action == '3':
363 steam_client = SteamClient(api)
364 steam_client.login(login, pswd, steamguard)
365 Thread(target=price_offers).start()
366 Thread(target=updating).start()
367 Thread(target=Trades).start()
368 jsonUpd = {"items": []}
369 with open('C:\\pytest\\position.json', 'w') as file:
370 json.dump(jsonUpd, file, indent=4)
371 file.close()
372
373 price_offers()
374
375if bot_action == '4':
376 print('В общем: ' + sumItems() + ' рублей')