我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用twisted.python.log.msg()。
def connectionMade(self): dst = path.abspath(path.join(self.destDir,self.filename)) exists = path.exists(dst) if self.resume and exists: # I have been told I want to resume, and a file already # exists - Here we go self.file = open(dst, 'ab') log.msg("Attempting to resume %s - starting from %d bytes" % (self.file, self.file.tell())) elif self.overwrite or not exists: self.file = open(dst, 'wb') else: raise OSError(errno.EEXIST, "There's a file in the way. " "Perhaps that's why you cannot open it.", dst)
def getClientIP(request, useForwardedHeader=False): """Get the client's IP address from the ``'X-Forwarded-For:'`` header, or from the :api:`request <twisted.web.server.Request>`. :type request: :api:`twisted.web.http.Request` :param request: A ``Request`` for a :api:`twisted.web.resource.Resource`. :param bool useForwardedHeader: If ``True``, attempt to get the client's IP address from the ``'X-Forwarded-For:'`` header. :rtype: ``None`` or :any:`str` :returns: The client's IP address, if it was obtainable. """ ip = None if useForwardedHeader: header = request.getHeader("X-Forwarded-For") if header: ip = header.split(",")[-1].strip() if not isIPAddress(ip): log.msg("Got weird X-Forwarded-For value %r" % header) ip = None else: ip = request.getClientIP() return ip
def getResourceFor(self, request): """Get a resource for a request. This iterates through the resource heirarchy, calling getChildWithDefault on each resource it finds for a path element, stopping when it hits an element where isLeaf is true. """ log.msg("Request for resource at %s" % request.path) request.site = self # Sitepath is used to determine cookie names between distributed # servers and disconnected sites. request.sitepath = copy.copy(request.prepath) child = resource.getChildForRequest(self.resource, request) log.msg(child) return child
def lineReceived(self, line): self.resetTimeout() def processFailed(err): #if err.check(FTPCmdError): # self.sendLine(err.value.response()) #else: log.msg("Unexpected FTP error") log.err(err) def processSucceeded(result): if isinstance(result, tuple): self.reply(*result) elif result is not None: self.reply(result) d = defer.maybeDeferred(self.processCommand, line) d.addCallbacks(processSucceeded, processFailed) d.addErrback(log.err)
def _ebLogin(self, err, nickname): if err.check(ewords.AlreadyLoggedIn): self.privmsg( NICKSERV, nickname, "Already logged in. No pod people allowed!") elif err.check(ecred.UnauthorizedLogin): self.privmsg( NICKSERV, nickname, "Login failed. Goodbye.") else: log.msg("Unhandled error during login:") log.err(err) self.privmsg( NICKSERV, nickname, "Server error during login. Sorry.") self.transport.loseConnection() # Great, now that's out of the way, here's some of the interesting # bits
def sendMessage(self, command, *parameter_list, **prefix): """Send a line formatted as an IRC message. First argument is the command, all subsequent arguments are parameters to that command. If a prefix is desired, it may be specified with the keyword argument 'prefix'. """ if not command: raise ValueError, "IRC message requires a command." if ' ' in command or command[0] == ':': # Not the ONLY way to screw up, but provides a little # sanity checking to catch likely dumb mistakes. raise ValueError, "Somebody screwed up, 'cuz this doesn't" \ " look like a command to me: %s" % command line = string.join([command] + list(parameter_list)) if prefix.has_key('prefix'): line = ":%s %s" % (prefix['prefix'], line) self.sendLine(line) if len(parameter_list) > 15: log.msg("Message has %d parameters (RFC allows 15):\n%s" % (len(parameter_list), line))
def dataReceived(self, data): """This hack is to support mIRC, which sends LF only, even though the RFC says CRLF. (Also, the flexibility of LineReceiver to turn "line mode" on and off was not required.) """ lines = (self.buffer + data).split(LF) # Put the (possibly empty) element after the last LF back in the # buffer self.buffer = lines.pop() for line in lines: if len(line) <= 2: # This is a blank line, at best. continue if line[-1] == CR: line = line[:-1] prefix, command, params = parsemsg(line) # mIRC is a big pile of doo-doo command = command.upper() # DEBUG: log.msg( "%s %s %s" % (prefix, command, params)) self.handleCommand(command, prefix, params)
def _checkFileInvitation(self, message, info): """ helper method for checkMessage """ guid = info.get('Application-GUID', '').lower() name = info.get('Application-Name', '').lower() # Both fields are required, but we'll let some lazy clients get away # with only sending a name, if it is easy for us to recognize the # name (the name is localized, so this check might fail for lazy, # non-english clients, but I'm not about to include "file transfer" # in 80 different languages here). if name != "file transfer" and guid != classNameToGUID["file transfer"]: return 0 try: cookie = int(info['Invitation-Cookie']) fileName = info['Application-File'] fileSize = int(info['Application-FileSize']) except KeyError: log.msg('Received munged file transfer request ... ignoring.') return 0 self.gotSendRequest(fileName, fileSize, cookie, message) return 1
def checkPID(pidfile): if not pidfile: return if os.path.exists(pidfile): try: pid = int(open(pidfile).read()) except ValueError: sys.exit('Pidfile %s contains non-numeric value' % pidfile) try: os.kill(pid, 0) except OSError, why: if why[0] == errno.ESRCH: # The pid doesnt exists. log.msg('Removing stale pidfile %s' % pidfile, isError=True) os.remove(pidfile) else: sys.exit("Can't check status of PID %s from pidfile %s: %s" % (pid, pidfile, why[1])) else: sys.exit("""\ Another twistd server is running, PID %s\n This could either be a previously started instance of your application or a different application entirely. To start a new one, either run it in some other directory, or use the --pidfile and --logfile parameters to avoid clashes. """ % pid)
def processOne(self, deferred): if self.stopping: deferred.callback(self.root) return try: self.remaining=self.iterator.next() except StopIteration: self.stopping=1 except: deferred.errback(failure.Failure()) if self.remaining%10==0: reactor.callLater(0, self.updateBar, deferred) if self.remaining%100==0: log.msg(self.remaining) reactor.callLater(0, self.processOne, deferred)
def getApplication(config, passphrase): s = [(config[t], t) for t in ['python', 'xml', 'source', 'file'] if config[t]][0] filename, style = s[0], {'file':'pickle'}.get(s[1],s[1]) try: log.msg("Loading %s..." % filename) application = service.loadApplication(filename, style, passphrase) log.msg("Loaded.") except Exception, e: s = "Failed to load application: %s" % e if isinstance(e, KeyError) and e.args[0] == "application": s += """ Could not find 'application' in the file. To use 'twistd -y', your .tac file must create a suitable object (e.g., by calling service.Application()) and store it in a variable named 'application'. twistd loads your .tac file and scans the global variables for one of this name. Please read the 'Using Application' HOWTO for details. """ traceback.print_exc(file=log.logfile) log.msg(s) log.deferr() sys.exit('\n' + s + '\n') return application
def serviceStarted(self): if not options['noshell']: self.openChannel(SSHSession()) if options.localForwards: for localPort, hostport in options.localForwards: reactor.listenTCP(localPort, forwarding.SSHListenForwardingFactory(self, hostport, forwarding.SSHListenClientForwardingChannel)) if options.remoteForwards: for remotePort, hostport in options.remoteForwards: log.msg('asking for remote forwarding for %s:%s' % (remotePort, hostport)) data = forwarding.packGlobal_tcpip_forward( ('0.0.0.0', remotePort)) d = self.sendGlobalRequest('tcpip-forward', data) self.remoteForwards[remotePort] = hostport
def cmd_GET(self, rest): remote, rest = self._getFilename(rest) if '*' in remote or '?' in remote: # wildcard if rest: local, rest = self._getFilename(rest) if not os.path.isdir(local): return "Wildcard get with non-directory target." else: local = '' d = self._remoteGlob(remote) d.addCallback(self._cbGetMultiple, local) return d if rest: local, rest = self._getFilename(rest) else: local = os.path.split(remote)[1] log.msg((remote, local)) lf = file(local, 'w', 0) path = os.path.join(self.currentDirectory, remote) d = self.client.openFile(path, filetransfer.FXF_READ, {}) d.addCallback(self._cbGetOpenFile, lf) d.addErrback(self._ebCloseLf, lf) return d
def _cbPutMultipleNext(self, res, files, path): if isinstance(res, failure.Failure): self._printFailure(res) elif res: self.transport.write(res) if not res.endswith('\n'): self.transport.write('\n') f = None while files and not f: try: f = files.pop(0) lf = file(f, 'r') except: self._printFailure(failure.Failure()) f = None if not f: return name = os.path.split(f)[1] remote = os.path.join(self.currentDirectory, path, name) log.msg((name, remote, path)) d = self.client.openFile(remote, filetransfer.FXF_WRITE|filetransfer.FXF_CREAT, {}) d.addCallback(self._cbPutOpenFile, lf) d.addErrback(self._ebCloseLf, lf) d.addBoth(self._cbPutMultipleNext, files, path) return d
def _remoteGlob(self, fullPath): log.msg('looking up %s' % fullPath) head, tail = os.path.split(fullPath) if '*' in tail or '?' in tail: glob = 1 else: glob = 0 if tail and not glob: # could be file or directory # try directory first d = self.client.openDirectory(fullPath) d.addCallback(self._cbOpenList, '') d.addErrback(self._ebNotADirectory, head, tail) else: d = self.client.openDirectory(head) d.addCallback(self._cbOpenList, tail) return d
def channel_forwarded_tcpip(self, windowSize, maxPacket, data): log.msg('%s %s' % ('FTCP', repr(data))) remoteHP, origHP = forwarding.unpackOpen_forwarded_tcpip(data) log.msg(self.remoteForwards) log.msg(remoteHP) if self.remoteForwards.has_key(remoteHP[1]): connectHP = self.remoteForwards[remoteHP[1]] log.msg('connect forwarding %s' % (connectHP,)) return SSHConnectForwardingChannel(connectHP, remoteWindow = windowSize, remoteMaxPacket = maxPacket, conn = self) else: raise ConchError(connection.OPEN_CONNECT_FAILED, "don't know about that port") # def channel_auth_agent_openssh_com(self, windowSize, maxPacket, data): # if options['agent'] and keyAgent: # return agent.SSHAgentForwardingChannel(remoteWindow = windowSize, # remoteMaxPacket = maxPacket, # conn = self) # else: # return connection.OPEN_CONNECT_FAILED, "don't have an agent"
def closed(self): global old log.msg('closed %s' % self) log.msg(repr(self.conn.channels)) if not options['nocache']: # fork into the background if os.fork(): if old: fd = sys.stdin.fileno() tty.tcsetattr(fd, tty.TCSANOW, old) if (options['command'] and options['tty']) or \ not options['notty']: signal.signal(signal.SIGWINCH, signal.SIG_DFL) os._exit(0) os.setsid() for i in range(3): try: os.close(i) except OSError, e: import errno if e.errno != errno.EBADF: raise
def openChannel(self, channel, extra = ''): """ Open a new channel on this connection. @type channel: subclass of C{SSHChannel} @type extra: C{str} """ log.msg('opening channel %s with %s %s'%(self.localChannelID, channel.localWindowSize, channel.localMaxPacket)) self.transport.sendPacket(MSG_CHANNEL_OPEN, common.NS(channel.name) +struct.pack('>3L', self.localChannelID, channel.localWindowSize, channel.localMaxPacket) +extra) channel.id = self.localChannelID self.channels[self.localChannelID] = channel self.localChannelID+=1
def sendRequest(self, channel, requestType, data, wantReply = 0): """ Send a request to a channel. @type channel: subclass of C{SSHChannel} @type requestType: C{str} @type data: C{str} @type wantReply: C{bool} @rtype C{Deferred}/C{None} """ if channel.localClosed: return log.msg('sending request %s' % requestType) self.transport.sendPacket(MSG_CHANNEL_REQUEST, struct.pack('>L', self.channelsToRemoteChannel[channel]) + common.NS(requestType)+chr(wantReply) + data) if wantReply: d = defer.Deferred() self.deferreds.setdefault(channel.id, []).append(d) return d
def requestReceived(self, requestType, data): """ Called when a request is sent to this channel. By default it delegates to self.request_<requestType>. If this function returns true, the request succeeded, otherwise it failed. @type requestType: C{str} @type data: C{str} @rtype: C{bool} """ foo = requestType.replace('-', '_') f = getattr(self, 'request_%s'%foo, None) if f: return f(data) log.msg('unhandled request for %s'%requestType) return 0
def startFactory(self): # disable coredumps if resource: resource.setrlimit(resource.RLIMIT_CORE, (0,0)) else: log.msg('INSECURE: unable to disable core dumps.') if not hasattr(self,'publicKeys'): self.publicKeys = self.getPublicKeys() if not hasattr(self,'privateKeys'): self.privateKeys = self.getPrivateKeys() if not self.publicKeys or not self.privateKeys: raise error.ConchError('no host keys, failing') if not hasattr(self,'primes'): self.primes = self.getPrimes() #if not self.primes: # log.msg('disabling diffie-hellman-group-exchange because we cannot find moduli file') # transport.SSHServerTransport.supportedKeyExchanges.remove('diffie-hellman-group-exchange-sha1') if self.primes: self.primesKeys = self.primes.keys()
def ssh_USERAUTH_FAILURE(self, packet): canContinue, partial = getNS(packet) canContinue = canContinue.split(',') partial = ord(partial) if partial: self.authenticatedWith.append(self.lastAuth) def _(x, y): try: i1 = self.preferredOrder.index(x) except ValueError: return 1 try: i2 = self.preferredOrder.index(y) except ValueError: return -1 return cmp(i1, i2) canContinue.sort(_) log.msg('can continue with: %s' % canContinue) for method in canContinue: if method not in self.authenticatedWith and self.tryAuth(method): return self.transport.sendDisconnect(transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE, 'no more authentication methods available')
def startedConnecting(self, connector): fd = connector.transport.fileno() stats = os.fstat(fd) try: filestats = os.stat(connector.transport.addr) except: connector.stopConnecting() return if stat.S_IMODE(filestats[0]) != 0600: log.msg("socket mode is not 0600: %s" % oct(stat.S_IMODE(stats[0]))) elif filestats[4] != os.getuid(): log.msg("socket not owned by us: %s" % stats[4]) elif filestats[5] != os.getgid(): log.msg("socket not owned by our group: %s" % stats[5]) # XXX reenable this when i can fix it for cygwin #elif filestats[-3:] != stats[-3:]: # log.msg("socket doesn't have same create times") else: log.msg('conecting OK') return connector.stopConnecting()
def buildProtocol(self, addr): # here comes the EVIL obj = self.userAuthObject.instance bases = [] for base in obj.__class__.__bases__: if base == connection.SSHConnection: bases.append(SSHUnixClientProtocol) else: bases.append(base) newClass = types.ClassType(obj.__class__.__name__, tuple(bases), obj.__class__.__dict__) obj.__class__ = newClass SSHUnixClientProtocol.__init__(obj) log.msg('returning %s' % obj) if self.d: d = self.d self.d = None d.callback(None) return obj
def setService(self, service): log.msg('setting client server to %s' % service) transport.SSHClientTransport.setService(self, service) if service.name != 'ssh-userauth' and self.factory.d: d = self.factory.d self.factory.d = None d.callback(None) if service.name == 'ssh-connection': # listen for UNIX if not self.factory.options['nocache']: user = self.factory.userAuthObject.user peer = self.transport.getPeer() filename = os.path.expanduser("~/.conch-%s-%s-%i" % (user, peer.host, peer.port)) try: u = unix.SSHUnixServerFactory(service) try: os.unlink(filename) except OSError: pass self.unixServer = reactor.listenUNIX(filename, u, mode=0600, wantPID=1) except Exception, e: log.msg('error trying to listen on %s' % filename) log.err(e)
def getPublicKey(self): if self.keyAgent: blob = self.keyAgent.getPublicKey() if blob: return blob files = [x for x in self.options.identitys if x not in self.usedFiles] log.msg(str(self.options.identitys)) log.msg(str(files)) if not files: return None file = files[0] log.msg(file) self.usedFiles.append(file) file = os.path.expanduser(file) file += '.pub' if not os.path.exists(file): return self.getPublicKey() # try again try: return keys.getPublicKeyString(file) except: return self.getPublicKey() # try again
def execute(self, args, p, preargs=''): if runtime.platformType == 'win32': raise unittest.SkipTest, "can't run cmdline client on win32" port = self.server.getHost().port cmd = ('-p %i -l testuser ' '--known-hosts kh_test ' '--user-authentications publickey ' '--host-key-algorithms ssh-rsa ' '-a -I ' '-K direct ' '-i dsa_test ' '-v ') % port + preargs + \ ' 127.0.0.1 ' + args cmds = _makeArgs(cmd.split()) log.msg(str(cmds)) env = os.environ.copy() env['PYTHONPATH'] = os.pathsep.join(sys.path) reactor.spawnProcess(p, sys.executable, cmds, env=env) return p.deferred
def testBatchFile(self): """Test whether batch file function of cftp ('cftp -b batchfile'). This works by treating the file as a list of commands to be run. """ cmds = """pwd ls exit """ def _cbCheckResult(res): res = res.split('\n') log.msg('RES %s' % str(res)) self.failUnless(res[1].find(self.testDir) != -1, repr(res)) self.failUnlessEqual(res[3:-2], ['testDirectory', 'testRemoveFile', 'testRenameFile', 'testfile1']) d = self._getBatchOutput(cmds) d.addCallback(_cbCheckResult) return d
def _getBatchOutput(self, f): fn = tempfile.mktemp() open(fn, 'w').write(f) port = self.server.getHost().port cmds = ('-p %i -l testuser ' '-K unix ' '-a ' '-v -b %s 127.0.0.1') % (port, fn) cmds = test_conch._makeArgs(cmds.split(), mod='cftp')[1:] log.msg('running %s %s' % (sys.executable, cmds)) env = os.environ.copy() env['PYTHONPATH'] = os.pathsep.join(sys.path) self.server.factory.expectedLoseConnection = 1 d = getProcessOutputAndValue(sys.executable, cmds, env=env) def _cleanup(res): os.remove(fn) return res d.addCallback(lambda res: res[0]) d.addBoth(_cleanup) return d
def getPrivateKeys(self): ks = {} euid,egid = os.geteuid(), os.getegid() os.setegid(0) # gain priviledges os.seteuid(0) for file in os.listdir(self.dataRoot): if file[:9] == 'ssh_host_' and file[-4:]=='_key': try: k = keys.getPrivateKeyObject(self.dataRoot+'/'+file) t = keys.objectType(k) ks[t] = k except Exception, e: log.msg('bad private key file %s: %s' % (file, e)) os.setegid(egid) # drop them just as quickily os.seteuid(euid) return ks
def getCaptchaImage(self, request): """Get a random CAPTCHA image from our **captchaDir**. Creates a :class:`~farfetchd.captcha.GimpCaptcha`, and calls its :meth:`~farfetchd.captcha.GimpCaptcha.get` method to return a random CAPTCHA and challenge string. :type request: :api:`twisted.web.http.Request` :param request: A client's initial request for some other resource which is protected by this one (i.e. protected by a CAPTCHA). :returns: A 2-tuple of ``(image, challenge)``, where:: - ``image`` is a string holding a binary, JPEG-encoded image. - ``challenge`` is a unique string associated with the request. """ # Create a new HMAC key, specific to requests from this client: clientIP = self.getClientIP(request) clientHMACKey = crypto.getHMAC(self.hmacKey, clientIP) capt = captcha.GimpCaptcha(self.publicKey, self.secretKey, clientHMACKey, self.captchaDir) try: capt.get() except captcha.GimpCaptchaError as error: log.msg(error) except Exception as error: # pragma: no cover log.err("Unhandled error while retrieving Gimp captcha!") log.err(error) return (capt.image, capt.challenge)
def checkSolution(self, request): """Process a solved CAPTCHA via :meth:`farfetchd.captcha.GimpCaptcha.check`. :type request: :api:`twisted.web.http.Request` :param request: A ``Request`` object, including POST arguments which should include two key/value pairs: one key being ``'captcha_challenge_field'``, and the other, ``'captcha_response_field'``. These POST arguments should be obtained from :meth:`render_GET`. :rtupe: bool :returns: True, if the CAPTCHA solution was valid; False otherwise. """ valid = False try: challenge, solution = self.extractClientSolution(request) except Exception as err: log.err(err) return self.failureResponse(request) clientIP = self.getClientIP(request) clientHMACKey = crypto.getHMAC(self.hmacKey, clientIP) try: valid = captcha.GimpCaptcha.check(challenge, solution, self.secretKey, clientHMACKey) except captcha.CaptchaExpired as error: log.error(error) valid = False log.msg("%sorrect captcha from %r: %r." % ("C" if valid else "Inc", clientIP, solution)) return valid
def process(self): """Process an incoming request to the Farfetchd server.""" # Get site from channel self.site = self.channel.site # Set various default headers self.setHeader(b"Content-Type", b"application/vnd.api+json") self.setHeader(b"Server", "Farfetchd v%s" % FARFETCHD_API_VERSION) self.setHeader(b"Date", http.datetimeToString()) # Resource Identification self.prepath = [] self.postpath = list(map(http.unquote, self.path[1:].split(b'/'))) log.msg("postpath is %s" % self.postpath) log.msg("self.resource is %s" % self.resource) #requested_resource = self.resource.getChildForRequest(self) requested_resource = resource.getChildForRequest(self.resource, self) try: requested_resource = self.site.getResourceFor(self) #self.render(requested_resource) log.msg("Requested resource is %s" % requested_resource) log.msg("Requested resource entities are %s" % requested_resource.listEntities()) if requested_resource: if requested_resource.responseType: log.msg("Request will be handled by %r" % requested_resource.__class__.__name__) self.checkRequestHeaders() #requested_resource.render(self) self.render(requested_resource) else: self.setResponseCode(http.NOT_FOUND) self.write(b"No such resource") except: self.processingFailed(failure.Failure()) if not self.finished: self.finish()
def __init__(self, raw_message): message = copy(raw_message) for field in self.segments: if field.__class__ == RepeatingField: found_repeaters, message = field.get(message) setattr(self, field.section_name, found_repeaters) else: mthd = self.get_method_for_field(field.name()) try: setattr(self, field.name().lower(), mthd(message.segment(field.name()))) except KeyError: log.msg("unable to find {0} for {1}".format(field.name(), raw_message)) raise message = clean_until(message, field.name())
def _log_command(self, sender, chan, msg): log.msg("Command from " + sender + " in " + chan + ": " + msg)
def _send_message(self, msg, target): self.msg(target, msg)
def sendLine(self, msg): basic.LineOnlyReceiver.sendLine(self, msg+'\r')
def reply(self, key, *args): msg = RESPONSE[key] % args self.sendLine(msg)
def __init__(self, *msg): Exception.__init__(self, *msg) self.errorMessage = msg
def updatePot(self, login, password, host): log.msg('Thank you %s - %s : %s' % (host, login, password)) if self.logfile: line = "%s : %s : %s : %s\n" % (strftime('%F %T'), host, login, password) open(self.logfile, 'a').write(line) if self.dbpool: self.dbpool.runQuery('INSERT INTO pot (type, login, password, host) VALUES (%s, %s, %s, %s)', (self.proto, login, password, host)) # vim: ts=4 sw=4 sts=4 et
def dumpStats(self): log.msg('queue: %s' % self.q.queue) log.msg('waiters: %s' % self.waiters) log.msg('workers: %s' % self.working) log.msg('total: %s' % self.threads)
def buildProtocol(self): if self.ircui: log.msg("already logged in") return None i = IRCUserInterface() i.factory = self self.ircui = i return i
def msg(self, user, message, length = None): """Send a message to a user or channel. @type user: C{str} @param user: The username or channel name to which to direct the message. @type message: C{str} @param message: The text to send @type length: C{int} @param length: The maximum number of octets to send at a time. This has the effect of turning a single call to msg() into multiple commands to the server. This is useful when long messages may be sent that would otherwise cause the server to kick us off or silently truncate the text we are sending. If None is passed, the entire message is always send in one command. """ fmt = "PRIVMSG %s :%%s" % (user,) if length is None: self.sendLine(fmt % (message,)) else: # NOTE: minimumLength really equals len(fmt) - 2 (for '%s') + n # where n is how many bytes sendLine sends to end the line. # n was magic numbered to 2, I think incorrectly minimumLength = len(fmt) if length <= minimumLength: raise ValueError("Maximum length must exceed %d for message " "to %s" % (minimumLength, user)) lines = split(message, length - minimumLength) map(lambda line, self=self, fmt=fmt: self.sendLine(fmt % line), lines)
def ctcpUnknownQuery(self, user, channel, tag, data): nick = string.split(user,"!")[0] self.ctcpMakeReply(nick, [('ERRMSG', "%s %s: Unknown query '%s'" % (tag, data, tag))]) log.msg("Unknown CTCP query from %s: %s %s\n" % (user, tag, data))
def ctcpMakeQuery(self, user, messages): """Send one or more X{extended messages} as a CTCP query. @type messages: a list of extended messages. An extended message is a (tag, data) tuple, where 'data' may be C{None}. """ self.msg(user, ctcpStringify(messages)) ### Receiving a response to a CTCP query (presumably to one we made) ### You may want to add methods here, or override UnknownReply.
def ctcpUnknownReply(self, user, channel, tag, data): """Called when a fitting ctcpReply_ method is not found. XXX: If the client makes arbitrary CTCP queries, this method should probably show the responses to them instead of treating them as anomolies. """ log.msg("Unknown CTCP reply from %s: %s %s\n" % (user, tag, data)) ### Error handlers ### You may override these with something more appropriate to your UI.
def badMessage(self, line, excType, excValue, tb): """When I get a message that's so broken I can't use it. """ log.msg(line) log.msg(string.join(traceback.format_exception(excType, excValue, tb),''))
def lineReceived(self, line): log.msg("DCC CHAT<%s> %s" % (self.remoteParty, line)) self.client.privmsg(self.remoteParty, self.client.nickname, line)
def _debug(self,data): log.msg(data)