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