def greetings(self): subject = "H!, I'm Caroline, your system health doctor." message = "Your computer slept fine, any way It's up now and I will update you as soon as I spot any abnormally :)" send_message(message=message, subject=subject) with open('logs.txt', 'w') as f: f.write('{}' + message + '\n'.format(str(datetime.datetime.now()))) f.close()
def update_moisture_reading(start_time=None, refresh_threshold_sec=ONE_HOUR): if start_time and (time.time() - start_time) < refresh_threshold_sec: seconds_passed = time.time() - start_time min, sec = get_next_reading(refresh_threshold_sec - seconds_passed) update_string = '{} minutes'.format(min) conn.update_status({'moisture_reading_time': update_string}) return start_time else: start_time = time.time() now = datetime.datetime.now() GPIO.output(GPIO_MOISTURE_POWER_PIN, GPIO.HIGH) # tiny delay to let the sensor pull low time.sleep(1) reading = GPIO.input(GPIO_MOISTURE_INPUT_PIN) # check initial None state if reading == garden_state[GPIO_MOISTURE_INPUT_PIN]: print "{} nothing changed".format(now) elif reading: conn.update_status({'moisture': 'Dry'}) print "{} Soil Dry".format(now) garden_state[GPIO_MOISTURE_INPUT_PIN] = reading send_message("water me") else: conn.update_status({'moisture': 'OK'}) print "{} Soil Ok".format(now) garden_state[GPIO_MOISTURE_INPUT_PIN] = reading GPIO.output(GPIO_MOISTURE_POWER_PIN, GPIO.LOW) return start_time
def morning_update(): users = dataHandler.get_users() for user in users: today = datetime.now() if today.isoweekday() == 1: # Monday clear_old_purchases(user) days_left = (user["end_date"] - today).days week_days = 7 if days_left > 7 else days_left per_day = user["total_budget"] / (user["end_date"] - user["start_date"]).days week_money_left = (per_day * week_days) - sum_purchases( user["week_spent"]) total_spent = sum_purchases(user["total_spent"]) + \ sum_purchases(user["week_spent"]) days_done = (today - user["start_date"]).days days_done = days_done if days_done != 0 else 1 delta = days_done // 7 * (per_day * 7) - sum_purchases(user["total_spent"]) msg = \ "Happy {0}, {1}!\n" \ .format(today.strftime("%A"), today.strftime("%D")) + \ "${0:.2f} left this week (${1:.2f}/day)\n" \ .format(week_money_left, per_day) + \ "${0:.2f} w/rollover (delta ${1:.2f})\n" \ .format(week_money_left + delta, delta) + \ "running avg/day ${0:.2f} (net ${1:.2f})" \ .format(total_spent/(days_done), total_spent) messaging.send_message(msg, number=user["number"])
def send_command(self, command): if not command in self.board_commands: msg = f"{command} not in {self.board_commands}" print(msg) #raise Exception(msg) return messaging.send_message(self.sc, command) self.board_commands = messaging.recv_message(self.sc)
def socket_handle_query_boxes(self, sc, user_id): board_ids = set(self.config.get_boards_ids()) with self.lock: claimed_boards = self.claimed_boards claimed_last_by_user = self.claimed_last_by_user board_ids_unclaimed = board_ids - claimed_boards boards_unclaimed = list(map(lambda x: {"id": x, "type": self.config.get_board_type(x)}, board_ids_unclaimed)) board_ids_to_users = [] for board_id in claimed_boards: board_ids_to_users.append([board_id, claimed_last_by_user[board_id]]) messaging.send_message(sc, {"unclaimed": boards_unclaimed, "claimed": board_ids_to_users})
def handle_message(sender, text): blob = TextBlob(text, np_extractor=extractor) for noun in blob.noun_phrases: print blob.noun_phrases for word, tag in blob.tags: print word + ' --> ' + tag if len(blob.noun_phrases) == 0: return 'okay', 200 print blob results = search_yelp(blob.noun_phrases) print results elements = [] print results.businesses if len(results.businesses) > 0: for business in list(results.businesses): print business buttons = [] restaurant = { 'buttons': buttons, 'title': business.name, 'subtitle': business.snippet_text } if business.image_url is not None: restaurant.image_url = business.image_url.replace('ms.jpg', 'l.jpg') print business.__dict__ if business.reservation_url is not None: buttons.append(templates.button('web_url', 'reserve', business.reservation_url)) if business.mobile_url is not None: buttons.append(templates.button('web_url', 'visit yelp', business.mobile_url)) message = templates.generic_template(sender, { 'template_type': 'generic', 'elements': elements }) else: message = templates.button_template(sender, 'Do you want to checkout yelp?', buttons) print messaging print messaging.send_message(message).text return 'okay', 200
def _request_to_server(sc, request_type, user_id): # is this request type available? request_types = messaging.recv_message(sc) if not request_type in request_types: raise BoxServerNoBoardException( f"{request_type} is no available request type; available types are {request_types}" ) # send request request = [request_type, user_id] messaging.send_message(sc, request) # receive result return messaging.recv_message(sc)
def _init_from_settings(self): """ Reads the settings file to extract information about all users. Creates and returns a dict with all important values for each user. """ users = [] with open("settings.json", "r") as settings_file: settings = json.load(settings_file) for user in settings["users"]: start_date = datetime(user["start_date"]["year"], user["start_date"]["month"], user["start_date"]["day"], user["morning_update_time"]["hour"], user["morning_update_time"]["minute"]) end_date = datetime(user["end_date"]["year"], user["end_date"]["month"], user["end_date"]["day"], user["morning_update_time"]["hour"], user["morning_update_time"]["minute"]) if datetime.now() > start_date: print("WARNING: Start date is in the past.") if start_date >= end_date: print("ERROR: Your budget term is negative days long!\nExit.") raise Exception() total_budget = user["total_budget"] total_days = (end_date - start_date).days messaging.send_message( "Budgeting ${0} over {1} days, which gives a budget of \ ${2:.2f} per week, or ${3:.2f} per day".format(total_budget, total_days, total_budget / (total_days / 7), total_budget / total_days), user["phone_number"]) users.append({ "number": user["phone_number"], "total_budget": total_budget, "start_date": start_date, "end_date": end_date, "week_spent": [], "total_spent": [] }) # append a user stored as a dictionary return users
def send(): """ Sends a message to a given phone number. Returns a result message indicating if the message was properly sent. """ # Get the number and the message from the url number = request.args.get('number') message = request.args.get('message') # Send the message and return the result message return send_message(number, message)
def socket_handle(self, sc, addr): try: with sc: logging.info(f"Connection established to {addr[0]}:{addr[1]}") #while True: # messaging.send_message(sc, messaging.recv_message(sc)) # 0a. send available request types request_types = list(self.request_handlers.keys()) messaging.send_message(sc, request_types) # 0b. receive request type request = messaging.recv_message(sc) if not isinstance(request, list) and len(request) != 2: raise Exception("input error, request has to contain the request type and a user_id") request_type = request[0] user_id = request[1] if not request_type in request_types: raise Exception("input error, request type not available") self.request_handlers[request_type](sc, user_id) finally: logging.info(f"Connection lost with {addr[0]}:{addr[1]}")
def start(self): self.sc.connect((self.hostname, self.port)) try: # select to request a board and select board type board_types = BoxClient._request_to_server(self.sc, "get_board", self.user_id) # fix case insensitive board type board_types_match = list( filter(lambda x: x.lower() == self.board_type.lower(), board_types)) if len(board_types_match) == 1: self.board_type = board_types_match[0] if not self.board_type in board_types: raise BoxServerNoBoardException( f"{self.board_type} is no available board type; available types are {board_types}" ) messaging.send_message(self.sc, self.board_type) # select board board_ids = messaging.recv_message(self.sc) #print(board_ids) logging.info("requesting board") if self.box_name == None or self.board_name == None: messaging.send_message(self.sc, -1) else: board_id_choose = [self.box_name, self.board_name] if not board_id_choose in board_ids: raise BoxServerNoBoardException( f"board id {board_id_choose} is not available; available boards are {board_ids}" ) messaging.send_message(self.sc, board_ids.index(board_id_choose)) # recieve claimed board (self.board_idx, self.board_id, msg) = messaging.recv_message(self.sc) if self.board_idx < 0: raise BoxServerNoBoardException(msg) self.board_commands = messaging.recv_message(self.sc) except: self.sc.close() raise
def socket_handle_get_board(self, sc, user_id): # 1. send available board types board_types = self.config.get_board_types() messaging.send_message(sc, board_types) # 2a. receive required board board_type = messaging.recv_message(sc) if not board_type in board_types: raise Exception("input error, requested board type is not available") # 2b. send available board_ids board_ids = set(self.config.get_boards(board_type)) with self.lock: # for safety under the lock board_ids = board_ids - self.claimed_boards board_ids = list(board_ids) messaging.send_message(sc, board_ids) # 2c. take selection as "wish index" relative to the list of boards sent before, unless negative user_idx = messaging.recv_message(sc) if not isinstance(user_idx, int): raise Exception("input format error, board_index") if (user_idx >= 0) and (user_idx >= len(board_ids)): raise Exception("input format error, board_index") # 3. claim one from the available boards and send its name board_id = -1 try: # calim board try: board_id = self.claim_board(user_id, board_ids, user_idx) except BoardNotAvailableException: logging.warning(f"No {board_type} available") messaging.send_message(sc, [-1,board_id,"no board available"]) return #initialize board try: self.init_board(board_id) except: logging.error(f"Error while initializing {board_id}") messaging.send_message(sc, [-2,board_id,"could not initialize board"]) raise # claimed and initialize, inform the client messaging.send_message(sc, [self.config.get_board(board_id)['index'],board_id,"ok"]) logging.info(f"Creating command handlers for board {board_id}") commands = {} if 'pin_reset' in self.config.get_board(board_id).keys(): commands["stop"] = lambda board_id=board_id: self.set_board_reset(board_id, True) commands["start"] = lambda board_id=board_id: self.set_board_reset(board_id, False) if "client_cmds" in self.config.get_board(board_id).keys(): client_cmds = self.config.get_board(board_id)["client_cmds"] for client_cmd in client_cmds.keys(): commands[client_cmd] = lambda board_id=board_id, client_cmd=client_cmd: self.exec_client_cmd(board_id, client_cmd) while True: # 4. send available commands messaging.send_message(sc, list(commands.keys())) # 5. receive selected command and act command = messaging.recv_message(sc) if not command in commands.keys(): raise Exception("input error, requested command is not available") else: commands[command]() except messaging.SocketDiedException: pass except ConnectionResetError: pass finally: # always yield the board here self.yield_board(board_id)
def interface(self): # greet when system starts self.greetings() while True: # checkers # get CPU temperature values cpu_temperatures = self.__sys_info.check_temperature() temp_list = list() for cpu in cpu_temperatures: temp_list.append(cpu.get('current_temp')) # print(max(temp_list)) average_temperature = np.average(temp_list) print(average_temperature) # get CPU utilization values cpu_util = self.__sys_info.check_cpu_util() cpu_util = cpu_util.get('cpu_utilization') temp_list = list() for cpu in cpu_util: temp_list.append(cpu.get('percentage')) average_utilization = np.average(temp_list) # get memory consumption data memory = self.__sys_info.check_memory() memory = memory.get('results') # get disk consumption data disk = self.__sys_info.check_disk() disk = disk.get('results') # notify if battery percentage is less than 50% and not on charge battery_info = self.__sys_info.check_battery() if not battery_info.get( 'power_plugged') and battery_info.get('percentage') < 30: if self.__battery_flag == 0: subject = "Laptop Battery Running Down" message = "Current Battery Percentage is {}% and time remaining is {} seconds. "\ "Please connect to a power supply".format(battery_info.get('percentage'), battery_info.get('timeLeft')) try: send_message(subject=subject, message=message) self.__battery_flag = 1 except Exception as e: self.__battery_flag = 1 with open('logs.txt', 'w') as f: f.write(str(e)) f.write('\n') f.close() # notify if battery percentage is greater than 95% and on charge elif battery_info.get( 'power_plugged') and battery_info.get('percentage') > 95: if self.__battery_flag == 0: subject = "Laptop Battery almost fully charged" message = "Current Battery Percentage is {}%. "\ "Please disconnect from power supply".format(battery_info.get('percentage')) try: send_message(subject=subject, message=message) self.__battery_flag = 1 except Exception as e: self.__battery_flag = 1 with open('logs.txt', 'w') as f: f.write(str(e)) f.write('\n') f.close() else: battery_flag = 0 # notify if average CPU temperature percentage > 85 if average_temperature > 80: if self.__temperature_flag == 0: # send the individual temperature of all CPUs subject = "Edited: Average CPU temperature above {} Deg. Celc.".format( average_temperature) message = "" for cpu in cpu_temperatures: message += "{} : {} Deg. Celc. ".format( cpu.get('label'), cpu.get('current_temp')) try: send_message(subject=subject, message=message) self.__temperature_flag = 1 except Exception as e: self.__temperature_flag = 1 with open('logs.txt', 'w') as f: f.write(str(e)) f.write('\n') f.close() else: self.__temperature_flag = 0 # notify if cpu_utilization > 70% if average_utilization > 70: if self.__utilization_flag == 0: # send individual utilization of all CPUs subject = "(Warning) Average CPU temperature above {} %.".format( average_utilization) message = "" for cpu in cpu_util: message += "{} : {} %. ".format( cpu.get('label'), cpu.get('percentage')) try: send_message(subject=subject, message=message) self.__utilization_flag = 1 except Exception as e: self.__utilization_flag = 1 with open('logs.txt', 'w') as f: f.write(str(e)) f.write('\n') f.close() else: self.__utilization_flag = 0 # notify if available memory < 100 MB if memory.get('available_memory') < 100: if self.__memory_flag == 0: subject = "(Warning) Running Low on Virtual Memory" message = "System only has {} MB of Virtual Memory at the " \ "moment. Consumed {} MB of memory".format(memory.get('available_memory'),memory.get('used_memory') ) try: send_message(subject=subject, message=message) self.__memory_flag = 1 except Exception as e: self.__memory_flag = 1 with open('logs.txt', 'w') as f: f.write(str(e)) f.write('\n') f.close() else: self.__memory_flag = 0 # notify if free disk space < 20GB if disk.get('disk_available') < 20000: if self.__disk_flag == 0: subject = "(Warning) Running Low of Physical Storage" message = "System only has {} MB of Physical Storage at the moment" \ ". Consumed {} MB of Storage. ({} %)".format(disk.get('disk_available'), disk.get('disk_used'), \ disk.get('disk_percent_usage')) try: send_message(subject=subject, message=message) self.__disk_flag = 1 except Exception as e: self.__disk_flag = 1 with open('logs.txt', 'w') as f: f.write(str(e)) f.write('\n') f.close() else: self.__disk_flag = 0 time.sleep(10)
def sendMessage(addr, message): """Send a message""" counter = messaging._get_message_prefix(addr) message = messaging.encode_message(message, counter) messaging.send_message(addr, message, send=True) click.echo('Sent!')
def meat_show(): send_message("welcome to the meat show")
def LA_time(): if random.randrange(2) == 0: send_message("9:08, LA time")
def test_scheduler(): send_message("scheduled message in memory of JP")
def five_o_clock(): if random.randrange(10) == 0: send_message("It's 5 o'clock in the morning")
from messaging import send_message send_message(True,True, 'Test to Toby', 'Does this work?')
def incoming_message(): if flask.request.method == 'GET': return 'page loaded' print("in incoming_message") print("incoming_message got: {}".format(flask.request.data)) message_dict = flask.request.get_json(force=True, silent=True) if not message_dict: print("ERROR with message format, data is: {}".format( flask.request.data)) return 'bad message format' if message_dict["sender_type"] != "user": return "ignoring bot messages" dic = pyphen.Pyphen(lang='en') message = message_dict["text"] username = message_dict["name"] user_id = message_dict["user_id"] conversation_id = message_dict["group_id"] message_id = message_dict["id"] sender_id = message_dict["sender_id"] austin_sender_id = "37816131" # bot commands if (message.startswith("@bot")): full_command = message.split() if len(full_command) < 2: return 'invalid bot command' command = full_command[1].lower() if command in ['help', 'commands', 'command', 'options', 'option']: help_message = "Commands:\n'@bot lyrics <Artist>, <Song>'\n'@bot brother'\n'@bot accolades'\n'@bot repost'\n'@bot slatt'\n'@bot nuke' (no longer supported)" messaging.send_message(help_message) elif command == 'lyrics': try: artist_song = message[len("@bot lyrics "):] lyrics_args = artist_song.split(',') artist = lyrics_args[0] song = lyrics_args[1][1:] print("lyrics looking for: {}, {}".format(artist, song)) messaging.send_message(PyLyrics.getLyrics(artist, song)) except ValueError: messaging.send_message( "Song ({}) or Singer ({}) does not exist or the API does not have Lyrics" .format(song, artist)) elif command == 'brother': messaging.send_message("Hell yeah, brother!") elif command == 'accolades': messaging.send_message( "I'm more successful, I have more accolades, I'm more charismatic, and more people know who I am. All because of my brain and how I use it, cole. U know if u pay attention maybe u could learn something." ) elif command == 'repost': messaging.send_message( "*Sniff sniff* What's this? OwO IS THIS A REPOST?") elif command == 'slatt': messaging.send_message("Slime Love All The Time") elif command == 'nuke': for i in range(30): messaging.send_message("You brought this upon yourself") else: messaging.send_message("invalid command") # responses to single word messages elif message.lower() == "nice": messaging.send_message("Yeah, nice.") elif message.lower() == "wow": messaging.send_message( "https://media1.fdncms.com/stranger/imager/u/original/25961827/28378083_1638438199580575_8366019535260245188_n.jpg" ) # responses to substrings else: # case sensitive operations if "Bush" in message: messaging.send_message("George W. Bush, best president") return 'message sent' # remove punctuation and make lowercase message = re.sub(r'[^\w\s]', '', message).lower() print(message) # multi-word strings if "what time" in message: messaging.send_message("Time to get a watch!") return 'message sent' elif "que hora" in message: messaging.send_message("Es hora obtener un reloj!") return 'message sent' # message contains single key-word for word in message.split(): if word in ['updog', 'ligma', 'sugma']: messaging.send_message("What's {}?".format(word)) return 'message sent' if word in ["u", "ur"] and sender_id == austin_sender_id: if word == "u": messaging.send_message( "You said \"{},\" did you mean \"you?\"".format(word)) else: messaging.send_message( "You said \"{},\" did you mean \"your?\"".format(word)) return 'message sent' syllables = dic.inserted(word).split('-') print(syllables) if (random.randrange(3) == 0 and syllables[-1] == 'er' and word not in [ 'other', 'another', 'ever', 'never', 'together', 'whatever', 'whenever', 'earlier', 'whomever', 'whoever' ]): messaging.send_message("{}? I barely even know her!".format( word.capitalize())) return 'message sent' return 'good'