예제 #1
1
def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('gmail', 'v1', credentials=creds)

    # Call the Gmail API
    results = service.users().labels().list(userId='me').execute()
    labels = results.get('labels', [])

    if not labels:
        print('No labels found.')
    else:
        print('Labels:')
        for label in labels:
            print(label['name'])
예제 #2
0
def main():
    """Shows basic usage of the Tasks API.
    Prints the title and ID of the first 10 task lists.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('tasks', 'v1', credentials=creds)

    # Call the Tasks API
    results = service.tasklists().list(maxResults=10).execute()
    items = results.get('items', [])

    if not items:
        print('No task lists found.')
    else:
        print('Task lists:')
        for item in items:
            print(u'{0} ({1})'.format(item['title'], item['id']))
예제 #3
0
def get_sheets_service(auth_path):
    credentials_path = auth_path + '/credentials.json'
    token_path = auth_path + '/token.pickle'
    creds = None
    if not os.path.exists(auth_path):
        LOGGER.info("Creating auth dir '" + auth_path + "'")
        os.makedirs(auth_path)
    if not os.path.exists(credentials_path):
        raise Exception('Missing credentials.json.\n'
                        'Go to: https://developers.google.com/sheets/api/quickstart/python\n'
                        "Under Step 1, click 'ENABLE THE GOOGLE SHEETS API'\n"
                        "Click 'DOWNLOAD CLIENT CONFIGURATION'\n"
                        'Save to your auth_path (' + auth_path + ') as credentials.json')
    if os.path.exists(token_path):
        with open(token_path, 'rb') as token:
            creds = pickle.load(token)
            LOGGER.info('Loaded credentials from ' + token_path)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            LOGGER.info('Refreshing credentials...')
            creds.refresh(Request())
        else:
            LOGGER.info('Could not find credentials. Requesting new credentials.')
            flow = InstalledAppFlow.from_client_secrets_file(credentials_path, SCOPES)
            creds = flow.run_local_server()
        with open(token_path, 'wb') as token:
            pickle.dump(creds, token)
    service = build('sheets', 'v4', credentials=creds)
    sheets = service.spreadsheets()
    return sheets
예제 #4
0
def driveClient():
    """Shows basic usage of the Sheets API.
    Prints values from a sample spreadsheet.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)

    return service
예제 #5
0
def main():
    """Shows basic usage of the Docs API.
    Prints the title of a sample document.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('docs', 'v1', credentials=creds)

    # Retrieve the documents contents from the Docs service.
    document = service.documents().get(documentId=DOCUMENT_ID).execute()

    print('The title of the document is: {}'.format(document.get('title')))
예제 #6
0
 def youtube_authenticated_service(self):
     flow = InstalledAppFlow.from_client_secrets_file(self.client_secrets_file, SCOPES)
     storage = Storage(self.client_oauth2_file)
     credentials = storage.get()
     if credentials is None or credentials.invalid:
         credentials = flow.run_console()
     self.youtube = build(API_SERVICE_NAME, API_VERSION, credentials = credentials)
예제 #7
0
def main():
    """Shows basic usage of the Slides API.
    Prints the number of slides and elments in a sample presentation.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('slides', 'v1', credentials=creds)

    # Call the Slides API
    presentation = service.presentations().get(
        presentationId=PRESENTATION_ID).execute()
    slides = presentation.get('slides')

    print('The presentation contains {} slides:'.format(len(slides)))
    for i, slide in enumerate(slides):
        print('- Slide #{} contains {} elements.'.format(
            i + 1, len(slide.get('pageElements'))))
예제 #8
0
def main():
    """Shows basic usage of the Classroom API.
    Prints the names of the first 10 courses the user has access to.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('classroom', 'v1', credentials=creds)

    # Call the Classroom API
    results = service.courses().list(pageSize=10).execute()
    courses = results.get('courses', [])

    if not courses:
        print('No courses found.')
    else:
        print('Courses:')
        for course in courses:
            print(course['name'])
def getService(serviceName, apiVersion):
    # For some reason, the drive API suggests 'v3' for the api version, but gmail wants 'v1'. Ok.


    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.
    homeTempDirectory = getSaddlebagsDirectory()
    #jsonFileLocation = join(homeTempDirectory, 'credentials.json')
    jsonFileLocation = join(homeTempDirectory, 'client_secrets.json')
    tokenPickleLocation = join(homeTempDirectory, 'token.pickle')


    if os.path.exists(tokenPickleLocation):
        with open(tokenPickleLocation, '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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                jsonFileLocation, SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open(tokenPickleLocation, 'wb') as token:
            pickle.dump(creds, token)
    service = build(serviceName, apiVersion, credentials=creds)
    return service
예제 #10
0
def get_authenticated_service():

  # When running locally, disable OAuthlib's HTTPs verification. When
  # running in production *do not* leave this option enabled.
  os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

  flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
  credentials = flow.run_console()
  return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)
  
예제 #11
0
def main():
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('docs', 'v1', credentials=creds)

    document = service.documents().get(documentId=DOCUMENT_ID).execute()

    title = document.get('title')
    print('The title of the document is: {}'.format(title))

    # Find & Replace
    value1 = 'I am just a text'
    value2 = 'Some randomness: {}'.format(random.randint(0, 1000))
    requests = [
        {
            'replaceAllText': {
                'containsText': {
                    'text': '{{param1}}',
                    'matchCase': 'true'
                },
                'replaceText': value1 + '\n{{param1}}',
            }
        },
        {
            'replaceAllText': {
                'containsText': {
                    'text': '{{param2}}',
                    'matchCase': 'true'
                },
                'replaceText': value2 + '\n{{param2}}'
            }
        }
    ]

    result = service.documents().batchUpdate(documentId=DOCUMENT_ID, body={'requests': requests}).execute()
    print(result)
예제 #12
0
def main():
    """Calls the Apps Script API.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('script', 'v1', credentials=creds)

    # Call the Apps Script API
    try:
        # Create a new project
        request = {'title': 'My Script'}
        response = service.projects().create(body=request).execute()

        # Upload two files to the project
        request = {
            'files': [{
                'name': 'hello',
                'type': 'SERVER_JS',
                'source': SAMPLE_CODE
            }, {
                'name': 'appsscript',
                'type': 'JSON',
                'source': SAMPLE_MANIFEST
            }]
        }
        response = service.projects().updateContent(
            body=request,
            scriptId=response['scriptId']).execute()
        print('https://script.google.com/d/' + response['scriptId'] + '/edit')
    except errors.HttpError as error:
        # The API encountered a problem.
        print(error.content)
예제 #13
0
def loadAlbums():
    global loading
    global shouldRepeat
    if loading:
        shouldRepeat = True
        return
    
    loading = True
    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.
    dirname = os.path.dirname(__file__)
    token_path = os.path.join(dirname, 'token.pickle')
    cred_path = os.path.join(dirname, 'credentials.json')

    if os.path.exists(token_path):
        with open(token_path, 'rb') as token:
            creds = pickle.load(token)
            print(creds.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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                cred_path, SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open(token_path, 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)

    albums_path = os.path.join(dirname, '../../albums.csv')

    with open(albums_path, 'w') as f:
        f.write("")

    rootFolder = "1hnoUcsxODd22-Vauz8zjWhIRvW9JkERJ"
    loadFiles(rootFolder, service, "root")

    loading = False  
    if shouldRepeat:
        shouldRepeat = False
        loadAlbums()
예제 #14
0
def main():
    """Shows basic usage of the Drive Activity API.
    Prints information about the last 10 events that occured the user's Drive.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('appsactivity', 'v1', credentials=creds)

    # Call the Drive Activity API
    results = service.activities().list(source='drive.google.com',
        drive_ancestorId='root', pageSize=10).execute()
    activities = results.get('activities', [])

    if not activities:
        print('No activity.')
    else:
        print('Recent activity:')
        for activity in activities:
            event = activity['combinedEvent']
            user = event.get('user', None)
            target = event.get('target', None)
            if user is None or target is None:
                continue
            time = datetime.datetime.fromtimestamp(
                int(event['eventTimeMillis'])/1000)
            print(u'{0}: {1}, {2}, {3} ({4})'.format(time, user['name'],
                event['primaryEventType'], target['name'], target['mimeType']))
예제 #15
0
def main():
    """Shows basic usage of the Drive Activity API.

    Prints information about the last 10 events that occured the user's Drive.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('driveactivity', 'v2', credentials=creds)

    # Call the Drive Activity API
    results = service.activity().query(body={
        'pageSize': 10
    }).execute()
    activities = results.get('activities', [])

    if not activities:
        print('No activity.')
    else:
        print('Recent activity:')
        for activity in activities:
            time = getTimeInfo(activity)
            action = getActionInfo(activity['primaryActionDetail'])
            actors = map(getActorInfo, activity['actors'])
            targets = map(getTargetInfo, activity['targets'])
            print(u'{0}: {1}, {2}, {3}'.format(time, truncated(actors), action,
                                               truncated(targets)))
def init_service(credentials_filename, token_filename):
    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(token_filename):
        with open(token_filename, '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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                credentials_filename, SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open(token_filename, 'wb') as token:
            pickle.dump(creds, token)

    return build('drive', 'v3', credentials=creds)
예제 #17
0
def main():
    """Shows basic usage of the Admin SDK Directory API.
    Prints the emails and names of the first 10 users in the domain.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('admin', 'directory_v1', credentials=creds)

    # Call the Admin SDK Directory API
    print('Getting the first 10 users in the domain')
    results = service.users().list(customer='my_customer', maxResults=10,
                                orderBy='email').execute()
    users = results.get('users', [])

    if not users:
        print('No users in the domain.')
    else:
        print('Users:')
        for user in users:
            print(u'{0} ({1})'.format(user['primaryEmail'],
                user['name']['fullName']))
예제 #18
0
def main():
    """Shows basic usage of the Admin SDK Reports API.
    Prints the time, email, and name of the last 10 login events in the domain.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('admin', 'reports_v1', credentials=creds)

    # Call the Admin SDK Reports API
    print('Getting the last 10 login events')
    results = service.activities().list(userKey='all', applicationName='login',
        maxResults=10).execute()
    activities = results.get('items', [])

    if not activities:
        print('No logins found.')
    else:
        print('Logins:')
        for activity in activities:
            print(u'{0}: {1} ({2})'.format(activity['id']['time'],
                activity['actor']['email'], activity['events'][0]['name']))
예제 #19
0
def main():
    """Shows basic usage of the Sheets API.
    Prints values from a sample spreadsheet.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                CREDENTIALS, SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('sheets', 'v4', credentials=creds)

    # Call the Sheets API
    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                                range=SAMPLE_RANGE_NAME).execute()
    values = result.get('values', [])

    if not values:
        print('No data found.')
    else:
        print('Name, Major:')
        for row in values:
            # Print columns A and E, which correspond to indices 0 and 4.
            print('%s, %s' % (row[0], row[4]))
예제 #20
0
def main():
    """Shows basic usage of the People API.
    Prints the name of the first 10 connections.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('people', 'v1', credentials=creds)

    # Call the People API
    print('List 10 connection names')
    results = service.people().connections().list(
        resourceName='people/me',
        pageSize=10,
        personFields='names,emailAddresses').execute()
    connections = results.get('connections', [])

    for person in connections:
        names = person.get('names', [])
        if names:
            name = names[0].get('displayName')
            print(name)
예제 #21
0
def main():
    """Shows basic usage of the Google Calendar API.
    Prints the start and name of the next 10 events on the user's calendar.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)

    # Call the Calendar API
    now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
    print('Getting the upcoming 10 events')
    events_result = service.events().list(calendarId='primary', timeMin=now,
                                        maxResults=10, singleEvents=True,
                                        orderBy='startTime').execute()
    events = events_result.get('items', [])

    if not events:
        print('No upcoming events found.')
    for event in events:
        start = event['start'].get('dateTime', event['start'].get('date'))
        print(start, event['summary'])
예제 #22
0
def main():
    """Calls the Admin SDK Reseller API. Prints the customer ID, SKU ID,
    and plan name of the first 10 subscriptions managed by the domain.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('reseller', 'v1', credentials=creds)

    # Call the Admin SDK Reseller API
    print('Getting the first 10 subscriptions')
    results = service.subscriptions().list(maxResults=10).execute()
    subscriptions = results.get('subscriptions', [])
    if not subscriptions:
        print('No subscriptions found.')
    else:
        print('Subscriptions:')
        for subscription in subscriptions:
            print(u'{0} ({1}, {2})'.format(subscription['customerId'],
                subscription['skuId'], subscription['plan']['planName']))
예제 #23
0
def get_api_resource():
    """
    Return a Google API Resource object using a pickled token or get a new one.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    return build('drive', 'v3', credentials=creds)
예제 #24
0
def get_authenticated_service():
    flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE,
                                                     SCOPES)
    credentials = flow.run_console()
    return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
예제 #25
0
    def handle_update_end_date(self):
        # Getting the credentials for G.People API
        storage = Storage('info.dat')
        credentials = storage.get()
        if credentials is None or credentials.invalid is True:
            credentials = tools.run_flow(FLOW, storage)

        http = httplib2.Http()
        http = credentials.authorize(http)

        people_service = build(serviceName='people', version='v1', http=http)

        results = people_service.people().connections().list(
            resourceName='people/me',
            pageSize=10,
            personFields='emailAddresses,names').execute()
        connections = results.get('connections', [])

        # Get credentials for google calendar with [email protected]
        # and token management
        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('token.pickle'):
            with open('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:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    'credentials.json', SCOPES)
                creds = flow.run_local_server()
            # Save the credentials for the next run
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        service = build('calendar', 'v3', credentials=creds)
        # Getting the event you want to update
        title = self.get_response('what\'s the name of the event')
        events_result = service.events().list(calendarId='primary',
                                              maxResults=1,
                                              singleEvents=True,
                                              orderBy='startTime',
                                              q=title).execute()
        events = events_result.get('items', [])
        if not events:
            self.speak('event not found')
        for event in events:
            eventid = event['id']

        # Getting inputs
        end = self.get_response('when does it end?')
        et = extract_datetime(end)
        event['start'] = et
        # Updating the Event
        service.events().update(calendarId='primary',
                                eventId=eventid,
                                body=event).execute()
        self.speak_dialog('successful.update')
예제 #26
0
def serviceaccountfactory(
    credentials='credentials.json',
    token='token.pickle',
    path=None,
    list_projects=False,
    list_sas=None,
    create_projects=None,
    max_projects=12,
    enable_services=None,
    services=['iam','drive'],
    create_sas=None,
    delete_sas=None,
    download_keys=None
    ):
    selected_projects = []
    proj_id = loads(open(credentials,'r').read())['installed']['project_id']
    creds = None
    if os.path.exists(token):
        with open(token, 'rb') as t:
            creds = pickle.load(t)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(credentials, SCOPES)

            # creds = flow.run_local_server(port=0)
            creds = flow.run_console()

        with open(token, 'wb') as t:
            pickle.dump(creds, t)

    cloud = build('cloudresourcemanager', 'v1', credentials=creds)
    iam = build('iam', 'v1', credentials=creds)
    serviceusage = build('serviceusage','v1',credentials=creds)

    projs = None
    while projs == None:
        try:
            projs = _get_projects(cloud)
        except HttpError as e:
            if loads(e.content.decode('utf-8'))['error']['status'] == 'PERMISSION_DENIED':
                try:
                    serviceusage.services().enable(name='projects/%s/services/cloudresourcemanager.googleapis.com' % proj_id).execute()
                except HttpError as e:
                    print(e._get_reason())
                    input('Press Enter to retry.')
    if list_projects:
        return _get_projects(cloud)
    if list_sas:
        return _list_sas(iam,list_sas)
    if create_projects:
        print("creat projects: {}".format(create_projects))
        if create_projects > 0:
            current_count = len(_get_projects(cloud))
            if current_count + create_projects <= max_projects:
                print('Creating %d projects' % (create_projects))
                nprjs = _create_projects(cloud, create_projects)
                selected_projects = nprjs
            else:
                sys.exit('No, you cannot create %d new project (s).\n'
                      'Please reduce value of --quick-setup.\n'
                      'Remember that you can totally create %d projects (%d already).\n'
                      'Please do not delete existing projects unless you know what you are doing' % (create_projects, max_projects, current_count))
        else:
            print('Will overwrite all service accounts in existing projects.\n'
                  'So make sure you have some projects already.')
            input("Press Enter to continue...")

    if enable_services:
        ste = []
        ste.append(enable_services)
        if enable_services == '~':
            ste = selected_projects
        elif enable_services == '*':
            ste = _get_projects(cloud)
        services = [i + '.googleapis.com' for i in services]
        print('Enabling services')
        _enable_services(serviceusage,ste,services)
    if create_sas:
        stc = []
        stc.append(create_sas)
        if create_sas == '~':
            stc = selected_projects
        elif create_sas == '*':
            stc =  _get_projects(cloud)
        for i in stc:
            _create_remaining_accounts(iam,i)
    if download_keys:
        try:
            os.mkdir(path)
        except OSError as e:
            if e.errno == errno.EEXIST:
                pass
            else:
                raise
        std = []
        std.append(download_keys)
        if download_keys == '~':
            std = selected_projects
        elif download_keys == '*':
            std = _get_projects(cloud)
        _create_sa_keys(iam,std,path)
    if delete_sas:
        std = []
        std.append(delete_sas)
        if delete_sas == '~':
            std = selected_projects
        elif delete_sas == '*':
            std = _get_projects(cloud)
        for i in std:
            print('Deleting service accounts in %s' % i)
            _delete_sas(iam,i)
예제 #27
0
def main():
    # Get credentials
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('docs', 'v1', credentials=creds)

    # Retrieve the documents contents from the Docs service.
    document = service.documents().get(documentId=DOCUMENT_ID).execute()
    document_content = document.get('body').get('content')
    print('The title of the document is: {}'.format(document.get('title')))

    # Find location to insert text
    getNextCell = False
    fillLocation = []
    for value in document_content:
        if 'table' in value:
            #print(value)
            table = value.get('table')
            #print(table)
            for row in table.get('tableRows'):
                cells = row.get('tableCells')
                for cell in cells:
                    startIndex = cell.get('content')[0].get('paragraph').get(
                        'elements')[0].get('startIndex')
                    endIndex = cell.get('content')[0].get('paragraph').get(
                        'elements')[0].get('endIndex')
                    text = cell.get('content')[0].get('paragraph').get(
                        'elements')[0].get('textRun').get('content')
                    #print(startIndex, endIndex, text)
                    if getNextCell:
                        if text.lstrip().rstrip() == '':
                            fillLocation = [startIndex, endIndex]
                        getNextCell = False
                    if TARGETCELLTEXT in text:
                        getNextCell = True

    # Insert NTR
    if len(fillLocation) != 0:
        requests = [
            #{'deleteContentRange': {
            #  'range': {
            #    'startIndex': fillLocation[0],
            #    'endIndex':fillLocation[1]
            #    }
            #  }
            #},
            {
                'insertText': {
                    'location': {
                        'index': fillLocation[0],
                    },
                    'text': TEXTTOINSERT
                }
            },
        ]
        result = service.documents().batchUpdate(documentId=DOCUMENT_ID,
                                                 body={
                                                     'requests': requests
                                                 }).execute()
        print('Inserted ' + TEXTTOINSERT)
예제 #28
0
    def handle_update_location(self):
        # list of rooms
        listofroomsadress = [
            '*****@*****.**',
            '*****@*****.**',
            '*****@*****.**',
            '*****@*****.**',
            '*****@*****.**',
            '*****@*****.**',
            '*****@*****.**',
            '*****@*****.**',
            '*****@*****.**',
            '*****@*****.**',
            '*****@*****.**',
            '*****@*****.**'
        ]
        listofroomsnames = [
            'FOCUS-1ere-Midoune Meeting Room (10)',
            'FOCUS-1ere-Aiguilles Meeting Room (10)',
            'FOCUS-1ere-Barrouta Meeting Room (10)',
            'FOCUS-1ere-Kantaoui Meeting Room (10)',
            'FOCUS-2eme-Gorges Meeting Room (10)',
            'FOCUS-2eme-Ichkeul Meeting Room (10)',
            'FOCUS-2eme-Khemir Meeting Room (10)',
            'FOCUS-2eme-Tamaghza Meeting Room (10)',
            'FOCUS-RDC-Friguia Meeting Room (15)',
            'FOCUS-RDC-Ksour Meeting Room (10)',
            'FOCUS-RDC-Medeina Meeting Room (10)',
            'FOCUS-RDC-Thyna Meeting Room (10)'
        ]
        # Getting the credentials for G.People API
        storage = Storage('info.dat')
        credentials = storage.get()
        if credentials is None or credentials.invalid is True:
            credentials = tools.run_flow(FLOW, storage)

        http = httplib2.Http()
        http = credentials.authorize(http)

        people_service = build(serviceName='people', version='v1', http=http)

        results = people_service.people().connections().list(
            resourceName='people/me',
            pageSize=10,
            personFields='emailAddresses,names').execute()
        connections = results.get('connections', [])

        # Get credentials for google calendar with [email protected]
        # and token management
        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('token.pickle'):
            with open('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:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    'credentials.json', SCOPES)
                creds = flow.run_local_server()
            # Save the credentials for the next run
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        service = build('calendar', 'v3', credentials=creds)
        # Getting the event you want to update
        title = self.get_response('what\'s the name of the event')
        events_result = service.events().list(calendarId='primary',
                                              maxResults=1,
                                              singleEvents=True,
                                              orderBy='startTime',
                                              q=title).execute()
        events = events_result.get('items', [])
        if not events:
            self.speak('event not found')
        for event in events:
            eventid = event['id']
            attendees = event['attendees']
            l = len(attendees)

        # Getting inputs
        r = self.get_response('what\'s the new location of your event?')
        maxattendees = 10
        if r == "Midoun meeting room":
            room = "*****@*****.**"
        elif r == "Aiguilles Meeting Room":
            room = "*****@*****.**"
            roomname = 'FOCUS-1ere-Aiguilles Meeting Room (10)'
        elif r == "Barrouta Meeting Room":
            room = "*****@*****.**"
            roomname = ''
        elif r == "Kantaoui Meeting Room":
            room = "*****@*****.**"
            roomname = ''
        elif r == "Gorges Meeting Room":
            room = "*****@*****.**"
            roomname = ''
        elif r == "Ichkeul Meeting Room":
            room = "*****@*****.**"
            roomname = ''
        elif r == "Khemir Meeting Room":
            room = "*****@*****.**"
            roomname = ''
        elif r == "Tamaghza Meeting Room":
            room = "*****@*****.**"
            roomname = ''
        elif r == "Friguia Meeting Room":
            room = "*****@*****.**"
            roomname = ''
            maxattendees = 15
        elif r == "Ksour Meeting Room":
            room = "*****@*****.**"
        elif r == "Medeina Meeting Room":
            room = "*****@*****.**"
        elif r == "Thyna Meeting Room":
            room = "*****@*****.**"

        # In this part we have to get the list of attendees, then extract the email of the meeting room to reserve
        # then change it with the email matching the input new location to the email list of rooms
        o = 0
        p = 0
        t = 0
        y = 0
        attendemail = []
        attendname = []
        finallist = []
        l = len(attendees)
        while o != l:
            attendemail.append(attendees[o]['email'])
            attendname.append(attendees[o].get('displayName'))
            o = o + 1
        while p != len(attendemail):
            while t != len(listofroomsadress):
                if attendemail[p] == listofroomsadress[t]:
                    attendemail[p] = room
                    attendname[p] == r
                t = t + 1
            p = p + 1
        while y != len(attendemail):
            mr = {'email': attendemail[y]}
            finallist.append(mr)
            y = y + 1

        event['attendees'] = finallist
        # event['location'] = r
        updated_event = service.events().update(calendarId='primary',
                                                eventId=eventid,
                                                body=event).execute()
        # Updating the Event
        service.events().update(calendarId='primary',
                                eventId=eventid,
                                body=event).execute()
        self.speak_dialog('successful.update')
예제 #29
0
def getMail():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('gmail', 'v1', credentials=creds)
    results = service.users().messages().list(userId='me',labelIds = ['INBOX'], q='job opportunity OR position OR openings OR roles OR hiring newer_than:30d').execute()
    messages = results.get('messages', [])
    emailsList = []

    if not messages:
        print ("No messages found.")
    else:
        for message in messages:
            stackrank = ['CCNA', 'CCNP', 'LAN', 'Cisco','Network Engineer', 'Salary', 'Remote']
            weight = 0
            temp_dict = {}
            msg = service.users().messages().get(userId='me', id=message['id']).execute()
            payload = msg['payload']
            header = payload['headers']
            if "data" in payload['body']:
                data = payload['body']
                body = list(data.values())[0]
            elif "data" in payload['parts'][0]['body']:
                body = payload['parts'][0]['body']['data']
            else:
                if "parts" in payload['parts'][0]:
                        if len(payload['parts'][0]['parts']) >= 3:
                            if "data" in payload['parts'][0]['parts'][2]['body']:
                                print("DATA FOUND IN PAYLOAD PARTS 0 PARTS 2 BODY****")
                                body = payload['parts'][0]['parts'][2]['body']['data']
                            else:
                                pass
                        else: 
                            body = "none"
                else:
                        body = "none"


                # PULLING IN HEADER INFO (Date, Sender, Subject)
            for one in header: # getting the Subject
                if one['name'] == 'Subject':
                    msg_subject = one['value']
                    temp_dict['Subject'] = msg_subject
                else:
                    pass


            for two in header: # getting the date
                if two['name'] == 'Date':
                    msg_date = two['value']
                    date_parse = (parser.parse(msg_date))
                    m_date = (date_parse.date())
                    temp_dict['Date'] = str(m_date)
                else:
                    pass

            for three in header: # getting the Sender
                if three['name'] == 'From':
                    msg_from = three['value']
                    temp_dict['Sender'] = msg_from
                else:
                    pass

            temp_dict['Snippet'] = msg['snippet'] # fetching message snippet


            # Cleaning up the Email Body
            if(body == "none"):
                print("NO EMAIL MESSAGE DATA FOUND")
            else:
                decode = base64.urlsafe_b64decode(body.encode("ascii")) # Decode the base64 data returned from the API for the body
                clean = BeautifulSoup(decode,"html.parser") # Strip out all of the html elements to get text only
                bodyclean = clean.get_text() # Email Body Data in Decoded/HTML Cleaned Format
            # Return the Results
            found = []
            for word in stackrank:
                if word in bodyclean:
                        weight += 25
                        found.append(word)
            email = {
            "Date" : temp_dict['Date'],
            "From" : temp_dict['Sender'],
            "Subject" : temp_dict['Subject'],
            "Excerpt" : temp_dict['Snippet'],
            "Weight" : weight,
            "Found" : ', '.join(found)
            }
            emailsList.append(email)

    rankstacked = sorted(emailsList, key=lambda k: k['Weight'], reverse=True)
    return rankstacked
def main():
    if getattr(sys, 'frozen', False):
        # running in a bundle
        chromedriver_path = os.path.join(sys._MEIPASS, 'chromedriver')

    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    #Creates an API service for Google Tasks using the Credentials in the token.pickle file
    service = build('tasks', 'v1', credentials=creds)

    #Clears the terminal and prints a welcome message
    os.system('cls||clear')
    print("=================================================================")
    print("|                    Zach's Task Manager                        |")
    print("=================================================================")

    #Prompts for user input to get action
    act = input("Would you like to [view] or [add] or [addwebassign] tasks? ")

    #If user input view, get the tasks from default list and print them
    if act == "view":
        #Retreives tasks
        tasks = service.tasks().list(tasklist='@default').execute()
        #If no tasks are found print that
        if not tasks:
            print("No tasks found")
        #Otherwise print all the tasks in the default list
        else:
            for task in tasks['items']:
                print("Task: " + task['title'])
                date = task['due'].split("-")
                year = date[0]
                month = date[1]
                dayS = date[2].split("T")
                day = dayS[0]
                print("     Due: " + month + "-" + day + "-" + year)
        input("Press enter to continue ")
        main()
    #If the input is add, prompt for the title and due date and add it to the default list
    elif act == "add":
        tit = input("Title: ")
        date_time_str = input("Due date (MON DD YYYY  H:MMPM): ")
        date_time_obj = datetime.datetime.strptime(date_time_str,
                                                   '%b %d %Y %I:%M%p')
        add = {
            'title': tit,
            'notes': "Due @ " + date_time_str.split(" ")[-1],
            'due': date_time_obj.isoformat() + 'Z'
        }
        result = service.tasks().insert(tasklist='@default',
                                        body=add).execute()
        time.sleep(1)
        main()
        #If result is empty there was an error
        if not result:
            print('Could not add')
        #Otherwise print the result id
        else:
            print(result['id'])
    #If the input is exit, exit the program
    elif act == "exit":
        sys.exit()
    #If the input is remove, remove all tasks with the prefix in the default list
    elif act == "remove":
        fullTasks = service.tasks().list(tasklist='@default',
                                         showCompleted=True,
                                         showHidden=True,
                                         maxResults=100).execute()
        for task in fullTasks['items']:
            if prefix in task['title']:
                service.tasks().delete(tasklist='@default',
                                       task=task['id']).execute()
        print("Removed all automated tasks")
        time.sleep(1)
        main()
    #If the input is removeauth, remove the auth file and reprompt for authorization
    elif act == "removeauth":
        remove()
        main()
    #If the input is addwebassign, scrape webassign for data, get all asignments for each class and add them as tasks
    elif act == "addwebassign":
        #Opens the password file
        file = open("userpass.txt")
        #Reads the first two lines, should be unity id and password (currently in plain text)
        user = file.readline()
        pas = file.readline()
        #Options to run selenium in "headless" mode, disabled for now.
        chrome_options = Options()
        #chrome_options.add_argument("--headless")
        chrome_options.add_argument('log-level=3')
        chrome_path = "resources\\chromedriver.exe"
        log_path = 'NUL'
        driver = webdriver.Chrome(chrome_path, options=chrome_options)
        #Opens chrome in automated testing mode using provided chromedriver file
        #driver = webdriver.Chrome("resources\\chromedriver.exe")
        driver.set_page_load_timeout("10")
        #Page to scrape data from, currently setup for ncsu webassign. This is where homework for classes are assigned.
        driver.get("https://www.webassign.net/ncsu/login.html")
        #Finds the login button on the page and clicks it
        driver.find_element_by_id("loginbtn").click()
        timeout = 10
        #Waits for the page to load and the username and password fields are visible, otherwise catches the exception
        try:
            element_present = EC.presence_of_element_located(
                (By.NAME, 'j_username'))
            WebDriverWait(driver, timeout).until(element_present)
        except TimeoutException:
            print("Timed out waiting for page to load.")
            time.sleep(2)
            main()
        #Uses the stored username and password values to login to webassign
        driver.find_element_by_name("j_username").send_keys(user)
        driver.find_element_by_name("j_password").send_keys(pas)
        #driver.find_element_by_id("formSubmit").click()
        #Waits for next page to load
        while True:
            try:
                driver.find_element_by_name("_eventId_proceed").click()
                break
            except Exception as e:
                None
        print("Adding Courses to Task List...")
        #Keep track of the number of courses that were added, change and a counter
        numAdded = 0
        numChanged = 0
        i = 1
        try:
            element_present = EC.presence_of_element_located(
                (By.XPATH, '//*[@id="single-course-info"]/div[2]'))
            WebDriverWait(driver, timeout).until(element_present)
        except TimeoutException:
            print("Timed out waiting for page to load.")
            time.sleep(2)
            main()
        currentClass = driver.find_element_by_xpath(
            '//*[@id="single-course-info"]/div[2]')
        currentClass = currentClass.text.split(",")[0]
        # if currentClass == "PY 206" or currentClass == "PY 209":
        #     continue
        print("Searching %s" % currentClass)
        #Tries to find all assignments, if an exception occurs it is assumed there are no assignments and the program proceeds to the next class
        try:
            assignmentList = driver.find_element_by_xpath(
                "/html/body/form/div/main/div[6]/div[1]/div[1]/section/ul")
            assignments = assignmentList.find_elements_by_tag_name("li")
        except Exception as e:
            None
        #For each assigment get the name and the due date and add it to Google Tasks
        for assignment in assignments:
            try:
                assignmentName = assignment.find_element_by_xpath(
                    "a/div/span").text
                assignmentDue = assignment.find_element_by_xpath(
                    "a/div[3]").text
            except Exception as e:
                continue
            #Gets the assigment due date
            aTS = assignmentDue.split(", ")
            #Gets the time that the assigment is due
            aTHMS = aTS[3].split(" ")
            #Create a datetime object to format the time for Google Tasks API
            date_time_obj = datetime.datetime.strptime(aTS[1] + " " + aTS[2],
                                                       '%b %d %Y')
            #Formats the task name
            titleC = currentClass + " - " + assignmentName
            #Creates a new task to be added to the Google Tasks list
            add = {
                'title': prefix + currentClass + " - " + assignmentName,
                'notes': 'Due @ ' + aTHMS[0] + aTHMS[1],
                'due': date_time_obj.isoformat() + '.000Z'
            }
            #Calls the API and gets a list of all the tasks on the list for searching
            fullTasks = service.tasks().list(tasklist='@default',
                                             showCompleted=True,
                                             showHidden=True,
                                             maxResults=100).execute()
            #To booleans to store if the value is found or it needs a date time change
            found = False
            dtChange = False
            #Searches all tasks on the tasklist and sees if it exists or needs a datetime change
            for task in fullTasks['items']:
                if task['title'] == prefix + currentClass + " - " + assignmentName or task[
                        'title'] == currentClass + " - " + assignmentName:
                    if task['due'] != add['due']:
                        dtChange = True
                    else:
                        found = True
                    break
            #If the task needs a datetime change we need to remove it and readd it
            if dtChange:
                for task in fullTasks['items']:
                    if task['title'] == add['title']:
                        service.tasks().delete(tasklist='@default',
                                               task=task['id']).execute()
            #If it is found or the assignment is ignored, skip it
            if found or ignore(assignmentName):
                continue
            #Otherwise call the API and add it to the task list
            result = service.tasks().insert(tasklist='@default',
                                            body=add).execute()
            #If result is nothing then it was not added correclty, otherwise print the information about the assignment
            if not result:
                print('Could not add')
            else:
                if dtChange:
                    print("Change Date/Time: " + currentClass + " - " +
                          assignmentName)
                    numChanged = numChanged + 1
                else:
                    print("Added: " + currentClass + " - " + assignmentName)
                    numAdded = numAdded + 1
            i = i + 1
        #If an exception occurs anywhere in execution, print the message and stop execution
        #Exits chrome
        driver.quit()
        #Prints the number of assignmets added and number of assignments changed
        print("Assignments Added: %i, Assignments Changed: %i" %
              (numAdded, numChanged))
        #Waits for the user to hit enter to return to the main page and close chrome
        input("Press enter to return to main page")
        main()
    #Otherwise the input is not valid and the user is reprmpted
    else:
        print("Not valid input")
        time.sleep(1)
        main()
예제 #31
0
SAMPLE_SPREADSHEET_ID = '1lsbQSm_gsb_CQNOnSuoZ4mZclxorLjsMj3V5CvstO_A'
SAMPLE_RANGE_NAME = 'Sheet1!A1:F10'

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('token.pickle'):
    with open('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:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            'credentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)

service = build('sheets', 'v4', credentials=creds)

sheet = service.spreadsheets()


def clear_vals():
    # Clear values first
    request = sheet.values().clear(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                                   range=SAMPLE_RANGE_NAME).execute()
예제 #32
0
def main():
    """Shows basic usage of the Google Calendar API.
    Prints the start and name of the next 10 events on the user's calendar.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)

    # Call the Calendar API
    now = datetime.datetime.utcnow().isoformat(
    ) + 'Z'  # 'Z' indicates UTC time
    print('Getting the upcoming 10 events')
    events_result = service.events().list(calendarId='primary',
                                          timeMin=now,
                                          maxResults=10,
                                          singleEvents=True,
                                          orderBy='startTime').execute()
    # events = events_result.get('items', [])

    #if not events:
    #   print('No upcoming events found.')
    # for event in events:

    #    start = event['start'].get('dateTime', event['start'].get('date'))
    #    print(start, event['summary'])

    event = {
        'summary':
        'Google I/O 2015',
        'location':
        '800 Howard St., San Francisco, CA 94103',
        'description':
        'A chance to hear more about Google\'s developer products.',
        'start': {
            'dateTime': '2020-08-10T09:00:00-07:00',
            'timeZone': 'America/Los_Angeles',
        },
        'end': {
            'dateTime': '2015-05-28T17:00:00-07:00',
            'timeZone': 'America/Los_Angeles',
        },
        'recurrence': ['RRULE:FREQ=DAILY;COUNT=2'],
        'attendees': [
            {
                'email': '*****@*****.**'
            },
            {
                'email': '*****@*****.**'
            },
        ],
        'reminders': {
            'useDefault':
            False,
            'overrides': [
                {
                    'method': 'email',
                    'minutes': 24 * 60
                },
                {
                    'method': 'popup',
                    'minutes': 10
                },
            ],
        },
    }

    event = service.events().insert(calendarId='primary', body=event).execute()
    print('Event created: %s' % (event.get('htmlLink')))
예제 #33
0
def updateSheet(bonked: str, bonker: str, sheetID: str):
    SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
    RANGE_NAME = 'Sheet1!A2:C'

    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_folder / 'token.pickle'):
        with open(data_folder / '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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                data_folder / 'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open(data_folder / 'token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('sheets', 'v4', credentials=creds)
    # Call the Sheets API
    sheet = service.spreadsheets()

    # Read
    readResult = sheet.values().get(spreadsheetId=sheetID,
                                    range=RANGE_NAME).execute()
    values = readResult.get('values', [])

    if not values:
        print('No data found.')
        return False
    else:
        users = []
        for row in values:
            users.append(str(row[0]))
            # Bonker -> Column B
            # Bonked -> Column C
            # If user is the bonker
            if str(row[0]) == bonker:
                row[1] = int(row[1]) + 1
                row[2] = int(row[2])
            # If user is the bonked
            elif str(row[0]) == bonked:
                row[1] = int(row[1])
                row[2] = int(row[2]) + 1
            # Even if user is not both, we rewrite the data
            # Because otherwise there is data type mismatch
            # And this results in existing entries disregarded, causing duplicate entries
            else:
                row[1] = int(row[1])
                row[2] = int(row[2])
        if bonker not in users:
            values.append([bonker, 1, 0])
        if bonked not in users:
            values.append([bonked, 0, 1])

    # Write
    body = {'values': values}
    writeResult = sheet.values().update(spreadsheetId=sheetID,
                                        range=RANGE_NAME,
                                        valueInputOption='USER_ENTERED',
                                        body=body).execute()
    return True
예제 #34
0
def main():
    """Shows basic usage of the Google Calendar API.
    Prints the start and name of the next 10 events on the user's calendar.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)

    # Call the Calendar API
    now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
    print('Getting the upcoming 10 events')
    events_result = service.events().list(calendarId='primary', timeMin=now,
                                        maxResults=10, singleEvents=True,
                                        orderBy='startTime').execute()
    events = events_result.get('items', [])

    f = open("your_events.json", "w+")
    f.write(jsp.encode(events))
    f.close()

    if not events:
        print('No upcoming events found.')
    for event in events:
        start = event['start'].get('dateTime', event['start'].get('date'))
        print(start, event['summary'])

    my_event1 = {
      'description': 'A chance to hear more about Google\'s developer products.',
      'start': {
        'dateTime': '2015-05-28T09:00:00-07:00',
        'timeZone': 'America/Los_Angeles',
      },
      'end': {
        'dateTime': '2015-05-28T17:00:00-07:00',
        'timeZone': 'America/Los_Angeles',
      },
    }

    my_event2 = {
      'summary': 'Google I/O 2015',
      'start': {
        'dateTime': '2016-05-28T09:00:00-07:00',
        'timeZone': 'America/Los_Angeles',
      },
      'end': {
        'dateTime': '2017-05-28T17:00:00-07:00',
        'timeZone': 'America/Los_Angeles',
      },
      'attendees': [
        {'email': '*****@*****.**'},
      ],
    }

    my_events = [my_event1, my_event2]
    for event in my_events:
        event = service.events().insert(calendarId='primary', body=event).execute()
        print('Event created: {}'.format(event.get('htmlLink')))
예제 #35
0
def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('gmail', 'v1', credentials=creds)

    # Call the Gmail API
    results = service.users().labels().list(userId='me').execute()
    labels = results.get('labels', [])

    label_id = None
    if not labels:
        print('No labels found.')
    else:
        print('Labels:')
        for label in labels:
            if 'Daily Coding Problems' in label['name']:
                label_id = label['id']

    dir_info = {"Easy": "C:\\Users\\s0095057\\Documents\\Personal\\Projects\\DailyCodingProblems\\Easy",
                "Medium": "C:\\Users\\s0095057\\Documents\\Personal\\Projects\\DailyCodingProblems\\Medium",
                "Hard": "C:\\Users\\s0095057\\Documents\\Personal\\Projects\\DailyCodingProblems\\Hard"}
    if label_id is not None:
        results = service.users().messages().list(userId='me', labelIds=[label_id], maxResults=10000).execute()
        messages = results.get('messages', [])
        if not messages:
            print("No messages found.")
        else:
            print("Message snippets:")
            for message in messages:
                msg = service.users().messages().get(userId='me', id=message['id']).execute()
                subject = [sub['value'] for sub in msg['payload']['headers'] if sub['name']=='Subject'][0]
                if 'Daily Coding Problem: Problem #' in subject:
                    subject = subject.replace('Daily Coding Problem: Problem #', '')
                    sub_info = subject.split(' ')
                    _type = sub_info[-1].replace('[','').replace(']','')
                    _file_path = os.path.join(dir_info[_type], 'problem_%s.txt' %sub_info[0])
                    coded_data = msg['payload']['parts'][0]['body']['data']
                    _data = base64.urlsafe_b64decode(coded_data.encode("ASCII")).decode("utf-8")
                    sents = _data.split('\n')
                    start = "Good morning! Here's your coding interview problem for today."
                    end = "Upgrade to premium"
                    outp = []
                    start_flag = False
                    for sent in sents:
                        if end in sent:
                            break
                        if start_flag and start not in sent:
                            outp.append(sent)
                        if start in sent:
                            start_flag = True

                    print('Problem %s' %sub_info[0])
                    with open(_file_path, 'w', encoding="utf-8") as f:
                        for line in outp:
                            f.write(line)
                    print('---------')
예제 #36
0
def main():
    """Shows basic usage of the Google Calendar API.
    Prints the start and name of the next 10 events on the user's calendar.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)

    # Call the Calendar API
    now = datetime.datetime.utcnow().isoformat() + 'Z'  # 'Z' indicates UTC time
    print('Getting the upcoming 10 events')
    events_result = service.events().list(calendarId='primary', timeMin=now,
                                        maxResults=10, singleEvents=True,
                                        orderBy='startTime').execute()
    events = events_result.get('items', [])

    if not events:
        print('No upcoming events found.')
    for event in events:
        start = event['start'].get('dateTime', event['start'].get('date'))
        print(start, event['summary'])

# Refer to the Python quickstart on how to setup the environment:
# https://developers.google.com/calendar/quickstart/python
# Change the scope to 'https://www.googleapis.com/auth/calendar' and delete any
# stored credentials.
    event = {
    'summary': 'Moringa Presentations',
    'location': 'Ngong Lane Plaza,Nairobi Kenya',
    'description': 'Booking an interview date',
    'start': {
        'dateTime':  '2019-08-1T09:00:00-07:00',
        'timeZone':  'Africa/Nairobi',
    },
    'end': {
        'dateTime': '2019-08-1T17:00:00-07:00',
        'timeZone': 'Africa/Nairobi',
    },
    'recurrence': [
        'RRULE:FREQ=DAILY;COUNT=2'
    ],
    'attendees': [
        {'email': ''},
        {'email': ''},
    ],
    'reminders': {
        'useDefault': False,
        'overrides': [
        {'method': 'email', 'minutes': 24 * 60},
        {'method': 'popup', 'minutes': 10},
        ],
    },
    }

    event = service.events().insert(calendarId='primary', body=event).execute()
    print('Event created: {}'.format((event.get('htmlLink'))))
    if event:
        print('Event created')
예제 #37
0
def main():
    """Show basic usage of the Google Calendar API.
    Prints the start and name of the next 10 events on the user's calendar.
    """
    try:
        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('token.pickle'):
            with open('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:
                print('refresh creds\n')
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    '/home/pi/RaspberryPi/python3/credentials.json', SCOPES)
                try:
                    creds = flow.run_local_server(port=0)
                except Exception as e:
                    print('creds doesnt work' + str(e))

            # Save the credentials for the next run
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        service = build('calendar', 'v3', credentials=creds)

        # Call the Calendar API
        now = datetime.datetime.now().isoformat(
        ) + 'Z'  # 'Z' needed make service.events() work
        # Sets the time stamp to 12am (00:00:00 military time) so full day of meetings is
        # always displayed.
        print(now)
        NOW = list(now)
        for i in range(11, 18):
            if i != 13 and i != 16:
                NOW[i] = '0'
        NOW[18] = '1'
        now = ''.join(NOW)
        print('Getting the upcoming 10 events')
        events_result = service.events().list(
            calendarId=HQ1_ENGINEERING_CONFERENCE_CAL_ID,
            showDeleted=False,
            timeMin=now,
            maxResults=10,
            singleEvents=True,
            orderBy='startTime').execute()
        events = events_result.get('items', [])

        events_temp = []  # Temporary list to store event data
        if not events:
            print('No upcoming events found.')

        for event in events:
            start = event['start'].get('dateTime', event['start'].get('date'))
            end = event['end'].get('dateTime', event['end'].get('date'))
            events_temp.append((event['summary'], start, end))
            print(start, end, event['summary'])

        return events_temp

    except Exception as e:
        print('exception: ' + str(e))
        main()
예제 #38
0
def main():
    """Buscando chave de acesso no token (pen drive)
    Caso não seja encontrada, a chave recebe o valor 0, e o drive_service None, 
    invalidando qualquer operação na GUI.
    """
    try:
        if os.name == 'posix':
            f = open("/media/allan/KINGSTON/text.txt", "r")
        else:
            f = open("F:/text.txt", "r")
        key = f.readline().encode()
        f.close()
    except:
        key = 0

    connected = False
    drive_service = None

    #Informações descriptografadas são salvas no dicionário info
    if key != 0:

        #Autenticacao utilizando credenciais no arquivo JSON ou arquivo PICKLE
        try:
            creds = None
            if os.path.exists('token.pickle'):
                with open('token.pickle', 'rb') as token:
                    creds = pickle.load(token)
            if not creds or not creds.valid:
                if creds and creds.expired and creds.refresh_token:
                    creds.refresh(Request())
                else:
                    flow = InstalledAppFlow.from_client_secrets_file(
                        'credentials.json', SCOPES)
                    creds = flow.run_local_server(port=0)
                with open('token.pickle', 'wb') as token:
                    pickle.dump(creds, token)

            #Autenticação google drive
            drive_service = build('drive', 'v3', credentials=creds)
            connected = True

        except Exception as e:
            print(
                "Não foi possível conectar ao Drive. Utilizandos dados locais."
            )

        #Se houver conexão, atualizar dados locais através do drive
        if connected:
            request = drive_service.files().get_media(fileId=DATA_FILE_ID)
            fh = io.BytesIO()
            downloader = MediaIoBaseDownload(fh, request)
            done = False
            while done is False:
                status, done = downloader.next_chunk()

            fh.seek(0)
            data = fh.read()

            with open('data', 'wb') as file:
                file.write(data)

        #Lendo dados salvos localmente, após tentar atualiza-los
        with open("data", "r") as data:
            for line in data:
                dec = Fernet(key).decrypt(bytes(line, 'utf-8')).decode('utf-8')
                pwd, user, site = dec.strip().split(',')
                info[site] = (pwd, user)

    #Instanciação da GUI
    app = QApplication(sys.argv)
    win = Window(drive_service, key, connected)
    win.show()
    sys.exit(app.exec_())
예제 #39
0
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
import json


# scope is readonly
flow = InstalledAppFlow.from_client_secrets_file(
            'client_secret.json', 
            scopes=['https://www.googleapis.com/auth/admin.directory.user.readonly']
        )

flow.run_local_server(port=8080, prompt='consent', authorization_prompt_message='')

credentials = flow.credentials

admin = build('admin' , 'directory_v1', credentials=credentials)

# update the email address
userKey = '*****@*****.**'

request = admin.users().get(
    userKey=userKey,
    customFieldMask=None,
    projection=None,
    viewType=None)

response = request.execute()

# uncomment if you want to print it to the console
# print(json.dumps(response['lastLoginTime'], sort_keys=True, indent=4))
예제 #40
0
    "https://www.googleapis.com/auth/drive",
    "https://www.googleapis.com/auth/drive.metadata",
    "https://www.googleapis.com/auth/drive.scripts"
]

creds = None

if p.exists(app_token):
    with open(app_token, "rb") as token:
        creds = pickle.load(token)

if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            app_credentials, SCOPES)
        creds = flow.run_local_server(port=0)

    with open(app_token, "wb") as token:
        pickle.dump(creds, token, protocol=2)

service = build("drive", "v3", credentials=creds)


# webpage renders
@app.route("/", methods=["GET"])
def Index():
    return render_template("Index.html")


@app.route("/Documents", methods=["GET"])
예제 #41
0
파일: Riki.py 프로젝트: codyesm/CSC440
from wiki import create_app
"""
import calendar

print(calendar.weekheader(3))
print()

print(calendar.month(2020,4))
"""

from apiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow

scopes = ['https://www.googleapis.com/auth/calendar']

flow = InstalledAppFlow.from_client_secrets_file("client_secret.json", scopes=scopes)
credentials = flow.run_console()

#pickle.dump(credentials, open("token.pkl", "wb"))
#credentials = pickle.load(open("token.pkl", "rb"))

service = build("calendar", "v3", credentials=credentials)

result = service.calendarList().list().execute()


directory = os.getcwd()
app = create_app(directory)

if __name__ == '__main__':
    app.run(host='127.0.0.1', debug=True)
예제 #42
0
    def handle_add_attendees(self):
        # Getting the credentials for G.People API
        storage = Storage('info.dat')
        credentials = storage.get()
        if credentials is None or credentials.invalid is True:
            credentials = tools.run_flow(FLOW, storage)

        http = httplib2.Http()
        http = credentials.authorize(http)

        people_service = build(serviceName='people', version='v1', http=http)

        results = people_service.people().connections().list(
            resourceName='people/me',
            pageSize=10,
            personFields='emailAddresses,names').execute()
        connections = results.get('connections', [])

        # Get credentials for google calendar with [email protected]
        # and token management
        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('token.pickle'):
            with open('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:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    'credentials.json', SCOPES)
                creds = flow.run_local_server()
            # Save the credentials for the next run
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        service = build('calendar', 'v3', credentials=creds)
        # Getting the event you want to update
        title = self.get_response('what\'s the name of the event')
        events_result = service.events().list(calendarId='primary',
                                              maxResults=1,
                                              singleEvents=True,
                                              orderBy='startTime',
                                              q=title).execute()
        events = events_result.get('items', [])
        if not events:
            self.speak('event not found')
        for event in events:
            invitedattendees = event['attendees']
            eventid = event['id']
        # Getting the contact ALL READY invited
        invitedattendemail = []
        invitedattendname = []
        o = 0
        l = len(invitedattendees)
        while o != l:
            invitedattendemail.append(invitedattendees[o]['email'])
            invitedattendname.append(invitedattendees[o].get('displayName'))
            o = o + 1
        # at this stage we have 3 lists
        # 1) invitedattend[] which is what we get from the google calendar
        # 2) invitedattendname[]the list of names of each attendee
        # 3) invitedattendemail[] the list of emails of each attendee

        # Now we have to figure out the number of attendees that we can add no more then the capacity of the room
        maxattendees = 10
        if event['location'] == 'FOCUS-RDC-Friguia Meeting Room (15)':
            maxattendees = 15
        at = self.get_response('how many attendees would like to add ?')
        na = maxattendees - at
        if l == maxattendees:
            self.speak(
                'infortunatly you can\'t add more attendees because the room is full'
            )
        elif na < at:
            self.speak_dialog('max.attendees ', data={'na': na})
        else:
            na = at

        # Getting the Attendees from input
        attemail = []
        noms = []
        f = 0
        i = 1
        g = 0
        found = False
        found2 = False
        # get all contacts in a list
        for person in connections:
            emailAddresses = person.get('emailAddresses', [])
            names = person.get('names', [])
            attemail.append(emailAddresses[0].get('value'))
            noms.append(names[0].get('displayName'))
        # print(noms)
        p = len(noms)
        # Int a list of attendees and it's length is the maximum number of attendees according to the room chosen befor
        attendees = ['blabla@blabla'] * na
        # first attendee
        # print('attendees :')
        a = self.get_response('how do you want to add ?')
        # looking for the contact in contact list
        if a != '':
            while (g != p) & (found is False):
                # if the name in the input matches the a name in the list we add the email of that person to the attendees
                # list which will be treated later to delete the examples '*****@*****.**'
                if noms[g] == a:
                    attendees[0] = attemail[g]
                    g = g + 1
                    found = True
                else:
                    g = g + 1
            if found is False:
                self.speak('contact not found try again please')
        else:
            self.speak('no attendees added')
        # other attendees to add less then max number of attendees
        while i != na:
            a = self.get_response('how many attendees would like to add ?')
            if a == '':
                break
            else:
                while (f != p) | (found2 is False):
                    if noms[f] == a:
                        attendees[i] = attemail[f]
                        found2 = True
                    f = f + 1
            i = i + 1
        # until this stage we have a list of attendees + blanks filled with [email protected]
        l = len(attendees)
        # in this part we are going to get the attendees without the blanks
        t = 0
        att = []
        while t != l:
            if attendees[t] != 'blabla@blabla':
                att.append(attendees[t])
                t = t + 1
            else:
                t = t + 1
        w = 0
        attendemail = []
        while w != len(attendees):
            attendemail.append(attendees[w])
            w = w + 1
        attendee = []
        for s in range(len(invitedattendemail)):
            email = {'email': invitedattendemail[s]}
            attendee.append(email)
        for r in range(len(attendemail)):
            email = {'email': attendemail[r]}
            attendee.append(email)
        event['attendees'] = attendee

        updated_event = service.events().update(calendarId='primary',
                                                eventId=eventid,
                                                body=event).execute()
        self.speak_dialog('successful.update')
def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                CREDENTIALS, SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)
    
    emailMessage = """
        Sample Email Message to be sent to the user.
    """

    with open(READ_CSV, newline='') as csvrfile:
        reader = csv.reader(csvrfile)
        with open(WRITE_CSV, 'w', newline='') as csvwfile:
            writer = csv.writer(csvwfile)
            row = list(reader)
            for r in row:
                file_name = r[0] #Column name from CSV to whic file is to be renamed.
                user1 = r[1].lower() #1st user to whom permission are to be allocated
                user2 = r[2].lower() #1st user to whom permission are to be allocated
                
                try:
                    #Create copy of the origin file. copy_file stores the response.
                    copy_file = service.files().copy(
                        fileId=ORIGINAL_FILE).execute()

                    #Rename the new file
                    updateMetaData = {
                        'name': name
                    }
                    updateName = service.files().update(
                        body=updateMetaData, fileId=copy_file['id']).execute()
                    
                    #Create Permission instance
                    batch = service.new_batch_http_request(callback=callback)
                    user1_permission = {
                        'type': 'user', #assign type
                        'role': 'writer', #assign role
                        'emailAddress': user1
                    }
                    batch.add(service.permissions().create(
                            fileId=copy_file['id'],
                            body=user1_permission,
                            fields='id',
                            emailMessage=emailMessage
                    ))
                    user2_permission = {
                        'type': 'user', #assign type
                        'role': 'writer', #assign role
                        'emailAddress': user2
                    }
                    batch.add(service.permissions().create(
                            fileId=copy_file['id'],
                            body=user2_permission,
                            fields='id',
                            emailMessage=emailMessage
                    ))
                    
                    #Execute batch permission update
                    batch.execute()
                    
                    #Sample successful log
                    writer.writerow([name, 'File copied & updated',copy_file['id']])
                except Exception as e:
                    writer.writerow([name, 'Error occured.', e])
예제 #44
0
def handshake():
    scopes = ['https://www.googleapis.com/auth/calendar.events']
    flow = InstalledAppFlow.from_client_secrets_file("client_secret.json",
                                                     scopes=scopes)
    return flow.run_console()
예제 #45
0
def create_save_credentials():
    scopes = ['https://www.googleapis.com/auth/calendar']
    flow = InstalledAppFlow.from_client_secrets_file(JSON_CLIENT_SECRET,
                                                     scopes=scopes)
    credentials = flow.run_console()
    pickle.dump(credentials, open(TOKEN, "wb"))
예제 #46
0
def main():
    # os.remove('token.json')
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # 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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    files = listdir('Scripts')

    service = build('drive', 'v3', credentials=creds)
    page_token = None
    while True:
        root_folder_name = input('Please type the name of the root folder carefully (case insensitive): ')
        query = "name = '" + root_folder_name + "' and mimeType='application/vnd.google-apps.folder' and trashed=False"
        root_folder = search(query, service)
        if root_folder:
            print('Are you sure you want to set the root folder as ' + root_folder[0]['name'] + '? <y/n>')
            if m.getch().decode('ASCII') == 'y':
                root = "'" + root_folder[0]['id'] + "'"
                break
        else:
            print('Invalid name')
            

    # Set up emails
    email_list = dict()
    with open('mail.txt') as file:
        data = file.readlines()
        for line in data:
            line = line.rstrip()
            name = line.split(sep=',')[1]
            email = line.split(sep=',')[4]
            email_list[name] = email
            
    batch = service.new_batch_http_request(callback=callback)
    # Call the Drive v3 API
    for f in files:
        full_name = f.split(sep='-')[1].strip().split(sep='.')[0]
        print(full_name)
        query = "name = '" + full_name + "' and mimeType='application/vnd.google-apps.folder'" + " and " + root + " in parents and trashed=False"
        folders = search(query, service)
        
        if len(folders) == 1:
            print("Found perfect match for " + f + ": " + folders[0]['name'])

            # Search for possible file duplicates within folder and delete
            query = "name = '" + f + "' and mimeType='application/pdf' and '" + folders[0]['id'] + "' in parents and trashed=False"
            duplicates = search(query, service)
            if len(duplicates) > 0:
                print('Duplicates found in folder with same file name. Proceeding to delete...')
                for duplicate in duplicates:
                    service.files().delete(fileId=duplicate['id']).execute()

            upload(f, folders[0]['id'], service)
        
        elif len(folders) == 0:
            print('No match for ' + f + '. Attempting to create new folder and upload.')
            print('Do you want the folder name to be ' + full_name + '? <y/n>')
            if m.getch().decode('ASCII') != 'y':
                # Check whether this folder already exists
                while True:
                    print('Please enter the destination folder name for ' + f)
                    new_folder_name = input()
                    query = "name = '" + new_folder_name + "' and mimeType='application/vnd.google-apps.folder'" + " and root in parents and trashed=False"
                    possible_duplicate_folders = search(query, service)
                    if len(possible_duplicate_folders) > 0:
                        print('A folder with this name already exists.')
                        continue
                    else:
                        break
            else:
                new_folder = create_new_folder(full_name, service)
                new_folder_id = new_folder['id']
                new_folder_link = new_folder['link']
                print(new_folder_link)
                upload(f, new_folder_id, service)
                try:
                    if check(email_list[full_name]) == False:
                        raise KeyError
                    share(new_folder_id, new_folder_link, full_name, email_list[full_name], batch, service)
                except KeyError:
                    print('Could not find a valid email address for ' + full_name + '. Do you still want to share this folder? <y/n>')
                    if m.getch().decode('ASCII') != 'y':
                        continue
                    while True:
                        print('Enter email address for ' + full_name)
                        man_email = input()
                        if check(man_email):
                            share(new_folder_id, new_folder_link, full_name, man_email, batch, service)
                            break
                        print('Invalid email.')

    batch.execute()
예제 #47
0
def authenticate(client_config, credentials=None, serialize=None, flow="web"):
    """
    The `authenticate` function will authenticate a user with the Google Search
    Console API.

    Args:
        client_config (collections.abc.Mapping or str): Client configuration
            parameters in the Google format specified in the module docstring.
        credentials (collections.abc.Mapping or str): OAuth2 credentials
            parameters in the Google format specified in the module docstring
        serialize (str): Path to where credentials should be serialized.
        flow (str): Authentication environment. Specify "console" for environments (like Google Colab)
            where the standard "web" flow isn't possible.

    Returns:
        `searchconsole.account.Account`: Account object containing web
        properties that can be queried.

    Usage:
        >>> import searchconsole
        >>> account = searchconsole.authenticate(
        ...     client_config='auth/client_secrets.json',
        ...     credentials='auth/credentials.dat'
        ... )
    """

    if not credentials:

        if isinstance(client_config, collections.abc.Mapping):

            auth_flow = InstalledAppFlow.from_client_config(
                client_config=client_config,
                scopes=['https://www.googleapis.com/auth/webmasters.readonly'])

        elif isinstance(client_config, str):

            auth_flow = InstalledAppFlow.from_client_secrets_file(
                client_secrets_file=client_config,
                scopes=['https://www.googleapis.com/auth/webmasters.readonly'])

        else:

            raise ValueError(
                "Client secrets must be a mapping or path to file")

        if flow == "web":
            auth_flow.run_local_server()
        elif flow == "console":
            auth_flow.run_console()
        else:
            raise ValueError(
                "Authentication flow '{}' not supported".format(flow))

        credentials = auth_flow.credentials

    else:

        if isinstance(credentials, str):

            with open(credentials, 'r') as f:
                credentials = json.load(f)

        credentials = Credentials(token=credentials['token'],
                                  refresh_token=credentials['refresh_token'],
                                  id_token=credentials['id_token'],
                                  token_uri=credentials['token_uri'],
                                  client_id=credentials['client_id'],
                                  client_secret=credentials['client_secret'],
                                  scopes=credentials['scopes'])

    service = discovery.build(
        serviceName='webmasters',
        version='v3',
        credentials=credentials,
        cache_discovery=False,
    )

    if serialize:

        if isinstance(serialize, str):

            serialized = {
                'token': credentials.token,
                'refresh_token': credentials.refresh_token,
                'id_token': credentials.id_token,
                'token_uri': credentials.token_uri,
                'client_id': credentials.client_id,
                'client_secret': credentials.client_secret,
                'scopes': credentials.scopes
            }

            with open(serialize, 'w') as f:
                json.dump(serialized, f)

        else:

            raise TypeError('`serialize` must be a path.')

    return Account(service, credentials)
예제 #48
0
def main():

    # If modifying these scopes, delete the file token.pickle.
    SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']

    # load config file
    config = load_config()
    check_interval = config.get('check_interval')

    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    # Google API uses UTC time
    checkTime = datetime.datetime.utcnow()

    # Connect to Google API
    service = build('drive', 'v3', credentials=creds)

    # Trigger a library refresh on startup to catch updates while the
    # program wasn't running
    update_library(config)

    # Loop forever until program is killed
    while True:
        # Update the time used to check for changes
        checkTime = datetime.datetime.utcnow()
        time.sleep(check_interval * 60)

        # Google wants dates in iso8601 format
        checkTimeIso = checkTime.isoformat()

        # Finds audio and video files updated after the last run
        # Reference: https://developers.google.com/drive/api/v3/reference/files/list?apix_params=%7B%22q%22%3A%22mimeType%20contains%20%27video%2F%27%22%2C%22fields%22%3A%22files(id%2C%20name%2C%20modifiedTime)%22%2C%22prettyPrint%22%3Atrue%7D
        results = service.files().list(
            fields="files(name)",
            q=f"(mimeType contains 'video/' or mimeType contains 'audio/') and"
            f" modifiedTime > '{checkTimeIso}'").execute()
        items = results.get('files', [])
        if not items:
            print('No updates found.')
        else:
            # Updates found, trigger library update
            num_files = len(items)
            print(f'Found {num_files} update(s)')
            update_library(config)
예제 #49
0
def get_events():
    """Shows basic usage of the Google Calendar API.
    Prints the start and name of the next 10 events on the user's calendar.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)

    # hack to get events from today but not last night. Day ends at 4am.
    now = datetime.datetime.now()
    now -= datetime.timedelta(hours=4)
    now_str = now.replace(
        hour=8, minute=0, second=0,
        microsecond=0).isoformat() + 'Z'  # 'Z' indicates UTC time
    print('Getting data from google calendar...')
    # Call the Calendar API
    events_result = service.events().list(calendarId='primary',
                                          timeMin=now_str,
                                          maxResults=10,
                                          singleEvents=True,
                                          orderBy='startTime').execute()
    events = events_result.get('items', [])
    # return events
    results = []
    for event in events:
        start = event['start'].get('dateTime', None)
        start_dt = None
        fmt = ''
        if start is None:
            # all day
            start_date = event['start'].get('date')
            start_dt = datetime.datetime.strptime(start_date, r'%Y-%m-%d')
        else:
            start_dt = parse(start)
            fmt = start_dt.strftime(
                "%H:%M") if start_dt.minute else start_dt.strftime("%H")

        # results.append((fmt, start_dt.date(), event['summary']))
        if start_dt.date() <= datetime.datetime.now().date():
            results.append((fmt, event['summary']))

    if len(results) == 0:
        return [('', "Nothing on the agenda")]
    else:
        return results
예제 #50
0
def main():
    """Shows basic usage of the Sheets API.
    Prints values from a sample spreadsheet.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('sheets', 'v4', credentials=creds)

    # Call the Sheets API
    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                                range=SAMPLE_RANGE_NAME).execute()
    values = result.get('values', [])

    if not values:
        print('No data found.')
    else:
        cols = [
            'Winner', 'Player1', 'Player2', 'Player3', 'Player4', 'Player5',
            'Player6', 'Winner2'
        ]
        df = pd.DataFrame(values, columns=cols)
        print('Dataframe:\n%s' % df.head())
        df.to_csv('working.csv')
        # mu -> sigma, beta, tau ; recommendation by trueskill.org
        rec_sig_beta_tau = lambda mew: tuple(
            [float(mew) / 3.0,
             float(mew) / 3.0 / 2.0,
             float(mew) / 3.0])
        mu = 25
        sigma, beta, tau = rec_sig_beta_tau(mu)
        env = trueskill.TrueSkill(mu=mu,
                                  sigma=sigma,
                                  beta=beta,
                                  tau=tau,
                                  draw_probability=.75,
                                  backend='scipy')
        player_to_skill = get_true_skills(df)
        data = [(k, v.mu, v.sigma) for k, v in player_to_skill.items()]
        skills_df = pd.DataFrame(data, columns=['Player', 'mu', 'sigma'])
        skills_df['TrueSkill'] = skills_df['mu'] - 3 * skills_df[
            'sigma']  # Definition of TrueSkill (used for leaderboards): 99% likelihood your skill is > this

        # Pretty up results
        skills_df.sort_values(by=['TrueSkill', 'mu'],
                              ascending=False,
                              inplace=True)
        skills_df.reset_index(inplace=True)
        skills_df.index = skills_df.index + 1
        skills_df.index.name = 'Leaderboard Position'
        skills_df.to_csv('skills.csv',
                         columns=['Player', 'TrueSkill', 'mu', 'sigma'])
예제 #51
0
def main():

    annoyance_limit = 9

    # read list of bad words from file into a list
    with open('badwords.txt') as f:
        bad_words = f.read().splitlines()
    f.close()

    # begin Google API's quickstart code for Python
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('gmail', 'v1', credentials=creds)

    results = service.users().messages().list(userId='me',
                                              labelIds='INBOX').execute()
    messages = results.get('messages', [])
    #end of Google's quickstart code

    num_bad_emails = 0

    for msg in messages:
        bad_aspects = 0
        email = service.users().messages().get(userId='me',
                                               id=msg['id']).execute()
        email_elements = email['payload']['headers']
        for email_element in email_elements:
            if email_element['name'] == 'To':
                if "*****@*****.**" in email_element[
                        'value'] and email_element['value'].count(
                            '@wright.edu') < 2:
                    bad_aspects += 1
            if email_element['name'] == 'From':
                studentEmailRegEx = '[a-zA-Z]*[.][0-9][email protected]'
                if re.search(studentEmailRegEx, email_element['value']):
                    bad_aspects += 1
            if email_element['name'] == 'Subject':
                text = (email_element['value'] + " " +
                        email['snippet']).lower()
                text = text.translate(str.maketrans('', '',
                                                    string.punctuation))
                bad_word_count = 0
                for bad_word in bad_words:
                    if (" " + bad_word + " ") in text:
                        bad_word_count += 1
                if bad_word_count > 2:
                    bad_aspects += 1
        if bad_aspects >= 2:
            num_bad_emails += 1

    print("num bad emails: ", num_bad_emails)

    modifier = round(255.0 / annoyance_limit)
    brightness = round(min(255, num_bad_emails * modifier))
    red = round(min(255, num_bad_emails * modifier))
    if num_bad_emails > annoyance_limit:
        blue = 255
    else:
        blue = round(min(255, (annoyance_limit - num_bad_emails) * modifier))
    print("red: ", red, "  blue: ", blue, "  brightness: ", brightness)
    newConditions = {
        "command": "set",
        "state": "on",
        "light": "glow_ball",
        "rgb_color": [red, 0, blue],
        "brightness": brightness
    }
    params = json.dumps(newConditions).encode('utf8')
    req = urllib.request.Request(lightURL,
                                 data=params,
                                 headers={'content-type': 'application/json'})
    response = urllib.request.urlopen(req)
예제 #52
0
nrow = len(df.index)

#%%
if nrow > 0:
    SCOPES = 'https://www.googleapis.com/auth/gmail.send'
    creds = None
    
    if os.path.exists('/path_to_token/token.pickle'):
        with open('/path_to_token/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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                '/path_to_credentials/credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('/path_to_token/token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    
    service = build('gmail', 'v1', credentials=creds)
    
    message_text = 'www.recreation.gov/camping/campgrounds/232487/availability'
    message = MIMEText(message_text)
    message['to'] = '*****@*****.**'
    message['from'] = '*****@*****.**'
    message['subject'] = 'Campsite available'
    message = {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}

    service.users().messages().send(userId='*****@*****.**', body=message).execute()
예제 #53
0
def main():
    """Shows basic usage of the Google Calendar API.
    Prints the start and name of the next 10 events on the user's calendar.
    """
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)

    # Call the Calendar API
    # creates a event everyday for dinner for the next week

    length = 0

    print(meals)
    # Get all the timings right and use a for loopt to create a event each day
    for i in meals:
        d = datetime.now().date()
        tomorrow = datetime(d.year, d.month, d.day, 17)
        start = (tomorrow + timedelta(days=length)).isoformat()
        end = (tomorrow + timedelta(days=length)).isoformat()
        events = {
            "summary": i,
            "description": 'Dinner',
            "start": {
                "dateTime": start,
                "timeZone": 'Europe/London'
            },
            "end": {
                "dateTime": end,
                "timeZone": 'Europe/London'
            },
            "attendees": [
                {
                    "email": RECIEVER,
                    # Other attendee's data...
                },
            ],
        }

        length += 1

        event_result = service.events().insert(calendarId='primary',
                                               body=events).execute()

        print("created event")
        print(event_result['id'])
        # Sleep so it doesn't overwhelm the API
        time.sleep(10)
예제 #54
0
def get_authenticated_service():
  flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
  credentials = flow.run_console()
  return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)
예제 #55
0
def get_dates(calendar_id, max_number, categories):
    # Credentials for Google Calendar API
    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('token.pickle'):
        with open('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:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)

    # Call the Calendar API
    now = datetime.utcnow().isoformat() + 'Z'  # 'Z' indicates UTC time
    print('Getting the upcoming', max_number, 'events')
    events_result = service.events().list(calendarId=calendar_id,
                                          timeMin=now,
                                          maxResults=max_number,
                                          singleEvents=True,
                                          orderBy='startTime').execute()  # pylint: disable=maybe-no-member
    events = events_result.get('items', [])

    if not events:
        print('No upcoming events found.')
        return

    eventList = []

    for event in events:
        evnt = {}

        # .get() tries to get first argument value from dictionary, second argument is alternative!
        start = event['start'].get('dateTime', event['start'].get('date'))
        start_dttm = datetime.fromisoformat(start)

        end = event['end'].get('dateTime', event['end'].get('date'))
        end_dttm = datetime.fromisoformat(end)

        evnt['start_dttm_iso'] = start
        evnt['start_date'] = start_dttm.date().strftime("%d.%m.%Y")
        evnt['start_day'] = start_dttm.date().strftime("%-d")
        evnt['start_month'] = start_dttm.date().strftime("%b")
        evnt['end_dttm_iso'] = end
        evnt['start_weekday'] = start_dttm.time().strftime("%A")
        if start_dttm.time().strftime("%H:%M") == "00:00" and end_dttm.time(
        ).strftime("%H:%M") == "00:00":
            evnt['start_time'] = "whole day"
            evnt['end_time'] = ""
        else:
            evnt['start_time'] = start_dttm.time().strftime("%H:%M")
            evnt['end_time'] = end_dttm.time().strftime("%H:%M")

        evnt['title'] = event['summary'].replace(": ", ":\n", 1)

        if 'description' in event.keys():
            desc = event['description']
            evnt['description'] = desc.replace("\n\n\n", "\n\n")
            for category in categories:
                if category in desc:
                    evnt['type'] = category
        else:
            evnt['description'] = event['summary']
            evnt['type'] = ""

        if not 'location' in event.keys():
            evnt['location'] = ""
        else:
            loc = event['location']
            evnt['location'] = loc
            if len(loc.split(", ", 1)) > 1:
                evnt['locationName'] = loc.split(", ", 1)[0]
                evnt['locationAddress'] = loc.split(", ", 1)[1]
            else:
                evnt['locationName'] = loc
                evnt['locationAddress'] = ""
            evnt[
                'locationMapsSearch'] = "https://google.com/maps/search/" + evnt[
                    'locationName'].replace(" ", "+")

        eventList.append(evnt)

    return eventList