def init(port): try: server = MyTCPServer(("0.0.0.0", port), MyTCPServerHandler) server.timeout = 10 server_thread = threading.Thread(target=server.serve_forever) server_thread.timeout = 10 # iniciando agente _print("Esperando fumadores...") server_thread.daemon = True server_thread.start() while True: verify_smoking() global smoke_code smoke_code = choice(codes) _print("Agente: Tengo disponible {}!".format(store.get(smoke_code)["required"])) global smoke smoke = True store.get(smoke_code)["request"].send("enable".encode("UTF-8")) _print("Agente: fumador {} servido!".format(store.get(smoke_code)["name"])) except KeyboardInterrupt: _print("Cerrando conexiones...") server.shutdown() server.server_close()
def get_image_hash(self, resource_id, hasher=sha256, blocksize=4096): start_t = time() image_detail = self.inspect_image(resource_id) image_id = image_detail['Id'] size = image_detail['Size'] image = self.get_image(resource_id) f_handler, filename = tempfile.mkstemp(suffix='.tar', text=False) with open(filename, 'wb') as f: f.write(image.data) tar_file = tarfile.open(fileobj=open(filename)) members = tar_file.getmembers() hashes = [] for m in members: f = tar_file.extractfile(m) if f is None: continue h = md5() while True: buf = f.readline(blocksize) if not buf: break h.update(buf) hashes.append(h.hexdigest()) os.remove(filename) h = hasher() h.update("$".join(sorted(hashes))) rt = h.hexdigest() end_t = time() b = Bucket(_S.get('RECENT_HASH_TIME', []), RECENT_HASH_TIME_BUCKET_SIZE) b.push((size, (end_t - start_t))) _S.set('RECENT_HASH_TIME', b) if _S.get(image_id) != rt: _S.set(image_id, rt) return rt
def finish(self): _print("Fumador desconectado *{}*".format(store.get(self.code)["name"])) if self.rejected is False: store.get(self.code)["flag"] = False global smoke_code if smoke_code == self.code: global smoke smoke = False
def show_karma(parsed, user, target, text): text = text[len('.karma'):].strip().lower() if not text: try: top = json.loads( store.get('karma.top.{}'.format(target)).decode()) or dict() bottom = json.loads( store.get( 'karma.bottom.{}'.format(target)).decode()) or dict() except AttributeError: store.set('karma.top.{}'.format(target), dict()) store.set('karma.bottom.{}'.format(target), dict()) else: user_karma = get_karma(target, user.nick) response = 'Top karma: {}. Flop karma: {}. Karma for {}: {}'.format( ', '.join('{}: {}'.format(key, value) for key, value in top.items()), ', '.join('{}: {}'.format(key, value) for key, value in bottom.items()), user.nick, user_karma, ) bot.say(target, response) else: to_print = [] in_literal = [] for word in text.split(): if in_literal: if word.endswith('"'): in_literal.append(word[:-1]) to_print.append(' '.join(in_literal)) in_literal = [] else: in_literal.append(word) elif word.startswith('"'): if word.endswith('"'): to_print.append(word[1:-1]) else: in_literal.append(word[1:]) else: to_print.append(word) response = ', '.join( '{}: {}'.format(word, get_karma(target, word.lower())) for word in to_print) bot.say(target, response)
async def check_state_change(): ts_state, _ = get_space() state = store.get('open') if str(ts_state) != str(state, 'utf-8'): store.set('open', ts_state) await update_spaceapi(ts_state) say_state(ts_state)
def get_image_hash_with_cache(self, resource_id, *args): image_id = self.image_id(resource_id) h = _S.get(image_id) if not h: h = self.get_image_hash(resource_id, *args) _S.set(image_id, h) return h
async def check_blog(): blog_key = 'shack.blogpost' while True: await asyncio.sleep(60) try: async with aiohttp.ClientSession() as session: with async_timeout.timeout(30): async with session.get( 'http://blog.shackspace.de/?feed=rss2') as resp: soup = bs4.BeautifulSoup(await resp.text(), 'lxml-xml') latest_post = soup.rss.find('item') last_post = store.get(blog_key) last_post = last_post.decode() if last_post else '' store.set(blog_key, latest_post.link.text) if last_post != latest_post.link.text: bot.say( '#shackspace', 'New blog post! »{title}« by {author}: {url}'. format( title=latest_post.title.text, author=latest_post.find('creator').text, url=latest_post.link.text, )) except (asyncio.CancelledError, asyncio.TimeoutError): print('timeout')
async def check_wiki(): wiki_key = 'shack.wikichange' while True: await asyncio.sleep(60) try: async with aiohttp.ClientSession() as session: with async_timeout.timeout(30): async with session.get( 'http://wiki.shackspace.de/feed.php') as resp: feed = feedparser.parse(await resp.text()) latest_change = feed.entries[0] last_change = store.get(wiki_key) last_change = last_change.decode( ) if last_change else '' store.set(wiki_key, latest_change['id']) if last_change != latest_change['id']: response = 'Page changed: ' + latest_change['title'] response += ' by ' + latest_change['authors'][0][ 'name'] if latest_change.get('authors') else '' response += ' – ' + latest_change['links'][0][ 'href'] bot.say('#shackspace', response) except (asyncio.CancelledError, asyncio.TimeoutError): print('timeout')
def get_bound_orgs_with_local_eth_accounts(self): eth_accounts = web3_client().eth.accounts bound_org = _S.get('BOUND_ORG') if bound_org and _S.get('LAST_ETH_ACCOUNTS') == eth_accounts: return bound_org bound_org = {} for o, addrs in self.get_all_bound_addresses().items(): bound_addrs = [] for a in addrs: if a in eth_accounts: bound_addrs.append(a) if bound_addrs: bound_org[o] = bound_addrs if bound_org: _S.set('BOUND_ORG', bound_org) _S.set('LAST_ETH_ACCOUNTS', eth_accounts) return bound_org
def handle(self): # Proceso de reconocimiento # cur_thread = threading.current_thread() self.code = self.request.recv(packet_size).decode("UTF-8") self.rejected = False self.smoke_released = False _print("Conectando fumador...") if store.get(self.code)["flag"] is False: store.get(self.code)["request"] = self.request store.get(self.code)["flag"] = True _print("Fumador aceptado *{}*".format(store.get(self.code)["name"])) self.request.send("accepte".encode("UTF-8")) self.process() else: self.rejected = True _print("Fumador rechazado *{}*".format(store.get(self.code)["name"])) self.request.send("rejected".encode("UTF-8"))
def update_scores(target, karma, value): try: top = json.loads(store.get( 'karma.top.{}'.format(target)).decode()) or dict() bottom = json.loads( store.get('karma.bottom.{}'.format(target)).decode()) or dict() except: top = dict() bottom = dict() top.update({karma: value}) bottom.update({karma: value}) top = dict( sorted(top.items(), key=operator.itemgetter(1), reverse=True)[:3]) bottom = dict( sorted(bottom.items(), key=operator.itemgetter(1), reverse=False)[:3]) store.set('karma.top.{}'.format(target), json.dumps(top)) store.set('karma.bottom.{}'.format(target), json.dumps(bottom))
def process(self): while True: message = self.request.recv(packet_size).decode("UTF-8") if message == "need": _print("{}: Necesito {}!".format(store.get(self.code)["name"], store.get(self.code)["required"])) if self.smoke_released: self.smoke_released = False global smoke smoke = False elif message == "enable": _print("{}: Termino de fumar!".format(store.get(self.code)["name"])) self.smoke_released = True elif message == "ack": time.sleep(time_smoke) elif message == "exit": break time.sleep(time_sleep)
def status(parsed, user, target, text): bot = Bot() _status = store.get('status') if not _status: _status = 0 else: _status = int(_status) print(type(_status)) store.incr('status', 1) bot.say(target, "everything is ok, {} [{}]".format(user.nick, _status))
def _handle_repeat(url, bot, target): bare_url = '{0.netloc}{0.path}?{0.query}'.format(urlsplit(url)) redis_string = 'urls.{}§{}'.format(target, bare_url) count = int(store.get(redis_string) or 0) if count: if count == 1: message = 'This url has been posted already, lame!' elif count == 2: message = 'This url has been posted twice before, must be important.' else: message = 'This url has been posted {} times before.'.format(count) bot.say(target, message) store.incr(redis_string, 1) else: store.set(redis_string, 1)
async def check_site(): while True: await asyncio.sleep(60) status = await _is_open() if status is True: new = 'open' elif status is False: new = 'closed' else: new = 'no data' old = store.get('shack.state') old = old.decode() if old else '' if status is not None: store.set('shack.state', new) if 'open' in new and 'closed' in old: bot.say('#shackspace', 'The shack has been opened.') elif 'open' in old and 'closed' in new: bot.say('#shackspace', 'The shack has been closed.')
def process(code, request): message = '' while True: if message != 'ack': _print('Esperando {}!'.format(store.get(code)['required'])) request.send('need'.encode('UTF-8')) message = request.recv(packet_size).decode('UTF-8') if message == 'enable': _print('Servido!') time.sleep(time_sleep) request.send('ack'.encode('UTF-8')) _print('Armando cigarro!') time.sleep(time_sleep) _print('Fumando!!!') time.sleep(time_smoke) request.send('enable'.encode('UTF-8')) elif message == 'ack': pass time.sleep(time_sleep)
def estimate_image_hash_time(self, resource_id, with_cache=False): b = _S.get('RECENT_HASH_TIME', []) if with_cache and _S.has(self.image_id(resource_id)): return 0 size = self.inspect_image(resource_id)['Size'] if b: points = {} for i in b: if i[0] in points: points[i[0]] = (points[i[0]] + i[1]) / 2.0 else: points[i[0]] = i[1] x = points.keys() y = points.values() if len(x) > 2: predict = PolyFit(x, y)[size] if predict < 0: return 0.5 return predict else: efficiency = sum(x) / sum(y) return size / efficiency return size / 5e6
def get(self): default_address = _S.get('default_address') return dict(default_address=default_address), 200
def get_karma(target, karma): return int(store.get('karma.{}§{}'.format(target, karma.lower())) or 0)
def default_namespace(self): return _S.get('DEFAULT_USER_NAME_SPACE')