Advertisement
Guest User

Untitled

a guest
Aug 27th, 2016
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.66 KB | None | 0 0
  1. import telnetlib, thread
  2. from threading import Lock
  3.  
  4. class TeamSpeak:
  5. def __init__(self, host='localhost', port=10011):
  6. self.host = host
  7. self.port = port
  8. self.__ioLock = Lock()
  9. self.listenThread = None
  10. self.encoding = {
  11. "\\":"\\\\", "/":"\\/",
  12. " ":"\\s", "|":"\\p",
  13. "\a":"\\a", "\b":"\\b",
  14. "\f":"\\f", "\n":"\\n",
  15. "\r":"\\r", "\t":"\\t",
  16. "\v":"\\v"
  17. }
  18. def connected(self):
  19. try:
  20. self.connection.write('\n\r')
  21. return True
  22. except:
  23. return False
  24.  
  25. def decode(self, result):
  26. """
  27. Decodes the result
  28. """
  29. if '|' in result:
  30. decodable = result.split('|')
  31. decoded = []
  32. for d in decodable:
  33. decoded.append(self.__decodeSingle(d))
  34. return decoded
  35. return self.__decodeSingle(result)
  36.  
  37. def __decodeSingle(self, result):
  38. decodable = result.split()
  39. decoded = {}
  40. for decodeme in decodable:
  41. expl = decodeme.split('=',1)
  42. if len(expl) != 2:
  43. decoded[decodeme]=''
  44. continue
  45. for o,r in self.encoding.iteritems():
  46. expl[0] = expl[0].replace(r,o)
  47. expl[1] = expl[1].replace(r,o)
  48. decoded[expl[0]]=expl[1]
  49. return decoded
  50.  
  51. def encode(self, args={}):
  52. """
  53. Encodes the arguments
  54. """
  55. if isinstance(args,int): args = str(args)
  56. if isinstance(args,str):
  57. for r,o in self.encoding.iteritems():
  58. args = args.replace(r,o)
  59. return args
  60. encoded = ''
  61. for k,v in args.iteritems():
  62. if not isinstance(v,int):
  63. for r,o in self.encoding.iteritems():
  64. v = v.replace(r,o)
  65. encoded += ' '+k
  66. if v != '': encoded += '='+v
  67. else:
  68. encoded += ' '+k+'='+str(v)
  69. return encoded.strip()
  70.  
  71. def sendCommand(self, command, preRead=0, postRead=0):
  72. """
  73. Send a command to the server and receive the output
  74. """
  75. if not self.connected():
  76. raise Exception('Not connected to a TeamSpeak server')
  77. self.__ioLock.acquire()
  78. self.connection.write(command+'\n\r')
  79. for i in range(preRead): self.connection.read_until("\n\r", 5)
  80. data = self.connection.read_until('\n\r',5)
  81. for i in range(postRead): self.connection.read_until("\n\r", 5)
  82. self.__ioLock.release()
  83. return data
  84.  
  85. def registerEvent(self, **args):
  86. """
  87. Creates a listener that will be destroyed once the callback returns false
  88. Make sure that the permissions are set properly
  89.  
  90. The username and password must be set if used becuase the listener session has to log in again if the server disconnects the client
  91. """
  92. # Parse ALL the arguments!
  93. # Todo: clean this shit up
  94. callback = None
  95. event='textchannel'
  96. cid=None
  97. username=None
  98. password=None
  99.  
  100. if args.has_key("event") and isinstance(args['event'],str): event = args['event']
  101. elif args.has_key("event") and not isinstance(args['event'],str): raise Exception('Event is not a string')
  102.  
  103. if args.has_key("callback") and hasattr(args['callback'], '__call__'): callback = args['callback']
  104. elif args.has_key("callback") and not hasattr(args['callback'], '__call__'): raise Exception('callback is not a function')
  105.  
  106. if args.has_key("channel") and isinstance(args['channel'],int): cid = args['channel']
  107. elif args.has_key("channel") and not isinstance(args['channel'],int): raise Exception('channel is not a integer')
  108.  
  109. if args.has_key("username") and isinstance(args['username'],str): username = args['username']
  110. elif args.has_key("username") and not isinstance(args['username'],str): raise Exception('username is not a string')
  111.  
  112. if args.has_key("password") and isinstance(args['password'],str): username = args['password']
  113. elif args.has_key("password") and not isinstance(args['password'],str): raise Exception('password is not a string')
  114.  
  115. if not self.connected(): raise Exception('Not connected to a TeamSpeak server')
  116. self.callback = callback
  117. if username != None and password != None:
  118. data = self.decode(self.sendCommand('login '+encode(username)+' '+encode(password)))
  119. if data['id'] != '0':
  120. raise Exception('Login refused')
  121. if not cid==None:
  122. whoami = self.decode(self.sendCommand('whoami',1,1))
  123. data = self.decode(self.sendCommand('clientmove '+self.encode({'clid':whoami['client_id'],'cid': cid})))
  124. if data['id'] != '0' and data['id'] != '770':
  125. raise Exception('Could not move client: '+data['msg'])
  126. command = 'servernotifyregister ' + self.encode({'event':event})
  127. if not cid==None:
  128. command = 'servernotifyregister ' + self.encode({'event':event,'id': cid})
  129. data = self.decode(self.sendCommand(command))
  130. if data['id'] != '0':
  131. raise Exception('listener registration refused: '+data['msg'])
  132. while True:
  133. try:
  134. message = self.connection.read_until('\n\r',7200)
  135. try:
  136. self.decode(message)['invokername']
  137. except:
  138. continue
  139. elif: callback != None:
  140. if callback(self, message) == False: return
  141. else: # Default callback
  142. print self.decode(message)['invokername']+': '+self.decode(message)['msg']
  143. except:
  144. self.connect()
  145. if username != None:
  146. data = self.decode(self.sendCommand('login '+encode(username)+' '+encode(password)))
  147. if data['id'] != '0':
  148. raise Exception('Login refused: '+data['msg'])
  149. if not cid==None:
  150. whoami = self.decode(self.sendCommand('whoami'))
  151. data = self.decode(self.sendCommand('clientmove '+self.encode({'clid':whoami['client_id'],'cid': cid})))
  152. if data['id'] != '0' and data['id'] != '770':
  153. raise Exception('Could not move client: '+data['msg'])
  154. command = 'servernotifyregister '+self.encode({'event':event})
  155. if not cid==None: command = 'servernotifyregister '+self.encode({'event':event,'id': cid})
  156. data = self.decode(self.sendCommand(command))
  157. if data['id'] != '0':
  158. raise Exception('listener registration refused')
  159.  
  160. def connect(self, server=1):
  161. """
  162. Create a new connection
  163. """
  164. self.virtualserver = server
  165. #Create new connection
  166. self.__ioLock.acquire()
  167. self.connection = telnetlib.Telnet(self.host,self.port)
  168. data = self.connection.read_until('\n\r',5)
  169. self.connection.read_until("\n\r", 5)
  170. self.__ioLock.release()
  171. if not 'TS3' in data:
  172. raise Exception('Teamspeak connection refused')
  173. #connect to the Virtual Server
  174. self.__ioLock.acquire()
  175. self.connection.write('use '+str(self.virtualserver)+'\n\r')
  176. raw = self.connection.read_until('\n\r',5)
  177. data = self.decode(raw)
  178. self.__ioLock.release()
  179. if int(data['id']) != 0:
  180. raise Exception('Unable to select virtual server\n\r'+raw)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement