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'])
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 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
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
def main(client_id, client_secret, scopes): """Retrieve and display the access and refresh token.""" client_config = ClientConfigBuilder( client_type=ClientConfigBuilder.CLIENT_TYPE_WEB, client_id=client_id, client_secret=client_secret) flow = InstalledAppFlow.from_client_config( client_config.Build(), scopes=scopes) # Note that from_client_config will not produce a flow with the # redirect_uris (if any) set in the client_config. This must be set # separately. flow.redirect_uri = _REDIRECT_URI auth_url, _ = flow.authorization_url(prompt='consent') print ('Log into the Google Account you use to access your DFP account' 'and go to the following URL: \n%s\n' % (auth_url)) print 'After approving the token enter the verification code (if specified).' code = raw_input('Code: ').strip() try: flow.fetch_token(code=code) except InvalidGrantError as ex: print 'Authentication has failed: %s' % ex sys.exit(1) print 'Access token: %s' % flow.credentials.token print 'Refresh token: %s' % flow.credentials.refresh_token
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
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'))))
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)
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')))
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']))
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)
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)
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)
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()
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']))
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)
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']))
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'])
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)
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']))
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]))
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)
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']))
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) global service 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', now) #'2019-03-26T09:00:00+09:00' , now # 2019 1/1 is work list events_result = service.events().list(calendarId='primary', timeMin='2019-01-01T00:00:00+09:00', timeMax='2019-01-01T23:59:59+09:00', maxResults=50, 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(event['start'],start, event['summary'] , event['end'] , event['id']) x = event['summary'].split('-') node = x[0].strip().replace(" ", " ") workContent.append(node) for workCount, workEvent in enumerate(sorted(workContent)): #print(workCount , "[",workEvent,"]") sortedWorkContent.append(workEvent) # 2019 1/2 is project list events_result = service.events().list(calendarId='primary', timeMin='2019-01-02T00:00:00+09:00', timeMax='2019-01-02T23:59:59+09:00', maxResults=50, 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(event['start'],start, event['summary'] , event['end'] , event['id']) x = event['summary'].split('-') node = x[0].strip().replace(" ", " ") projectContent.append(node) for projectCount, projectEvent in enumerate(sorted(projectContent)): #print(projectCount , "[",projectEvent,"]") sortedProjectContent.append(projectEvent) #/ This is delete source # current eventId has been deleted. #event = service.events().delete(calendarId='primary', eventId="1pcsgsu56j6vhmft6f70ghvuc8", sendUpdates=None).execute() #/ This is insert source #event = service.events().insert(calendarId='primary', body=eventIns).execute() #print 'Event created: %s'%(event.get('htmlLink')) #/ This is delete source # current eventId has been deleted. #event = service.events().delete(calendarId='primary', eventId="1pcsgsu56j6vhmft6f70ghvuc8", sendUpdates=None).execute() #/ This is insert source #event = service.events().insert(calendarId='primary', body=eventIns).execute() #print 'Event created: %s'%(event.get('htmlLink')) now = datetime.datetime.utcnow() # 'Z' indicates UTC time print("now =", now) print(now.strftime("%d/%m/%Y %H:%M:%S")) print("Current date and time using instance attributes:") print("Current year: %d" % now.year) print("Current month: %d" % now.month) print("Current day: %d" % now.day) print("Current hour: %d" % now.hour) print("Current minute: %d" % now.minute) print("Current second: %d" % now.second) print("Current microsecond: %d" % now.microsecond) loop()
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_n = datetime.datetime.today() now = now_n.isoformat() + 'Z' # 'Z' indicates UTC time end_date_n= now_n + datetime.timedelta(7) end_date = end_date_n.isoformat() + 'Z' print('Getting upcoming events for the next 7 days:') print("\n Y O U R C A L E N D E R") print("DATE TIME EVENT") events_result = service.events().list(calendarId='primary',timeMin=now,timeMax=end_date, singleEvents=True, orderBy='startTime').execute() events = events_result.get('items', []) with open("events.pkl","wb") as cal_events: pickle.dump(events,cal_events) if not events: print('No upcoming events found.') # Load pickle files with open("events.pkl","rb") as cal_events: new_data = pickle.load(cal_events) for event in new_data: start = event['start'].get('dateTime', event['start'].get('date')) start_date = start.split("T") start= datetime.datetime.strptime(start_date[0], '%Y-%m-%d') start = start.strftime("%d %b %Y") time_start= start_date[1].split("+") print(start," ",time_start[0]," ",event['summary']) print("\n C O D E C L I N I C C A L E N D E R ") print("DATE TIME EVENT") events_result = service.events().list(calendarId='*****@*****.**',timeMin=now,timeMax=end_date, singleEvents=True, orderBy='startTime').execute() events = events_result.get('items', []) # Saving events into a pickle file with open("events_clinic.pkl","wb") as cal_clinic_events: pickle.dump(events,cal_clinic_events) if not events: print('No upcoming events found.') # Load pickle files with open("events_clinic.pkl","rb") as cal_clinic_events: new_clinic_data = pickle.load(cal_clinic_events) for event in new_clinic_data: start = event['start'].get('dateTime', event['start'].get('date')) start_date = start.split("T") start= datetime.datetime.strptime(start_date[0], '%Y-%m-%d') start = start.strftime("%d %b %Y") time_start= start_date[1].split("+") print(start," ",time_start[0]," ",event['summary'])
def main(): # Get inputs print("What's the name of the event?") n = input() '''print('what the day of the event') d = input() print("month: ") m = input() print('year : ') y = input() print('attendees : ') a = input() print('Meeting Room : ') r = input() maxattendees = 10''' '''if r == "Midoun meeting room": room = "*****@*****.**" elif r == "Aiguilles Meeting Room": room = "*****@*****.**" elif r == "Barrouta Meeting Room": room = "*****@*****.**" elif r == "Kantaoui Meeting Room": room = "*****@*****.**" elif r == "Gorges Meeting Room": room = "*****@*****.**" elif r == "Ichkeul Meeting Room": room = "*****@*****.**" elif r == "Khemir Meeting Room": room = "*****@*****.**" elif r == "Tamaghza Meeting Room": room = "*****@*****.**" elif r == "Friguia Meeting Room": room = "*****@*****.**" maxattendees = 15 elif r == "Ksour Meeting Room": room = "*****@*****.**" elif r == "Medeina Meeting Room": room = "*****@*****.**" elif r == "Thyna Meeting Room": room = "*****@*****.**"''' l = "FOCUS-1ere-Midoune Meeting Room (10)" """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) events_result = service.events().list(calendarId='primary', maxResults=1, singleEvents=True, orderBy='startTime', q=n).execute() events = events_result.get('items', []) attendemail = [] attendname = [] attendstatus = [] confattend = [] i = 0 k = 0 j = 0 if not events: print('event not found.') for event in events: start = event['start'].get('dateTime', event['start'].get('date')) attendees = event['attendees'] print(attendees) #print(attendees[0]['displayName']) l = len(attendees) while i != l: attendemail.append(attendees[i]['email']) attendstatus.append(attendees[i]['responseStatus']) attendname.append(attendees[i].get('displayName')) i = i + 1 while k != l: if attendname[k] is None: attendname[k] = attendemail[k] k = k + 1 while j != l: if attendees[j]['responseStatus'] == 'accepted': confattend.append(attendemail[j]) j = j + 1 print(attendemail) print(attendname) print(attendstatus) print(confattend)
def get_authenticated_service(): flow = InstalledAppFlow.from_client_secrets_file(CREDENTIALS_FILE, SCOPES) credentials = flow.run_console() return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
def main(): creds = None Word = "DevOps" # token.pickle guarda el acceso del usuario y actualiza los tokens, # es creado automáticamente cuando el flujo de autorización se completa por primera vez. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # Si no hay credenciales válidas disponibles, el usuario deberá loguearse 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) # Guarda las crecenciales para la siguiente tanda with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('gmail', 'v1', credentials=creds) # Llamado a la API de Gmail mensajesJson = service.users().messages().list(userId='me', q=Word).execute() if mensajesJson: ServerName = "sql10.freemysqlhosting.net" Username = "******" Password = "******" DBName = "sql10300498" #Se conceta con la base de datos enviando las credenciales necesarias: Nombre del server, username, password, nombre de la base de datos db = pymysql.connect(ServerName, Username, Password, DBName) cursor = db.cursor() #Obtiene un Json con los mensajes con los mensajes que contienen el word (DevOps en este caso) y sus respectivos IDs mensajes = mensajesJson['messages'] for mensaje in mensajes: #Por cada uno de esos mensajes debe solicitar, con el ID correspondiente, información sobre ese mensaje mensajesJson2 = service.users().messages().get( userId='me', id=mensaje['id']).execute() if mensajesJson2: #Guardo los datos de interés en base a su ubicación en la estructura Json que se devuelve key = str(mensajesJson2['id']) fecha = str( mensajesJson2['payload']['headers'][1]['value'] ) #Dentro del subconjunto 'headers' la fecha se encuentra en la posición 1 subject = str( mensajesJson2['payload']['headers'][3]['value'] ) #Dentro del subconjunto 'headers' el subject se encuentra en la posición 3 de = str( mensajesJson2['payload']['headers'][4]['value'] ) #Dentro del subconjunto 'headers' el emisor se encuentra en la posición 4 #Se usa 'INSERT IGNORE' para ignorar aquellas solicitudes que generen un error (como insertar registros con una PK ya exitente) #Esto es especialemente útil si se va a necesitar hacer grandes cantidades de INSERTs sql = "INSERT IGNORE INTO mails_DevOps(id, DE, SUBJECT, FECHA) VALUES ('" + key + "','" + de + "','" + subject + "','" + fecha + "')" try: cursor.execute(sql) db.commit() except: db.rollback() print("Hubo un error con el registro:" + str(key)) print('La base de datos ha sido actualizada') else: print('No se encontraron mensajes.')
def main(): """Shows basic usage of the Sheets API. Prints values from a sample spreadsheet. """ sql_create_regions_table = """ CREATE TABLE IF NOT EXISTS regions ( id INTEGER PRIMARY KEY, name TEXT UNIQUE NOT NULL ) """ sql_create_organizations_table = """ CREATE TABLE IF NOT EXISTS organizations ( id INTEGER PRIMARY KEY, name TEXT UNIQUE NOT NULL, url TEXT NOT NULL, region_id INTEGER NOT NULL, logo TEXT, FOREIGN KEY (region_id) REFERENCES regions (id) ) """ 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=SPREADSHEET_ID, range=RANGE_NAME).execute() values = result.get('values', []) database = "jobs_for_hope.db" if not values: print('No data found.') else: conn = create_connection(database) if conn is None: print("Error! cannot create the database connection.") create_table(conn, sql_create_regions_table) create_table(conn, sql_create_organizations_table) # regions table regions = {} for row in values: # Print columns A and E, which correspond to indices 0 and 3. if row[2] is not None: service_regions = row[2].replace('\n', ',').split(',') for region in service_regions: if len(region) > 0: regions[region.lstrip()] = 1 for key, value in regions.items(): #print('%s %d' % (key, value)) create_region(conn, [key]) select_all_regions(conn) # organization table for row in values: if len(row) == 3: # get region_id from region name region_name = row[2].replace('\n', ',').split(',')[0] region_id = select_region_id_by_name(conn, [region_name]) create_organization(conn, [row[0], row[1], region_id[0], '']) if len(row) == 4: # get region_id from region name # TODO take the first region listed for now. This needs to be # reworked. region_name = row[2].replace('\n', ',').split(',')[0] region_id = select_region_id_by_name(conn, [region_name]) create_organization(conn, [row[0], row[1], region_id[0], row[3]]) select_all_organizations(conn) conn.commit() conn.close()
def authenticate(client_config, credentials=None, serialize=None): """ 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. 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): flow = InstalledAppFlow.from_client_config( client_config=client_config, scopes=['https://www.googleapis.com/auth/webmasters.readonly']) elif isinstance(client_config, str): 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") flow.run_local_server() credentials = 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)
def main(): """Utilizes the Gmail API. Lists the users Gmail Messages. """ 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:20d' ).execute() messages = results.get('messages', []) if not messages: print("No messages found.") else: for message in messages: temp_dict = {} msg = service.users().messages().get(userId='me', id=message['id']).execute() payload = msg['payload'] header = payload['headers'] print(payload['mimeType']) 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 # print("Date: " + temp_dict['Date'] + " - From:" + temp_dict['Sender'] + " - Subject: " + temp_dict['Subject']) print("Date: " + temp_dict['Date']) print("From: " + temp_dict['Sender']) print("Subject: " + temp_dict['Subject']) print("Body: " + bodyclean) print() print()
def makeCalendarEntries(entriesRaw, action): creds = None eventsCreated = [] 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) if (action == ACTION_MAKE): for entryRaw in entriesRaw: startVacationSunday = pd.to_datetime( startVacation) + pd.DateOffset(days=-1) startVacationSunday = str(startVacationSunday.year) + "-" + str( startVacationSunday.month) + "-" + str(startVacationSunday.day) endVacationMonday = pd.to_datetime(endVacation) + pd.DateOffset( days=1) endVacationMonday = str(endVacationMonday.year) + "-" + str( endVacationMonday.month) + "-" + str(endVacationMonday.day) event1 = service.events().insert( calendarId='primary', body=generateEventJson(entryRaw, startSemesterDay, startVacationSunday, 1)).execute() eventsCreated.append(event1['id']) event2 = service.events().insert(calendarId='primary', body=generateEventJson( entryRaw, endVacationMonday, endSemester, 1)).execute() eventsCreated.append(event2['id']) print('Event1 created: ' + event1.get('htmlLink')) print('Event2 created: ' + event2.get('htmlLink')) with open("createdEvents.txt", "w") as ids: ids.truncate() for id in eventsCreated: ids.write(id + "\n") ids.close() elif (action == ACTION_DELETE): with open("createdEvents.txt", "r") as ids: eventIdList = ids.readlines() eventIdList = [x.strip() for x in eventIdList] for id in eventIdList: page_token = None while True: events = service.events().instances( calendarId='primary', eventId=id, pageToken=page_token).execute() for event in events['items']: print("Deleting eventId " + event['id'] + " with title: " + event['summary']) service.events().delete(calendarId='primary', eventId=event['id']).execute() page_token = events.get('nextPageToken') if not page_token: break
def run(args): # load config conf = util.load_conf(args.config) # configure variables global stagedir, tempdir tempdir = Path(conf["temp_dir"]) stagedir = Path(conf["stage_dir"]) PICKLE_FILE = conf["youtube_pickle_path"] CLIENT_SECRET_FILE = conf["youtube_client_path"] API_NAME = 'youtube' API_VERSION = 'v3' SCOPES = [ # Only force-ssl is required, but both makes it explicit. "https://www.googleapis.com/auth/youtube.upload", # Videos.insert "https://www.googleapis.com/auth/youtube.force-ssl" # Captions.insert ] # handle logout if args.id == "logout": try: os_remove(PICKLE_FILE) cprint("#dLogged out of Google API session#r") except: util.exit_prog( 11, "Failed to remove credentials for YouTube account.") return # load stages, but dont upload # Handle id/all stagedata = None stagedatas = None if args.id == "all": cprint("#dLoading stages...", end=" ") # create a list of all the hashes and sort by date streamed, upload chronologically stagedatas = StageData.load_all_stages(stagedir) stagedatas.sort(key=sort_stagedata) else: cprint("#dLoading stage...", end=" ") # check if stage exists, and prep it for upload stagedata = StageData.load_from_id(stagedir, args.id) cprint(f"About to upload stage {stagedata.id}.#r") # authenticate youtube service if not os_exists(CLIENT_SECRET_FILE): util.exit_prog(19, "Missing YouTube Client ID/Secret file.") cprint("Authenticating with Google...", end=" ") service = None credentials = None if os_exists(PICKLE_FILE): with open(PICKLE_FILE, "rb") as f: credentials = pickle.load(f) if not credentials or credentials.expired: try: if credentials and credentials.expired and credentials.refresh_token: credentials.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( CLIENT_SECRET_FILE, SCOPES) credentials = flow.run_console() except RefreshError: flow = InstalledAppFlow.from_client_secrets_file( CLIENT_SECRET_FILE, SCOPES) credentials = flow.run_console() with open(PICKLE_FILE, "wb") as f: pickle.dump(credentials, f) try: service = build(API_NAME, API_VERSION, credentials=credentials) except Exception as err: util.exit_prog(50, f"Failed to connect to YouTube API, \"{err}\"") cprint("Authenticated.", end=" ") # Handle id/all if args.id == "all": # begin to upload cprint(f"About to upload {len(stagedatas)} stages.#r") for stage in stagedatas: video_id = upload_video(conf, service, stage) if video_id is not None: chat_success = True if conf["chat_upload"]: chat_success = upload_captions(conf, service, stage, video_id) if conf["stage_upload_delete"] and chat_success: try: os_remove(str(stagedir / f"{stage.id}.stage")) except: util.exit_prog( 90, f"Failed to remove stage `{stage.id}` after upload." ) print() else: # upload stage cprint(f"About to upload stage {stagedata.id}.#r") video_id = upload_video(conf, service, stagedata) if video_id is not None: chat_success = True if conf["chat_upload"]: chat_success = upload_captions(conf, service, stagedata, video_id) if conf["stage_upload_delete"] and chat_success: try: os_remove(str(stagedir / f"{stagedata.id}.stage")) except: util.exit_prog( 90, f"Failed to remove stage `{stagedata.id}` after upload." )
def check1on1( ): #カレンダー上で1on1があるペアの中で、検証対象であるペアのリストを返す 。例外のリストprintされる。#期間のみ指定可能 """Shows basic usage of the Google Calendar API. Prints the start and name of the next 10 events on the user's calendar. """ """引数はどちらも、isoformatである必要がある""" if request.method == "GET": return """ <p>いつ以降の1on1を把握したいですか?</p> <p>記入例)2019-11-01 10:00</p> <form action="/" method="POST"> <input name="checkbefore" value = "2019-11-01 10:00"></input> <p>いつまでの1on1を把握したいですか?</p> <p>記入例)2019-11-01 19:00</p> <input name="checkafter" value = "2019-11-01 19:00"></input> <input type="submit" value="check"> </form> """ else: try: check_timeMin = tra_Z_JST_isoformat(request.form["checkbefore"]) check_timeMax = tra_Z_JST_isoformat(request.form["checkafter"]) 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 for ids in mentor_id_list: #検証シートの「新検証ペア」に記載されている、メンターのアドレスについて繰り返し処理 try: events_result = service.events().list( calendarId=ids, timeMin=check_timeMin, singleEvents=True, timeMax=check_timeMax, orderBy='startTime').execute() except: continue events = events_result.get('items', []) if not events: print(id_name_dic[ids], '指定された期間に予定はありません') for event in events: pair = [] if "summary" in event.keys() and "attendees" in event.keys( ): #attendeesがいなくなる場合は?attendeesがいなくても1on1をする場合があるか? if ("振り返り" in event["summary"] ) or ("目標設定" in event["summary"]) or ( "評価面談" in event["summary"] ) or ("1on1" in event["summary"]) or ( "パフォーマンスレビュー" in event["summary"] ) or ("1on1" in event["summary"]) or ( "1on1" in event["summary"]) or ( "1on1" in event["summary"]) or ( "1 on 1" in event["summary"]) or ( "1 on1" in event["summary"]) or ( "1on 1" in event["summary"]): start = event['start'].get( 'dateTime', event['start'].get('date')) for attendee in event[ "attendees"]: #1on1とタイトルにあり、attendeeがいるイベントについて、各attendeeについて繰り返し処理 if attendee["email"] in id_name_dic.keys( ): #「東京本社 Daisy」とかを省くために、メール一覧に名前があるかを用いて制約を課す pair.append(attendee["email"] ) #1on1があるペアのアドレスのリストを作成 if (pair in test_pair_id_list) or ( pair in inverse_test_pair_id_list): if (pair not in pair_id_list) and ( pair.reverse() not in pair_id_list): pair_id_list.append(pair) #print(start, event["summary"]) #print(pair) #print("-------------------") elif len(pair) > 2: #print("例外",id_name_dic[ids],start,event["summary"]) if pair not in exception_pair_id_list: exception_pair_id_list.append([ id_name_dic[ids], start, event["summary"] ]) #if exception_pair_id_list: # print("1on1の疑いあり:",exception_pair_id_list) # print("---------------------------------------") pair_name_list = [] for pair_ids in pair_id_list: if '#N/A' not in pair_ids: pair_name_list.append( [id_name_dic[pair_ids[0]], id_name_dic[pair_ids[1]]]) return """1on1がある人はこの人達です!{} <p>1on1の疑いがある人たちは以下の人達です</p>{}""".format(pair_name_list, exception_pair_id_list) except ValueError: return """値が不正でした!もう一度お願いします!
acc_dir = args.path gaddr = args.groupaddr credentials = glob.glob(args.credentials) creds = None if os.path.exists('credentials/token.pickle'): with open('credentials/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[0], scopes=[ 'https://www.googleapis.com/auth/admin.directory.group', 'https://www.googleapis.com/auth/admin.directory.group.member' ]) # creds = flow.run_local_server(port=0) creds = flow.run_console() # Save the credentials for the next run with open('credentials/token.pickle', 'wb') as token: pickle.dump(creds, token) group = googleapiclient.discovery.build("admin", "directory_v1", credentials=creds) print(group.members()) batch = group.new_batch_http_request()
def authenticate_user(host, debug=False): """ Begins authentication flow, getting Google auth, opening web browser if needed, getting username and state from ARENA server. host: The hostname of the ARENA webserver. debug: True to skip SSL verify for localhost tests. Returns: Username from arena-account, or None. """ global debug_toggle global _id_token debug_toggle = debug print("Signing in to the ARENA...") local_token = _local_token_check() if local_token: return local_token["username"] creds = None browser = None try: browser = webbrowser.get() except (webbrowser.Error) as err: print("Console-only login. {0}".format(err)) # store the user's access and refresh tokens if os.path.exists(_user_gauth_path): print("Using cached Google authentication.") with open(_user_gauth_path, 'rb') as token: creds = pickle.load(token) session = AuthorizedSession(creds) # if no credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: print("Requesting refreshed Google authentication.") creds.refresh(Request()) session = AuthorizedSession(creds) else: print("Requesting new Google authentication.") gauth_json = _get_gauthid(host) flow = InstalledAppFlow.from_client_config(json.loads(gauth_json), _scopes) if browser: # TODO: select best client port to avoid likely conflicts creds = flow.run_local_server(port=8989) else: creds = flow.run_console() session = flow.authorized_session() with open(_user_gauth_path, 'wb') as token: # save the credentials for the next run pickle.dump(creds, token) os.chmod(_user_gauth_path, 0o600) # set user-only perms. username = None _id_token = creds.id_token user_info = _get_user_state(host, _id_token) _user_info = json.loads(user_info) if 'authenticated' in _user_info and 'username' in _user_info: username = _user_info["username"] profile_info = session.get( 'https://www.googleapis.com/userinfo/v2/me').json() if profile_info: print(f'Authenticated Google account: {profile_info["email"]}') return username
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.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('drive', 'v3', credentials=creds) listOfFiles = [] a=txt.get() b=a.split('/') c=b[5].split('?') # print(c[0]) tttt=c[0] # query = f"'1XItNg77h4gW_YJTcjTIfmC4KTEx-RXYR' in parents" query = "'{}' in parents".format(tttt) page_token = None while True: response = service.files().list( q=query, fields="nextPageToken, files(id, name)", pageToken=page_token, includeItemsFromAllDrives=True, supportsAllDrives=True ).execute() for file in response.get('files', []): listOfFiles.append(file) page_token = response.get('nextPageToken', None) if page_token is None: break #-------------------------------------------------------- nam=[] main.dlink=[] for x in listOfFiles: nam.append("https://drive.google.com/"+"uc?id="+x['id']+"&export=download") main.dlink.append([x['name'],"https://drive.google.com/"+"uc?id="+x['id']+"&export=download"]) ml= int(max(len(x[0]) for x in main.dlink)) # headers = ["Available Direct Download Links From Shared Folder :" ] # row_format ="{:<8}" # left or right align, with an arbitrary '8' column width listbox.insert(0,"File Name :"+" "*67+"Direct links :") for items in main.dlink: listbox.insert(END, items[0]+" "*(ml-len(items[0]))+" #"+items[1])
from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import datefinder from datetime import datetime, timedelta # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/calendar'] timezone = 'Asia/Kolkata' 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( 'client_secret.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) else: flow = InstalledAppFlow.from_client_secrets_file('client_secret.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)
from google.auth.transport.requests import Request from google_auth_oauthlib.flow import InstalledAppFlow import os.path import pickle credentials = None if os.path.exists("token.pickle"): with open("token.pickle", "rb") as token: credentials = pickle.load(token) if not credentials or not credentials.valid: if credentials and credentials.expired and credentials.refresh_token: credentials.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( "credentials.json", ["https://www.googleapis.com/auth/classroom.courses.readonly"], ) credentials = flow.run_local_server(port=5000) with open("token.pickle", "wb") as token: pickle.dump(credentials, token)
analysis_tests['test_ids'].append(14) analysis_tests['experiment_cells'].append('Resultados!D208') analysis_tests['global_cells'].append('Resultados!D211') analysis_tests['date_cells'].append('Resultados!O208') ''' 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', scope) creds = flow.run_local_server() with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('sheets', 'v4', credentials=creds) sheet = service.spreadsheets() spreadsheed_id = '19hheWj9MSthuXFvL7hTtiJY4MzZo3MrD4MUo-a9g6kw' for i in range(len(analysis_tests['test_ids'])): ind = i test_id = analysis_tests['test_ids'][i] query_analysis = open( '{0}/test_offer_analysis.sql'.format(sql_dir), 'r').read() query_analysis = query_analysis.format(test_id) analysis = run_query(query_analysis, 'bi', user, pwd, host)
def main(): """Shows basic usage of the Gmail API. Lists the user's Gmail labels. """ creds = None # Remove/comment-out these lines to actually process this script print("This work is done, unless it's been a while") return print("Setting things up...") # 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) # example_filter_id = "" # put in filter ID to test these lines # example_from_address = "" # put an example e-mail address in for a filter # example_label_id = "Label_1" # put a different label id hook here # # results = service.users().settings().filters().get(userId='me', id=example_filter_id).execute() # filter_to_replace = {'id': example_filter_id, 'criteria': {'from': example_from_address}, 'action': {'addLabelIds': [example_label_id], 'removeLabelIds': None}} # filter_replaced = {'criteria': {'from': example_from_address}, 'action': {'addLabelIds': [example_label_id], 'removeLabelIds': None}} # # results = service.users().settings().filters().delete(userId='me', id=example_filter_id).execute() # # results = service.users().settings().filters().create(userId='me', body=filter_replaced).execute() print("Getting list of GMail filters...") filters = {} filters_tofix = [] filters_previously_fixed = [] active_filters_base_filename = 'filters-20210227-active' active_filters_filename = active_filters_base_filename + '.json' processed_active_filters_filename = active_filters_base_filename + '-processedForRemoveFromInbox.json' with open(active_filters_filename, 'r') as file_object: filters = json.loads(file_object.read()) # results = service.users().settings().filters().list(userId='me').execute() # filters = results['filter'] print("Total active filters: " + str(len(filters))) with open(processed_active_filters_filename, 'r') as file_object: filters_previously_fixed = json.loads(file_object.read()) if not filters: print('Exiting: no active filters to process.') else: print("Finding filters with 'removeLabelIds'...") for f in filters: if f not in filters_previously_fixed and 'removeLabelIds' in f['action'] and 'INBOX' in f['action']['removeLabelIds']: filters_tofix.append(f) print('Filters found to be fixed: ' + str(len(filters_tofix))) first_ten_filters_tofix = filters_tofix[:10] print(f"Fixing ({str(len(first_ten_filters_tofix))}) filters...") filters_fixed = filters_previously_fixed count_filters_fixed = 0 for f in first_ten_filters_tofix: count_filters_fixed += 1 print(f"...{count_filters_fixed}") filters_fixed.append(f) replace_removeLabelIds_filter(service, f) with open(processed_active_filters_filename, "w") as processed_filters_file: processed_filters_file.write(json.dumps(filters_fixed))
def main(): print( """Welcome to the activism email bot! This bot sends emails to 119 elected officials accross the U.S. calling for action from our elected officials. (template from nomoreracistcops.github.io) Credits for this app to go https://github.com/alandgton/activism-mail-bot.\n""" ) print( """When you press enter, a browser window will launch, asking you to give this app permission to send emails from your gmail account. (At the time of this writing, we have not gotten our app verified yet as it takes a couple days to do so and so you will need to click on the Advanced button to bypass it on the webpage)\n""") print( """We promise we are not doing anything malicious with your email creds and we are using them only for the purpose of sending emails to elected officials. You can check the source code in link above to check if you would like.\n""") input("Press Enter to continue to begin!") 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( resource_path('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) print("\nNow that we've finished authenticating lets get started:\n") src_name = input("Type your name (first, last) and press enter: ") src_email = input("Type your email and press enter:") print("\nWhat would you like the subject (title) of your email to be?") subject = input( "Type here and press enter (a random one will be generated if blank): " ) recv = recipients.gen_recipients() while recv: recipient = recv.pop() dst_name = recipient[0] location = recipient[1] dst_email = recipient[2] subject = subject if subject else messages.gen_subject() body = messages.gen_body(src_name, dst_name, location) message = create_message(src_email, dst_email, subject, body) send_message(service, "me", message) print_email(dst_email, subject, body) # print if we get through without time.sleep(0.1)
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(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) # # 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[1])) # The A1 notation of a range to search for a logical table of data. # Values will be appended after the last row of the table. range_ = 'Darkness!A:E' # TODO: Update placeholder value. # How the input data should be interpreted. value_input_option = 'USER_ENTERED' # TODO: Update placeholder value. # How the input data should be inserted. insert_data_option = 'INSERT_ROWS' # TODO: Update placeholder value. value_range_body = { 'values' : [ ['Testing','This Should be The Second','3','Fourth','Fifth'], ['Testing2','watching it grow'] ] } request = service.spreadsheets().values().append(spreadsheetId=spreadsheet_id, range=range_, valueInputOption=value_input_option, insertDataOption=insert_data_option, body=value_range_body) response = request.execute() # TODO: Change code below to process the `response` dict: pprint(response)
def main(): # 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', []) # Getting the credentials for G.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() # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('calendar', 'v3', credentials=creds) # Get inputs print("What's the name of the event?") n = input() l = "FOCUS-1ere-Midoune Meeting Room (10)" """Shows basic usage of the Google Calendar API. Prints the start and name of the next 10 events on the user's calendar. """ events_result = service.events().list(calendarId='primary', maxResults=1, singleEvents=True, orderBy='startTime', q=n).execute() events = events_result.get('items', []) if not events: print('event not found.') for event in events: start = event['start'].get('dateTime', event['start'].get('date')) print(start, event['summary']) eventid = event['id'] listeofattendees = event['attendees'] #print(event['id']) #print(eventid) print( 'what do you want to update? Summery - Start Date/Time - End Date/Time - Location - Attendees - Meeting Room?' ) u = input() if u == 'Summery': print('what\'s the new summery of the event') ns = input() event['summary'] = ns updated_event = service.events().update(calendarId='primary', eventId=eventid, body=event).execute() elif u == 'Location': print('what\'s the new location of the event') r = input() maxattendees = 10 if r == "Midoun meeting room": room = "*****@*****.**" elif r == "Aiguilles Meeting Room": room = "*****@*****.**" elif r == "Barrouta Meeting Room": room = "*****@*****.**" elif r == "Kantaoui Meeting Room": room = "*****@*****.**" elif r == "Gorges Meeting Room": room = "*****@*****.**" elif r == "Ichkeul Meeting Room": room = "*****@*****.**" elif r == "Khemir Meeting Room": room = "*****@*****.**" elif r == "Tamaghza Meeting Room": room = "*****@*****.**" elif r == "Friguia Meeting Room": room = "*****@*****.**" maxattendees = 15 elif r == "Ksour Meeting Room": room = "*****@*****.**" elif r == "Medeina Meeting Room": room = "*****@*****.**" elif r == "Thyna Meeting Room": room = "*****@*****.**" listofroomsadress = [ '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**' ] listofroomsnames = [ 'Midoun meeting room', 'Aiguilles Meeting Room', 'Barrouta Meeting Room', 'Kantaoui Meeting Room', 'Gorges Meeting Room', 'Ichkeul Meeting Room', 'Khemir Meeting Room', 'Tamaghza Meeting Room', 'Friguia Meeting Room', 'Ksour Meeting Room', 'Medeina Meeting Room', 'Thyna Meeting Room' ] o = 0 p = 0 t = 0 y = 0 attendemail = [] # meetingroom = [] attendname = [] finallist = [] #mr = {'email': room} # meetingroom.append(mr) # event['attendees'] = meetingroom attend = event['attendees'] l = len(attend) while o != l: attendemail.append(attend[o]['email']) attendname.append(attend[0].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() #updated_event = service.events().insert(calendarId='primary', eventId=eventid, body=event).execute() # updating the attendees elif u == 'Attendees': # Getting the all ready invited attendees invitedattendees = event['attendees'] invitedattendemail = [] invitedattendname = [] finallist = [] 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'] == 'Friguia Meeting Room': maxattendees = 15 print('how many attendees would like to add ?') at = int(input()) na = maxattendees - at if na <= 0: print('you can\'t add attendees') elif na < at: print('you can only add ', na, ' attendees') 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 = input() # 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: print('contact not found try again please') else: print('no attendees added') # other attendees to add less then max number of attendees while i != na: a = input() 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] # print(attendees) l = len(attendees) # print(l) # 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 l2 = len(att) print(att) # print(l2) w = 0 attendemail = [] while w != len(attendees): print(attendees[w]) attendemail.append(attendees[w]) w = w + 1 # attendname.append(attendees[0].get('displayName')) attendee = [] print(attendemail) for s in range(len(invitedattendemail)): email = {'email': invitedattendemail[s]} attendee.append(email) print(attendee) for r in range(len(attendemail)): email = {'email': attendemail[r]} attendee.append(email) print(attendee) event['attendees'] = attendee updated_event = service.events().update(calendarId='primary', eventId=eventid, body=event).execute() elif u == 'Start Date/Time': start = event['start'].get('dateTime', event['start'].get('date')) print('Your event starts at ', start) print('what\'s the new start date of the event? yyyy-mm-ddT00:00:00') nsd = input() event['start'] = nsd updated_event = service.events().update(calendarId='primary', eventId=eventid, body=event).execute() elif u == 'End': end = event['end'].get('dateTime', event['start'].get('date')) print('Your event ends at ', end) print('what\'s the new end date of the event? yyyy-mm-ddT00:00:00') ned = input() nedt = ned.get('dateTime') event['end'] = nedt + '+01:00' updated_event = service.events().update(calendarId='primary', eventId=eventid, body=event).execute()
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 page_token = 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) # Work calendarId workCalendar = "*****@*****.**" # Call the Calendar API weekAgo = datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time weekAgo_object = datetime.strptime(weekAgo, "%Y-%m-%dT%H:%M:%S.%fZ") weekAgo_object = weekAgo_object - timedelta(days=14) weekAgo = datetime.strftime(weekAgo_object, "%Y-%m-%dT%H:%M:%S.%fZ") now = datetime.utcnow().isoformat() + 'Z' print('Getting the upcoming 10 events') events_result = service.events().list(calendarId=workCalendar, timeMin=weekAgo, timeMax=now, singleEvents=True, orderBy='startTime').execute() events = events_result.get('items', []) wb = Workbook("invoice " + datetime.strftime(weekAgo_object, "%b %d %Y") + " - " + datetime.strftime(datetime.now(), "%b %d %Y") + ".xlsx") sheet1 = wb.add_worksheet() sheet1.set_column(1, 1, 15) sheet1.write(0, 0, "Client") sheet1.write(0, 1, "Start Date") sheet1.write(0, 2, "End Date") sheet1.write(0, 3, "No. Hours") sheet1.write(0, 4, "Rate") sheet1.write(0, 5, "Class Type") sheet1.write(0, 6, "Total") row = 1 total = 0 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']) if "COLES" in event['summary']: continue else: writeToInvoice(event, wb, sheet1, row) row = row + 1 calculateTotalRevenue(sheet1, row) wb.close()
async def generate_credentials(gdrive): """ - Only generate once for long run - """ if helper.get_credentials(str(gdrive.sender_id)) is not None: await gdrive.edit("`You already authorized token...`") await asyncio.sleep(1.5) await gdrive.delete() return False """ - Generate credentials - """ if G_DRIVE_DATA is not None: try: configs = json.loads(G_DRIVE_DATA) except json.JSONDecodeError: await gdrive.edit( "`[AUTHENTICATE - ERROR]`\n\n" "`Status` : **BAD**\n" "`Reason` : **G_DRIVE_DATA** entity is not valid!") return False else: """ - Only for old user - """ if G_DRIVE_CLIENT_ID is None and G_DRIVE_CLIENT_SECRET is None: await gdrive.edit( "`[AUTHENTICATE - ERROR]`\n\n" "`Status` : **BAD**\n" "`Reason` : please get your **G_DRIVE_DATA** " "[here](https://telegra.ph/How-To-Setup-Google-Drive-04-03)") return False configs = { "installed": { "client_id": G_DRIVE_CLIENT_ID, "client_secret": G_DRIVE_CLIENT_SECRET, "auth_uri": GOOGLE_AUTH_URI, "token_uri": GOOGLE_TOKEN_URI, } } await gdrive.edit("`Creating credentials...`") flow = InstalledAppFlow.from_client_config(configs, SCOPES, redirect_uri=REDIRECT_URI) auth_url, _ = flow.authorization_url(access_type="offline", prompt="consent") msg = await gdrive.respond( "`Go to your BOTLOG group to authenticate token...`") async with gdrive.client.conversation(BOTLOG_CHATID) as conv: url_msg = await conv.send_message( "Please go to this URL:\n" f"{auth_url}\nauthorize then reply the code") r = conv.wait_event( events.NewMessage(outgoing=True, chats=BOTLOG_CHATID)) r = await r code = r.message.message.strip() flow.fetch_token(code=code) creds = flow.credentials await asyncio.sleep(3.5) await gdrive.client.delete_messages(gdrive.chat_id, msg.id) await gdrive.client.delete_messages(BOTLOG_CHATID, [url_msg.id, r.id]) """ - Unpack credential objects into strings - """ creds = base64.b64encode(pickle.dumps(creds)).decode() await gdrive.edit("`Credentials created...`") helper.save_credentials(str(gdrive.sender_id), creds) await gdrive.delete() return
import webbrowser import datetime import wikipedia from googleapiclient import discovery from googleapiclient.discovery import build from googleapiclient import errors from google.auth.transport.requests import Request import datefinder from google_auth_oauthlib.flow import InstalledAppFlow from datetime import datetime, timedelta import os from google.oauth2 import service_account from googleapiclient.discovery import build import pickle scopes=['https://www.googleapis.com/auth/calendar.events'] flow = InstalledAppFlow.from_client_secrets_file("credentials.json", scopes=scopes) try: credentials = pickle.load(open("token.pkl", "rb")) except Exception : # speak('please follow this link to allow jarvis to vreate evnts') print('please follow this link to allow jarvis to vreate evnts\n') # speak('Copy and paste the token to autorize the app') print('Copy and paste the token to autorize the app\n') credentials = flow.run_console() pickle.dump(credentials, open("token.pkl", "wb")) servicecal = build("calendar", "v3", credentials=credentials) #opening google classrom
def main(): api_service_name = "youtube" api_version = "v3" client_secrets_file = "client_secret.json" if os.path.isfile("credentials.json"): with open("credentials.json", 'r') as f: credentials_data = json.load(f) credentials = Credentials(credentials_data['token']) else: flow = InstalledAppFlow.from_client_secrets_file( client_secrets_file, scopes) credentials = flow.run_console() credentials_data = { 'token': credentials.token, 'refresh_token': credentials.refresh_token, 'token_uri': credentials.token_uri, 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, 'scopes': credentials.scopes } print(credentials_data) with open("credentials.json", 'w') as outfile: json.dump(credentials_data, outfile) youtube = build(api_service_name, api_version, credentials=credentials) subscriptionsRequest = youtube.subscriptions().list( part="snippet,contentDetails", maxResults=2000, prettyPrint=True, mine=True) subscriptionsList = subscriptionsRequest.execute() for subscriptionItem in subscriptionsList["items"]: channelId = subscriptionItem['snippet']['resourceId']['channelId'] channelRequest = youtube.channels().list( part="snippet,contentDetails,statistics", prettyPrint=True, id=channelId) responseChannelInfo = channelRequest.execute() for item in responseChannelInfo['items']: name = item['snippet']['title'] description = item['snippet']['description'] publishedAt = item['snippet']['publishedAt'] country = item['snippet']['country'] if 'country' in item[ 'snippet'] else "NONE" videoUploads = item['statistics']['videoCount'] subscribers = item['statistics']['subscriberCount'] viewers = item['statistics']['viewCount'] thumbnail = item['snippet']['thumbnails']['high']['url'] timestamp = int(time.time() * 1000.0) print(">> Channel Name: {}\n".format(name)) sqliteChannelCreate(conn, channelId, name, description, country, videoUploads, subscribers, viewers, thumbnail, publishedAt, timestamp, timestamp) print(">> -----------------------\n")
def get_auth_url(self): flow = InstalledAppFlow.from_client_secrets_file( CLIENT_SECRETS_FILE, SCOPES) flow.redirect_uri = 'http://localhost' #credentials = flow.run_console() return flow.authorization_url()[0]
def makeAppointment(email, name, projectName, address, recommendedOfferPrice): """Shows basic usage of the Google Calendar API. Prints the start and name of the next 10 events on the user's calendar. """ calendarSlot = {} email_A = [] name_A = [] timeslot_A = [] project_A = [] address_A = [] price_A = [] for i in range (336): now = datetime.utcnow() + timedelta(hours=(8+i)) date = now.strftime('%m-%dT%H') calendarSlot.update({date:'F'}) 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 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')) start = start[5:13] if len(start) == 5: start = start + 'T00' end = event['end'].get('dateTime', event['end'].get('date')) end = end[5:13] if len(end) == 5: end = end + 'T23' calendarSlot[start] = 'S' calendarSlot[end] = 'E' busy = False for i in range (336): now = datetime.utcnow() + timedelta(hours=(8+i)) date = now.strftime('%m-%dT%H') if busy: if calendarSlot[date] == 'F': calendarSlot[date] = 'B' elif calendarSlot[date] == 'E': busy = False if calendarSlot[date] == 'S': busy = True #loop through the calendarSlot and find the earliest appointments for i in range (331): now = datetime.utcnow() + timedelta(hours=(11+i)) nowP1 = datetime.utcnow() + timedelta(hours=(12+i)) nowP2 = datetime.utcnow() + timedelta(hours=(13+i)) date = now.strftime('%m-%dT%H') dateP1 = nowP1.strftime('%m-%dT%H') dateP2 = nowP2.strftime('%m-%dT%H') if int(now.strftime('%H')) > 12 and int(now.strftime('%H')) < 20 and calendarSlot[date] == 'F' and calendarSlot[dateP1] == 'F' and calendarSlot[dateP2] == 'F': hour = int(nowP1.strftime('%I')) day = nowP1.strftime('%d %b') timeslot = f'{day}, {hour}PM' email_A.append(email) name_A.append(name) timeslot_A.append(timeslot) project_A.append(projectName) address_A.append(address) price_A.append(recommendedOfferPrice) Appointment_Detail = {'Email':email_A, 'Client Name':name_A, 'Appointment': timeslot_A, 'Project Name': project_A,'Address': address_A, 'Predicted Price': price_A} df = DataFrame(Appointment_Detail, columns=['Email','Client Name','Appointment','Project Name','Address','Predicted Price']) export_csv = df.to_csv('user_appointment_detail.csv', index = None)
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(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) # Call the Sheets API sheet = service.spreadsheets() result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID, range=SAMPLE_RANGE_NAME).execute() values = result.get('values', []) for i in range(len(values)): values[i].pop(1) cols = values.pop(0) df = pd.DataFrame(values,columns=cols) df.rename(columns={ df.columns[1]: "new_col_name" }) del df['R'] '''Easiest way of fixing team values and make them easy to search for using Regex and Pandas filtering.''' df.replace(to_replace='.Galatasaray',value=' GS',inplace=True,regex=True) df.replace(to_replace='.Fenerbahce',value=' FB',inplace=True,regex=True) df.replace(to_replace='.Besiktas',value=' BJK',inplace=True,regex=True) df.replace(to_replace='.Ankaragucu',value=' ANK',inplace=True,regex=True) df.replace(to_replace='.Istanbul Basaksehir',value=' IBFK',inplace=True,regex=True) df.replace(to_replace='.Kayserispor',value=' KAY',inplace=True,regex=True) df.replace(to_replace='.Konyaspor',value=' KON',inplace=True,regex=True) df.replace(to_replace='.Kasimpasa',value=' KAS',inplace=True,regex=True) df.replace(to_replace='.Alanyaspor',value=' ALN',inplace=True,regex=True) df.replace(to_replace='.Sivasspor',value=' SIV',inplace=True,regex=True) df.replace(to_replace='.Bursaspor',value=' BUR',inplace=True,regex=True) df.replace(to_replace='.Erzurum BB',value=' ERZ',inplace=True,regex=True) df.replace(to_replace='.Trabzonspor',value=' TS',inplace=True,regex=True) df.replace(to_replace='.Antalyaspor',value=' ANT',inplace=True,regex=True) df.replace(to_replace='.Rizespor',value=' RIZE',inplace=True,regex=True) df.replace(to_replace='.Akhisarspor',value=' AKH',inplace=True,regex=True) df.replace(to_replace='.Goztepe',value=' GOZ',inplace=True,regex=True) df.replace(to_replace='.Yeni Malatyaspor',value=' YMS',inplace=True,regex=True) goalkeeper = df[df.Pos1.str.contains('G.')] defender = df[df.Pos1.str.contains('D\(.') | df.Pos2.str.contains('D\(.')] midfielder = df[df.Pos1.str.contains('.?M\(?.')| df.Pos2.str.contains('.?M\(.')] forward= df[df.Pos1.str.contains('F.') | df.Pos2.str.contains('F.')] defender = defender.sort_values(by=['Drb','Crosses','KeyP','ThrB'], ascending=False) '''Some example searches below.''' young_midfielders = midfielder[pd.to_numeric(midfielder['Age'])<=25)] print(young_midfielders)
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()
def main(email, date, time): """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') event = { 'summary': 'Appointment', #'location': '800 Howard St., San Francisco, CA 94103', 'description': 'Virtual Meeting', 'start': { 'date': date, 'timeZone': 'America/Los_Angeles', }, 'end': { 'date': date, 'timeZone': 'America/Los_Angeles', }, 'recurrence': ['RRULE:FREQ=DAILY;COUNT=1'], 'attendees': [ { 'email': email }, ], 'reminders': { 'useDefault': False, 'overrides': [ { 'method': 'email', 'minutes': 24 * 60 }, { 'method': 'popup', 'minutes': 10 }, ], }, } event = service.events().insert(calendarId='primary', sendNotifications=True, body=event).execute()
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)
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( \ #'/home/tgaldes/Dropbox/Fraternity PM/dev_private/docs_credentials.json', SCOPES) '/home/tgaldes/Dropbox/Fraternity PM/dev_private/cfldv1_secret.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) title = 'USC Kappa Alpha George Bremer' body = {'title': title} doc = service.documents() \ .create(body=body).execute() print('Created document with title: {0}'.format(doc.get('documentId'))) print(doc) # Retrieve the documents contents from the Docs service. document = service.documents().get(documentId=DOCUMENT_ID).execute() print(document) print(document['body']['content'][-1]) print('The title of the document is: {}'.format(document.get('title'))) smarket = 'BULLETS' emarker = 'ENDBULLETS' fs = '\tThis is the first paragraph.\n' ss = '\n\tThis is the second paragraph.\n' #+ smarker + 'test first line\ntest second\ntest third' + emarker bullets = 'test first line\ntest second\ntest third\n' '''{ 'insertInlineImage': { 'location': { 'index': 1 }, 'uri': 'https://cleanfloorslockingdoors.com/wp-content/uploads/2020/07/frame.png', 'objectSize': { 'height': { 'magnitude': 100, 'unit': 'PT' }, 'width': { 'magnitude': 100, 'unit': 'PT' } } } }, ''' requests = [ { 'insertText': { 'location': { 'index': 1, }, 'text': ss } }, \ { 'insertText': { 'location': { 'index': 1, }, 'text': bullets } }, \ { 'insertText': { 'location': { 'index': 1, }, 'text': fs } }, \ { 'createParagraphBullets': { 'range': { 'startIndex': len(fs) + 1, 'endIndex': len(bullets) + 1 + len(fs) }, 'bulletPreset': 'BULLET_DISC_CIRCLE_SQUARE', } } ] result = service.documents().batchUpdate(documentId=DOCUMENT_ID, body={ 'requests': requests }).execute()