-
Notifications
You must be signed in to change notification settings - Fork 2
/
SteamTradeOffers.py
170 lines (162 loc) · 6.88 KB
/
SteamTradeOffers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
from SteamLogin import SteamLogin
from SteamExceptions import ReceiptFailed
from utils import ignoreConnectionErrors
from SteamInventory import Inventory, Item
from urlparse import urlparse, parse_qs
import re, json
class Offer(object):
def __init__(self,Login,**kwargs):
assert isinstance(Login, SteamLogin), str(Login) + " is not an instance of SteamLogin"
self.Login = Login
self.request = Login.request
self.MySteamID = Login.steamID
self.myAssets = []
self.theirAssets = []
self.tradeMessage = ""
self.tradeURL = kwargs.get('tradeURL')
self.offerID = None
if self.tradeURL is not None:
self.newOffer(self.tradeURL)
else:
raise Exception("Empty TradeOffer")
self.sent = False
for x in self.request.cookies:
if x.name == 'sessionid':
self.sessionid = x.value
break
else:
raise Exception("Sessionid is missing from Login cookies")
@ignoreConnectionErrors
def newOffer(self,tradeURL):
self.tradeURL = tradeURL
o = urlparse(tradeURL)
try:
assert o.scheme == 'https'
assert o.netloc == 'steamcommunity.com'
assert o.path == '/tradeoffer/new/'
q = parse_qs(o.query)
assert 'partner' in q.keys()
assert 'token' in q.keys()
self.partner = q['partner'][0]
self.token = q['token'][0]
except AssertionError:
print("Invalid TradeURL")
raise TradeURLInvalid
tradeURLResponse = self.request.get(tradeURL)
self.tradeURLResponse = tradeURLResponse
if tradeURLResponse.status_code != 200:
print tradeURLResponse.text
raise Exception("Server Error" + str(tradeURLResponse.status_code))
text = tradeURLResponse.text
try:
self.MyContexts = json.loads(re.search(r"var g_rgAppContextData = ([\s\"\\\/\-\w\d\{\}\[\]\:\.\,\'\_\&]+);",text).group(1))
self.PartnerContexts = json.loads(re.search(r"var g_rgPartnerAppContextData = ([\s\"\\\/\-\w\d\{\}\[\]\:\.\,\'\_\&]+);",text).group(1))
self.PartnerSteamID = long(re.search(r"UserThem\.SetSteamId\( \'(\d+)\' \);",text).group(1))
self.OurEscrow = int(re.search(r"var g_daysMyEscrow = (\d+);",text).group(1))
self.TheirEscrow = int(re.search(r"var g_daysTheirEscrow = (\d+);",text).group(1))
except AttributeError:
from bs4 import BeautifulSoup
import pdb
soup = BeautifulSoup(text,'html.parser')
error_msg = soup.find(id="error_msg")
error = error_msg.text.strip() if error_msg is not None else "Malformed Response"
raise TradeOfferException(error)
@ignoreConnectionErrors
def loadPartnerInventory(self,appID,contextID):
sessionid = self.sessionid
url = "https://steamcommunity.com/tradeoffer/new/partnerinventory"
parameters = {
"sessionid":sessionid,
"partner":self.PartnerSteamID,
"appid":appID,
"contextid":contextID,
}
self.request.headers['Referer'] = self.tradeURL
data = self.request.get(url,params=parameters).json()
self.PartnerInventory = Inventory(self.Login,steamID=self.PartnerSteamID)
self.PartnerInventory.createItemsFromResponse(appID,contextID,data)
@ignoreConnectionErrors
def loadOurInventory(self,appID,contextID):
self.request.headers['Referer'] = self.tradeURL
self.MyInventory = Inventory(self.Login,steamID=self.MySteamID)
self.MyInventory.getInventory(appID,contextID)
def addOurItem(self,item):
assert isinstance(item,Item)
self.myAssets.append(item)
def addTheirItem(self,item):
assert isinstance(item,Item)
self.theirAssets.append(item)
def _get_json_tradeoffer(self):
payload = {
'newversion':True,
'version':2,
'me':{
'assets':[],
'currency':[],
'ready':False,
},
'them':{
'assets':[],
'currency':[],
'ready':False,
},
'captcha':"",
}
for x in self.myAssets:
asset = {}
asset['appid'] = str(x.appid)
asset['contextid'] = str(x.contextid)
asset['amount'] = x.amount
asset['assetid'] = str(x.itemid)
payload['me']['assets'].append(asset)
for x in self.theirAssets:
asset = {}
asset['appid'] = str(x.appid)
asset['contextid'] = str(x.contextid)
asset['amount'] = x.amount
asset['assetid'] = str(x.itemid)
payload['them']['assets'].append(asset)
return json.dumps(payload,separators=(',',':'))
def _get_trade_offer_create_params(self):
payload = {
'trade_offer_access_token':self.token,
}
return json.dumps(payload,separators=(',',':'))
@ignoreConnectionErrors
def sendOffer(self):
if self.offerID is not None:
raise OfferAlreadySent("This offer has been already sent")
self.request.headers['Referer'] = self.tradeURL
tradedata = {
'sessionid':self.sessionid,
'serverid':1,
'partner':str(self.PartnerSteamID),
'tradeoffermessage':self.tradeMessage,
'json_tradeoffer':self._get_json_tradeoffer(),
'trade_offer_create_params':self._get_trade_offer_create_params(),
}
url = "https://steamcommunity.com/tradeoffer/new/send"
self.sendOfferResponse = self.request.post(url,data=tradedata)
offerdata = self.sendOfferResponse.json()
self.offerID, self.needsMobileConfirmation, self.needEmailConfirmation, self.email_domain = (offerdata.get('tradeofferid'),
offerdata.get('needs_mobile_confirmation'), offerdata.get('needs_email_confirmation'), offerdata.get('email_domain'))
class Receipt(object):
@ignoreConnectionErrors(echo=True)
def __init__(self,Login,tradeID):
assert isinstance(Login,SteamLogin)
url = "".join(["http://steamcommunity.com/trade/",str(tradeID),"/receipt/"])
self.response = Login.request.get(url)
try:
data = json.loads(self.response.text)
if data['success'] == False:
raise ReceiptFailed
except ValueError:
pass
self.item = json.loads(re.search(r"oItem = ([\s\"\\\/\-\w\d\{\}\[\]\:\.\,\'\_\|\(\)]+);",self.response.text).group(1))
self.__dict__.update(self.item)
class TradeOfferException(Exception):
pass
class TradeURLInvalid(Exception):
pass
class OfferAlreadySent(Exception):
pass