import socket import gobject import Connection class MsnConnection(Connection.Connection): '''a connection with a MSN server''' def __init__(self, host, port): '''object contructor''' Connection.Connection.__init__(self) self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) gobject.io_add_watch(self.socket, gobject.IO_IN, self.on_data_readable) gobject.io_add_watch(self.socket, gobject.IO_OUT, self.on_data_writable) gobject.io_add_watch(self.socket, gobject.IO_ERR | gobject.IO_HUP, self.on_connection_error) self.host, self.port = host, port self.tid = 1 self.socket.connect((self.host, self.port)) def _read(self): '''read data available on the socket and add it to self.out_msgs''' buf = '' c = self.socket.recv(1) while c != '\n' and c != '': buf += c c = self.socket.recv(1) buf += '\n' self.out_msgs.append(buf) self.emit('data-received', buf) return True def _write(self): '''write data available to the socket, remove it from self.in_msgs ''' while self.in_msgs: msg = self.in_msgs.pop() self.socket.send(msg) self.emit('data-sent', msg) return True def send_command(self, command, params='', payload=''): if type(payload) == unicode: payload = str(payload.encode('utf-8')) if payload: if not params: text = '%s %s %s\r\n%s' % ( command, self.tid, len(payload), payload) else: text = '%s %s %s %s\r\n%s' % ( command, self.tid, params, len(payload), payload) else: if not params: text = '%s %s\r\n' % (command, self.tid) else: text = '%s %s %s\r\n' % (command, self.tid, params) self.tid += 1 self.in_msgs.append(text) gobject.type_register(MsnConnection) if __name__ == '__main__': s = MsnConnection('messenger.hotmail.com', 1863) count = 0 def read(connection, data): global count, s print 'data received:', repr(data) connection.out_msgs.pop() count += 1 if count == 1: s.send_command('CVR', '0x0c0a winnt 5.1 i386 MSNMSGR 8.0.0792 msmsgs %s' % ( 'xmxsxn@gmail.com')) def sent(connection, data): print 'data sent:', repr(data) def error(connection): print 'error' s.connect('data-received', read) s.connect('data-sent', sent) s.connect('connection-error', error) s.send_command('VER', 'MSNP13 CVR0') gobject.MainLoop().run()