· 5 years ago · May 12, 2020, 11:28 AM
1import requests
2import json
3from time import sleep
4from threading import Thread
5from steampy.client import SteamClient
6
7api = ''
8api2 = ''
9i = 2
10avg = 0
11# Set steam API key
12api_key = ''
13# Set path to SteamGuard file
14steamguard_path = 'C:/pytest/3/maFiles/.maFile'
15# Steam username
16username = ''
17# Steam password
18password = ''
19
20
21def trades(): # Проверка на наличие трейдов
22 Checking_trades()
23
24
25def Checking_trades():
26 while i > 1:
27 sleep(5)
28 try:
29 sleep(5)
30 a = requests.get('https://market.csgo.com/api/v2/trade-request-give-p2p-all?key=' + f'{api}').json()
31 userData = json.load((open('C:\\pytest\\itemPosition.json')))
32 userData.update(a)
33 with open('C:\\pytest\\itemPosition.json', 'w') as file:
34 json.dump(userData, file, indent=4)
35 file.close()
36 if a['success'] == False:
37 sleep(10)
38 print('Офферов пока нету, ждем когда что-то появится...')
39 elif a['success'] == True:
40 b = requests.get('https://market.csgo.com/api/ItemRequest/in/1/?key=' + f'{api}').json()
41 print('Создал запрос на передачу! Ждем пока sda подтвердит...')
42
43
44
45
46 except json.decoder.JSONDecodeError:
47 print('Ошибка при проверке трейд офферов. Возможно лагают сервера тма или стима')
48 sleep(10)
49 Checking_trades()
50
51
52def updating():
53 try:
54 i = 2
55 while i > 1: # Обновление ивентаря и включение продаж каждые 3 минуты
56 inventUpdate()
57 ping()
58 sleep(160)
59 except json.decoder.JSONDecodeError:
60 print('Вылезла ошибка! Отдыхаю 15 секунд')
61 sleep(15)
62 Thread(target=updating).start()
63
64
65def ping():
66 status = requests.get('https://market.csgo.com/api/v2/ping?key=' + f'{api2}')
67 status2 = status.json()
68 if status2['success'] == True:
69 print('Продажи были успешно включены!')
70
71 elif status2['success'] == False and status2['message'] == 'too early for pong':
72 print('Продажи и так были включены')
73
74 else:
75 print('Ошибка включения продаж! Попробую еще раз через 160 секунд...')
76
77
78def inventUpdate():
79 status = requests.get('https://market.csgo.com/api/v2/update-inventory/?key=' + f'{api2}').json()
80 if status['success'] == True:
81 print('Инвентарь был успешно обновлен!')
82 elif status['success'] == False:
83 print('Ошибка обновления инвентаря! Попробую еще раз через 160 секунд...')
84
85
86def itemsOnSale():
87 try:
88 items_sale = requests.get('https://market.csgo.com/api/v2/my-inventory/?key=' + f'{api}').json() ####ОШИБКА
89 for x in items_sale['items']:
90 try:
91 hashed_name = x['market_hash_name']
92 try:
93 history = requests.get(
94 'https://market.csgo.com/api/v2/get-list-items-info?key=' + f'{api}' + '&list_hash_name[]=' + f'{hashed_name}').json()[
95 'data'][hashed_name]['history']
96 except json.decoder.JSONDecodeError:
97 print('Тм лагает, попробуем позже...')
98 itemsOnSale()
99
100 def calc():
101 global avg
102 try:
103 for x in history[:40]:
104 avg = avg + x[1]
105 avg = round(avg, 0)
106 return avg
107 except NameError:
108 print('ТМ лагает!')
109 itemsOnSale()
110
111 try:
112 item_name = x['market_hash_name']
113 item_price = (calc() / 40) * 100
114 item_price = int(round(item_price, 0))
115 bestOffer_status = requests.get(
116 'https://market.csgo.com/api/BestSellOffer/' + x['classid'] + '_' + x[
117 'instanceid'] + '/?key=' + f'{api}').json()['success']
118 bestOffer_price = requests.get(
119 'https://market.csgo.com/api/BestSellOffer/' + x['classid'] + '_' + x[
120 'instanceid'] + '/?key=' + f'{api}').json()['best_offer']
121
122 item = f'{item_name}' + ' по цене ' + f'{item_price / 100}' + ' rub' + ' был успешно выставлен на продажу!'
123 if int(item_price) > 1000000:
124 global avg
125 avg = 0
126 pass
127 else:
128 if bestOffer_status == True:
129 if int(bestOffer_price) > int(item_price):
130 requests.get('https://market.csgo.com/api/SetPrice/new_' + x['classid'] + '_' + x[
131 'instanceid'] + '/' + f'{bestOffer_price}' + '/?key=' + f'{api}')
132 print(
133 f'{item_name}' + ' по цене ' + f'{int(bestOffer_price) / 100}' + ' rub' + ' был успешно выставлен на продажу!')
134 avg = 0
135 else:
136 requests.get('https://market.csgo.com/api/SetPrice/new_' + x['classid'] + '_' + x[
137 'instanceid'] + '/' + f'{item_price}' + '/?key=' + f'{api}')
138 print(item)
139 avg = 0
140 except KeyError:
141 avg = 0
142 pass
143 except json.decoder.JSONDecodeError:
144 avg = 0
145 pass
146
147 except TypeError:
148 avg = 0
149 pass
150 except json.decoder.JSONDecodeError:
151 avg = 0
152 itemsOnSale()
153
154
155
156def price_offers():
157 global item
158 try:
159 list_items = requests.get('https://market.csgo.com/api/GetMySellOffers/?key=' + f'{api}').json()['offers']
160
161 for x in list_items:
162 name = x['i_market_hash_name']
163 start_price = int(x['ui_price']) * 100
164 classid = x['i_classid']
165 instanceid = x['i_instanceid']
166 end_price = int(start_price * 0.97)
167 end_price = round(end_price, 1)
168
169 userData = json.load((open('C:\\pytest\\position.json')))
170
171 userData["items"].append({'start_price': f'{start_price}',
172 'end_price': f'{end_price}',
173 'classid': f'{classid}',
174 'instanceid': f'{instanceid}',
175 'name': f'{name}'})
176
177 with open('C:\\pytest\\position.json', 'w') as file:
178 json.dump(userData, file, indent=4)
179 file.close()
180
181 except TypeError:
182 sleep(1)
183 price_offers()
184 except json.decoder.JSONDecodeError:
185 sleep(1)
186 price_offers()
187 except KeyError:
188 sleep(1)
189 price_offers()
190
191 Thread(target=startDump).start()
192
193
194
195def startDump():
196 while i > 1:
197 ds = json.load((open('C:\\pytest\\position.json')))
198 output_data = [v for v in {inp['name']: inp for inp in ds['items']}.values()]
199 json_str = {"items": output_data}
200
201 with open('C:\\pytest\\position.json', 'w') as file:
202 json.dump(json_str, file, indent=4)
203 file.close()
204
205 dataFor_dump = json.load((open('C:\\pytest\\position.json')))['items']
206 for x in dataFor_dump:
207 try:
208 classid = x['classid']
209 instanceid = x['instanceid']
210 name = x['name']
211 end_price = x['end_price']
212
213 bestOffer = requests.get(
214 'https://market.csgo.com/api/BestSellOffer/' + f'{classid}' + '_' + f'{instanceid}' + '/?key=' + f'{api}').json()[
215 'best_offer']
216
217 if int(bestOffer) > int(end_price):
218 price = int(bestOffer) - 1
219
220 requests.get(
221 'https://market.csgo.com/api/MassSetPrice/' + f'{classid}' + '_' + f'{instanceid}' + '/' + f'{price}' + '/?key=' + f'{api}').json()
222 print('ЦЕНА НА ' + str(name) + ' ' + str(price / 100))
223 else:
224 pass
225
226 except json.decoder.JSONDecodeError:
227 startDump()
228 except KeyError:
229 pass
230
231
232def sumItems():
233 try:
234 items = (requests.get('https://market.csgo.com/api/Trades/?key=' + f'{api}').json())
235 totalPrice = 0
236 for item in items:
237 price = item['ui_price']
238 totalPrice = int(totalPrice) + int(price)
239
240 print('На продаже: ' + str(totalPrice * 0.9) + ' рублей')
241 print('Баланс: ' + str(
242 requests.get('https://market.csgo.com/api/GetMoney/?key=' + f'{api}').json()['money'] / 100))
243 full = str(float(totalPrice * 0.9) + float(
244 requests.get('https://market.csgo.com/api/GetMoney/?key=' + f'{api}').json()['money'] / 100))
245 return full
246 except json.decoder.JSONDecodeError:
247 sumItems()
248
249
250bot_action = input(
251 '"0" - включить продажи и обновление инвентаря' + '\n'
252 + '"1" - автоматичестки выставить все предметы по минимальной цене, включить передачу и продажи' + '\n'
253 + '"2" - выставить предметы на продажу по минимальной цене' + '\n'
254 + '"3" - включить автодамп цен + продажи (beta)' + '\n'
255 + '"4" - узнать баланс предметов на продаже' + '\n'
256 + 'Что нужно сделать?: ')
257
258if bot_action == '0':
259 Thread(target=updating).start()
260
261
262
263if bot_action == '1':
264 Thread(target=updating).start()
265 Thread(target=trades).start()
266 itemsOnSale()
267 jsonUpd = {"items": []}
268 with open('C:\\pytest\\position.json', 'w') as file:
269 json.dump(jsonUpd, file, indent=4)
270 file.close()
271
272 price_offers()
273
274if bot_action == '2':
275 itemsOnSale()
276
277if bot_action == '3':
278 Thread(target=price_offers).start()
279 Thread(target=updating).start()
280 Thread(target=trades).start()
281 jsonUpd = {"items": []}
282 with open('C:\\pytest\\position.json', 'w') as file:
283 json.dump(jsonUpd, file, indent=4)
284 file.close()
285
286 price_offers()
287
288if bot_action == '4':
289 print('В общем: ' + sumItems() + ' рублей')