class NotiBday: def __init__(self): self.calendar = GCal(config.CONTACTS_CAL_ID) self.agenda = GContacts() self.agenda.retrieve_contacts() @staticmethod def parse_bday_event(event): date, summary = event if not summary.startswith('Aniversario'): name = re.split(r'\s*-\s*', summary)[0] date = datetime.datetime.strptime(date, '%Y-%m-%d') else: name, date = None, None return name, date def notify_today_birthdays(self): events = self.calendar.get_events() if events: buf = ['Hoy es el cumpleaños de:'] for event in sorted(events, key=lambda t: t[1]): name, _ = NotiBday.parse_bday_event(event) if name: age = self.agenda.get_contact_age(name) buf.append(f'🎂 *{name}* ({age})') msg = os.linesep.join(buf) send_message(msg) def _get_birthdays_at_delta(self, delta, caption, use_vip=True): try: with open(config.VIP_FILE) as f: vips = [line.strip() for line in f.readlines()] except FileNotFoundError: use_vip = False events = self.calendar.get_events(delta=delta) if events: buf = [] for event in sorted(events, key=lambda t: t[1]): name, date = NotiBday.parse_bday_event(event) if name and ((not use_vip) or (use_vip and name in vips)): date = date.strftime("%-d/%-m") age = self.agenda.get_contact_age(name) buf.append(f'🎈 *{name}* ({date}) {age}') if buf: buf.insert(0, caption) msg = os.linesep.join(buf) else: msg = '' return msg def notify_next_birthdays(self): buf = [] for next_birthday in NEXT_BIRTHDAYS: birthdays = self._get_birthdays_at_delta(*next_birthday) if birthdays: buf.append(birthdays) buf.append(2 * os.linesep) if buf: send_message(''.join(buf))
def clear_all(self): gcal = GCal() event_files = os.listdir(resource_path('events')) for ef in event_files: with open(resource_path('events/' + ef), 'r') as f: events = json.load(f) for event in events: gcal.del_event(event['id']) os.remove(resource_path('events/' + ef))
def start(self, username, password, save_credentials_bool, term, export, color_bool, room_bool, location_bool, privacy_bool, availability_bool, reminders_bool, reminders_type, reminders_time): self.set_username(username) self.set_password(password) if save_credentials_bool: with open(resource_path('save.json'), 'w') as f: json.dump({'username': self.username, 'password': self.password}, f) # if export == 'google calendar': exporter = GCal() self.set_term(term) data = [] with Browser() as self.browser: for cmd in self.commands: data = cmd() if not data: return False converter = Converter(color_bool, room_bool, location_bool, privacy_bool, availability_bool, reminders_bool, reminders_type, reminders_time) events = converter.convert_uschedule_to_gevent(data) added_events = [] for event in events: print event added_event = exporter.add_event(event.get_dict()) added_events.append(added_event) self.save_events(added_events) return True
async def main(): logger = get_logger() logger.info("Start") auth = GAuth(logger) with open(f'{os.environ.get("SECRETS")}/creds.json', 'r') as f: creds = json.load(f) mail = GMail(auth.mail, logger) session = aiohttp.ClientSession() reports = Reports(session, mail, creds, logger) # Login login = asyncio.create_task(reports.login()) # Get events to process calendar = GCal(auth.calendar, creds["cal_id"], logger) calendar.query_calendar() # Make sure we're logged in & process events await login if len(calendar.users) > 0: # Call reports.dowload_reports_and_send_draft for each new event, this downloads report and creates draft done, pending = await asyncio.wait([ reports.download_reports_and_send_draft(data) for data in calendar.users ]) # Patch events that drafts were succesfully created for (returned +ve) for task in done: if result := task.result(): calendar.patch(result)
def main(): parser = argparse.ArgumentParser(parents=[tools.argparser]) parser.add_argument('-n', '--new-creds', action='store_true', default=False, help="Clear previously saved Google credentials") cms_group = parser.add_mutually_exclusive_group() cms_group.add_argument('-s', '--skip-cms', action='store_true', default=False, help="Skip enrolling to CMS courses") cms_group.add_argument('-o', '--only-cms', action='store_true', default=False, help="Only enrol to CMS courses") args = parser.parse_args() if not args.only_cms: gcal = GCal(args.new_creds) set_cal(gcal) reg_sections = erp.get_reg_sections() print("Fetched registered courses from ERP.") final_secions = override_sections(reg_sections) for course_code, sections in final_secions.items(): course = get_course(course_code, sections) if not args.skip_cms: enrol_cms(course_code, sections) if not args.only_cms: for event in make_course_events(course): gcal.create_event(event) gcal.print_event(event, "Created", "in GCal.")
def __init__(self): self.calendar = GCal(config.CONTACTS_CAL_ID) self.agenda = GContacts() self.agenda.retrieve_contacts()
def viewCal(): gcal = GCal() id1 = gcal.get_tempID() oldEvents = gcal.get_events(calendar='temp', daysPast=2, daysFuture=7) gcal.delete_multiple('main', oldEvents) if request.method == 'GET': sciPyLAS.run() tempList = gcal.get_events(calendar='temp', daysPast=0, daysFuture=7) if request.method == 'POST': gcal.migrate_events() for i in tempList: ID = i.name try: temp = request.form[ID] gcal.delete_event('temp', ID) except: pass return render_template('viewCal.html', id1=id1, tempList=tempList)
try: temp = request.form[ID] gcal.delete_event('temp', ID) except: pass return render_template('viewCal.html', id1=id1, tempList=tempList) @app.route('/createEvent', methods=['GET', 'POST']) #Function that runs when page opens def event(): elements = {'name': '', 'startTime': '0', 'endTime': '0'} if request.method == 'POST': #Checks to see if all the boxes are filled for i in elements: if request.form[i] != '': elements[i] = request.form[i] event = generateEvent(elements['name'], elements['startTime'], elements['endTime']) return redirect(url_for('index')) #Defines what html page runs when page is opened return render_template('event.html') if __name__ == '__main__': cal = GCal() app.run()
def set_cal(gcal: GCal): cal_name = get_cal_name() print("Creating calendar for", cal_name) if gcal.set_cal(cal_name): print("Calendar", cal_name, "already exists. Clearing old events.") gcal.clear_cal()
def __init__(self, weather_api_token,google_cloud_api_key=None): self.weather_api_token = weather_api_token self.google_cloud_api_key = google_cloud_api_key self.calendar = GCal()
class Knowledge(object): def __init__(self, weather_api_token,google_cloud_api_key=None): self.weather_api_token = weather_api_token self.google_cloud_api_key = google_cloud_api_key self.calendar = GCal() def find_weather(self, address=None): loc_obj = self.get_location(address) lat = loc_obj['lat'] lon = loc_obj['lon'] weather_req_url = "https://api.darksky.net/forecast/%s/%s,%s?%s" % (self.weather_api_token, lat, lon,"units=si") r = requests.get(weather_req_url) weather_json = json.loads(r.text) if 'currently' in weather_json : temperature = int(weather_json['currently']['temperature']) current_forecast = weather_json['currently']['summary'] icon = weather_json['currently']['icon'] wind_speed = int(weather_json['currently']['windSpeed']) else: current_forecast = '' if 'minutely' in weather_json : minutely_forecast = weather_json['minutely']['summary'] # gio trong ngay else: minutely_forecast = '' if 'hourly' in weather_json : hourly_forecast = weather_json['hourly']['summary'] ## hom nay else: hourly_forecast = '' if 'daily' in weather_json : tomorrow_forecast = weather_json['daily']['data'][0]['summary'] # get weather tomorrow weekly_forecast = weather_json['daily']['summary'] # on week else: weekly_forecast = '' tomorrow_forecast = '' return {'temperature': temperature, 'icon': icon, 'windSpeed': wind_speed, 'current_forecast': current_forecast, 'hourly_forecast': hourly_forecast, #'weeken_forecast': weeken_forecast, 'tomorrow_forecast': tomorrow_forecast, 'weekly_forecast': weekly_forecast, 'location': address} def get_location(self,location = 'shibuya'): # get location # location_req_url = "http://freegeoip.net/json/%s" % self.get_ip() # r = requests.get(location_req_url) # location_obj = json.loads(r.text) # # lat = location_obj['latitude'] # lon = location_obj['longitude'] location_req_url = "https://maps.googleapis.com/maps/api/geocode/json?address=%s" % location r = requests.get(location_req_url) location_obj = json.loads(r.text) if location_obj['status'] == 'OK': lat = location_obj['results'][0]['geometry']['location']['lat'] lon = location_obj['results'][0]['geometry']['location']['lng'] else: lat = 35 lon = 139 return {'lat': lat, 'lon': lon} def get_ip(self): ip_url = "http://jsonip.com/" req = requests.get(ip_url) ip_json = json.loads(req.text) return ip_json['ip'] def get_map_url(self, location, map_type=None): if map_type == "satellite": return "http://maps.googleapis.com/maps/api/staticmap?center=%s&zoom=13&scale=false&size=1200x600&maptype=satellite&format=png" % location elif map_type == "terrain": return "http://maps.googleapis.com/maps/api/staticmap?center=%s&zoom=13&scale=false&size=1200x600&maptype=terrain&format=png" % location elif map_type == "hybrid": return "http://maps.googleapis.com/maps/api/staticmap?center=%s&zoom=13&scale=false&size=1200x600&maptype=hybrid&format=png" % location else: return "http://maps.googleapis.com/maps/api/staticmap?center=%s&zoom=13&scale=false&size=1200x600&maptype=roadmap&format=png" % location def get_direction_map(self, origin, destination): url = "https://maps.googleapis.com/maps/api/directions/json?origin=%s&destination=%s&mode=roadmap&key=%s" % (origin,destination,self.google_cloud_api_key) res = requests.get(url) pos = [] makers = [] if res.status_code == 200: res_json = json.loads(res.text) star = '%s, %s' % (res_json['routes'][0]['legs'][0]['start_location']['lat'],res_json['routes'][0]['legs'][0]['start_location']['lng']) end = '%s, %s' % (res_json['routes'][0]['legs'][0]['end_location']['lat'],res_json['routes'][0]['legs'][0]['end_location']['lng']) start_makers = 'markers=color:red|label:S|%s' % star end_makers = 'markers=color:red|label:S|%s' % star pos.append(star) locations = res_json['routes'][0]['legs'][0]['steps'] for loc in locations: p = "%s,%s" % (loc['end_location']['lat'],loc['end_location']['lng']) pos.append(p) pos_str = "|".join(pos) print(pos_str) return "https://maps.googleapis.com/maps/api/staticmap?size=1200x600&maptype=roadmap&path=color:red|weight:3|%s&%s&%s" % (pos_str, start_makers, end_makers) def get_news(self,country='vi'): ret_headlines = [] if country == 'jp': url = "https://www3.nhk.or.jp/rss/news/cat0.xml" else: url = "http://feeds.bbci.co.uk/vietnamese/vietnam/rss.xml" d = feedparser.parse(url) for post in d.entries: new = { 'title':post.title, 'summary':post.summary, 'link':post.link } ret_headlines.append(new) return ret_headlines def get_holidays(self,country='vn'): if country.lower() == 'nhật bản': holidays = self.calendar.get_cal("vi.japanese#[email protected]") else: holidays = self.calendar.get_cal("vi.vietnamese#[email protected]") if holidays: return holidays def get_country_code(country_name): r = requests.get("https://restcountries.eu/rest/v2/name/%s" % country_name) json_data = json.loads(r.text) country_code = json_data[0]['alpha2Code'] return country_code