def digest(ch, method, properties, body): start = time.time() ch.basic_ack(delivery_tag=method.delivery_tag) message = json.loads(body) print(termcolor.colored(str(message), 'cyan'), flush=True) if message['tag'] == 'normal': start_normal(message) elif message['tag'] == 'normal_force': start_normal_force(message) elif message['tag'] == 'paid': start_paid(message) elif message['tag'] == 'paid_force': start_paid_force(message) else: print(termcolor.colored('Unknown tag context ↑↑↑', 'red', attrs=['reverse']), flush=True) end = time.time() helper.send_message( message['ip'], message['tag'] + ' Done in ' + str(time.strftime('%H:%M:%S', time.gmtime(round(end - start, 1))))) print(termcolor.colored( 'Done in ' + str(time.strftime('%H:%M:%S', time.gmtime(round(end - start, 1)))), 'green', attrs=['reverse']), flush=True)
def digest(ch, method, properties, body): start = time.time() ch.basic_ack(delivery_tag=method.delivery_tag) message = json.loads(body) print(termcolor.colored(message, 'cyan'), flush=True) if message['tag'] == 'convert': start_convert(message) elif message['tag'] == 'tablet': start_tablet(message) elif message['tag'] == 'announce': start_announce(message) elif message['tag'] in ['rabiea', 'rabiea-480', 'rabiea-sizeless']: start_rabiea(message) else: print('Unknown tag context ... ->' + str(message), flush=True) end = time.time() helper.send_message( message['ip'], message['tag'] + ' Done in ' + str(time.strftime('%H:%M:%S', time.gmtime(round(end - start, 1))))) print(termcolor.colored( 'Done in ' + str(time.strftime('%H:%M:%S', time.gmtime(round(end - start, 1)))), 'green', attrs=['reverse']), flush=True)
def future_spread_alerting(spread, return_annual, symbol=None, is_spread_neg=False, send_to_chat=True): future_price_df = get_future_price() future_price_df = filter_future_price(future_price_df, spread, return_annual, symbol=symbol, is_spread_neg=is_spread_neg) formated = format_df(future_price_df) string_file = save_formated_df_picture(formated) if send_to_chat: send_message( string_file, chat_id, telegram_token, caption='Checkout the Coin-M future spread 🦅', disable_notification=False, ) else: return string_file
def timeFailure(self, node, seconds): if (node in self.queue_list): print("Process already frozen or failed") return self.queue_list.append(node) send_message("freeze", node.port) time.sleep(seconds) send_message("unfreeze", node.port) print(f"P{node.id_} is unfrozen") self.queue_list.remove(node)
def arbFailure(self, node, seconds): if (node in self.queue_list): print("Process already frozen or failed") return self.queue_list.append(node) send_message("fail", node.port) time.sleep(seconds) send_message("unfail", node.port) print(f"P{node.id_} is no longer failing at life") self.queue_list.remove(node)
def startWebsite(userID, message, type='text'): response_yes = globalVar.localdata["product_page"][globalVar.locale] if type == 'payload' and getPayload(message) == 'yes': bot.send_button_message(userID, response_yes, buttons.business_type) globalVar.userState[userID].currState = 'selectingType' return elif type == 'payload' and getPayload(message) == 'no': response_no = "Todo fill this later" send_message(userID, response_no,bot) return
def checkOnProcesses(self): if (self.coordinator == None or send_message("here?", self.coordinator.port) != "ok"): print("No coordinator, no progress") return False ok = True for node in self.node_list: if (node != self.coordinator): if (send_message("here?", node.port) != "ok"): ok = False break return ok
def startBusiness(userID, message, type='text'): response = globalVar.localdata["template"][globalVar.locale] if type == 'payload' and (getPayload(message) in {'business','community'}): globalVar.userState[userID].currState = 'insertName' globalVar.userState[userID].businessType = getPayload(message) send_message(userID, response, bot) buttons.send_carousel(userID, ACCESS_TOKEN) return elif type == 'payload': send_message(userID, "Sorry, that's not a valid option! Please try again!", bot) buttons.send_carousel(userID, ACCESS_TOKEN) return
def main(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((server_ip, int(server_port_number))) response = base64.b64decode(s.recv(1024)) with open("server_pub.txt", "wb") as pu: pu.write(response) server_public_key = load_pem_public_key(response) new_client = input("Are you a new client(y/n): ") if new_client == "y": # Registration with KDC print("Please register with KDC....") password = input("Enter password(max characters-8): ") data = { 'type': 'Registration', 'name': user_name, 'passwd': password, } encrypted_data = encrypt_msg(server_public_key, data) s.sendall(encrypted_data) response = json.loads(s.recv(1024)) if response['code'] == "OK": print("Registration Succesful!! :)") is_ssh_request = input("Do you wish to ssh into the server?(y/n): ") if is_ssh_request == "y": password = input(f"Hi {user_name}, Please enter your password: "******"OK": print( "You are now authenticated to access the server's shell!!") while True: command = input("Enter command to be executed: ") if command == "logout": break iv_bytes = os.urandom(16) iv = base64.b64encode(iv_bytes).decode('utf-8') encrypted_command = encrypt_with_AES( session_key_bytes, iv_bytes, command) message = {"command": encrypted_command, "iv": iv} send_message(message, s) response = json.loads(s.recv(1024)) print(response)
def digest(ch, method, properties, body): start = time.perf_counter() ch.basic_ack(delivery_tag=method.delivery_tag) message = json.loads(body) print(termcolor.colored(message, 'cyan'), flush=True) if message['tag'] == 'axis': start_axis(message) else: print('Unknown tag context ... ->' + str(message), flush=True) end = time.perf_counter() helper.send_message( message['ip'], message['tag'] + ' Done in ' + str(time.strftime('%H:%M:%S', time.gmtime(round(end - start, 1))))) print(termcolor.colored( 'Done in ' + str(time.strftime('%H:%M:%S', time.gmtime(round(end - start, 1)))), 'green', attrs=['reverse']), flush=True)
def digest(ch, method, properties, body): start = time.perf_counter() ch.basic_ack(delivery_tag=method.delivery_tag) message = json.loads(body) print(termcolor.colored(str(message), 'cyan'), flush=True) if message['tag'] == 'normal': start_upload(message, PATH_NORMAL, PATH_UPSTREAM_NORMAL) elif message['tag'] == 'paid': start_upload(message, PATH_PAID, PATH_UPSTREAM_PAID) elif message['tag'] == 'pamphlet': start_upload(message, PATH_PAMPHLET, PATH_UPSTREAM_PAMPHLET) elif message['tag'] == 'introVideo': start_upload(message, PATH_INTRO_VIDEO, PATH_UPSTREAM_INTRO_VIDEO) else: print(termcolor.colored('Unknown tag context ↑↑↑', 'red', attrs=['reverse']), flush=True) end = time.perf_counter() helper.send_message(message['ip'], message['tag'] + ' Done in ' + str( time.strftime('%H:%M:%S', time.gmtime(round(end - start, 1))))) print( termcolor.colored('Done in ' + str(time.strftime('%H:%M:%S', time.gmtime(round(end - start, 1)))), 'green', attrs=['reverse']), flush=True)
def middleWare(message, recipient_id, bot): if message['message'].get('text') == 'debug reset': resetState() send_message(recipient_id, 'Debug: Your State should now be reset!', bot) print('Resetting State') return True if message['message'].get('text') == 'debug toggle': if globalVar.locale == "cn": globalVar.locale = "en" elif globalVar.locale == "en": globalVar.locale = "cn" else: print("error") message = 'Debug' + 'Toggling Language To ' + globalVar.locale print(message) send_message(recipient_id, message, bot) return True return False
def send_msg(): while True: message = sys.stdin.readline().rstrip('\n') if message == "Exit()": print("Connection closed") # close connection with central server client_socket.send((send_message(message, sym_key_with_central_server))) client_socket.close() # close connection with all other clients for j in client_dic: sym_key = client_dic[j]["key"] j.send(send_message(message, sym_key)) j.send(send_message(username + " has left the server", sym_key)) sys.exit() else: for j in client_dic: sym_key = client_dic[j]["key"] j.send(send_message(username + ": " + message, sym_key)) prompt()
def handleCreation(self, id_, is_coordinator, lastValue): # add each node to the network with Node class node_id = int(id_.replace("P", "")) # Create Node obj to store in the node_list node_obj = Process(node_id, is_coordinator, self.current_port, self.consistency_history[-1]) create(node_obj.id_, node_obj.is_coordinator, node_obj.port, node_obj.value) reply = send_message("here?", node_obj.port) if reply == "ok": self.node_list.append(node_obj) if node_obj.is_coordinator: self.coordinator = node_obj print( f"Node {node_obj.label} has been created on PORT {self.current_port}" )
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # allow to reconnect to the same port server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(('', client_PORT_recv_msg)) server_socket.listen(10) # client connecting to server server_host = input("Please Enter Server IP Address: ") username = input("Create Your Username: "******"Enter the room number you want to join: ") client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((server_host, server_PORT)) print("Connect to central server successfully. ") print("-----Enter 'Exit()' to leave anytime-----") sym_key_with_central_server = encryption_gen_sym(client_socket) client_socket.send(send_message( room_number, sym_key_with_central_server)) # send room number client_socket.send( send_message(str(client_PORT_recv_msg), sym_key_with_central_server) ) # send client's port for receiving message # ____________________________________________________________________ socket_list = [socket.socket(), server_socket, client_socket] # store all the sockets client_dic = {} # store all other clients' info prompt() if __name__ == '__main__': client_dic = {} Thread(target=send_msg, args=()).start() Thread(target=recv_msg, args=()).start() while True:
connecting_socket, connecting_address = server_socket.accept() ip_address, port = connecting_address print("Accept new connection from: " + str(ip_address) + ": " + str(port)) sym_key_with_client = encryption_recv_sym(connecting_socket) room_number = receive_message(connecting_socket, sym_key_with_client) client_port = receive_message( connecting_socket, sym_key_with_client) # client's port for receiving message socket_list.append(connecting_socket) for j in client_dic: # send the new client's ip address in existing dictionary if room_number == client_dic[j]["room"]: j.send(send_message(str(ip_address), client_dic[j]["key"])) j.send(send_message(str(client_port), client_dic[j]["key"])) client_dic[connecting_socket] = { "room": room_number, "key": sym_key_with_client } # add the new client to the dictionary else: # existing connection sym_key_with_client = client_dic[i]["key"] message = receive_message(i, sym_key_with_client) # the client wants to leave if message == "Exit()": print("Some client has just left.")
def receive_message(): try: print('Received Message') # get whatever message a user sent the bot output = request.get_json() for event in output['entry']: if ("messaging" not in event): print('No messages in event') return "Message Processed" messaging = event['messaging'] for message in messaging: # Check if user exists in state management, if not create user if message.get('message'): recipient_id = message['sender']['id'] print(recipient_id) print(message) print("Processing Message") if (middleWare(message, recipient_id, bot) == True): return "Message Processed" if (recipient_id not in globalVar.userState): createUser(recipient_id) sendInitialMessage(recipient_id) print('Created user with id ', recipient_id) return "Messaged Processed" else: currState = globalVar.userState[recipient_id].currState if currState == 'initial': startWebsite(recipient_id, message['message'].get('text'), 'text') if(message['message'].get('text') == 'yes'): return "test" elif currState == 'insertName': send_message(recipient_id, "Sorry, that's not a valid option! Please try again!", bot) buttons.send_carousel(recipient_id, ACCESS_TOKEN) elif currState == 'insertName2': # You can validate name here businessName = message['message'].get('text') globalVar.userState[recipient_id].websiteName = businessName responseTemp = "Your business name is " + businessName send_message(recipient_id, responseTemp, bot) send_message(recipient_id, globalVar.localdata["business_address"][globalVar.locale], bot) globalVar.userState[recipient_id].currState = 'insertAddress' elif currState == 'insertAddress': addressName = message['message'].get('text') globalVar.userState[recipient_id].address = addressName responseTemp = "Your business address is " + addressName send_message(recipient_id, responseTemp, bot) send_message(recipient_id, globalVar.localdata["business_email"][globalVar.locale], bot) globalVar.userState[recipient_id].currState = 'insertEmail' elif currState == 'insertEmail': emailName = message['message'].get('text') globalVar.userState[recipient_id].email = emailName responseTemp = "Your email address is " + emailName send_message(recipient_id, responseTemp, bot) send_message(recipient_id, globalVar.localdata["business_phoneNumber"][globalVar.locale], bot) globalVar.userState[recipient_id].currState = 'insertNumber' elif currState == 'insertNumber': numberName = message['message'].get('text') globalVar.userState[recipient_id].phoneNumber = numberName responseTemp = "Your phone number is " + numberName send_message(recipient_id, responseTemp, bot) generateJson(recipient_id) send_message(recipient_id, "Done! We have generated your site!", bot) test = 'https://dynamic-website-builder.herokuapp.com' send_message(recipient_id, test, bot) globalVar.userState[recipient_id].currState = 'free' elif currState == 'free': nlp = message["message"].get("nlp") entities = nlp.get("entities") intent = entities.get("Intent")[0].get("value") website_feat = entities.get("website_feature")[0].get("value") if website_feat == "phone number": web_feat_val = entities.get("phone_number")[0].get("value") globalVar.userState[recipient_id].phoneNumber = web_feat_val responseNLP = "Sure thing! Changing your phoneNumber" send_message(recipient_id, responseNLP, bot) elif website_feat == "address": web_feat_val =entities.get("location")[0].get("value") globalVar.userState[recipient_id].address = web_feat_val responseNLP = "Sure thing! Changing your address!" send_message(recipient_id, responseNLP, bot) elif website_feat == "email": web_feat_val =entities.get("email")[0].get("value") globalVar.userState[recipient_id].email = web_feat_val responseNLP = "Sure thing! Changing your email!" send_message(recipient_id, responseNLP, bot) elif website_feat == "title": web_feat_val =entities.get("title")[0].get("value") globalVar.userState[recipient_id].websiteName = web_feat_val responseNLP = "Sure thing! Changing your business name!" send_message(recipient_id, responseNLP, bot) elif website_feat == "description": web_feat_val =entities.get("slogan")[0].get("value") globalVar.userState[recipient_id].slogan = web_feat_val responseNLP = "Sure thing! Changing your slogan!" send_message(recipient_id, responseNLP, bot) finalJson = generateJson(recipient_id) return "banana" # Do analysis here for NLP if message.get('postback'): recipient_id = message['sender']['id'] currState = globalVar.userState[recipient_id].currState print(currState) if currState == 'initial': startWebsite(recipient_id, message, 'payload') elif currState == 'selectingType': startBusiness(recipient_id, message, 'payload') elif currState == 'insertName': print('test') send_message(recipient_id, globalVar.localdata["business_name"][globalVar.locale], bot) globalVar.userState[recipient_id].currState = 'insertName2' return "Message Processed" except Exception as e: print("There was an error bug I'm ignoring it") print(e) return "Errored out!"
def process_command(self, command): message = "" if (command == 'list'): for node in self.node_list: message += send_message("list", node.port) + "\n" elif (command == 'history' or command == 'hist'): message = self.consistency_history # this is problematic, the coordinator isn't doing anything, he is treated just like other nodes # if you remove the -, you need to change the split function in Process elif (command.startswith('set-value') or command.startswith("st")): value = int(command.split(" ")[1]) if (self.checkOnProcesses()): for node in self.node_list: message += send_message(f"value {value}", node.port) + "\n" self.consistency_history.append(value) else: message = "Aborted, not all nodes are active" elif (command.startswith("rollback")): N = int(command.split(" ")[1]) if (N >= len(self.consistency_history)): message = "Aborted, N value too big" elif (N <= 0): message = "Aborted, N value must be bigger than 0" elif (self.checkOnProcesses()): self.consistency_history = self.consistency_history[:N] newValue = self.consistency_history[-1] for node in self.node_list: message += send_message(f"value {newValue}", node.port) + "\n" else: message = "Aborted, not all nodes are active" elif (command.startswith("add")): nd = command.split(" ")[1] check = True for node in self.node_list: if (send_message("id", node.port) == str(nd[1])): message = "Aborted, such a Process already exists" check = False break if (check): self.handleCreation(nd, False, self.current_port) message = f"{nd} added" elif command.startswith('remove') or command.startswith( "rm"): # Solved? try: id_ = int(command.split(' ')[1][1]) except: print("Please specify the process id") return print(id_) for node in self.node_list: if node.id_ == id_: send_message("kill", node.port) print(f"Process {node.id_} is going to leave") self.node_list.remove(node) # should check algorithm later if node.is_coordinator: self.coordinator = None break elif command.startswith("Time-failure") or command.startswith("tf"): # smug process_, secs = command.split(" ")[1], int(command.split(" ")[2]) node = self.findProcess(process_) if (node != None): t = threading.Thread(target=self.timeFailure, args=( node, secs, )) t.start() message = f"P{node.id_} is frozen for {secs} seconds" else: message = "No such process" elif command.startswith("Arbitrary-failure") or command.startswith( "af"): # smug process_, secs = command.split(" ")[1], int(command.split(" ")[2]) node = self.findProcess(process_) if (node != None): t = threading.Thread(target=self.arbFailure, args=( node, secs, )) t.start() message = f"P{node.id_} is a failure for {secs} seconds" else: message = "No such process" print(message)
def funding_alert(threshold, futures_type, symbol=None, is_neg=False, disable_notification=False, is_both=False, send_to_chat=True): # FuturesType.USD_M # FuturesType.COIN_M global is_handling is_handling = True time_str = datetime.now().strftime("%Y-%m-%d_%H%M%S") file_name = f'data/temp_funding_{time_str}.csv' if futures_type == FuturesType.COIN_M: str_corbak = 'COIN-M' elif futures_type == FuturesType.USD_M: str_corbak = 'USD-M' def handle_socket_message(msg, time_str=''): global is_handling data = msg['data'] data = pd.DataFrame(data) data.to_csv(f'data/temp_funding_{time_str}.csv', index=False) is_handling = False return "123...soleil" handle_socket_message = partial(handle_socket_message, time_str=time_str) twm = ThreadedWebsocketManager(api_key=api_key, api_secret=api_secret) twm.start() twm.start_all_mark_price_socket( callback=handle_socket_message, futures_type=futures_type, ) while is_handling: pass twm.stop() my_file = Path(file_name) if my_file.is_file(): data = pd.read_csv(file_name) data = _df_funding_astype(data, futures_type=futures_type) data = _df_funding_filter(data, symbol=symbol, threshold=threshold, is_neg=is_neg, is_both=is_both) if not data.empty: data = _df_funding_format(data, futures_type=futures_type) file_name = save_formated_df_picture(data, 'funding_df') if send_to_chat: send_message( file_name, chat_id, telegram_token, caption=f'{str_corbak} funding rates 🦅', disable_notification=disable_notification, ) else: return file_name else: funding_alert(threshold, futures_type, symbol, is_neg, disable_notification, is_both, send_to_chat)