def loadCalendar(self): calendar_refresh_time = int(self.getConfig('calendarRefreshTime')) self.ThreadManager.doLater(interval=calendar_refresh_time, func=self.loadCalendar) self.logInfo(f'Scheduled next calendar load in {calendar_refresh_time} seconds') key = self.getConfig('cronofykey') calendarID = self.getConfig('calendarID') cronofy = pycronofy.Client(access_token=key) timezone_id = 'US/Pacific' tz = pytz.timezone(timezone_id) now = datetime.now(tz=tz) from_date = now.strftime("%Y-%m-%d") two_days = now + timedelta(days=2) to_date = two_days.strftime("%Y-%m-%d") all_events = cronofy.read_events(calendar_ids=(calendarID,), from_date=from_date, to_date=to_date, tzid=timezone_id, localized_times=True ).all() event_list = [] for event in all_events: event_end = datetime.strptime(event["end"]["time"], "%Y-%m-%dT%H:%M:%S%z") self.logInfo(f'Event: {event["summary"]}') if event_end > now: self.logInfo(f'Added') event_list.append(event) self.updateConfig(key="eventList", value=json.dumps(event_list))
def calendar(): print("1") #global cronofy #cronofy = pycronofy.Client(client_id="BQYkMYzj2xSA8iZUnumgng0-NthBcRZy", client_secret="7ckUqdSRcFHaaWx2LoIWrN_7SyQzcBErRqfV2VJ33T673TOYWu8VUF_WdhPyuHwcFa3Tecqv8ADYyhpeKrtuYQ") print("2") code = str(request.args.get('code', None)) print("3") print("code is ", code) auth = cronofy.get_authorization_from_code(code) print("4") global cronofy cronofy = pycronofy.Client( client_id="BQYkMYzj2xSA8iZUnumgng0-NthBcRZy", client_secret= "7ckUqdSRcFHaaWx2LoIWrN_7SyQzcBErRqfV2VJ33T673TOYWu8VUF_WdhPyuHwcFa3Tecqv8ADYyhpeKrtuYQ", access_token=auth['access_token'], refresh_token=auth['refresh_token'], token_expiration=auth['token_expiration']) calendars = cronofy.list_calendars() for i in range(len(calendars)): print("calendar: " + str(calendars[i]["calendar_id"])) calendarIDs.append(calendars[i]["calendar_id"]) # calendarIDs.append(calendarID) # print(calendarID) findFreeBlocks() if len(calendarIDs) > 2: return redirect(url_for("CombinedCalendar"), code=302) return "you did it!"
def __init__(self): self.cronofy = pycronofy.Client( access_token="wzOWhqxK-cmgld6AqZa6HA59qTNESn7o") self.calendars = {} self.events = [] self.calendar_names_to_track = ["School", "Away"] self.calendars_to_track = [] self.update()
def authorizeUserCalendar(): global cronofy cronofy = pycronofy.Client( client_id="BQYkMYzj2xSA8iZUnumgng0-NthBcRZy", client_secret= "7ckUqdSRcFHaaWx2LoIWrN_7SyQzcBErRqfV2VJ33T673TOYWu8VUF_WdhPyuHwcFa3Tecqv8ADYyhpeKrtuYQ" ) url = cronofy.user_auth_link('http://palebone.myddns.me/calendar') #print('Go to this url in your browser, and paste the code below') #print(url) #code = input('Paste Code Here: ') # raw_input() for python 2. #auth = cronofy.get_authorization_from_code(code) #print(auth) # site = "https://app.cronofy.com/oauth/authorize?response_type=code&client_id=BQYkMYzj2xSA8iZUnumgng0-NthBcRZy&redirect_uri=http://palebone.myddns.me/calendar&scope=read_events&state=true" return redirect(url, code=302)
def event(): global data global id_name global name data = User.query.filter_by(id=id_name).first() cal_id = data.cal_id cronofy = pycronofy.Client(access_token="Ru-JiYhxeyAaCRyCevGnLzv3BrUvZwWU") timezone_id = 'Asia/Calcutta' from_date = datetime.date.today() to_date = (datetime.date.today() + datetime.timedelta(days=1)) YOUR_CAL_ID = cal_id all_events = cronofy.read_events(calendar_ids=(YOUR_CAL_ID, ), from_date=from_date, to_date=to_date, tzid=timezone_id).all() conv = json.dumps(all_events) return conv
def events(): global data global id_name global name # = Camera.ret_names() data = User.query.filter_by(id=id_name).first() cal_id = data.cal_id cronofy = pycronofy.Client(access_token="hr3pyQW_wTYL1gF3QEWOb0w62lCl4SPk") timezone_id = 'Asia/Calcutta' from_date = datetime.date.today() to_date = (datetime.date.today() + datetime.timedelta(days=1)) YOUR_CAL_ID = cal_id all_events = cronofy.read_events(calendar_ids=(YOUR_CAL_ID, ), from_date=from_date, to_date=to_date, tzid=timezone_id).all() conv = json.dumps(all_events) return conv
def get_outlook_calendar_events(): CLIENT_ID = 'oVjF0tuVTnGiEKfaKfgtOt6dQDVjr5IZ' SECRET_ID = '54J2YKoVlNBX-yTk1Nwm6Yx5vLLBdglBlp-hUP7YSRFdOKk6D5vRpXhIifWzkkK_PBFUVlbYvudb4PgLq9m9GA' cronofy = pycronofy.Client(access_token="cF-JVep9yCEUk3jxDNDi1rFzedvxXXsj") events = cronofy.read_events() holidays = [ 'Christmas Day', 'Boxing Day', 'Boxing Day Bank Holiday', 'New Year\'s Day', 'New Year\'s Day (2nd Day) (Scotland)', 'New Year\'s Day (2nd Day) (Scotland) (Observed)', 'St. Patrick\'s Day (N. Ireland)', 'Good Friday', 'Easter Day', 'Easter Monday', 'May Day Bank Holiday', 'Spring Bank Holiday', 'Battle of the Boyne (N. Ireland)', 'August Bank Holiday (Scotland)' ] upcoming = [] for event in events.all(): if event['summary'] not in holidays: try: upcoming.append( (event['summary'], datetime.datetime.strptime(event['start'][:19], '%Y-%m-%dT%H:%M:%S'), datetime.datetime.strptime(event['end'][:19], '%Y-%m-%dT%H:%M:%S'), random.choice(["blue", "red", "green"]), True)) except ValueError: upcoming.append(( event['summary'], datetime.datetime.strptime(event['start'][:19], '%Y-%m-%d'), datetime.datetime.strptime(event['end'][:19], '%Y-%m-%d') - datetime.timedelta(days=1), random.choice(["blue", "red", "green"]), False)) return (upcoming)
def createEvents(self): key = self.getConfig('cronofykey') calendar_id = self.getConfig('calendarID') cronofy = pycronofy.Client(access_token=key) timezone_id = 'US/Pacific' # First delete events. cronofy.delete_all_events(calendar_ids=(calendar_id)) event_id = 'finalprojectalice-%s' % uuid.uuid4() event = { 'event_id': event_id, 'summary': 'Main Website Demo', 'description': 'Show off what\'s new on the main website.', 'start': datetime.utcnow(), 'end': datetime.utcnow() + timedelta(minutes=15), 'tzid': timezone_id, 'location': { 'description': 'Machine Room' } } cronofy.upsert_event(calendar_id=calendar_id, event=event) event_id = 'finalprojectalice-%s' % uuid.uuid4() event = { 'event_id': event_id, 'summary': 'Salesforce Deployment Stand-up', 'description': 'Daily stand-up of the Salesforce Deployment project.', 'start': datetime.utcnow() + timedelta(minutes=30), 'end': datetime.utcnow() + timedelta(minutes=45), 'tzid': timezone_id, 'location': { 'description': 'Machine Room' } } cronofy.upsert_event(calendar_id=calendar_id, event=event)
def connect_calendar(): return pycronofy.Client(access_token=CRONOFY_ACCESS_TOKEN)
def checkout(request): if request.method == "POST": # If the user is attempting to make an appointment do the following# order_form = OrderForm(request.POST) payment_form = MakePaymentForm(request.POST) # If the Order Form, Payment Form and Booking Radio Type Button has a value # if order_form.is_valid() and payment_form.is_valid( ) and request.POST.get('what-button') is not None: order = order_form.save(commit=False) order.date = timezone.now() order.save() # Get the details of the product the user is trying to book # cart = request.session.get('cart', {}) total = 0 for id, quantity in cart.items(): product = get_object_or_404(Product, pk=id) total += quantity * product.price order_line_item = OrderLineItem(order=order, product=product, quantity=quantity) order_line_item.save() # Try to charge the users card for the ammount of the product# try: customer = stripe.Charge.create( amount=int(total * 100), currency="EUR", description=request.user.email, card=payment_form.cleaned_data['stripe_id'], ) # If Stripe returns an error give an error message # except stripe.error.CardError: messages.error(request, "Your card was declined!") # If the payment id succesfull do the following # if customer.paid: # Get the value of the button clicked # what_button = request.POST.get('what-button') # Remove the characters and split at each space # b = "{},'" for char in b: what_button = what_button.replace(char, "") refine_what_button = what_button.split(' ') # Access the Cronofy Api and use the details from 'what_button' value to update a booking in the google calendar# cronofy = pycronofy.Client( access_token=os.getenv("PYCRONOFY_TOKEN")) event = { 'event_uid': refine_what_button[ 3], # The id of the event in google calendar that's to be updated # 'summary': "Your Booking with C&K Physio", # Add the users details to the event so we know who has booked what appointment # 'description': "A Booking has been made, Username: "******" email: " + request.user.email, 'start': refine_what_button[10], # Start time of the event # 'end': refine_what_button[12], # End time of the event # 'tzid': 'Europe/Dublin', # Timezone to use# 'location': { 'description': "Google Building Gordon House, 4 Barrow St, Dublin, D04 E5W5", # The address for where the booking is for, !! Address used for development only# }, "attendees": { "invite": [{ "email": request.user. email, # Sends an invitation to the user by email that they can accept and it will add it to their calender # "display_name": "Your Booking with C&K Physio" }], }, "reminders": [ # Reminder notifications 15, 60 mins before start time and 1 day before # { "minutes": 60 }, { "minutes": 1440 }, { "minutes": 15 } ] } event_2 = { # If the booking is for groups then this is used# 'event_uid': refine_what_button[3], 'summary': "Your Booking with C&K Physio", 'description': "A Booking has been made, Username: "******" email: " + request.user.email, 'start': refine_what_button[22], 'end': refine_what_button[24], 'tzid': 'Europe/Dublin', 'location': { 'description': "N Wall Quay, North Dock, Dublin 1", }, "attendees": { "invite": [{ "email": request.user.email, "display_name": "Your Booking with C&K Physio" }], }, "reminders": [{ "minutes": 60 }, { "minutes": 1440 }, { "minutes": 15 }] } try: # Try Add event and if it's sucesful set the cart to 0 and send the user to the success page # cronofy.upsert_event(calendar_id=refine_what_button[1], event=event) request.session['cart'] = {} return render(request, 'success.html') except: # If the event fails then it must be a group booking # cronofy.upsert_event(calendar_id=refine_what_button[1], event=event_2) request.session['cart'] = {} return render(request, 'success.html') else: messages.warning(request, "Unable to take payment") else: # Give the user feedback if they haven't picked a time/date button # messages.warning( request, "We were unable to take a payment with that card!") messages.warning(request, "Please pick a Date and Time!") else: # Generate the page with the forms# user_details = { 'full_name': request.user.first_name + " " + request.user.last_name } payment_form = MakePaymentForm() order_form = OrderForm(user_details) # Get what product the user picked# cart = request.session.get('cart', {}) what_calendar = [] # Gets the events from a particular calendar depending on what item is picked by the user # if '7' in cart: what_calendar = ['cal_XYjaVHVZYgBgrZFs_HEpo3dw86uG4SHGyFZb0lA'] elif '8' in cart: what_calendar = ['cal_XYjaVHVZYgBgrZFs_dUC2DLLCz8SKCrL07bzZmg'] elif '9' in cart: what_calendar = ['cal_XYjaVHVZYgBgrZFs_dzk27HOsMzv32vRQOsmyaQ'] # Get todays date and get the events for the next 20 days # get_date = datetime.now() + timedelta(days=1) start_date = datetime.strftime(get_date, '%Y-%m-%dT%H:%M:%SZ') future_date = datetime.now() + timedelta(days=20) end_date = datetime.strftime(future_date, '%Y-%m-%dT%H:%M:%SZ') cronofy = pycronofy.Client(access_token=os.getenv("PYCRONOFY_TOKEN")) events = cronofy.read_events(calendar_ids=what_calendar, from_date=start_date, to_date=end_date, tzid='Europe/Dublin') refine_data = (events.json()) return render( request, "checkout.html", { 'order_form': order_form, 'payment_form': payment_form, 'publishable': settings.STRIPE_PUBLISHABLE, 'data': refine_data })
import pycronofy import pprint pp = pprint.PrettyPrinter(indent=4) cronofy = pycronofy.Client(access_token="1pghMu9Cll9dPcXyH-Eq8wi_u3ppc3i0") event = { 'calendar_id': "cal_XP9@Yw7C@wC-6Bjo_xpI@DzAnyq6nxaM9bicguw", 'event_id': "unique-event-id2", 'summary': "Board meeting", 'description': "Discuss plans for the next quarter.", 'start': "2019-06-15T12:00:00Z", 'end': "2019-06-15T12:30:00Z", 'tzid': "Europe/Amsterdam", 'location': { 'description': "Board room" } } print(cronofy.read_events().all())
def deleteEvent(self, eventID: str): key = self.getConfig('cronofykey') calendarID = self.getConfig('calendarID') cronofy = pycronofy.Client(access_token=key) cronofy.delete_event(calendar_id=calendarID, event_id=eventID)
def getCredentials(): """ This method checks if the user had logged into google calendar and apple icloud, if not it prompts the user and and saves the credentials. :param: None :return: Google API object :return: Apple API object """ # Google part creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('Data/token.pickle'): with open('Data/token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: try: creds.refresh(Request()) except: print("Error! No internet connection.") else: flow = InstalledAppFlow.from_client_secrets_file( 'Data/credentials.json', SCOPES) creds = flow.run_local_server() # Save the credentials for the next run with open('Data/token.pickle', 'wb') as token: pickle.dump(creds, token) print("Authenticating Google API..." ) # Test if the Google API doesn't trow an error try: googleAPI = build('calendar', 'v3', credentials=creds) # Generates google API object except: print("Something went wrong with authenticating Google") print("Google authenticated succesfully!\n") while True: if os.path.exists( 'Data/AppleToken.txt' ): # Checks if the user has added the cronify api token AppleCreds = open('Data/AppleToken.txt', 'r') apple_token = AppleCreds.readline() break else: # If file doesn't exist ask the user for the token and save it in Data/AppleToken.txt and check again AppleCreds = open('Data/AppleToken.txt', 'w') print("Acces token? --> See readme!") AppleCreds.write( str( input( "Please paste your access token string here and press enter.\n" ))) AppleCreds.close() print("retrying") print("Authenticating Apple API" ) # Test if the Apple API doesn't trow an error try: appleAPI = pycronofy.Client( access_token=apple_token) # Generates cronofy (apple) API object except: print("Something went wrong with authenticating Apple") print("Apple authenticated succesfully!\n") return googleAPI, appleAPI
def get_calendar_events(): cronofy = pycronofy.Client(access_token=settings.ACCESS_TOKEN) events = cronofy.read_events() for event in events: print event