def notify_me(pincode, mobiles): # supress warning due to self signed certificates for devlopment environment. urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) today = date.today().strftime('%d-%m-%Y') # get next 7 days vaccine slots near to your area pincode url = f"https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode={pincode}&date={today}" header = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} # always verify signature in production environment response = requests.get(url, headers=header, verify=False) output = response.json() for center in output['centers']: for session in center['sessions']: message = f"Center: {center['name']}, Date: {session['date']}, Slots: {session['available_capacity']}" # sms me when 1 or more slots are free if session['available_capacity'] > 0: print('Hurrey!! you have found free slot. Go ahead and book fast!!') print(message) send_alert(mobiles=mobiles, message=message) else: print(message)
def __init__(self, json_config, ip_obj): self.json_config = json_config self.pinger = Ping( get_config(self.json_config, 'ping_package_number', 3), get_config(self.json_config, 'ping_slow_threshold', 500), get_config(self.json_config, 'ping_timeout', 30), get_config(self.json_config, 'ping_source_ip', None) ) self.fail_threshold = get_config(self.json_config, 'looping_check_fail_threshold', 10) self.ok_threshold = get_config(self.json_config, 'looping_check_ok_threshold', 3) self.looping_interval = get_config(self.json_config, 'looping_check_interval', 30) self.ok_list = [] self.fail_list = [] self.ip_obj = {} (self.ip_obj['address'], self.ip_obj['name']) = self.get_ip_object( ip_obj) log.debug("IP_OBJ: {%s ; %s}" % (self.ip_obj['address'], self.ip_obj['name'])) if self.ip_obj['address'] is None or self.ip_obj['name'] is None: log.error('Wrong def: %s' % ip_obj) send_alert('Wrong def: %s' % ip_obj, log) exit(1)
def fail_alert(self): mess = 'Fail ping: %s' % \ ', '.join([obj['name'] for obj in self.fail_list]) log.error(mess) try: stop_alert_file = os.path.join(WORKING_DIR, 'stop_alert_file') with open(stop_alert_file, 'r') as fp: first_line = fp.readline().rstrip('\n') if first_line: try: log.debug('Got from %s: %s' % (stop_alert_file, first_line)) if first_line == datetime.now().strftime('%Y%m%d'): log.debug('Marked to stop announce for today') return except Exception: log.debug('Found %s but wrong content' % stop_alert_file) pass except Exception: log.debug('Cannot open stop-alert-file') pass send_alert(mess, log) try: for ip in self.fail_list: file_path = os.path.join(WORKING_DIR, '%s%s' % (ALERT_FILE_HEADING, ip['address'])) with open(file_path, 'a') as fp: fp.close() log.debug('created %s' % file_path) except Exception: log.warning('fail_alert wrong in processing alert_<ip> file.') pass
def main(): settings = json.load(open('settings.json')) weekdays = settings['weekdays'] sleep_update = settings['defaults']['sleepUpdateTime'] notifs = settings['notifs'] weekend_gap = 8 - weekdays end_of_week = weekdays - 1 now = datetime.datetime.now() noClassLeft = auto_class() if noClassLeft: now = datetime.datetime.now() if now.weekday() == end_of_week: #Skip weekends # gap = weekend_gap gap = datetime.timedelta(weekend_gap) else: gap = datetime.timedelta(1) tom = datetime.datetime(now.year, now.month, now.day, 8, 00, 00) + gap print("Done for today") if notifs: send_alert(custom_msg="Done for today\nSleeping till tomorrow") with open('meet.txt', 'w') as fh: #Delete all entries in the meet links file pass print(f'Sleeping for {(tom - now)}') m = (tom-now).total_seconds() while m>=0: if m <= sleep_update: sleep(m) break sleep(sleep_update) m = (tom - datetime.datetime.now()).total_seconds() main()
def ok_alert(self): try: for ip in self.ok_list: file_path = os.path.join(WORKING_DIR, '%s%s' % (ALERT_FILE_HEADING, ip['address'])) if os.path.isfile(file_path): mess = '%s back to NORMAL' % ip['name'] send_alert(mess, log) log.debug(mess) os.remove(file_path) except Exception: log.warning('ok_alert wrong in processing alert_<ip> file.') pass
def get_config(json_config, key, default_value=None): try: return json_config[key] except Exception: return default_value if __name__ == "__main__": config_file = os.path.join(os.path.dirname(__file__), 'ping_server.conf') with open(config_file) as json_file: json_data = None try: json_data = json.load(json_file) except Exception: send_alert('Load %s failed' % config_file) exit(1) log_file = get_config(json_data, 'log_file', 'ping_server.log') if not log_file.startswith('/'): log_file = os.path.join(WORKING_DIR, log_file) log_level = { 'debug': logging.DEBUG, 'info': logging.INFO }[get_config(json_data, 'level', 'info')] logging.basicConfig() log = logging.getLogger("ping_server") try: os.makedirs(os.path.dirname(log_file)) except OSError as e: if e.errno != errno.EEXIST:
from db_helper import insert_event, is_indb from extract_events import find_all_contetns_on_page, extract_coin_detail from send_alert import send_alert import time if __name__ == '__main__': db_name = "./coin_alert.db" table = "coinalerts" while (True): page_num = 1 url = 'http://coinmarketcal.com/?form%5Bmonth%5D=&form%5Byear%5D=&form%5Bsort_by%5D=created_desc&form%5Bsubmit%5D=&page=' contents = find_all_contetns_on_page(url, str(page_num)) print("------Start crawling ... ---------") for content in contents: details = extract_coin_detail(content) if (is_indb(db_name, table, details)): print("%s aleady in db ... pass" % details["coin_name"]) else: print("can't find the event about %s" % details["coin_name"]) print("inserting ...") insert_event("./coin_alert.db", "coinalerts", details) print("Finished insert ...") print("calling slack bot ...") send_alert(details) print("------End crawling: wait 300minutes ---------") time.sleep(300)
def open_class(link, runtime, class_name, record_class=False, debug_port=debug_port, exec_path=exec_path, user_data_dir=user_data_dir, exit_browser=True): if "https://" not in link: link = "https://" + link debug_address = "127.0.0.1:" + str(debug_port) cmd = "chrome --remote-debugging-port=" + str( debug_port) + " --user-data-dir=" + user_data_dir chrome_options = Options() chrome_options.add_experimental_option("debuggerAddress", debug_address) if mute: chrome_options.add_argument("--mute-audio") try: print("Trying to connect to driver") driver = webdriver.Chrome(options=chrome_options, executable_path=exec_path) print("Connected") except selenium.common.exceptions.WebDriverException as e: print("Couldnt connect\nTrying to open") if 'cannot connect to chrome at' in str(e): process = subprocess.Popen(cmd) print("Trying to connect") driver = webdriver.Chrome(options=chrome_options, executable_path=exec_path) print("Connected") else: print("unknown error") driver.get(link) driver.maximize_window() sleep(10) mic_off = True cam_off = True src = driver.page_source sleep(2) #Mic and cam off check count = 0 while True: if count == 10: if notifs: send_alert(custom_msg="Couldnt swtich off camera or mic") break if "Turn on microphone" in src and "Turn on camera" in src: break else: count += 1 driver.refresh() sleep(3) src = driver.page_source ask_to_join = False if "Ask to join" in src: ask_to_join = True #join_class try: j = driver.find_element_by_xpath(join_now_path) j.click() if not ask_to_join: if notifs: send_alert(joined_class=True, class_name=class_name) while ask_to_join: sleep( 30 ) #wait 30 seconds for someone to accept (10*30 seconds = 5 minutes) src = driver.page_source if "Ask to join" not in src: ask_to_join = False if notifs: send_alert(joined_class=True, class_name=class_name) if count == 10 or "You can't join this call" in src: if notifs: send_alert(joined_class=False, class_name=class_name) send_alert(custom_msg="Join request was not accepted") except: print("Error\nCouldnt find join button") if notifs: send_alert(joined_class=False, class_name=class_name) #Check for additional join confirmation in case of recording src = driver.page_source if "This meeting is being recorded" in src: try: r = driver.find_element_by_xpath(record_join_now_path) r.click() except: if notifs: send_alert( custom_msg="Joined class but couldnt get past record screen" ) if minimize_after_join: driver.minimize_window() driver.quit() sleep(runtime) #Sleep for the duration of the class #Connect again to exit class try: print("Connecting to driver") driver = webdriver.Chrome(options=chrome_options, executable_path=exec_path) print("Connected") except: print("Couldnt connect to driver") if notifs: send_alert(exit_class=False) #Check if the host ended the meeting before src = driver.page_source if "The meeting has ended" in src: print("Meeting ended by host before end time") if notifs: send_alert(custom_msg="Meeting ended by host before end time") else: try: l = driver.find_element_by_xpath(end_class_path) l.click() if notifs: send_alert(exit_class=True, class_name=class_name) except: print("Error\nCouldnt find the exit button") if notifs: send_alert(exit_class=False, class_name=class_name) if not exit_browser: driver.quit() elif exit_browser: try: driver.close() driver.quit() except: try: process.terminate() except: try: action = ActionChains(driver) action.key_down(Keys.ALT).key_down(Keys.F4).key_up( Keys.F4).key_up(Keys.ALT).perform() except: print("Error\nCouldnt exit the browser") if notifs: send_alert( custom_msg="Error\nCouldnt exit the browser")
def auto_class(): last_class = False while True: currentTime = datetime.datetime.today() meetlinks() with open('meet.txt', 'r') as fh: st = fh.read().splitlines() fh.close() # print(datetime.datetime.fromisoformat(st[0].split()[0])) first_start = (st[0].split()[0]) last_end = st[-1].split()[1] first_start = datetime.datetime.fromisoformat(first_start) last_end = datetime.datetime.fromisoformat(last_end) currentiso = currentTime.isoformat() end_times = [ datetime.datetime.fromisoformat(st_.split()[1]) for st_ in st ] index = -1 noClassLeft = False if currentTime < first_start: sleep_time = (first_start - currentTime).total_seconds() print(f"First class in {sleep_time} seconds") m = sleep_time while m: if m < sleep_update: sleep(m) break sleep(sleep_update) m = (first_start - datetime.datetime.now()).total_seconds() print( f'First class in {first_start - datetime.datetime.now()}') continue if currentTime > last_end: noClassLeft = True break for end in end_times: if currentTime <= end: index = end_times.index(end) break if index < 0: noClassLeft = True print("No class left") break elif index >= 0: start_time = st[index].split()[0] end_time = st[index].split()[1] start_time = datetime.datetime.fromisoformat(start_time) end_time = datetime.datetime.fromisoformat(end_time) if currentTime < start_time: sleep_time = (start_time - currentTime) while sleep_time.total_seconds(): print(f'Class not starting for {sleep_time}') if sleep_time.total_seconds() <= sleep_update: sleep(sleep_time.total_seconds()) break sleep(sleep_update) sleep_time = (start_time - datetime.datetime.now()) elif currentTime >= start_time: if index == len(st) - 1: last_class = True link = st[index].split()[-1] runtime = (end_time - currentTime).total_seconds() if ".com" in link: class_name = print_details(st[index].split()) open_class(link, runtime, class_name, exit_browser=last_class) else: print("No meet link available for this event") sleep(runtime) else: print("Unknown Error") if notifs: send_alert(custom_msg="Some unknown error has occured") if noClassLeft: break if noClassLeft: return noClassLeft