forked from renefritze/relayhost
-
Notifications
You must be signed in to change notification settings - Fork 3
/
autohost.py
417 lines (394 loc) · 14.5 KB
/
autohost.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# -*- coding: utf-8 -*-
import commands
import thread
import signal
import os
import time
import subprocess
import platform
import sys
import traceback
import glob
if platform.system() == "Windows":
import win32api
from tasbot.utilities import *
from tasbot.plugin import IPlugin
import udpinterface
def addorreplace(scripttxt, key, value):
s1 = scripttxt.find(key + "=")
if s1 >= 0: # replace existing line
s2 = scripttxt.find(";", s1) + 1
return scripttxt.replace(scripttxt[s1:s2],"%s=%s;" % (key, value), 1)
# add new entry at top of file
index = scripttxt.find('{') + 1
return scripttxt[:index] +"\n\t%s=%s;\n" %(key, value) + scripttxt[index:]
class Main(IPlugin):
def __init__(self,name,tasclient):
IPlugin.__init__(self,name,tasclient)
self.sock = self.tasclient.socket
self.app = None
self.hosted = 0
self.battleowner = ""
self.battleid = 0
self.status = 0
self.pr = 0
self.noowner = True
self.script = ""
self.used = 0
self.hosttime = 0.0
self.redirectjoins = False
self.gamestarted = False
if platform.system() == "Windows":
self.scriptbasepath = os.environ['USERPROFILE']
else:
self.scriptbasepath = os.environ['HOME']
self.redirectspring = False
self.redirectbattleroom = False
self.users = dict()
self.logger.debug( "INIT MoTH" )
self.engineversion = ""
self.u = None
def ecb(self,event,data):
if self.redirectspring:
ags = []
data2 = ""
for c in data:
if ord(c) < 17:
ags.append(ord(c))
else:
data2 += c
self.saypm(self.battleowner,"#"+str(event)+"#".join(ags)+" "+data2)
def onloggedin(self,socket):
self.hosted = 0
self.sock = socket
def mscb(self,p,msg):
try:
if p == self.battleowner:
if msg.startswith("!"):
self.u.sayingame("/"+msg[1:])
except Exception, e:
self.logger.exception(e)
exc = traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2])
self.sayex("*** EXCEPTION: BEGIN")
for line in exc:
self.sayex(line)
self.sayex("*** EXCEPTION: END")
def killbot(self):
self.logger.info( "setting force_quit True" )
self.app.dying = True
self.u.running = False
def timeoutthread(self):
while 1:
time.sleep(20.0)
try:
if not ( not self.noowner and self.hosted == 1) and not self.gamestarted:
self.logger.error("Timeouted hosting")
self.killbot()
return
except Exception,e:
self.logger.debug('hosting timeout')
self.logger.exception(e)
def getspringded(self, enginever):
ver = os.path.basename(enginever)
res = self.app.config.get('tasbot', 'springdedpath').replace("{ENGINEVER}", ver)
if os.path.isfile(res) and os.access(res, os.X_OK):
return res
return ""
def getenginelist(self):
vers = glob.glob(self.app.config.get('tasbot', 'springdedpath').split("{ENGINEVER}")[0] + "*")
res = []
for ver in vers:
if not os.path.isdir(ver):
continue
name = os.path.basename(ver)
if not self.getspringded(name):
continue
res.append(name)
return sorted(res)
def startspring(self,socket,g):
currentworkingdir = os.getcwd()
try:
self.u.reset()
if self.gamestarted:
socket.send("SAYBATTLEEX *** Error: game is already running\n")
return
self.output = ""
socket.send("SAYBATTLEEX *** Starting game...\n")
socket.send("MYSTATUS 1\n")
st = time.time()
#status,j = commands.getstatusoutput("spring-dedicated "+os.path.join(self.scriptbasepath,"%f.txt" % g ))
springded = self.getspringded(self.engineversion)
scripttxt = os.path.join(self.scriptbasepath,"%f.txt" % g )
self.sayex('*** Starting spring: command line "%s %s"' % (springded, scripttxt))
if self.app.config.has_option('tasbot', "springdatapath"):
springdatapath = self.app.config.get('tasbot', "springdatapath")
if not springdatapath in sys.path:
sys.path.append(springdatapath)
os.chdir(springdatapath)
else:
springdatapath = None
if springdatapath!= None:
os.environ['SPRING_DATADIR'] = springdatapath
self.pr = subprocess.Popen((springded, scripttxt),stdout=subprocess.PIPE,stderr=subprocess.STDOUT,cwd=springdatapath)
self.gamestarted = True
l = self.pr.stdout.readline()
while len(l) > 0:
self.output += l
l = self.pr.stdout.readline()
status = self.pr.wait()
self.sayex("*** Spring has exited with status %i" % status )
et = time.time()
if status != 0:
socket.send("SAYBATTLEEX *** Error: Spring Exited with status %i\n" % status)
g = self.output.split("\n")
for h in g:
self.sayex("*** STDOUT+STDERR: "+h)
time.sleep(float(len(h))/900.0+0.05)
socket.send("MYSTATUS 0\n")
socket.send("SAYBATTLEEX *** Game ended\n")
except Exception,e:
exc = traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2])
self.sayex("*** EXCEPTION: BEGIN")
for line in exc:
self.sayex(line)
self.sayex("*** EXCEPTION: END")
try:
if int(self.app.config.get('autohost', "keepscript")) == 0:
os.remove(os.path.join(self.scriptbasepath,"%f.txt" % g))
except Exception,e:
self.logger.debug('failed to remove script')
os.chdir(currentworkingdir)
self.gamestarted = False
if self.noowner == True:
self.sayex("The host is no longer in the battle, exiting")
self.logger.info("Exiting")
self.killbot()
def onload(self,tasc):
try:
self.tasclient = tasc
self.app = tasc.main
self.hosttime = time.time()
self.start_thread(self.timeoutthread)
if not self.u:
self.u = udpinterface.UDPint(int(self.app.config.get('autohost', "ahport")),self.mscb,self.ecb)
except Exception, e:
self.logger.exception(e)
def oncommandfromserver(self,command,args,s):
#print "From server: %s | Args : %s" % (command,str(args))
self.sock = s
if command == "RING" and len(args) > 0:
s.send("RING " + self.app.config.get('autohost', "spawnedby") + "\n")
if command == "CLIENTBATTLESTATUS" and len(args) > 0 and self.redirectbattleroom:
self.saypm(self.app.config.get('autohost', "spawnedby"), "!" + command + " " + " ".join(args[0:]) )
if command == "SAIDBATTLE" and len(args) > 0:
if self.redirectbattleroom:
self.saypm(self.app.config.get('autohost', "spawnedby"), "!" + command + " " + " ".join(args[0:]))
if args[1].startswith("!") and args[0] == self.battleowner:
try:
msg = " ".join(args[1:])
self.u.sayingame("/"+msg[1:])
except Exception,e:
exc = traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2])
self.sayex("*** EXCEPTION: BEGIN")
for line in exc:
self.sayex(line)
if command == "SAIDBATTLEEX" and len(args) > 0 and self.redirectbattleroom:
self.saypm(self.app.config.get('autohost', "spawnedby"), "!" + command + " " + " ".join(args[0:]))
if command == "REQUESTBATTLESTATUS":
s.send( "MYBATTLESTATUS 4194816 255\n" )#spectator+synced/white
if command == "SAIDPRIVATE" and args[0] not in self.app.config.get('autohost', "bans") and args[0] == self.app.config.get('autohost', "spawnedby"):
if args[1] == "!openbattle":
if self.hosted == 1:
self.saypm(args[0],"E1 | Battle is already hosted")
return
if len(args) < 6:
self.logger.error("Got invalid openbattle with params:" + " ".join(args))
return
# last arg / first tab
engineversion = " ".join(args).split("\t")[1]
ded = self.getspringded(engineversion)
if not ded:
self.logger.error("Invalid engine version received:" + engineversion)
self.saypm(args[0], "Engine version %s isn't installed on the relayhost. Available versions are: " %(engineversion))
for ver in self.getenginelist():
self.saypm(args[0], ver)
return
self.logger.info("Using version %s for hosting" %(engineversion))
self.engineversion = engineversion
args[5] = self.app.config.get('autohost',"hostport")
self.logger.info("OPENBATTLE "+" ".join(args[2:]))
s.send("OPENBATTLE "+" ".join(args[2:])+"\n")
self.battleowner = args[0]
return
elif args[1] == "!supportscriptpassword":
self.redirectjoins = True
return
elif self.hosted == 1 and args[0] == self.battleowner:
if args[1] == "!setingamepassword":
try:
msg = " ".join(args[2:])
self.u.sayingame("/adduser "+msg)
except Exception,e:
exc = traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2])
self.sayex("*** EXCEPTION: BEGIN")
for line in exc:
self.sayex(line)
if args[1] == "!addstartrect":
s.send("ADDSTARTRECT "+" ".join(args[2:])+"\n")
if args[1] == "!setscripttags":
s.send("SETSCRIPTTAGS "+" ".join(args[2:])+"\n")
if args[1] == "!removestartrect":
s.send("REMOVESTARTRECT "+" ".join(args[2:])+"\n")
if args[1] == "!leavebattle":
s.send("LEAVEBATTLE\n")
self.hosted = 0
if args[1] == "!updatebattleinfo":
s.send("UPDATEBATTLEINFO "+" ".join(args[2:])+"\n")
if args[1] == "!kickfrombattle":
s.send("KICKFROMBATTLE "+" ".join(args[2:])+"\n")
if args[1] == "!addbot":
s.send("ADDBOT "+" ".join(args[2:])+"\n")
if args[1] == "!handicap":
s.send("HANDICAP "+" ".join(args[2:])+"\n")
if args[1] == "!forceteamcolor":
s.send("FORCETEAMCOLOR "+" ".join(args[2:])+"\n")
if args[1] == "!forceallyno":
s.send("FORCEALLYNO "+" ".join(args[2:])+"\n")
if args[1] == "!forceteamno":
s.send("FORCETEAMNO "+" ".join(args[2:])+"\n")
if args[1] == "!disableunits":
s.send("DISABLEUNITS "+" ".join(args[2:])+"\n")
if args[1] == "!enableallunits":
s.send("ENABLEALLUNITS "+" ".join(args[2:])+"\n")
if args[1] == "!removebot":
s.send("REMOVEBOT "+" ".join(args[2:])+"\n")
if args[1] == "!updatebot":
s.send("UPDATEBOT "+" ".join(args[2:])+"\n")
if args[1] == "!ring":
s.send("RING "+" ".join(args[2:])+"\n")
if args[1] == "!forcespectatormode":
s.send("FORCESPECTATORMODE "+" ".join(args[2:])+"\n")
if args[1] == "!redirectspring" and len(args) > 1:
try:
if ( self.tasclient.users[self.battleowner].bot ):
self.redirectspring = bool(args[2])
except Exception,e:
exc = traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2])
self.sayex("*** EXCEPTION: BEGIN")
for line in exc:
self.sayex(line)
self.sayex("*** EXCEPTION: END")
if args[1] == "!redirectbattleroom"and len(args) > 1:
try:
if ( self.tasclient.users[self.battleowner].bot ):
self.redirectbattleroom = bool(args[2])
except Exception,e:
exc = traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2])
self.sayex("*** EXCEPTION: BEGIN")
for line in exc:
self.sayex(line)
self.sayex("*** EXCEPTION: END")
if args[1] == "!cleanscript":
self.script = ""
if args[1] == "!appendscriptline":
self.script += " ".join(args[2:])+"\n"
if args[1].startswith("#") and args[0] == self.battleowner:
try:
msg = " ".join(args[1:])
self.u.sayingame(msg[1:])
except Exception,e:
exc = traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2])
self.sayex("*** EXCEPTION: BEGIN")
for line in exc:
self.sayex(line)
if args[1] == "!saybattle":
s.send("SAYBATTLE "+" ".join(args[2:])+"\n")
if args[1] == "!saybattleex":
s.send("SAYBATTLEEX "+" ".join(args[2:])+"\n")
if args[1] == "!startgame":
if not self.gamestarted:
s.send("MYSTATUS 1\n")
g = time.time()
try:
os.remove(os.path.join(self.scriptbasepath,"%f.txt" % g))
except Exception,e:
pass
f = open(os.path.join(self.scriptbasepath,"%f.txt" % g),"a")
self.script = addorreplace(self.script, "HostPort", self.app.config.get('autohost', 'hostport'))
self.script = addorreplace(self.script, "MyPlayerName", self.app.config.get('tasbot', "nick"))
self.script = addorreplace(self.script, "AutoHostPort", self.app.config.get('autohost', "ahport"))
if self.app.config.has_option('autohost', "bindip"):
self.script = addorreplace(self.script,"HostIP", self.app.config.get('autohost', "bindip"))
f.write(self.script)
f.close()
thread.start_new_thread(self.startspring,(s,g))
else:
self.saypm(args[0],"E3 | Battle already started")
else:
self.saypm(args[0],"E2 | Battle is not hosted")
if command == "OPENBATTLE":
self.battleid = int(args[0])
self.used = 1
self.sayex("Battle hosted succesfully , id is %s" % args[0])
if command == "JOINEDBATTLE" and len(args) >= 2 and int(args[0]) == self.battleid:
if args[1] == self.battleowner:
self.hosted = 1
self.noowner = False
self.sayex("The host has joined the battle")
s.send("SAYBATTLE Hello, the bot accepts all commands from normal spring prefixed with ! instead of /\n")
s.send("SAYBATTLE read Documentation/cmds.txt for a list of spring commands\n")
s.send("SAYBATTLE in order to stop a game immediately, use !kill\n")
if self.redirectjoins:
self.saypm(self.battleowner,command + " " + " ".join(args[0:])) # redirect the join command to the owner so he can manage script password
if command == "SERVERMSG":
self.saypm(self.battleowner," ".join(args))
if command == "LEFTBATTLE" and int(args[0]) == self.battleid and args[1] == self.battleowner:
if not self.gamestarted:
self.sayex("The host has left the battle and the game isn't running, exiting")
s.send("LEAVEBATTLE\n")
try:
if platform.system() == "Windows":
handle = win32api.OpenProcess(1, 0, self.pr.pid)
win32api.TerminateProcess(handle, 0)
else:
os.kill(self.pr.pid,signal.SIGKILL)
except Exception,e:
pass
self.killbot()
self.noowner = True
if command == "REMOVEUSER" and args[0] == self.battleowner:
if not self.gamestarted:
self.sayex("The host disconnected and game not started, exiting")
try:
if platform.system() == "Windows":
handle = win32api.OpenProcess(1, 0, self.pr.pid)
win32api.TerminateProcess(handle, 0)
else:
os.kill(self.pr.pid,signal.SIGKILL)
except Exception,e:
pass
self.killbot()
self.noowner = True
def onloggedin(self,socket):
self.noowner = True
self.hosted = 0
if self.gamestarted:
socket.send("MYSTATUS 1\n")
def saypm(self,p,m):
try:
self.logger.debug("PM To:%s, Message: %s" %(p,m))
self.tasclient.socket.send("SAYPRIVATE %s %s\n" %(p,m))
except Exception, e:
self.logger.exception(e)
def say(self,m):
try:
self.logger.debug("SAY autohost %s\n" % m)
self.tasclient.socket.send("SAY autohost %s\n" % m)
except Exception, e:
self.logger.exception(e)
def sayex(self,m):
try:
self.logger.debug("SAYEX autohost %s\n" % m)
self.tasclient.socket.send("SAYEX autohost %s\n" % m)
except Exception, e:
self.logger.exception(e)