def weekly(): if not viewFunctions.isLoggedIn(): return viewFunctions.displaySignup() conn = app.config['pool'].connection() cur = conn.cursor() uid = viewFunctions.getUid() cur.execute('select admin from user where user_id=%s',(uid,)) isAdmin = cur.fetchone()[0] if not isAdmin: cur.close() conn.close() return '' items = db.fetchWeekly(cur) cur.execute('select user_id,email from user where subscribe_trend=true') messages = [] for e in cur.fetchall(): track = str(uuid.uuid4())[:6] data = render_template('weekly.html',items=items,email=e[1],key=genKey(e[0]),track=track) messages.append(util.createMessage(e[1],items[0]['title']+' - OuterClub',data)) cur.close() conn.close() util.send(app.config,messages) return 'Success!'
def update(self, path): if path not in self.index: #print 'created:', path payload = {'event': 'created', 'path': path[len(self.prefix):], 'data': ''} util.send(self, payload) self.index[path] = 0 size = os.path.getsize(path) if size > self.index[path]: with open(path, 'r') as fin: fin.seek(self.index[path]) data = fin.read() filteredData = data for pattern in self.skip_patterns: filteredData = re.sub('[0-9]+:[0-9][^\n=]*' + pattern + '[^\n]*\n', '', filteredData) data = filteredData #print 'new data:', path, len(data) while len(data) and self.working: batch = data[:500000] data = data[len(batch):] payload = {'event': 'new line', 'path': path[len(self.prefix):], 'data': batch} util.send(self, payload) self.index[path] = size
def relay(message, from_id, bacon): parts = message.split(" ", 2) to = parts[1] return_str = "" if to not in bacon.roster or bacon.roster[to]['subscription'] == 'to': return_str += "%s is not subscribed to me, message may not be delivered. \n" % to send(config.username, to, parts[2], bacon.stream) return_str += "Message \"%s\" sent to %s" % (parts[2], to) return return_str
def help(update, context): text = 'Forward messages here for the bot to act on.\n'\ '\n'\ 'Any list of items (eg. /stock, ⚒Crafting, etc.) - Create all the /g_deposit commands to move everything to guild stock.\n'\ 'Any message with list of missing items - Create /g_withdraw command that you need to send to guild leader.\n'\ 'A message with /g_deposit commands from this bot - Create /g_withdraw command to get your stuff back out.\n'\ 'Any message that has your guild tag in it - Record you as a member of that guild.\n'\ 'Paste in multiple /g_withdraw commands - Create a more efficent /g_withdraw command.\n'\ '/warehouse - Show a list of things that have enough recipies & parts in guild stock to craft.\n'\ '/stock & /alch - List guild stock of these categories in decending order of quantity.\n'\ '\n'\ 'Some /settings available too.\n'\ logging.info(f'bot said:\n{text}') send(text, update, context)
def give_keys(self, s, msg_args): """Handles a request to give an RS""" balance, = msg_args # generate wallets if balance == 0: return False self.new_wallets = [bc.generate_keypair() for _ in range(balance)] # generate RSA key self.rsa_keys = RSA.generate(Constants.RSA_KEY_LENGTH) self.cipher = PKCS1_OAEP.new(self.rsa_keys) # send the RSA key send(s, self.rsa_keys.publickey().exportKey().decode(Constants.ENCODING)) return True
def run_event_loop(self): # File descriptor to re-register when waiting register_fd = None while True: event = self.event_queue.wait(register_fd=register_fd, oneshot=ONESHOT) register_fd = None if not event: logging.error('No events, exiting.') break src_fd, event_type = event # New connection available, accept it if src_fd == self.listen_sock.fileno(): self.accept() else: # Otherwise, we got an event on a tunneled socket assert src_fd in self.socket_dest src, dest = self.socket_dest[src_fd] # Error, disconnect if event_type == event_queue.ERROR: self.disconnect(src, dest) else: buf = util.recv(src, self.BUF_SIZE) # Error, disconnect if not buf: self.disconnect(src, dest) # XXX buffer if not writeable? take read fd out of poll set? elif not util.send(dest, buf): self.disconnect(src, dest) # Re-register this file descriptor elif ONESHOT: register_fd = src_fd
def new_server(self, msg_args): """Handles the creation of a new server.""" server_addr, server_pub_key = msg_args server_addr = tuple(server_addr) # update new server id server_id = self.num_servers send(server_addr, [Constants.UPDATE_ID, server_id]) # add server to ring ((host, port)) self.servers.append(server_addr) self.num_servers += 1 sys.stdout.write( '\r# servers: {} | {}'.format(self.num_servers, self.servers)) sys.stdout.flush()
def cancel(update, context): uid = update.effective_message.chat.id if not db.banned(uid): if not db.cached(uid): ut.not_started(update) else: if uid in STATE and STATE[uid] != ut.CMD.NOP: msg = (f"The command <code>{STATE[uid].value}</code> " f"has been cancelled. Anything else I can do for you?" f"\n\n" f"Send /help for a list of commands.") else: msg = ("No active command to cancel. " "I wasn't doing anything anyway.\nZzzzz...") ut.send(update, msg) _state(uid)
def set_resin(update, context): uid = update.effective_message.chat.id if not db.banned(uid): if not db.cached(uid): ut.not_started(update) else: msg = (f"❗ Argument must be an integer lower than {ut.RESIN_MAX}, " f"e.g. /set, /set 12") if context.args: msg = _set_resin(context.args, uid, msg) else: msg = (f"Tell me your current resin " f"(max: <code>{ut.RESIN_MAX}</code>)") _state(uid, ut.CMD.SET) db.dec_strikes(uid) ut.send(update, msg)
def invite(): #return render_template('invite.html',name='test') if not viewFunctions.isLoggedIn(): return '' uid = viewFunctions.getUid() conn = app.config['pool'].connection() cur = conn.cursor() cur.execute('select name,invites,admin from user where user_id=%s',(uid,)) username,numInvites,isAdmin = cur.fetchone() if not isAdmin and numInvites == 0: cur.close() conn.close() return flask.jsonify(error='No more invitations available!') error = None name = request.form['name'] email = request.form['email'].strip() if len(name) == 0: name = email elif len(email) == 0: error = 'Friend e-mail address must be provided.' elif not util.emailValid(email): error = "E-mail address was not valid." if not error: key = str(uuid.uuid4())[:7] cur.execute('insert into invite_key (email,code,myDate,user_id) values (%s,%s,NOW(),%s)',(email,key,uid)) if not isAdmin: cur.execute('update user set invites=%s where user_id=%s',(numInvites-1,uid)) conn.commit() cur.close() conn.close() # use formal invitation if admin, otherwise normal referer if isAdmin: data = render_template('invite.html',name=name,key=key) else: data = render_template('referral.html',name=name,key=key,alias=username) # only actually send if it's in prod mode if not app.config['DEBUG']: m = util.createMessage(email,'%s, welcome to OuterClub!' % (name),data) util.send(app.config,m) if error: return flask.jsonify(error=error) else: return '{}'
def run(): print(f"喜马拉雅极速版 (https://github.com/Zero-S1/xmly_speed/blob/master/xmly_speed.md ) ,欢迎打赏¯\(°_o)/¯") mins, date_stamp, _datatime, _notify_time = get_time() title = '⏰ 喜马拉雅极速版' table = [] for k, v in enumerate(cookiesList): print(f">>>>>>>【账号开始{k+1}】\n") cookies = str2dict(v) user_info_res = user_info(cookies) if XMLY_ACCUMULATE_TIME == 1: saveListenTime(cookies, date_stamp) listenData(cookies, date_stamp) stage(cookies) # 新手任务 read(cookies) # 阅读 bubble(cookies) # 收金币气泡 # continue continuousDays = checkin(cookies, _datatime) # 自动签到 # lottery_info(cookies) # 大转盘4次 answer(cookies) # 答题赚金币 cardReportTime(cookies, mins, date_stamp, _datatime) # 卡牌 getOmnipotentCard(cookies, mins, date_stamp, _datatime) # 领取万能卡 card(cookies, _datatime) # 抽卡 index_baoxiang_award(cookies) # 首页、宝箱奖励及翻倍 total, todayTotal, historyTotal = account(cookies) try: device = devices[k] except IndexError: device = cookies['device_model'] else: device = f"设备{k+1}" table.append((user_info_res['nickname'], total, todayTotal, historyTotal, continuousDays,)) if autoTakeOut and total >= amount: pay_info = third_pay_info(cookies) if pay_info and pay_info['name'] and pay_info['accountType'] and pay_info["accountNumber"]: body = {"name": pay_info['name'], "accountType": pay_info['accountType'], "accountNumber": pay_info["accountNumber"], "amount": amount, "takeOutType": takeOutType} task_out_res = task_out(cookies=cookies, body=body) if task_out_res: send(title=title, content=f"{user_info_res['nickname']} 提现到账户【{pay_info['accountNumber']}】20元成功") else: send(title=title, content=f"请先手动填写【user_info_res['nickname']】支付宝账号提现一次") print("###"*20) print("\n"*4)
def new_message(self, msg_args): """Handles posting a new message to the message board.""" client_msg, addresses, signatures, addr = msg_args if len(addresses) != len(signatures) or len(addresses) == 0: self.eprint('Invalid number of addresses/signatures.') return # verify wallets for (address, signature) in zip(addresses, signatures): if not bc.verify(address, address, signature): self.eprint('Signature verification failed.') return # pass on to coordinator send(config.COORDINATOR_ADDR, [Constants.POST_MESSAGE, client_msg, addresses, addr])
def track(update, context): uid = update.effective_message.chat.id if not db.banned(uid): if not db.cached(uid): ut.not_started(update) else: msg = ("❗ Argument must have format: mm:ss, " "e.g. /track, /track 5:35m /track -1") if context.args: msg = _track(context.args, context.bot, uid, msg) else: msg = ("Tell me your genshin timer " "in format <code>mm:ss</code>, " "or <code>-1</code> to disable") _state(uid, ut.CMD.TRACK) db.dec_strikes(uid) ut.send(update, msg)
def new_message(self, msg_args): """Handles a request to post a message. client_msg: The message to post. client_stp: The poster's short-term pseudonym. client_sig: The poster's signature. """ client_msg, client_stp, client_sig = msg_args # verify message, pseudonym, and signature if not self.verify_signature(client_msg, client_stp, client_sig): eprint(self.name, 'Message signature verification failed.') return client_rep = self.stp_list[client_stp] send(config.COORDINATOR_ADDR, [Constants.POST_MESSAGE, client_msg, client_stp, client_rep])
def startMonitor(port): while True: try: s = socket.socket() host = socket.gethostname() s.connect((host, port)) msg = Message(MessageType.Ready) send(s, msg.serialize()) response = s.recv(1024) print(response.decode()) s.close() break except ConnectionRefusedError: print("Connection refused by", host, port)
def spend(update, context): uid = update.effective_message.chat.id if not db.banned(uid): if not db.cached(uid): ut.not_started(update) else: cur_resin = db.get_resin(uid) msg = (f"❗ Argument must be an integer greater than 0 " f"and lower than {cur_resin}, " f"e.g. /spend, /spend 20") if context.args: msg = _spend(context.args, uid, msg, cur_resin) else: msg = (f"Tell me how much resin to spend " f"(max: <code>{cur_resin}</code>)") _state(uid, ut.CMD.SPEND) db.dec_strikes(uid) ut.send(update, msg)
def _verify_simple(sock, Gamma, R, S, g=Constants.G, p=Constants.P, q=Constants.Q): assert (len(R) == len(S)) n = len(R) # step 1 t = randkey(0, q - 1) send(sock, t) # step 2 Theta = recv(sock) # step 3 c = randkey(0, q - 1) send(sock, c) # step 4 alpha = recv(sock) # step 5 U = powm(g, -t % q, p) W = powm(Gamma, -t % q, p) R_hat = [(R[i] * U) % p for i in range(n)] S_hat = [(S[i] * W) % p for i in range(n)] ret = True for i in range(2 * n): if i < n: ver = powm(R_hat[i], alpha[i], p) * powm(S_hat[i], -alpha[i + 1] % q, p) ver %= p ret = ret and (Theta[i] == ver) else: ver = powm(Gamma, alpha[i], p) * powm( g, -alpha[(i + 1) % (2 * n)] % q, p) ver %= p ret = ret and (Theta[i] == ver) return ret
def refill(update, context): uid = update.effective_message.chat.id if not db.banned(uid): if not db.cached(uid): ut.not_started(update) else: cur_resin = db.get_resin(uid) max_resin = ut.RESIN_MAX - cur_resin msg = (f"❗ Argument must be an integer greater than 0 " f"and lower than {max_resin}, " f"e.g. /refill, /refill 20") if context.args: msg = _refill(context.args, uid, msg, cur_resin, max_resin) else: msg = (f"Tell me how much resin to refill " f"(max: <code>{max_resin}</code>)") _state(uid, ut.CMD.REFILL) db.dec_strikes(uid) ut.send(update, msg)
def say(update, context): '''say things as the bot''' if context.args: text = ' '.join(context.args[1:]) context.bot.send_message(chat_id=context.args[0], text=text, parse_mode=ParseMode.HTML) else: with open('user.persist', 'rb') as fp: d = pickle.load(fp) speakers = sorted(( f'{talker["meta"]["last_talked"]}, [{talker.get("guild","")}] @{talker["meta"]["user_details"]["username"]}, ' f'{talker["meta"]["user_details"]["first_name"]} {talker["meta"]["user_details"].get("last_name", "")}\n' f'<code>/say {id} </code>' for id, talker in d['user_data'].items() if talker.get('meta', '')), reverse=True)[:max(len(d['user_data']), 5)] text = '\n'.join(speakers) send(text, update, context) logging.info(f'bot said:\n{text}')
def shuffle(self, payload): """Shuffles a list of keys and adds own key as described in CoinShuffle.""" if len(payload) == 0: # first client in the ring deserialized = [] else: ciphertext_size = int.from_bytes(payload[:Constants.INTEGER_SIZE], byteorder='big') assert ((len(payload) - Constants.INTEGER_SIZE) % ciphertext_size == 0) deserialized = [ payload[i:i + ciphertext_size] for i in range( Constants.INTEGER_SIZE, len(payload), ciphertext_size) ] # decrypt each message in the list ciphertexts = [self.decrypt(ciphertext) for ciphertext in deserialized] # create layered encryption of public keys and add to list for wallet in self.new_wallets: cur = bytes(wallet.address, encoding=Constants.ENCODING) for key in self.e_keys: cur = self.encrypt(cur, key) ciphertexts.append(cur) # shuffle random.shuffle(ciphertexts) # if this client is the last one in the ring if len(self.e_keys) == 0: send(self.next_addr, [ Constants.SHUFFLE, [ct.decode(Constants.ENCODING) for ct in ciphertexts] ]) else: sendbytes( self.next_addr, len(ciphertexts[0]).to_bytes(Constants.INTEGER_SIZE, byteorder='big') + b''.join(ciphertexts)) self.wallets = self.new_wallets
def scan(self): scanInterval = self.config.getint('monitor.resources.scan.interval') mem = psutil.phymem_usage() self.info['memory'] = [mem.total, mem.percent] self.info['cpu'] = psutil.cpu_percent(interval=0, percpu=True) # Get io disk counters io = psutil.disk_io_counters() if not hasattr(self, 'read_bytes') or not hasattr(self, 'write_bytes'): self.info['disk_io'] = [0, 0] else: self.info['disk_io'] = [(io.read_bytes - self.read_bytes) / scanInterval, (io.write_bytes - self.write_bytes) / scanInterval] self.write_bytes = io.write_bytes self.read_bytes = io.read_bytes # Get net io counters net = psutil.net_io_counters() if not hasattr(self, 'bytes_sent') or not hasattr(self, 'bytes_recv'): self.info['net_io'] = [0, 0] else: self.info['net_io'] = [(net.bytes_sent - self.bytes_sent) / scanInterval, (net.bytes_recv - self.bytes_recv) / scanInterval] self.bytes_sent = net.bytes_sent self.bytes_recv = net.bytes_recv # Get resource information for each seep worker self.info['workers'] = self.scanWorkers() # Get other malicious data try: out = subprocess.check_output(['bash', 'check-logs-size.sh'], cwd=(self.seep_root + '/deploy')) self.info['logs'] = [int(x) for x in re.findall('[0-9]+(?=\t)', out)] except subprocess.CalledProcessError: self.info['logs'] = [0, 0] self.info['host'] = os.uname()[1] self.log.info('Resource Report', self.info) if os.uname()[1] == self.config['yarn.host']: self.info['cluster_metrics'] = self.getClusterMetrics() payload = {'event': 'resource report', 'data': json.dumps(self.info)} util.send(self, payload)
def text(update, context): uid = update.effective_message.chat.id if not db.banned(uid): if not db.cached(uid): ut.not_started(update) else: msg = "❗ Send only one argument, following the format." args = update.message.text.split() if len(args) == 1: if uid in STATE: if STATE[uid] == ut.CMD.SET: msg = (f"❗ Value must be an integer lower " f"than {ut.RESIN_MAX}.") msg = _set_resin(args, uid, msg) elif STATE[uid] == ut.CMD.SPEND: cur_resin = db.get_resin(uid) msg = (f"❗ Value must be an integer greater than 0 " f"and lower than {cur_resin}.") msg = _spend(args, uid, msg, cur_resin) elif STATE[uid] == ut.CMD.REFILL: cur_resin = db.get_resin(uid) max_resin = ut.RESIN_MAX - cur_resin msg = (f"❗ Value must be an integer greater than 0 " f"and lower than {max_resin}.") msg = _refill(args, uid, msg, cur_resin, max_resin) elif STATE[uid] == ut.CMD.TRACK: msg = "❗ Timer must have format: <code>mm:ss</code>." msg = _track(args, context.bot, uid, msg) elif STATE[uid] == ut.CMD.WARN: msg = (f"❗ Value must be an integer greater than 0 " f"and lower than {ut.RESIN_MAX}, " f"or <code>-1</code>.") msg = _warnings(args, uid, msg) elif STATE[uid] == ut.CMD.TZ: msg = ("❗ Hour must have format(24h): " "<code>hh:mm</code> " "or <code>-1</code>.") msg = _timezone(args, uid, msg) else: _state(uid) ut.send(update, msg)
def warnings(update, context): uid = update.effective_message.chat.id if not db.banned(uid): if not db.cached(uid): ut.not_started(update) else: msg = (f"❗ Argument must be an integer greater than 0 " f"and lower than {ut.RESIN_MAX}, or -1, " f"e.g. /warnings, /warnings -1, /warning 140") if context.args: msg = _warnings(context.args, uid, msg) else: cur_warn = db.get_warn(uid) if cur_warn == -1: cur_warn = "disabled" msg = (f"{ut.text_format('Warning threshold', cur_warn)}\n\n" f"Tell me resin value to be warned at, " f"or <code>-1</code> to disable") _state(uid, ut.CMD.WARN) db.dec_strikes(uid) ut.send(update, msg)
def lambda_handler(event, context): try: http_params = event["queryStringParameters"] if len(REQUIRED_PARAMS - set(http_params)) != 0: raise Exception() except: return send(400, "Bad Request") for param in http_params: if http_params[param].lower() in {"true", "false"}: http_params[param] = http_params[param] == "true" for opt_param in OPTIONAL_PARAMS: if opt_param in http_params: continue http_params[opt_param] = OPTIONAL_PARAMS[opt_param] # Adjusting the arguments convert boolean strings to bools. Also # Add the optional arguments. database = boto3.resource("dynamodb") rds_invoke = boto3.client('lambda') timeline = generate_timeline(database, http_params["start_date"], http_params['timeline']) useridmap = genrate_useridmap(rds_invoke) # get earliest date for filtering from interaction table earliest_date = timeline.earliest(datetime.strptime(http_params['start_date'], TIME_FORMAT)) http_params['earliest'] = earliest_date.strftime(TIME_FORMAT) timeline.register(ROOT_ID, datetime(2019, 1, 1), True) # mark patient zero as ill graph = generate_graph(database, http_params['earliest'], http_params['start_date'], timeline) tree = generate_tree(graph, http_params['earliest'], http_params['start_date'], useridmap, timeline) return send(200, json.dumps({ "timeline": structures.timelinetodict(timeline, http_params['earliest'], http_params['start_date'], TIME_FORMAT, useridmap), "level": structures.Node.DICT, "tree": structures.nodetodict(tree) }))
def qq_read_box(): title = f'📚企鹅读书' result = '' beijing_datetime = get_standard_time() obj_l = [] print(f'\n【企鹅读书】{beijing_datetime.strftime("%Y-%m-%d %H:%M:%S")}\n') with ProcessPoolExecutor(max_workers=5) as executor: for i in range(0, len(COOKIELIST)): obj = executor.submit(account_read, COOKIELIST[i]) obj_l.append(obj) executor.shutdown(wait=True) for future in obj_l: result += future.result() # 每天 23:00 发送消息推送 if beijing_datetime.hour == 23 and beijing_datetime.minute < 5: send(title=title, content=result) elif not beijing_datetime.hour == 23: print('未进行消息推送,原因:没到对应的推送时间点\n') else: print('未在规定的时间范围内\n')
def send_email(new_relays): # Constructs a mapping of nicknames to router status entries so we can # provide a listing that's sorted by nicknames. nickname_to_relays = {} for entry in new_relays: nickname_to_relays.setdefault(entry.nickname, []).append(entry) relay_entries = [] for nickname in sorted(nickname_to_relays.keys()): for relay in nickname_to_relays[nickname]: relay_entries.append(RELAY_ENTRY % (relay.nickname, relay.fingerprint, relay.address, relay.or_port, relay.version, relay.exit_policy)) try: body = EMAIL_BODY % len(new_relays) body += "\n".join(relay_entries) util.send(EMAIL_SUBJECT, body = body) except Exception as exc: log.warn("Unable to send email: %s" % exc)
def post(self, msg, rep): """Post a message.""" # see if wallets have enough reputation if len(self.wallets) < rep: eprint(self.name, 'You do not have enough reputation to post that.') return False # if rep is 0, generate a new wallet to use if rep == 0: wallets_to_use = [bc.generate_keypair()] # otherwise, use the first rep wallets in self.wallets else: wallets_to_use, self.wallets = self.wallets[:rep], self.wallets[ rep:] # sign public keys addresses = [w.address for w in wallets_to_use] signatures = [ bc.sign(w.privateKey, w.address).signature.hex() for w in wallets_to_use ] # if haven't already, start up a server for coinshuffle. if not self.listening: self.ss = socket.socket() self.ss.bind(config.CLIENT_ADDR) self.ss.listen(5) self.addr = self.ss.getsockname() self.listening = True Thread(target=self.start_server, args=(self.ss, ), daemon=True).start() send(self.server_addr, [Constants.NEW_MESSAGE, msg, addresses, signatures, self.addr]) return True
def run(): print(f"喜马拉雅极速版 (https://github.com/Zero-S1/xmly_speed/blob/master/xmly_speed.md ) ,欢迎打赏¯\(°_o)/¯") mins, date_stamp, _datatime, _notify_time = get_time() title = '⏰ 喜马拉雅极速版' table = [] for k, v in enumerate(cookiesList): print(f">>>>>>>【账号开始{k+1}】\n") cookies = str2dict(v) if XMLY_ACCUMULATE_TIME == 1: saveListenTime(cookies, date_stamp) listenData(cookies, date_stamp) stage(cookies) # 新手任务 read(cookies) # 阅读 bubble(cookies) # 收金币气泡 # continue continuousDays = checkin(cookies, _datatime) # 自动签到 # lottery_info(cookies) # 大转盘4次 answer(cookies) # 答题赚金币 cardReportTime(cookies, mins, date_stamp, _datatime) # 卡牌 getOmnipotentCard(cookies, mins, date_stamp, _datatime) # 领取万能卡 card(cookies, _datatime) # 抽卡 index_baoxiang_award(cookies) # 首页、宝箱奖励及翻倍 total, todayTotal, historyTotal = account(cookies) try: device = devices[k] except IndexError: device = cookies['device_model'] else: device = f"设备{k+1}" table.append((device, total, todayTotal, historyTotal, continuousDays,)) if autoTakeOut and total >= amount: pay_info = third_pay_info(cookies) if pay_info and pay_info['name'] and pay_info['accountType'] and pay_info["accountNumber"]: body = {"name": pay_info['name'], "accountType": pay_info['accountType'], "accountNumber": pay_info["accountNumber"], "amount": amount, "takeOutType": takeOutType} task_out_res = task_out(cookies=cookies, body=body) if task_out_res: send(title=title, content=f"{device} 提现到账户【{pay_info['accountNumber']}】20元成功") else: send(title=title, content=f"请先手动填写【账号{k+1}】支付宝账号提现一次") print("###"*20) print("\n"*4) if int(_notify_time.split()[0]) == notify_time and int(_notify_time.split()[1]) < 5: # if 1: message = '' for i in table: message += f"【设备】:{i[0].replace(' ',''):<9}\n" message += f"【当前剩余】:{i[1]:<6.2f}\n" message += f"【今天】:+{i[2]:<4.2f}\n" message += f"【历史】:{i[3]:<7.2f}\n" message += f"【连续签到】:{i[4]}/30\n" message += f"\n" send(title=title, content=message)
def timezone(update, context): uid = update.effective_message.chat.id if not db.banned(uid): if not db.cached(uid): ut.not_started(update) else: msg = ("❗ Argument must have format(24h): hh:mm or -1, " "e.g. /timezone, /timezone -1, /timezone 18:30") if context.args: msg = _timezone(context.args, uid, msg) else: tz_hour, tz_minutes = db.get_timezone(uid).split(':') if tz_hour == 'null': tz = "disabled" else: tz = ut.normalize_timezone(tz_hour, tz_minutes) msg = (f"{ut.text_format('Current timezone', tz)}\n\n" f"Tell me your current hour " f"in format(24h): <code>hh:mm</code>, " f"or <code>-1</code> to disable") _state(uid, ut.CMD.TZ) db.dec_strikes(uid) ut.send(update, msg)
def _master_loop(self): # global node_list # global active_node_list # global dead_node_set print("_master_loop ENTER") self._logger.info("Master Loop start") while self._continue: print("_master_loop while loop start") # 1) Check number of masters - this includes sleeping if self._get_master_count(1) == "TOO_HIGH": if not self._continue_as_master(): break # 2) Read node list file, update own node collections if needed self._ctx.resource_lock.acquire() print("_master_loop _sync_collections") node_list_changed = self._sync_collections(self._ctx.node_list)[0] # 3) Process notifications #mail_sender.send_notifications(ntf_reader.get_notifications(node_list)) self._ctx.ntf_manager.process_notifications(self._ctx.ntf_reader.get_notifications(self._ctx.node_list)) # 4) Send and store changes if node_list_changed: util.send(self._ctx.this_node, self._ctx.active_node_list, util.json_from_list(self._ctx.active_node_list, 'active_node_list')) util.store_list_to_file(self._ctx.active_node_list, self._ctx.active_node_list_file, self._ctx.this_node.group_name) # 5) release lock self._ctx.resource_lock.release() # Can not continue as master if self._continue: self._become_a_slave()
def sync(self, sock): util.send(sock, "ls -l") remote_data = util.recv(sock) remote_data = json.loads(remote_data) client_data = commands.ls(self.basedir, long=True) client_data = json.loads(client_data) client_filelist = list(map(lambda f: f["name"], client_data)) remote_filelist = list(map(lambda f: f["name"], remote_data)) cue_download = [] cue_upload = [] for file in remote_data: if file["name"] not in client_filelist: cue_download.append(file["name"]) for file in client_data: if file["name"] not in remote_filelist: cue_upload.append(file["name"]) for file in remote_data: if not file["name"] in client_filelist: continue # do not request hash if file was modified before previous sync if file['name'] in self.last_synced and file["mtime"] < self.last_synced[file['name']]: continue util.send(sock, f"hash {file['name']}") hsh = util.recv(sock) local_hsh = util.hashfile(os.path.join(self.basedir, file['name'])) if hsh != local_hsh: # IMPORTANT LOGIC local_file = [f for f in client_data if f.get('name')== f['name']][0] if file['mtime'] > local_file['mtime']: # server updated file after client cue_download.append(file['name']) else: # client updated dile after server cue_upload.append(file['name']) else: # mtime differs but file is in sync as compared by hash self.last_synced[file['name']] = time.time() for filename in cue_upload: util.send(sock, f"upload {filename}") file_transfer.upload_file(sock, self.basedir, filename) self.last_synced[filename] = time.time() for filename in cue_download: util.send(sock, f"download {filename}") file_transfer.download_file(sock, self.basedir, filename) self.last_synced[filename] = time.time()
def disp_board(self, s, msg_args): """Handles request for message board.""" send(s, self.board)
def qq_read_box(): title = f'📚企鹅读书' content = '' result = '' beijing_datetime = get_standard_time() print(f'\n【企鹅读书】{beijing_datetime.strftime("%Y-%m-%d %H:%M:%S")}\n') for account in COOKIELIST: headers = account['QQREAD_TIMEHD'] body = account['QQREAD_BODY'] guid = re.search(r'ywguid\=(\d+)\;', headers['Cookie']) content += f'【账号】:{guid.group(1)}' result += f'【账号】:{guid.group(1)}' error_catch = 0 if beijing_datetime.hour == 0: track_result = track(headers=headers, body=body) if track_result: content += f'\n【数据跟踪】跟踪成功!' else: content += f'\n【数据跟踪】跟踪失败!请重新抓取你的参数 body ' # 获取任务列表,查询金币余额 daily_tasks = get_daily_tasks(headers=headers) # 开宝箱领金币 if daily_tasks['treasureBox']['timeInterval'] <= 5000: print( f"等待{math.ceil(daily_tasks['treasureBox']['timeInterval'] / 1000)}秒,开启宝箱" ) time.sleep( math.ceil(daily_tasks['treasureBox']['timeInterval'] / 1000)) treasure_box_reward = open_treasure_box(headers=headers) if treasure_box_reward: content += f"\n【开启第{treasure_box_reward['count']}个宝箱】获得{treasure_box_reward['amount']}金币" error_catch = treasure_box_reward['amount'] # 宝箱金币奖励翻倍 daily_tasks = get_daily_tasks(headers=headers) if daily_tasks['treasureBox']['videoDoneFlag'] == 0: treasure_box_ads_reward = watch_treasure_box_ads(headers=headers) if treasure_box_ads_reward: content += f"\n【宝箱奖励翻倍】获得{treasure_box_ads_reward['amount']}金币" error_catch = treasure_box_ads_reward['amount'] if error_catch == 1: send(title=title, content=f'【账号】:{guid.group(1)} 数据异常') # 输出任务列表中的信息 if daily_tasks: content += f'\n【宝箱任务】已开{daily_tasks["treasureBox"]["count"]}个宝箱,下一个宝箱{daily_tasks["treasureBox"]["tipText"]}\n\n' result += f'\n【宝箱任务】:已开{daily_tasks["treasureBox"]["count"]}个宝箱\n\n' print(content) # 每天 23:00 发送消息推送 if beijing_datetime.hour == 23 and beijing_datetime.minute < 5: send(title=title, content=result) elif not beijing_datetime.hour == 23: print('未进行消息推送,原因:没到对应的推送时间点\n') else: print('未在规定的时间范围内\n')
def rev_announcement(self, s, msg_args): """Handles doing a reverse announcement. secret: Secret for ElGamal decryption. server_pub_keys: Public keys of servers. ann_list_pre: Announcement list before the previous server's modifications. ann_list_post: Announcement list after the previous server's modifications. g_, h_: Verifiable shuffle parameters init_id: The id of the server that was the first in the ring. """ (secret, server_pub_keys, ann_list_pre, ann_list_post, g_, h_, init_id) = msg_args ann_list = ann_list_post if init_id != self.server_id: if init_id == Constants.INIT_ID: init_id = self.server_id ann_list = [] ann_list.append([k for k in self.stp_list.keys()]) ann_list.append([(secret, v) for v in self.stp_list.values()]) else: # verify shuffle from prev server if not shuffle.verify(s, ann_list_pre, ann_list_post, g_, h_): eprint(self.name, 'Verifiable shuffle failed.') s.close() return s.close() self.eph_key = randkey() # update announcement list server_pub_keys.append(self.pub_key) self.secret = powm(secret, self.pri_key) secret = (secret * powm(Constants.G, self.eph_key)) % Constants.P ann_list[1] = [(sec, (rep * self.secret) % Constants.P) for sec, rep in ann_list[1]] new_ann_list = self.announcement_bwd(ann_list, secret, server_pub_keys) # shuffle announcement list n = len(new_ann_list[0]) pi = shuffle.generate_permutation(n) new_ann_list = [shuffle.shuffle(elts, pi) for elts in new_ann_list] # update parameters beta = self.eph_key g_ = Constants.G h_ = 1 for server_pub_key in server_pub_keys: h_ = (h_ * server_pub_key) % Constants.P # pass announcement list to next server s = socket.socket() s.connect(self.prev_addr) send(s, [ Constants.REV_ANNOUNCEMENT, secret, server_pub_keys, ann_list, new_ann_list, g_, h_, init_id ]) # prove shuffle to prev server if self.addr != self.prev_addr: shuffle.prove(s, ann_list, new_ann_list, pi, beta, g_, h_) else: # verify shuffle from next server (if more than one server) if self.addr != self.next_addr: if not shuffle.verify(s, ann_list_pre, ann_list_post, g_, h_): eprint(self.name, 'Verifiable shuffle failed.') s.close() return s.close() # initialize add announcement ltp_list = list(zip(ann_list[0], [rep for sec, rep in ann_list[1]])) ann_args = [ltp_list, secret, Constants.INIT_ID] self.replace_ltp(ann_args)
def get_stp_array(self, s, msg_args): """Handles a request for the short-term pseudonym list.""" send(s, self.stp_array)
def get_generator(self, s, msg_args): """Handles a request for the server's generator this round.""" send(s, self.generator)
def check_node_still_dead(self, node): print(" **************************ENTER check_node_still_dead") # ogger = logging.getLogger('nodechecker.ncv') self.logger.debug('*****************************ENTER check_node_still_dead') # global active_node_list # global new_dead_node_set # global dead_node_set # global min_time_diff # now = time.mktime(time.localtime()) self.logger.debug("hm root" + self._ctx.conf.hm_root) #path = os.path.join(self._ctx.conf.hm_root, self._ # ctx.conf.collectd_home, self._ctx.conf.collectd_rrd_dir, n.hostname) path = os.path.join(self._ctx.conf.hm_root, self._ctx.conf.collectd_home, self._ctx.conf.collectd_rrd_dir, node.hostname) path1 = os.path.join(self._ctx.conf.hm_root, self._ctx.conf.collectd_home, self._ctx.conf.collectd_rrd_dir) path2 = os.path.join(self._ctx.conf.hm_root, self._ctx.conf.collectd_home) # path3= os.path.join(self._ctx.conf.hm_root, self._ctx.conf.collectd_home, self. # _ctx.conf.collectd_rrd_dir, node.hostname) self.logger.debug("path1" + path1) self.logger.debug("path2" + path2) self._ctx.resource_lock.acquire() try: self._ctx.min_time_diff = -1 self.logger.debug("path" + path) os.path.walk(path, self.find_minimal_rrd_timestamp, [time.mktime(time.localtime())]) diff = self._ctx.min_time_diff self.logger.debug("dif:" + str(diff)) self.logger.debug("timeout" + str(self._ctx.dead_node_timeout)) if 0 < diff < self._ctx.dead_node_timeout: self.logger.debug('check_node_still_dead() node is alive: Diff < self._ctx.dead_node_timeout') pass else: self.logger.debug('check_node_still_dead() node is dead' + node.ip_address) if node in self._ctx.active_node_list: self._ctx.active_node_list.remove(node) else: print("this is strange") self._ctx.dead_node_set.add(node.ip_address) util.send(self._ctx.this_node, self._ctx.node_list, util.json_from_list( self._ctx.active_node_list, 'active_node_list')) self.logger.debug("process node status alerts...") self._ctx.ntf_manager.process_node_status_alerts([node], "DEAD_NODE") self.logger.debug("storing list to file...") util.store_list_to_file( self._ctx.active_node_list, self._ctx.active_node_list_file, self._ctx.this_node.group_name) #self.logger.debug("removing node from set of new dead...") #self._ctx.new_dead_node_set.remove(node.ip_address) except: self.logger.debug("Star 3") util.log_exception(sys.exc_info()) print(" EXCEPTION in check_node_still_dead" + str(sys.exc_info())) pass finally: self._ctx.new_dead_node_set.remove(node.ip_address) #self.logger.debug("self._ctx.new_dead_node_set.remove" + str(len(self._ctx.new_dead_node_set))) self._ctx.resource_lock.release() print(" exit check_node_still_dead")
def _process_active_node_list_change(self): util.send(self._ctx.this_node, self._ctx.node_list, util.json_from_list(self._ctx.active_node_list, 'active_node_list')) util.store_list_to_file(self._ctx.active_node_list, self._ctx.active_node_list_file, self._ctx.this_node.group_name)