def upload(config): """Upload file using ftp.""" while True: session = Session(config.server, config.mode, config.zflag) if not session.connect(): session.close() time.sleep(60) continue message = log.Message('Login to %s.' % config.server.host, log.Level.INFO) message.log() if config.server.dir: try: session.cwd(config.server.dir) except: message = log.Message( '%s not exists on %s' % (config.server.dir, config.server.host), log.Level.ERROR) message.log() return filefilter = config.filter for path in config.path: try: uploadfp(session, path, config.server.keep, filefilter, config.delay) except: pass session.close() message = log.Message('Upload done!', log.Level.INFO) message.log() if not config.interval: break time.sleep(config.interval)
def check(self): if not self.path: message = log.Message('No path upload!', log.Level.ERROR) message.log() return 0 for filepath in self.path: if not os.path.isdir(filepath): message = log.Message( 'Not find path to upload: %s.' % filepath, log.Level.WARNING) message.log() # return 0 (enable non-existed path) if not self.server.host or not self.server.user or not self.server.password: message = log.Message('Missing host server information.', log.Level.ERROR) message.log() return 0 if not self.regex: if self.rule not in ['sgl', 'com']: self.rule = 'sgl' if self.mode not in [0, 1]: self.mode = 0 if self.zflag not in [0, 1, 2]: self.zflag = 0 self.filter = filefilter(self.prefix, self.suffix, self.rule, self.regex, self.pattern) return 1
def storbinary(self, filepath, blocksize=1024): filename = os.path.basename(filepath) if self.zflag: with open(filepath, 'rb') as f_in: with gzip.open(filepath + '.gz', 'wb') as f_out: shutil.copyfileobj(f_in, f_out) if self.zflag == 2: try: os.remove(filepath) except: message = log.Message('remove %s failed.' % filepath, log.Level.ERROR) message.log() os.remove(filepath + '.gz') raise filename += '.gz' filepath += '.gz' if self.session: if self.mode == 0: with open(filepath, 'rb') as fp: self.session.storbinary('STOR %s' % filename, fp, blocksize) elif self.mode == 1: self.session.put(filepath, filename)
def connect(self): host = self.server.host.split(':') port = 21 if self.mode == 0 else 22 if len(host) > 1: try: port = int(host[1]) except: message = log.Message('port: %s is invalid.' % host[1], log.Level.ERROR) message.log() return False if self.mode == 0: self.session = ftplib.FTP() self.session.connect(host[0], port) self.session.login(self.server.user, self.server.password) else: ssh = SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host[0], port, username=self.server.user, password=self.server.password) self.session = SFTPClient.from_transport(ssh.get_transport()) return True
def listen_gif(self, person, gif): mind_message = "" for message in self.mind.messages(): mind_message += message.text + " " mind_message = gif + "\t" + mind_message.rstrip() mind_message = log.Message(mind_message, self.gif_log.size + 1) self.gif_log.add(mind_message) response = NoReply() if random.random() < 0.01: response = self.reply(mind_message) response.target = person self.gif_index.update(mind_message) return response
def update(self, messages): for word in self._state: self._state[word]["ttl"] -= 1 for message in messages: for word in message.components: self._state[word] = { "message": log.Message(word, message.offset), "ttl": 10, } new_state = dict() for word in self._state: if self._state[word]["ttl"] >= 0: new_state[word] = self._state[word] self._state = new_state self.empty = False
def reply(self, message): reply_type = random.random() response = NoReply() # Mente vazia faz o número nunca ser maior que 60%. if self.mind.empty: reply_type *= 0.6 # 10% chance of random message. if reply_type < 0.001: str_msg = " ".join( [message.text for message in self.mind.messages()]).capitalize() + "." response = MessageReply(log.Message(str_msg, 0)) self.why = "Buguei." elif reply_type < 0.10: response = MessageReply(self.read_random(self.message_log)) self.why = "Sei lá, respondi aquilo só pelo caos." # 20% chance of replying with gif elif reply_type < 0.3: response = self.reply_gif(message) # self.why is filled inside the function. # 50% of direct reply elif reply_type < 0.70: response = MessageReply( self.read_messages(self.message_log, self.message_index, [message])) self.why = 'Estava respondendo esta mensagem: "{}".'.format( message.text) # 40% chance of mindset reply else: response = MessageReply( self.read_messages(self.message_log, self.message_index, self.mind.messages())) # self.why is filled inside the function. self.mind.update([response.message]) return response
def listen_message(self, person, message): # Receives an escaped version of the message, and the number of times # it replaced the name of the bot for {nome} message = message.replace("{", "{{").replace("}", "}}") m, subs = self.regexp.subn("{nome}", message) message = log.Message(m, self.message_log.size + 1) self.message_log.add(message) response = NoReply() if subs > 0 or random.random() < 0.01: response = self.reply(message) response.quote_msg = (subs == 0 ) # Only quote if bot is interrupting self.message_index.update(message) # How many words we're going to remember? msg_count = int(5.0 * random.random() + 1.0) msg_list = self.scaled_list(self.message_index, [message], msg_count) self.mind.update(msg_list) return response
def configure(config_path): """read configure file.""" if not os.path.exists(config_path): message = log.Message('Not find configure file: %s.' % config_path, log.Level.ERROR) message.log() return 0 interval = None path = list() prefix = list() suffix = list() rule = None regex = list() pattern = list() delay = 0 host = None user = None password = None directory = None keep = None mode = None zflag = 0 with open(config_path) as f: for line in f: if line.startswith('interval'): interval = line.split('=')[1].strip() if line.startswith('path'): path.extend(line.split('=')[1].split()) if line.startswith('host'): host = line.split('=')[1].strip() if line.startswith('user'): user = line.split('=')[1].strip() if line.startswith('password'): password = line.split('=')[1].strip() if line.startswith('dir'): directory = line.split('=')[1].strip() if line.startswith('keep'): keep = line.split('=')[1].strip() if line.startswith('prefix'): prefix.extend(line.split('=')[1].split()) if line.startswith('suffix'): suffix.extend(line.split('=')[1].split()) if line.startswith('rule'): rule = line.split('=')[1].strip() if line.startswith('regex'): regex.extend(line.split('=')[1].split()) if line.startswith('pattern'): pattern.extend(line.split('=')[1].split()) if line.startswith('delay'): delay = line.split('=')[1].strip() if line.startswith('mode'): mode = line.split('=')[1].strip() if line.startswith('gz'): zflag = line.split('=')[1].strip() try: mode = int(mode) except: mode = 0 try: interval = int(interval) except: interval = 0 try: delay = int(delay) except: delay = 0 try: zflag = int(zflag) except: zflag = 0 if keep not in ['yes', 'no']: keep = 'no' config = Config(interval, path, prefix, suffix, rule, regex, pattern, delay, server(host, user, password, directory, keep), mode, zflag) if not config.check(): return 0 return config
def uploadfp(session, path, keep, filefilter, delay): """Upload file. Args: session:session. path:upload path. keep:keep directory structure. filefilter:file filter. delay: delay in seconds. """ if not os.path.isdir(path): return if keep == 'yes': directory = os.path.split(path)[1] if directory: try: session.mkd(directory) except: pass try: session.cwd(directory) except: pass ftpfiles = session.nlst() for subpath in os.listdir(path): localpath = os.path.join(path, subpath) if os.path.isfile(localpath): uploadflag = False subfile = subpath subfilepath = localpath if session.zflag in [1, 2]: subfile += '.gz' subfilepath += '.gz' if subfile in ftpfiles and os.path.exists(subfilepath): if os.stat(subfilepath).st_size <= session.size(subfile): continue if filefilter.pattern: for pattern in filefilter.pattern: pfile = PatternFile(pattern, delay) if re.match(r'^%s$' % pfile.filename, subpath): uploadflag = True elif filefilter.regex: for regex in filefilter.regex: if re.match(r'^%s$' % regex, subpath): uploadflag = True break else: if filefilter.rule == 'sgl': if filefilter.prefix: for prefix in filefilter.prefix: if subpath.startswith(prefix): uploadflag = True break if not uploadflag and filefilter.suffix: for suffix in filefilter.suffix: if subpath.endswith(suffix): uploadflag = True break elif filefilter.rule == 'com': for prefix, suffix in zip(filefilter.prefix, filefilter.suffix): if subpath.startswith(prefix) and subpath.endswith( suffix): uploadflag = True break if not uploadflag: continue try: session.storbinary(localpath) message = log.Message('Upload %s successful!' % localpath, log.Level.INFO) message.log() except: message = log.Message('Upload %s failed!' % localpath, log.Level.WARNING) message.log() elif os.path.isdir(localpath): uploadfp(session, localpath, keep, filefilter, delay) if keep == 'yes': session.cwd('..')