-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathscreepsapi.py
366 lines (263 loc) · 11.7 KB
/
screepsapi.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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# Copyright @dzhu, @tedivm
# https://gist.github.com/dzhu/d6999d126d0182973b5c
from __future__ import print_function
from base64 import b64decode
from collections import OrderedDict
from io import StringIO
from gzip import GzipFile
import json
import logging
import requests
import ssl
import websocket
import zlib
## Python before 2.7.10 or so has somewhat broken SSL support that throws a warning; suppress it
import warnings; warnings.filterwarnings('ignore', message='.*true sslcontext object.*')
class API(object):
def req(self, func, path, **args):
r = func(self.prefix + path, headers={'X-Token': self.token, 'X-Username': self.token}, **args)
r.raise_for_status()
if 'X-Token' in r.headers and len(r.headers['X-Token']) >= 40:
self.token = r.headers['X-Token']
try:
return json.loads(r.text, object_pairs_hook=OrderedDict)
except ValueError:
print('JSON failure: %s' % r.text)
return None
def get(self, _path, **args): return self.req(requests.get, _path, params=args)
def post(self, _path, **args): return self.req(requests.post, _path, json=args)
def __init__(self, u=None, p=None, ptr=False, host=None, secure=False):
self.ptr = ptr
self.host = host
self.secure = secure
if host is not None:
self.prefix = 'https://' if secure else 'http://'
self.prefix += host + '/api/'
else:
self.prefix = 'https://screeps.com/ptr/api/' if ptr else 'https://screeps.com/api/'
self.token = None
if u is not None and p is not None:
self.token = self.post('auth/signin', email=u, password=p)['token']
#### miscellaneous user methods
def me(self):
return self.get('auth/me')
def overview(self, interval=8, statName='energyHarvested'):
return self.get('user/overview', interval=interval, statName=statName)
def stats(self,id,interval=8):
return self.get('user/stats',id=id,interval=interval)
def user_find(self, username=None, user_id=None, shard='shard0'):
if username is not None:
return self.get('user/find', username=username, shard=shard)
if user_id is not None:
return self.get('user/find', id=user_id, shard=shard)
return False
def user_rooms(self, userid, shard='shard0'):
return self.get('user/rooms', id=userid, shard=shard)
def memory(self, path='', shard='shard0'):
ret = self.get('user/memory', path=path, shard=shard)
if 'data' in ret:
ret['data'] = json.load(GzipFile(fileobj=StringIO(b64decode(ret['data'][3:]))))
return ret
def set_memory(self, path, value, shard='shard0'):
return self.post('user/memory', path=path, value=value, shard=shard)
def get_segment(self, segment, shard='shard0'):
return self.get('user/memory-segment', segment=segment, shard=shard)
def set_segment(self, segment, data, shard='shard0'):
return self.post('user/memory-segment', segment=segment, data=data, shard=shard)
def console(self, cmd, shard='shard0'):
return self.post('user/console', expression=cmd, shard=shard)
#### room info methods
def room_overview(self, room, interval=8, shard='shard0'):
return self.get('game/room-overview', interval=interval, room=room, shard=shard)
def room_terrain(self, room, encoded=False, shard='shard0'):
return self.get('game/room-terrain', room=room, shard=shard, encoded=('1' if encoded else None))
def room_status(self, room, shard='shard0'):
return self.get('game/room-status', room=room, shard=shard)
#### market info methods
def orders_index(self, shard='shard0'):
return self.get('game/market/orders-index', shard=shard)
def my_orders(self, shard='shard0'):
return self.get('game/market/my-orders', shard=shard)
def market_order_by_type(self, resourceType, shard='shard0'):
return self.get('game/market/orders', resourceType=resourceType, shard=shard)
def market_history(self, page=None, shard='shard0'):
return self.get('user/money-history', page=page, shard=shard)
#### leaderboard methods
## omit season to get current season
def board_list(self, limit=10, offset=0, season=None, mode='world'):
if season is None:
## find current season (the one with max start time among all seasons)
seasons = self.board_seasons['seasons']
season = max(seasons, key=lambda s: s['date'])['_id']
ret = self.get('leaderboard/list', limit=limit, offset=offset, mode=mode, season=season)
for d in ret['list']:
d['username'] = ret['users'][d['user']]['username']
return ret
## omit season to get all seasons
def board_find(self, username, season=None, mode='world'):
return self.get('leaderboard/find', mode=mode, season=season, username=username)
def board_seasons(self):
return self.get('leaderboard/seasons')
#### messaging methods
def msg_index(self):
return self.get('user/messages/index')
def msg_list(self, respondent):
return self.get('user/messages/list', respondent=respondent)
def msg_send(self, respondent, text):
return self.post('user/messages/send', respondent=respondent, text=text)
#### world manipulation methods
def gen_unique_name(self, type):
return self.post('game/gen-unique-object-name', type=type)
def flag_create(self, room, x, y, name=None, color='white', secondaryColor=None):
if name is None:
name = self.gen_unique_name('flag')['name']
if secondaryColor is None:
secondaryColor = color
return self.post('game/create-flag', room=room, x=x, y=y, name=name, color=color, secondaryColor=secondaryColor)
def flag_change_pos(self, _id, room, x, y):
return self.post('game/change-flag', _id=_id, room=room, x=x, y=y)
def flag_change_color(self, _id, color, secondaryColor=None):
if secondaryColor is None:
secondaryColor = color
return self.post('game/change-flag-color', _id=_id, color=color, secondaryColor=secondaryColor)
def create_site(self, typ, room, x, y):
return self.post('game/create-construction', structureType=typ, room=room, x=x, y=y)
#### battle info methods
def battles(self, interval=None, start=None):
if start is not None:
return self.get('experimental/pvp', start=start)
if interval is not None:
return self.get('experimental/pvp', interval=interval)
return False
def nukes(self):
return self.get('experimental/nukes')
#### other methods
def time(self, shard='shard0'):
return self.get('game/time', shard=shard)['time']
def map_stats(self, rooms, statName, shard='shard0'):
return self.post('game/map-stats', rooms=rooms, statName=statName, shard=shard)
def worldsize(self, shard='shard0'):
return self.get('game/world-size', shard=shard)
def history(self, room, tick):
return self.get('../room-history/%s/%s.json' % (room, tick - (tick % 20)))
def get_shards(self):
try:
shard_data = self.shard_info()['shards']
shards = [x['name'] for x in shard_data]
if len(shards) > 0:
return shards
except:
pass
return False
def shard_info(self):
return self.get('game/shards/info')
def activate_ptr(self):
if self.ptr:
return self.post('user/activate-ptr')
class Socket(object):
def __init__(self, user, password, ptr=False, logging=False, host=None, secure=None):
self.settings = {}
self.user = user
self.password = password
self.ptr = ptr
self.host = host
self.secure = secure
self.logging = False
self.token = None
self.user_id = None
def on_error(self, ws, error):
print(error)
def on_close(self, ws):
self.disconnect()
def on_open(self, ws):
assert self.token != None
ws.send('gzip on')
ws.send('auth ' + self.token)
self.token = None
def gzip(enable):
if enable:
ws.send('gzip on')
else:
ws.send('gzip off')
def subscribe_user(self, watchpoint):
self.subscribe('user:' + self.user_id + '/' + watchpoint)
def subscribe(self, watchpoint):
self.ws.send('subscribe ' + watchpoint)
def set_subscriptions(self):
pass
def process_log(self, ws, message):
pass
def process_results(self, ws, message):
pass
def process_error(self, ws, message):
pass
def process_cpu(self, ws, data):
pass
def process_rawdata(self, ws, data):
pass
def on_message(self, ws, message):
if (message.startswith('auth ok')):
self.set_subscriptions()
return
if (message.startswith('time')):
return
if (message.startswith('gz')):
message = zlib.decompress(b64decode(message[3:]), 0)
try:
self.process_message(ws, message)
return
except AttributeError:
try:
data = json.loads(message)
except:
return
if data[0].endswith('console'):
if 'messages' in data[1]:
stream = []
if 'log' in data[1]['messages']:
for line in data[1]['messages']['log']:
self.process_log(ws, line)
if 'results' in data[1]['messages']:
for line in data[1]['messages']['results']:
self.process_results(ws, line)
if 'error' in data[1]:
self.process_error(ws, data[1]['error'])
if data[0].endswith('cpu'):
self.process_cpu(ws, data[1])
self.process_rawdata(ws, data)
def connect(self):
screepsConnection = API(u=self.user,p=self.password,ptr=self.ptr,host=self.host,secure=self.secure)
me = screepsConnection.me()
self.user_id = me['_id']
self.token = screepsConnection.token
if self.logging:
logging.getLogger('websocket').addHandler(logging.StreamHandler())
websocket.enableTrace(True)
else:
logging.getLogger('websocket').addHandler(logging.NullHandler())
websocket.enableTrace(False)
if self.host:
url = 'wss://' if self.secure else 'ws://'
url += self.host + '/socket/websocket'
elif not self.ptr:
url = 'wss://screeps.com/socket/websocket'
else:
url = 'wss://screeps.com/ptr/socket/websocket'
self.ws = websocket.WebSocketApp(url=url,
on_message=self.on_message,
on_error=self.on_error,
on_close=self.on_close,
on_open=self.on_open)
ssl_defaults = ssl.get_default_verify_paths()
sslopt_ca_certs = {'ca_certs': ssl_defaults.cafile}
if 'http_proxy' in self.settings and self.settings['http_proxy'] is not None:
http_proxy_port = self.settings['http_proxy_port'] if 'http_proxy_port' in self.settings else 8080
self.ws.run_forever(http_proxy_host=self.settings['http_proxy'], http_proxy_port=http_proxy_port, ping_interval=1, sslopt=sslopt_ca_certs)
else:
self.ws.run_forever(ping_interval=1, sslopt=sslopt_ca_certs)
def disconnect(self):
if self.ws:
self.ws.close()
self.ws = False
def start(self):
self.connect()