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