def get_user_permission(): """Run through the OAuth flow to get credentials.""" client_id_file = os.path.join(HERE, 'instance', CLIENT_SECRET) store = get_credentials_store() flow = client.flow_from_clientsecrets(client_id_file, SCOPES) flow.user_agent = APPLICATION_NAME tools.run_flow(flow, store)
def build(*args, **kwargs): ip = get_ipython() if 'google_credential_path' in kwargs: credential_path = kwargs['google_credential_path'] del kwargs['google_credential_path'] elif 'Googleapihelper' in ip.config and 'credential_path' in ip.config.Googleapihelper: credential_path = ip.config.Googleapihelper['credential_path'] else: logger.info('Credential store path not specified, trying default: '+ DEFAULT_CREDENTIALS_PATH) credential_path = DEFAULT_CREDENTIALS_PATH if 'google_secrets_path' in kwargs: secrets_path = kwargs['google_secrets_path'] del kwargs['google_secrets_path'] elif 'Googleapihelper' in ip.config and 'secrets_path' in ip.config.Googleapihelper: secrets_path = ip.config.Googleapihelper['secrets_path'] else: logger.info('Secrets path not specified, trying default: '+ DEFAULT_SECRETS_PATH) secrets_path = DEFAULT_SECRETS_PATH if 'redirect_uri' in kwargs: redirect_uri = kwargs['redirect_uri'] del kwargs['redirect_uri'] elif 'Googleapihelper' in ip.config and 'redirect_uri' in ip.config.Googleapihelper: redirect_uri = ip.config.Googleapihelper['redirect_uri'] else: logger.info('Redirect uri not specified, trying default: '+ DEFAULT_REDIRECT_URI) redirect_uri = DEFAULT_REDIRECT_URI if 'scope' in kwargs: scope = kwargs['scope'] del kwargs['scope'] elif 'Googleapihelper' in ip.config and 'scope' in ip.config.Googleapihelper: scope = ip.config.Googleapihelper['scope'] else: logger.error('No scope specified in options or ipython config. '+ 'Store scope in ipython profile or specify on command line.') return None storage = Storage(credential_path) credentials = storage.get() if credentials is None: flow = flow_from_clientsecrets(secrets_path, scope=scope, redirect_uri=redirect_uri) flags, kwargs = extract_flags_from_kwargs(kwargs) tools.run_flow(flow, storage, flags) credentials = storage.get() if credentials is None: logger.error("Unable to retrieve google oauth credentials") return None http = httplib2.Http() http = credentials.authorize(http) kwargs['http'] = http return discovery.build(*args, **kwargs)
def authorize_google_calendar(): FLOW = flow_from_clientsecrets(flask_config.INSTALLED_APP_SECRET_PATH, scope='https://www.googleapis.com/auth/calendar') # Save the credentials file here for use by the app storage = Storage(flask_config.INSTALLED_APP_CREDENTIALS_PATH) run_flow(FLOW, storage, FLAGS)
def get_credentials(): # type: () -> object """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, 'Google Drive/G/IT/Development/ETL/.credentials') # JLD - customized path to working directory if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'client_secret_anchorpath.json') store = oauth2client.file.Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run_flow(flow, store) print('Storing credentials to ' + credential_path) return credentials
def authenticate_main(): """ Authenticate using OAuth with the Task Queue API. """ import sys import argparse from oauth2client import tools from oauth2client.client import flow_from_clientsecrets if len(sys.argv) > 1 and sys.argv[0] == 'python': argv = sys.argv[2:] else: argv = sys.argv[1:] parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser]) parser.add_argument('client_secrets', metavar='SECRETS', help='Path to the client_secrets.json.') parser.add_argument('credentials', metavar='CREDENTIALS', help='Path where the credentials will be stored.') flags = parser.parse_args(argv) tools.run_flow( flow_from_clientsecrets(flags.client_secrets, scope="https://www.googleapis.com/auth/taskqueue"), storage=Storage(flags.credentials), flags=flags, ) print('Saved credentials to %s' % flags.credentials)
def acquire_token(client_secrets, oauth2_token, flags): """Handles the user consent process and saves the retrieved OAuth2 token Args: client_secrets - path to client_secrets file oauth2_token - path to save oauth2_token (YouTube Service Parameters) https://google-api-python-client.googlecode.com/hg/docs/epy/oauth2client.tools-module.html flags.auth_host_name - Host name to use when running a local web server to handle redirects during OAuth authorization. (default: 'localhost') flags..auth_host_port - Port to use when running a local web server to handle redirects during OAuth authorization.; repeat this option to specify a list of values (default: '[8080, 8090]') (an integer) flags.auth_local_webserver - True/False Run a local web server to handle redirects during OAuth authorization. (default: True) """ scope = ['https://www.googleapis.com/auth/youtube.upload'] message = ("Please specify a valid client_secrets.json file.\n" "For instructions to obtain one, please visit:\n" "https://docs.google.com/document/d/1ro9I8jnOCgQlWRRVCPbrNnQ5-bMvQxDVg6o45zxud4c/edit") flow = client.flow_from_clientsecrets(client_secrets, scope=scope, message=message) storage = file.Storage(oauth2_token) tools.run_flow(flow, storage, flags)
def get_credentials(flags=None): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'calendar-python-quickstart.json') store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run_flow(flow, store) print('Storing credentials to ' + credential_path) return credentials
def refresh_cache(labels=None): labels = labels if labels is not None else config.SYSTEM_LABELS.keys() flow = flow_from_clientsecrets( config.CLIENT_SECRET_FILE, scope=config.OAUTH_SCOPE) http = httplib2.Http() try: credentials = OAuth2Credentials.from_json( WF.get_password('gmail_credentials')) if credentials is None or credentials.invalid: credentials = run_flow(flow, PseudoStorage(), http=http) WF.save_password('gmail_credentials', credentials.to_json()) WF.logger.debug('Credentials securely updated') http = credentials.authorize(http) gmail_service = build('gmail', 'v1', http=http) for label in labels: WF.cache_data('gmail_%s' % label.lower(), get_list(http, gmail_service, label)) sleep(2) if not WF.cached_data_fresh('gmail_labels', max_age=300): WF.cache_data('gmail_labels', get_labels(gmail_service)) except PasswordNotFound: WF.logger.debug('Credentials not found') credentials = run_flow(flow, PseudoStorage(), http=http) WF.save_password('gmail_credentials', credentials.to_json()) WF.logger.debug('New Credentials securely saved') except httplib2.ServerNotFoundError: WF.logger.debug('ServerNotFoundError')
def setup(self, args): if self.credentials and not self.credentials.invalid: raise EnvironmentError('Already setup') # TODO add flag to redo home = os.path.expanduser('~') secrets_path = os.path.join(home, '.sixoclock_gdrive_secrets.json') flow = client.flow_from_clientsecrets(secrets_path, SCOPES) flow.user_agent = 'sixoclock' tools.run_flow(flow, store, args)
def main(): client_id = sys.argv[1] client_secret = sys.argv[2] scope = sys.argv[3] flow = OAuth2WebServerFlow(client_id, client_secret, scope) storage = Storage('google.json') flags = argparser.parse_args([]) run_flow(flow, storage, flags)
def test_run_flow_no_webserver_exchange_error(self, input_mock, logging_mock): input_mock.return_value = "auth_code" self.flow.step2_exchange.side_effect = FlowExchangeError() # Error while exchanging. with self.assertRaises(SystemExit): tools.run_flow(self.flow, self.storage, flags=self.flags) self.flow.step2_exchange.assert_called_once_with("auth_code", http=None)
def test_run_flow_webserver_no_code( self, webbrowser_open_mock, server_ctor_mock, logging_mock): server_ctor_mock.return_value = self.server self.server.query_params = {} # No code found in response with self.assertRaises(SystemExit): tools.run_flow(self.flow, self.storage, flags=self.server_flags) self.assertTrue(self.server.handle_request.called)
def test_run_flow_webserver_exchange_error( self, webbrowser_open_mock, server_ctor_mock, logging_mock): server_ctor_mock.return_value = self.server self.server.query_params = {'error': 'any error'} # Exchange returned an error code. with self.assertRaises(SystemExit): tools.run_flow(self.flow, self.storage, flags=self.server_flags) self.assertTrue(self.server.handle_request.called)
def getCredentials(secrets_file, tokens_file, scopes, flags): # create an auth flow in case we need to authenticate auth_flow = flow_from_clientsecrets(secrets_file, scope=scopes, message="Visit the APIs Console") # search for existing tokens storage = Storage(tokens_file) credentials = storage.get() if credentials is None or credentials.invalid: run_flow(auth_flow, storage, flags, http=Http()) return storage.get() return credentials
def get_credentials(): try: flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None store = file.Storage(_consts.STORAGE) creds = store.get() if not creds or creds.invalid: client.flow_from_clientsecrets(_consts.CLIENT_SECRET, _consts.SCOPES) tools.run_flow(flow, store, flags) return creds;
def create_credentials(client_secret_path): """Gets valid user credentials from storage. Args: path (str), path to client_secret.json file """ flow = client.flow_from_clientsecrets(client_secret_path, ' '.join(SCOPES)) flow.user_agent = 'Clouseau' flow.params['access_type'] = 'offline' flow.params['approval_prompt'] = 'force' store = oauth2client.file.Storage(CREDENTIALS_PATH) flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args(['--noauth_local_webserver']) tools.run_flow(flow, store, flags)
def client(self): http_client = httplib2.Http() credential_store = self.credential_store() credentials = credential_store.get() if not credentials or credentials.invalid: flow = client.OAuth2WebServerFlow( client_id=self.client_secrets["client_id"], client_secret=self.client_secrets["client_secret"], scope=self.scope, user_agent=self.user_agent, redirect_url="urn:ietf:wg:oauth:2.0:oob", ) tools.run_flow(flow, credential_store, self.args) credential_store.get().authorize(http_client) return http_client
def main(): client_id = sys.argv[1] client_secret = sys.argv[2] # Scopes of authorization activity = "https://www.googleapis.com/auth/fitness.activity.write" body = "https://www.googleapis.com/auth/fitness.body.write" nutrition = "https://www.googleapis.com/auth/fitness.nutrition.write" bp = "https://www.googleapis.com/auth/fitness.blood_pressure.write" scopes = activity + " " + body + " " + nutrition + " " + bp flow = OAuth2WebServerFlow(client_id, client_secret, scopes) storage = Storage('google.json') flags = argparser.parse_args([]) run_flow(flow, storage, flags)
def main(argv): #put(service) flags = parser.parse_args(argv[1:]) #sample.dat file stores the short lived access tokens, which your application requests user data, attaching the access token to the request. #so that user need not validate through the browser everytime. This is optional. If the credentials don't exist #or are invalid run through the native client flow. The Storage object will ensure that if successful the good # credentials will get written back to the file (sample.dat in this case). storage = file.Storage('sample.dat') credentials = storage.get() if credentials is None or credentials.invalid: credentials = tools.run_flow(FLOW, storage, flags) # Create an httplib2.Http object to handle our HTTP requests and authorize it # with our good Credentials. http = httplib2.Http() http = credentials.authorize(http) # Construct the service object for the interacting with the Cloud Storage API. service = discovery.build('storage', _API_VERSION, http=http) #def put(service): starting_time=time.time() fileupload=raw_input("please enter the name of the file") req = service.objects().insert( bucket=_BUCKET_NAME, name=fileupload,media_body='all_month.csv') resp = req.execute() ending_time=time.time()-starting_time print ending_time fields_to_return = 'nextPageToken,items(bucket,name,metadata(my-key))' print json.dumps(resp, indent=2)
def __enter__(self): # Ensure that we have not re-entered if self.temp_path != None or self.service != None: raise Exception('Cannot use multiple nested with blocks on same Youtube object!') flow = flow_from_clientsecrets( self.client_secrets_path, scope=YOUTUBE_UPLOAD_SCOPE, message=MISSING_CLIENT_SECRETS_MESSAGE) temp_file = NamedTemporaryFile(delete=False) self.temp_path = temp_file.name temp_file.close() storage = Storage(self.temp_path) credentials = storage.get() if credentials is None or credentials.invalid: credentials = run_flow( flow, storage, argparser.parse_args(list()) ) self.service = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, http=credentials.authorize(httplib2.Http())) return self
def setup(self, client_secrets): storage = Storage("credentials.dat") credentials = storage.get() if credentials is None or credentials.invalid: flow = flow_from_clientsecrets( client_secrets, scope="https://www.googleapis.com/auth/genomics", message="You need to copy a client_secrets.json file into this directory, " "or pass in the --client_secrets_filename option to specify where " "one exists. See the README for more help.", ) # There's probably a better way to generate the 'flags' object. Doing it this way for now. parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser] ) parser.add_argument( "--client_secrets_filename", default=client_secrets, help="The filename of a client_secrets.json file from a " 'Google "Client ID for native application" that ' "has the Genomics API enabled.", ) flags = parser.parse_args() credentials = run_flow(flow, storage, flags) # Create a genomics API service http = httplib2.Http() http = credentials.authorize(http) service = build("genomics", "v1beta2", http=http) return service
def get_or_create_credentials(scope, storage_key=DEFAULT_STORAGE_KEY): key_file = os.getenv('AUTH_KEY_FILE') # If AUTH_KEY_FILE is unset, use default auth key file if it exists. if not key_file and os.path.exists(DEFAULT_AUTH_KEY_FILE): key_file = DEFAULT_AUTH_KEY_FILE if key_file: key_file = os.path.expanduser(key_file) return (service_account. ServiceAccountCredentials.from_json_keyfile_name(key_file, scope)) if appengine and utils.is_appengine(): return appengine.AppAssertionCredentials(scope) credentials, storage = get_credentials_and_storage(scope, storage_key=storage_key) if credentials is None: parser = tools.argparser if os.getenv('INTERACTIVE_AUTH'): args = [] else: args = ['--noauth_local_webserver'] flags, _ = parser.parse_known_args(args) flow = client.OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, scope, redirect_uri=REDIRECT_URI) credentials = tools.run_flow(flow, storage, flags) # run_flow changes the logging level, so change it back. logging.getLogger().setLevel(getattr(logging, 'INFO')) return credentials
def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') #/Users/TMD credential_dir = os.path.join(home_dir, '.credentials') #This line adds the directory .credentials to my home_dir so /Users/TMD/.credentials print credential_dir #If the credentials directory does not exist, the conditional creates the credential #directory and joins it's json file containing the id and pwd to the credentials directory if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'task-manager.json') store = oauth2client.file.Storage(credential_path) #Creates an object named store <oauth2client.file.Storage object at 0x10324c6d0> credentials = store.get() #Applies the get() method on the object and stores the new object as credentials if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print 'Storing credentials to ' + credential_path return credentials
def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'calendar-quickstart.json') store = oauth2client.file.Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatability with Python 2.6 credentials = tools.run(flow, store) print 'Storing credentials to ' + credential_path return credentials
def main(argv): # Parse the command-line flags. flags = parser.parse_args(argv[1:]) # If the credentials don't exist or are invalid run through the native client # flow. The Storage object will ensure that if successful the good # credentials will get written back to the file. storage = file.Storage('sample.dat') credentials = storage.get() if credentials is None or credentials.invalid: credentials = tools.run_flow(FLOW, storage, flags) # Create an httplib2.Http object to handle our HTTP requests and authorize it # with our good Credentials. http = httplib2.Http() http = credentials.authorize(http) # Construct the service object for the interacting with the Google+ Domains API. service = discovery.build('plusDomains', 'v1', http=http) try: people_service = service.people() people_document = people_service.get(userId='me').execute() print 'ID: %s' % people_document.get('id') print 'Display name: %s' % people_document.get('displayName') print 'Image URL: %s' % people_document.get('image').get('url') print 'Profile URL: %s' % people_document.get('url') except client.AccessTokenRefreshError: print ("The credentials have been revoked or expired, please re-run" "the application to re-authorize")
def init(argv, name, version, doc, filename, scope=None, parents=[]): """A common initialization routine for samples. Many of the sample applications do the same initialization, which has now been consolidated into this function. This function uses common idioms found in almost all the samples, i.e. for an API with name 'apiname', the credentials are stored in a file named apiname.dat, and the client_secrets.json file is stored in the same directory as the application main file. Args: argv: list of string, the command-line parameters of the application. name: string, name of the API. version: string, version of the API. doc: string, description of the application. Usually set to __doc__. file: string, filename of the application. Usually set to __file__. parents: list of argparse.ArgumentParser, additional command-line flags. scope: string, The OAuth scope used. Returns: A tuple of (service, flags), where service is the service object and flags is the parsed command-line flags. """ if scope is None: scope = 'https://www.googleapis.com/auth/' + name # Parser command-line arguments. parent_parsers = [tools.argparser] parent_parsers.extend(parents) parser = argparse.ArgumentParser( description=doc, formatter_class=argparse.RawDescriptionHelpFormatter, parents=parent_parsers) flags = parser.parse_args(argv[1:]) # Name of a file containing the OAuth 2.0 information for this # application, including client_id and client_secret, which are found # on the API Access tab on the Google APIs # Console <http://code.google.com/apis/console>. client_secrets = os.path.join(os.path.dirname(filename), 'client_secrets.json') # Set up a Flow object to be used if we need to authenticate. flow = client.flow_from_clientsecrets(client_secrets, scope=scope, message=tools.message_if_missing(client_secrets)) # Prepare credentials, and authorize HTTP object with them. # If the credentials don't exist or are invalid run through the native client # flow. The Storage object will ensure that if successful the good # credentials will get written back to a file. storage = file.Storage(name + '.dat') credentials = storage.get() if credentials is None or credentials.invalid: credentials = tools.run_flow(flow, storage, flags) http = credentials.authorize(http = httplib2.Http()) # Construct a service object via the discovery service. service = discovery.build(name, version, http=http) return (service, flags)
def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'gmail-empty-trash.json') store = oauth2client.file.Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) print('Storing credentials to ' + credential_path) return credentials
def _get_credentials(self): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'calendar-python-sisgap.json') store = oauth2client.file.Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets( self._google_client_secret_file, self._google_scopes) flow.user_agent = self._google_application_name credentials = tools.run_flow(flow, store, None) return credentials
def get_credentials(self): if not os.path.exists(CLIENT_SECRET_FILE): print("the credentials file is missing. follow the tutorial in the readme so you know what to do") exit() """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'drive-python-quickstart.json') store = oauth2client.file.Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials
def main(argv): # create the orchestration object gce_cluster = GceCondor(None, PROJECT_ID) # create the top-level parser parser = argparse.ArgumentParser(parents=[argparser]) subparsers = parser.add_subparsers() # create the parser for the "start_cluster" command parser_start = subparsers.add_parser('start', help="start a condor cluster") parser_start.add_argument('node_count', type=int, default=1, help="the number of nodes, including master") parser_start.add_argument('-i', '--image', action="store_true", help="create instance from predefined image") parser_start.set_defaults(func=gce_cluster.start) # create the parser for the "terminate" command parser_terminate = subparsers.add_parser('terminate', help="shutdown cluster, ie terminate all instances in project") parser_terminate.set_defaults(func=gce_cluster.terminate) args = parser.parse_args(argv) # Perform OAuth 2.0 authorization. flow = flow_from_clientsecrets(CLIENT_SECRETS, scope=GCE_SCOPE) storage = Storage(OAUTH2_STORAGE) credentials = storage.get() if credentials is None or credentials.invalid: credentials = run_flow(flow, storage, args) http = httplib2.Http() auth_http = credentials.authorize(http) # update the orchestration object with the authorized Http object gce_cluster.set_auth_http(auth_http) # perform the command args.func(args)
def main(): CLIENT_SECRETS_FILE = "client_secrets.json" # This variable defines a message to display if the CLIENT_SECRETS_FILE is # missing. MISSING_CLIENT_SECRETS_MESSAGE = """ WARNING: Please configure OAuth 2.0 To make this sample run you will need to populate the client_secrets.json file found at: %s with information from the {{ Cloud Console }} {{ https://cloud.google.com/console }} For more information about the client_secrets.json file format, please visit: https://developers.google.com/api-client-library/python/guide/aaa_client_secrets """ % os.path.abspath( os.path.join(os.path.dirname(__file__), CLIENT_SECRETS_FILE)) # This OAuth 2.0 access scope allows for read-only access to the authenticated # user's account, but not other types of account access. YOUTUBE_READONLY_SCOPE = "https://www.googleapis.com/auth/youtube.readonly" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, message=MISSING_CLIENT_SECRETS_MESSAGE, scope=YOUTUBE_READONLY_SCOPE) storage = Storage("%s-oauth2.json" % sys.argv[0]) credentials = storage.get() if credentials is None or credentials.invalid: flags = argparser.parse_args() credentials = run_flow(flow, storage, flags) youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, http=credentials.authorize(httplib2.Http())) # Retrieve the contentDetails part of the channel resource for the # authenticated user's channel. channels_response = youtube.channels().list( mine=True, part="contentDetails").execute() for channel in channels_response["items"]: # From the API response, extract the playlist ID that identifies the list # of videos uploaded to the authenticated user's channel. uploads_list_id = channel["contentDetails"]["relatedPlaylists"][ "uploads"] resp = "Videos for id: %s which already exist on youtube\n\n" % uploads_list_id # Retrieve the list of videos uploaded to the authenticated user's channel. playlistitems_list_request = youtube.playlistItems().list( playlistId=uploads_list_id, part="snippet", maxResults=50) while playlistitems_list_request: playlistitems_list_response = playlistitems_list_request.execute() # Print information about each video. c = 1 for playlist_item in playlistitems_list_response["items"]: title = playlist_item["snippet"]["title"] video_id = playlist_item["snippet"]["resourceId"]["videoId"] resp += "%s. Title:%s Id:(%s)\n" % (c, title, video_id) c = c + 1 playlistitems_list_request = youtube.playlistItems().list_next( playlistitems_list_request, playlistitems_list_response) resp = resp.replace('\n', '<br \>\n') return resp
def get_outh_credentials(client_secret_file, credential_dir=None, outh_nonlocal=False): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. :param client_secret_file: path to outh2 client secret file :param credential_dir: path to directory where tokens should be stored 'global' if you want to store in system-wide location None if you want to store in current script directory :param outh_nonlocal: if the authorization should be done in another computer, this will provide a url which when run will ask for credentials :return Credentials, the obtained credential. """ lflags = flags if credential_dir == 'global': home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) elif not credential_dir: credential_dir = os.getcwd() else: pass # verify credentials directory if not os.path.isdir(credential_dir): raise IOError(2, "Credential directory does not exist.", credential_dir) credential_path = os.path.join(credential_dir, 'sheets.googleapis.com-python.json') # check if refresh token file is passed with warnings.catch_warnings(): warnings.simplefilter("ignore") try: store = Storage(client_secret_file) credentials = store.get() except KeyError: credentials = None # else try to get credentials from storage if not credentials or credentials.invalid: try: with warnings.catch_warnings(): warnings.simplefilter("ignore") store = Storage(credential_path) credentials = store.get() except KeyError: credentials = None # else get the credentials from flow if not credentials or credentials.invalid: # verify client secret file if not os.path.isfile(client_secret_file): raise IOError(2, "Client secret file does not exist.", client_secret_file) # execute flow flow = client.flow_from_clientsecrets(client_secret_file, SCOPES) flow.user_agent = 'pygsheets' if lflags: lflags.noauth_local_webserver = outh_nonlocal credentials = tools.run_flow(flow, store, lflags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials
def carro_new(request): if not request.user.is_authenticated: #request.session['error'] = "No logueado" request.session['ver'] = True mensaje(request, 'No logueado') return redirect('../../vehiculo/login') #Guardando la imagen resizeado size = (480, 320) if request.method == "POST": form = CarroForm(request.POST) if form.is_valid(): import re from PIL import Image carro = form.save(commit=False) carro.usuario = request.user #No usamos form-clean porque lo estoy trayendo de post... modelo = request.POST.get('modelo') modelo_ = modelo.replace( ' ', '') # quitamos los espacios (no son alfanumericos) patron = "\W" #CARACTERES NO ALFANUMERICOS (posible danino) if re.search(patron, modelo_): carro.save() #lanza error.... else: carro.modelo = Modelo.objects.get(id=modelo) myfile = request.FILES['imagen'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) carro.imagen_nombre = fs.url(filename) import os if os.name == 'posix': #name = 'media/'+filename name_ = os.path.join( os.path.dirname(os.path.dirname(__file__)), 'media/', filename) else: #name = 'C:\\Users\\lenov\\Documents\\python_Win_Deb\\site1\\media\\'+filename name_ = 'C:\\Users\\lenov\\Documents\\python_Win_Deb\\site1\\media\\' + filename n, e = os.path.splitext(name_) name = n + "thumbnail" + e img = Image.open(name_) img.resize(size).save(name) from apiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools from apiclient.http import MediaFileUpload # Setup the Drive v3 API SCOPES = 'https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file' store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = build('drive', 'v3', http=creds.authorize(Http())) folder_id = '158Sk_z9ERQR5pSY94x1bhw4_SOGeUjgg' file_metadata = {'name': filename, 'parents': [folder_id]} media = MediaFileUpload(name, mimetype='image/jpeg', resumable=True) file = service.files().create(body=file_metadata, media_body=media, fields='id').execute() #print('File ID: %s' % file.get('id')) carro.imagen_nombre = file.get('id') ciudad = request.POST.get('ciudad') ciudad_ = ciudad.replace( ' ', '') # quitamos los espacios (no son alfanumericos) patron = "\W" #CARACTERES NO ALFANUMERICOS (posible danino) if re.search(patron, ciudad_): carro.save() #lanza error.... else: carro.ciudad = Ciudad.objects.get(id=ciudad) carro.save() request.session['ver'] = True mensaje(request, "Carro " + carro.placa + " creado") ''' import os os.remove(name) ''' return redirect('ind') else: form = CarroForm() form.usuario = User.objects.get(id=request.user.id) form.fields['usuario'].initial = form.usuario.username #form.fields['provincia'].empty_label = None #form.fields['marca'].initial = 0 return render(request, 'vehiculo/carro_edit.html', {'form': form})
except ImportError: flags = None home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'youtube-python-quickstart.json') store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRETS_FILE, SCOPES) flow.user_agent = '206Youtube' if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) youtube = build('youtube', 'v3', credentials = credentials) os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' fileNames = ['emails.json', 'newsMessages.json', 'politicalAnalysis.json', 'youtubeData.json'] timeURL = 'https://plot.ly/~M4LL0C/4/popular-youtube-videos/' politicalURL = 'https://plot.ly/~M4LL0C/6/average-political-tendencies/' print('A political and temporal analysis of the Internet') print('-------------(At the most basic level)-----------')
def login(self, args): creds = self._set_expiration_to_long_time(tools.run_flow(flow, self.storage, args)) self.storage.put(creds) self.user_info = self._get_user_info()
def main(): # Setup the Gmail API SCOPES = 'https://mail.google.com/' store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = build('gmail', 'v1', http=creds.authorize(Http())) # Call the Gmail API response = service.users().messages().list(userId='me').execute() conn = sqlite3.connect('gmail.db') print("Opened database successfully") with open('rules.json') as outfile: jsondata = json.load(outfile) for rule in jsondata['rules']: value = {} if rule['overall_predicate'] == "all": message_id_list = [] condition_string = "" query_string = "SELECT * from GMAIL_MESSAGES WHERE " for condition in rule['conditions']: if condition['field'] == "from" and condition[ 'predicate'] == "contains": condition_string = condition_string + "message_from LIKE '%" + condition[ 'value'] + "%'" if condition['field'] == "to" and condition[ 'predicate'] == "contains": condition_string = condition_string + "message_to LIKE '%" + condition[ 'value'] + "%'" if condition['field'] == "subject" and condition[ 'predicate'] == "contains": condition_string = condition_string + "message_subject LIKE '%" + condition[ 'value'] + "%'" if condition['field'] == "from" and condition[ 'predicate'] == "equals": condition_string = condition_string + "message_from = '" + condition[ 'value'] + "' " if condition['field'] == "to" and condition[ 'predicate'] == "equals": condition_string = condition_string + "message_to = '" + condition[ 'value'] + "' " if condition['field'] == "subject" and condition[ 'predicate'] == "equals": condition_string = condition_string + "message_subject = '" + condition[ 'value'] + "' " if condition['field'] == "from" and condition[ 'predicate'] == "not_contains": condition_string = condition_string + "message_from NOT LIKE '%" + condition[ 'value'] + "%'" if condition['field'] == "to" and condition[ 'predicate'] == "not_contains": condition_string = condition_string + "message_to NOT LIKE '%" + condition[ 'value'] + "%'" if condition['field'] == "subject" and condition[ 'predicate'] == "not_contains": condition_string = condition_string + "message_subject NOT LIKE '%" + condition[ 'value'] + "%'" if condition['field'] == "from" and condition[ 'predicate'] == "not_equals": condition_string = condition_string + "message_from != '" + condition[ 'value'] + "' " if condition['field'] == "to" and condition[ 'predicate'] == "not_equals": condition_string = condition_string + "message_to != '" + condition[ 'value'] + "' " if condition['field'] == "subject" and condition[ 'predicate'] == "not_equals": condition_string = condition_string + "message_subject != '" + condition[ 'value'] + "' " if condition['field'] == "date" and condition[ 'predicate'] == "less_than_days": condition_string = condition_string + "message_date >= date('now','-" + condition[ 'value'] + " day') " if condition['field'] == "date" and condition[ 'predicate'] == "greater_than_days": condition_string = condition_string + "message_date < date('now','-" + condition[ 'value'] + " day') " if condition['field'] == "date" and condition[ 'predicate'] == "less_than_months": condition_string = condition_string + "message_date >= date('now','-" + condition[ 'value'] + " month') " if condition['field'] == "date" and condition[ 'predicate'] == "greater_than_months": condition_string = condition_string + "message_date < date('now','-" + condition[ 'value'] + " month') " if (rule['conditions'][-1] != condition): condition_string = condition_string + " AND " query_string = query_string + condition_string cursor = conn.execute(query_string) for row in cursor: message_id_list.append(row[1]) actions(service, rule['actions'], message_id_list) else: message_id_list = [] for condition in rule['conditions']: if condition['field'] == "from" and condition[ 'predicate'] == "contains": cursor = conn.execute( "SELECT * from GMAIL_MESSAGES WHERE(message_from LIKE '%" + condition['value'] + "%' );") for row in cursor: message_id_list.append(row[1]) if condition['field'] == "to" and condition[ 'predicate'] == "contains": cursor = conn.execute( "SELECT * from GMAIL_MESSAGES WHERE(message_to LIKE '%" + condition['value'] + "%' );") for row in cursor: message_id_list.append(row[1]) if condition['field'] == "subject" and condition[ 'predicate'] == "contains": cursor = conn.execute( "SELECT * from GMAIL_MESSAGES WHERE(message_subject LIKE '%" + condition['value'] + "%' );") for row in cursor: message_id_list.append(row[1]) if condition['field'] == "from" and condition[ 'predicate'] == "equals": cursor = conn.execute( "SELECT * from GMAIL_MESSAGES WHERE(message_from = '" + condition['value'] + "' );") for row in cursor: message_id_list.append(row[1]) if condition['field'] == "to" and condition[ 'predicate'] == "equals": cursor = conn.execute( "SELECT * from GMAIL_MESSAGES WHERE(message_to = '" + condition['value'] + "' );") for row in cursor: message_id_list.append(row[1]) if condition['field'] == "subject" and condition[ 'predicate'] == "equals": cursor = conn.execute( "SELECT * from GMAIL_MESSAGES WHERE(message_subject = '" + condition['value'] + "' );") for row in cursor: message_id_list.append(row[1]) if condition['field'] == "from" and condition[ 'predicate'] == "not_contains": cursor = conn.execute( "SELECT * from GMAIL_MESSAGES WHERE(NOT message_from LIKE '%" + condition['value'] + "%' );") for row in cursor: message_id_list.append(row[1]) if condition['field'] == "to" and condition[ 'predicate'] == "not_contains": cursor = conn.execute( "SELECT * from GMAIL_MESSAGES WHERE(NOT message_to LIKE '%" + condition['value'] + "%' );") for row in cursor: message_id_list.append(row[1]) if condition['field'] == "subject" and condition[ 'predicate'] == "not_contains": cursor = conn.execute( "SELECT * from GMAIL_MESSAGES WHERE(NOT message_subject LIKE '%" + condition['value'] + "%' );") for row in cursor: message_id_list.append(row[1]) if condition['field'] == "from" and condition[ 'predicate'] == "not_equals": cursor = conn.execute( "SELECT * from GMAIL_MESSAGES WHERE(NOT message_from != '" + condition['value'] + "' );") for row in cursor: message_id_list.append(row[1]) if condition['field'] == "to" and condition[ 'predicate'] == "not_equals": cursor = conn.execute( "SELECT * from GMAIL_MESSAGES WHERE(NOT message_to != '" + condition['value'] + "' );") for row in cursor: message_id_list.append(row[1]) if condition['field'] == "subject" and condition[ 'predicate'] == "not_equals": cursor = conn.execute( "SELECT * from GMAIL_MESSAGES WHERE(NOT message_subject != '" + condition['value'] + "' );") for row in cursor: message_id_list.append(row[1]) if condition['field'] == "date" and condition[ 'predicate'] == "less_than_days": cursor = conn.execute( "SELECT * from GMAIL_MESSAGES WHERE message_date >= date('now','-" + condition['value'] + " day') ") for row in cursor: message_id_list.append(row[1]) if condition['field'] == "date" and condition[ 'predicate'] == "greater_than_days": cursor = conn.execute( "SELECT * from GMAIL_MESSAGES WHERE message_date < date('now','-" + condition['value'] + " day') ") for row in cursor: message_id_list.append(row[1]) if condition['field'] == "date" and condition[ 'predicate'] == "less_than_months": cursor = conn.execute( "SELECT * from GMAIL_MESSAGES WHERE message_date >= date('now','-" + condition['value'] + " month') ") for row in cursor: message_id_list.append(row[1]) if condition['field'] == "date" and condition[ 'predicate'] == "greater_than_months": cursor = conn.execute( "SELECT * from GMAIL_MESSAGES WHERE message_date < date('now','-" + condition['value'] + " month') ") for row in cursor: message_id_list.append(row[1]) conn.close()
def GE_main(create, html_val, email_list, require_num): filename = "event.txt" ##Name for local file to save for google calendar event URL and event ID #json_data = jsonToList(json_file_name) #email_list = [ list(json_data.values())[0][i]["Email"] for i in list(json_data.values())[0]] store = file.Storage('token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) #flow = client.flow_from_clientsecrets('OpportunityHack.json', SCOPES) creds = tools.run_flow(flow, store) service = build('calendar', 'v3', http=creds.authorize(Http())) # Call the Calendar API event = { 'summary': 'Test for invitation', 'location': '1216 E Vista Del Cerro Dr,. APT 2103N, Tempe, AZ 85281', 'description': 'Opportunity Hack 2018', 'start': { 'dateTime': '2018-10-22T11:00:00-07:00', 'timeZone': 'America/Phoenix', }, 'end': { 'dateTime': '2018-10-22T11:00:00-07:00', 'timeZone': 'America/Phoenix', }, 'attendees': [], 'sendUpdates': 'all', 'reminders': { 'useDefault': False, 'overrides': [ { 'method': 'email', 'minutes': 24 * 60 }, { 'method': 'popup', 'minutes': 30 }, ], }, } for i in email_list: event['attendees'].append({'email': i}) #print(event) if not create: fs = open(filename, "r+") event_txt = fs.readlines() fs.close() for i, ival in enumerate(event_txt): #print(ival) if ival.replace('\n', '') == html_val: event = service.events().get(calendarId='primary', eventId=event_txt[i + 1].replace( '\n', '')).execute() result_list, accept, reject, not_decide = poll_attend( event_txt[i + 1].replace('\n', ''), service, html_val) ##old_email_list = [] ##for k in event['attendees']: ## old_email_list.append(k['email']) send_email_notify( event['htmlLink'], event['start']['dateTime'][:10] + " " + event['start']['dateTime'][11:17], event['end']['dateTime'][:10] + " " + event['end']['dateTime'][11:17], event['location'], email_list, require_num - accept - reject - not_decide) return result_list print("Event Not Found") return [] else: fs = open(filename, "a+") new_event = service.events().insert(calendarId='primary', body=event).execute() #print(new_event) fs.write(new_event["htmlLink"]) fs.write("\n") fs.write(new_event["id"]) fs.write("\n") send_email_notify( new_event['htmlLink'], new_event['start']['dateTime'][:10] + " " + new_event['start']['dateTime'][11:17], new_event['end']['dateTime'][:10] + " " + new_event['end']['dateTime'][11:17], new_event['location'], email_list, require_num) print("Event Built") return [new_event["htmlLink"]]
def twplaylist(): flow = OAuth2WebServerFlow(yt_id, yt_secret, scope) storage = Storage('credentials.dat') parser = argparse.ArgumentParser(parents=[tools.argparser]) flags = parser.parse_args() credentials = tools.run_flow(flow, storage, flags) if credentials is None or credentials.invalid: credentials = run(flow, storage) global http http = httplib2.Http() http = credentials.authorize(http) global youtube youtube = build('youtube', 'v3', http=http) global twitter twitter = tweepy.API(tweepy.OAuthHandler(t_id, t_secret)) user = twitter.get_user(t_user) last_id = '' while True: try: ytlinks = [] if last_id: print 'Grabbing ' + str( t_count ) + ' latest tweets from ' + user.screen_name + ' since ' + str( last_id) statuses = twitter.user_timeline(id=t_user, since_id=int(last_id), count=t_count) else: print 'Grabbing ' + str( t_count) + ' latest tweets from ' + user.screen_name statuses = twitter.user_timeline(id=t_user, count=t_count) if len(statuses) > 0: last_id = statuses[0].id for status in statuses: if (match in status.text.lower()) and ( status.entities.has_key('urls')): url = status.entities.get('urls')[0].get( 'expanded_url') ytcomlink = re.findall(ytcomReg, url) ytbelink = re.findall(ytbeReg, url) if ytbelink != []: ytlinks += ytbelink if ytcomlink != []: ytlinks += ytcomlink print 'Adding ' + str(len(ytlinks)) + ' video(s)' for video in ytlinks: insert = youtube.playlistItems().insert( part="snippet", body=dict( snippet=dict(playlistId=playlist, resourceId=dict(kind="youtube#video", videoId=video)))) response = insert.execute() else: print 'No new tweets since last attempt' print 'Waiting ' + str(sleep) + ' seconds' time.sleep(int(sleep)) except Exception, e: print e
import platform import psutil from googleapiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools from gmailworker import mailfunctions # We are going to need to get some emails, so we are going to need some gmail api magic. SCOPES = 'https://mail.google.com/' store = file.Storage('token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) creds = tools.run_flow(flow, store) service = build('gmail', 'v1', http=creds.authorize(Http())) print('Email Manager\n' 'TechdudeGames Inc.') print('Checking to make sure that MailWatcher is currently off.') for current_pid in psutil.pids(): try: if ('python' in psutil.Process(current_pid).as_dict()['name']) or ( 'MailWatcher' in psutil.Process(current_pid).as_dict()['name']): proc = psutil.Process(current_pid) proc_data = proc.as_dict() if ('MailWatcher' in proc_data['cmdline'][-1]): proc.kill() print('Found MailWatcher, and killed it.') except psutil._exceptions.NoSuchProcess:
def makeEvent(id, root, inputNeeded=True, summary=None, month=None, day=None, year=None, startTime=None, endTime=None): # Setup the Calendar API SCOPES = 'https://www.googleapis.com/auth/calendar' store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = build('calendar', 'v3', http=creds.authorize(Http()), cache=MemoryCache()) calendar_list_entry = service.calendarList().get(calendarId=id).execute() if inputNeeded: msg1 = 'name of event: ' summary = simpledialog.askstring('name', msg1, parent=root) msg2 = 'what month?' msg3 = 'what day?' msg4 = 'what year?' month = simpledialog.askstring('month', msg2, parent=root) day = simpledialog.askstring('day', msg3, parent=root) year = simpledialog.askstring('year', msg4, parent=root) msg5 = 'when does this event start?' msg6 = 'when does this event end?' startTime = simpledialog.askstring('start', msg5, parent=root) endTime = simpledialog.askstring('end', msg6, parent=root) else: summary = summary month = month day = day year = year startTime = startTime endTime = endTime month = getMonth(month) startTime = timeToMilitary(startTime) first = year + '-' + month + '-' + day + 'T' + startTime + ':00-04:00' endTime = timeToMilitary(endTime) last = year + '-' + month + '-' + day + 'T' + endTime + ':00-04:00' event = { 'summary': summary, 'location': "", 'description': "", 'start': { 'dateTime': first, 'timeZone': "", }, 'end': { 'dateTime': last, 'timeZone': "", }, 'recurrence': [], 'attendees': [], 'reminders': { 'useDefault': False, 'overrides': [ { 'method': 'email', 'minutes': 24 * 60 }, { 'method': 'popup', 'minutes': 10 }, ], }, } event = service.events().insert(calendarId=id, body=event).execute() print('Event created: %s' % (event.get('htmlLink')))
def main(): # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. global service today = datetime.date.today() # Doing authentication store = file.Storage('token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) creds = tools.run_flow(flow, store) service = build('sheets', 'v4', http=creds.authorize(Http())) # Todo: Send mail if authentication failed # Get logging data values = [] # Read fail log if exist --> /var/log/doorphone_fail.log if os.path.isfile(FAIL_LOG): with open(FAIL_LOG, mode='r', encoding='utf-8') as csvfile: rows = csv.reader(csvfile) for row in rows: value = [] # Skipped if name of card is "Test" if row[1] == 'Test': continue # Construct data to write to spreadsheet for each_col in row: value.append(each_col) if len(value) > 0: values.append(value) # Read log file --> /var/log/doorphone.tmp with open(TEMP_LOG, mode='r', encoding='utf-8') as csvfile: rows = csv.reader(csvfile) for row in rows: # Skipped if name of card is "Test" if row[1] == 'Test': continue # Construct data to write to spreadsheet if '{} {}'.format(STR_MONTH_MAP[today.month], str(today.day)).lower() in row[0].lower() \ or '{} {}'.format(STR_MONTH_MAP[today.month], str(today.day)).lower() in row[0].lower(): value = [_compose_date_format(row[0][:16])] for each_col in row[1:-1]: value.append(each_col) if len(value) > 0: values.append(value) # Separate data using year # Check if sheet of year exist --> if not, create new sheet of year try: # Use data to determine which year of sheet to write to first_cell = '{}!A1:A1'.format(today.year) service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID, range=first_cell).execute() except Exception as e: state = _add_new_sheet(SPREADSHEET_ID, str(today.year)) # Add new sheet failed if not state: _write_fail_log(values, FAIL_LOG) # Todo: Send mail if failed sys.exit(11) # Write data to Google Spreadsheet last_row = _get_last_row(SPREADSHEET_ID, '{}{}'.format(today.year, RANGE_FIRST_COL)) write_range = '{}!A{}:E'.format(today.year, last_row + 1) try: if values != []: _write_values(SPREADSHEET_ID, write_range, values) print('Write value success') else: print('No value to write') except Exception as e: print('Exception: {}'.format(e)) _write_fail_log(values, FAIL_LOG) # Todo: Send fail if failed sys.exit(11) else: if os.path.isfile(FAIL_LOG): os.remove(FAIL_LOG)
print "Video '%s' was not found." % video_id sys.exit(1) return videos_list_response["items"][0] flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, message=MISSING_CLIENT_SECRETS_MESSAGE, scope=YOUTUBE_READONLY_SCOPE) storage = Storage("%s-oauth2.json" % sys.argv[0]) credentials = storage.get() if credentials is None or credentials.invalid: flags = argparser.parse_args() credentials = run_flow(flow, storage, flags) youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, http=credentials.authorize(httplib2.Http())) # Retrieve the contentDetails part of the channel resource for the # authenticated user's channel. channels_response = youtube.channels().list(mine=True, part="contentDetails").execute() vid = {} vid['number_videos'] = 0 vid['videos'] = [] for channel in channels_response["items"]:
def get_actual_picks() : # Setup the Gmail API SCOPES = 'https://www.googleapis.com/auth/gmail.readonly' store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret_195389700512-1gscoh1moo86k7878o93pmi7j1l4uiv5.apps.googleusercontent.com.json', SCOPES) creds = tools.run_flow(flow, store) service = build('gmail', 'v1', http=creds.authorize(Http())) # Call the Gmail API results = service.users().labels().list(userId='me').execute() ttt_msgs = service.users().messages().list(userId='me',labelIds=['INBOX'], q="from:[email protected] newer_than:2d").execute() result = pd.DataFrame() if ttt_msgs['resultSizeEstimate'] != 0 : for msg in ttt_msgs['messages']: msg_id = msg['id'] message = service.users().messages().get(userId='me', id=msg_id, format='raw').execute() msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII')) html = msg_str soup = BeautifulSoup(html, "html.parser") table = soup.find("table", attrs={"class": "templateDataTable"}) trs = table.findAll("tr") for tr in trs : tds = tr.findAll("td") if len(tds) > 0 : dict = { 'matchdatetime' : tds[0].text.strip(), 'match' : tds[1].text.strip(), 'winner' : tds[2].text.strip(), 'bet_value' : tds[3].text.strip()[0:4], 'win_proba' : float(tds[5].text.strip()[0:4]), 'at_odd' : float(tds[4].text.strip()), # 'bet_value' : float(tds[6].text.strip()), 'event' : tds[6].text.strip(), 'level' : tds[7].text.strip(), #'html' : html } data = pd.DataFrame([dict]) result = result.append(data, ignore_index=True) return result
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. """ # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. scope = ['https://spreadsheets.google.com/feeds'] creds = ServiceAccountCredentials.from_json_keyfile_name('sync/client_secret.json', scope) client = gspread.authorize(creds) sheet = client.open_by_url( "https://docs.google.com/spreadsheets/d/1Q0OopBJjl5WuxeRNlqpi1V-RGl6PuZbqioPL85bJeSw/edit#gid=0").get_worksheet( 0) name = 'you' nominee = 'nominee_name' relation = 'relation' from oauth2client import file, client, tools store = file.Storage('sync/token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) creds = tools.run_flow(flow, store) """page_token = None while True: calendar_list = service.calendarList().list(pageToken=page_token).execute() for calendar_list_entry in calendar_list['items']: print(calendar_list_entry.items()) print() print() page_token = calendar_list.get('nextPageToken') if not page_token: break """ ##############################################Start from here############################################# calendarId_record = '*****@*****.**' calendarId_surgeries='*****@*****.**' calendarId_important = '*****@*****.**' service = build('calendar', 'v3', http=creds.authorize(Http())) page_token = None ids=sheet.col_values(21) row=sheet.row_values(6) row_to_update = len(ids)+1 for calendarId in [calendarId_record, calendarId_surgeries, calendarId_important ]: eventss = service.events().list(calendarId=calendarId, pageToken=page_token).execute() for key, value in eventss.items(): try: for key, value in value.items(): print(key,value) print() events_u=events['description'],events['htmlLink'] except: pass for event in eventss['items']: if event['id'] not in ids: row_to_update = row_to_update +1 time.sleep(1) if calendarId==calendarId_surgeries: sheet.update_cell(row_to_update, 16, 'no') sheet.update_cell(row_to_update, 19, 'Democalender') if calendarId==calendarId_important: sheet.update_cell(row_to_update, 16, 'no') sheet.update_cell(row_to_update, 19, 'Important') if calendarId==calendarId_record: sheet.update_cell(row_to_update, 16, 'yes') sheet.update_cell(row_to_update, 19, 'Records') sheet.update_cell(row_to_update, 21, event['id']) time.sleep(1) date_s = str(event['start']) ab=str(date_s[14:24]) bc= str(date_s[26:39]) try: loct = str(event['location']) sheet.update_cell(row_to_update, 10, loct) print(loct) except: pass sheet.update_cell(row_to_update, 16, str(event['reminders']["overrides"][0]["method"])) sheet.update_cell(row_to_update, 11, ab) time.sleep(1) sheet.update_cell(row_to_update, 13, bc) date_e = str(event['end']) print (date_e) de=str(date_s[14:24]) sheet.update_cell(row_to_update, 12, de) ef= str(date_s[26:39]) time.sleep(1) sheet.update_cell(row_to_update, 14, ef) des = str(event['description']).split("\n") print("Updating", event["id"]) a= str(des[1]) sheet.update_cell(row_to_update,1, a[10:]) b= str(des[2]) sheet.update_cell(row_to_update,2, b[8:]) time.sleep(1) c= str(des[3]) sheet.update_cell(row_to_update,3, c[9:]) d= str(des[4]) sheet.update_cell(row_to_update,4, d[5:]) e= str(des[5]) time.sleep(1) sheet.update_cell(row_to_update,6, e[24:]) f= str(des[6]) sheet.update_cell(row_to_update,7, f[12:]) time.sleep(1) sheet.update_cell(row_to_update, 20, event['htmlLink']) else: print("already Updating", event["id"])
def index(): organizer=request.args.get("organizer") starttime=request.args.get("starttime") endtime=request.args.get("endtime") meetingRoomAccount=request.args.get("meetingRoomAccount") home_dir = os.getcwd() credential_dir = os.path.join(home_dir, 'credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, '%s.dat' % (organizer)) storage = Storage(credential_path) # storage=Storage('anna.dat') credentials = storage.get() if credentials is None or credentials.invalid: credentials = tools.run_flow(flow, storage, tools.argparser.parse_args()) http = httplib2.Http() http = credentials.authorize(http) service = build('calendar', 'v3', http=http) # page_token=None # while True: # calendar_list=service.calendarList().list(pageToken=page_token).execute() # for calendar_list_entry in calendar_list['items']: # CalendarID=calendar_list_entry['id'] # CalendarName=calendar_list_entry['summary'] # print (CalendarID) # page_token=calendar_list.get('nextPageToken') # if not page_token: # break try: event = { 'summary': 'Meeting Invitation', 'description': 'A chance to hear more about Google\'s developer products.', 'start': { # 'dateTime': '2018-05-29T09:00:00-07:00', 'dateTime':'%s'%(starttime) # 'timeZone': "America/Los_Angeles", }, 'end': { # 'dateTime': '2018-05-29T18:00:00-07:00', 'dateTime':'%s'%(endtime) # 'timeZone': "America/Los_Angeles", }, 'attendees': [ {'email': '%s'%(meetingRoomAccount)} ], } even = service.events().insert(calendarId=organizer, body=event).execute() url=even.get('htmlLink') # print 'Event created: %s' % (even.get('htmlLink')) # webbrowser.open(url) return redirect(url) except AccessTokenRefreshError: print ('The credentials have been revoked or expired, please re-run' 'the application to re-authorize')
def authorize_new_account(self): store = Storage( os.path.join( self.settings.settings[app.src.config.MAIL_ACCOUNT_CREDS])) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(self.CLIENT_SCERET_PATH, SCOPES) flow.user_agent = USER_AGENT credentials = tools.run_flow(flow, store) if __name__ == '__main__': _store = Storage(os.path.join('../credentials/mail_account_secret.json')) _credentials = _store.get() if not _credentials or _credentials.invalid: flow = client.flow_from_clientsecrets( '../credentials/client_secret_637398666132-j8s19q7egap0u79l894jmuhauiv39ec7.apps.googleusercontent.com.json', ['https://www.googleapis.com/auth/gmail.send']) flow.user_agent = "LabSupport" _credentials = tools.run_flow(flow, _store) flow = AccessTokenCredentials( '../credentials/mail_account_secret.json', ['https://www.googleapis.com/auth/gmail.send']) # creds = ServiceAccountCredentials.from_json_keyfile_name('.gmail-api.json', ['https://www.googleapis.com/auth/gmail.send']) # creds = flow.run_local_server(port=0) # mail = EmailWriter(credentials) # mail.send_message( # mail.create_message("*****@*****.**", "*****@*****.**", "TEST", "TEST"))
# applications # The client_id and client_secret can be found in Google Developers Console FLOW = OAuth2WebServerFlow(client_id='your_project_id', client_secret='your_project_secret', scope='https://www.googleapis.com/auth/calendar', user_agent='Voice Task notifications/v1') # To disable the local server feature, uncomment the following line: # FLAGS.auth_local_webserver = False # If the Credentials don't exist or are invalid, run through the native client # flow. The Storage object will ensure that if successful the good # Credentials will get written back to a file. storage = Storage('credentials.dat') credentials = storage.get() if credentials is None or credentials.invalid == True: credentials = tools.run_flow(FLOW, storage) # Create an httplib2.Http object to handle our HTTP requests and authorize it # with our good Credentials. http = httplib2.Http() http = credentials.authorize(http) # Build a service object for interacting with the API. Visit # the Google Developers Console # to get a developerKey for your own application. service = build(serviceName='calendar', version='v3', http=http, developerKey='your_API_key')
# Check https://developers.google.com/gmail/api/auth/scopes # for all available scopes OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.readonly' # Location of the credentials storage file STORAGE = Storage('gmail.storage') # Start the OAuth flow to retrieve credentials flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=OAUTH_SCOPE) http = httplib2.Http() # Try to retrieve credentials from storage or run the flow to generate them credentials = STORAGE.get() if credentials is None or credentials.invalid: credentials = run_flow(flow, STORAGE, flags, http=http) # Authorize the httplib2.Http object with our credentials http = credentials.authorize(http) # Build the Gmail service from discovery gmail_service = build('gmail', 'v1', http=http) # Retrieve a page of threads threads = gmail_service.users().threads().list(userId='me').execute() # Print ID for each thread if threads['threads']: for thread in threads['threads']: print 'Thread ID: %s' % (thread['id'])
# > Google App Engine Admin API) CLIENT_ID = 'id' CLIENT_SECRET = 'secret' # Priority to begin inserting dos rules MAX_PRIORITY = 2147483646 # Get an access token to authenticate our request. flow = OAuth2WebServerFlow( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, scope= 'https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/cloud-platform', redirect_uri='http://example.com/oauth2callback') storage = Storage('creds.data') credentials = run_flow(flow, storage) credentials = storage.get() # Fetch the app's firewall config. url = 'https://appengine.googleapis.com/v1/apps/{}/firewall/ingressRules?pageSize=1000'.format( PROJECT) response = requests.get( url, headers={'Authorization': 'Bearer ' + credentials.access_token}) if (response.status_code != requests.codes.ok): print('Bad response. Could not retrieve firewall config.') exit() firewall_json = response.json() print('Original Firewall Config:') print(json.dumps(firewall_json))
def uploadtask(request): if request.method == 'POST': """ Request is what the client is sending to the user. A POST request means the client is POSTing or trying to WRITE in the server. """ code = str(request.POST.get('course_code')).lower() course_data = COURSE.objects.filter(code=code).first() if not course_data: course_data = COURSE(name=str( request.POST.get('course_name')).lower(), code=code) course_data.save() else: course_data.date = datetime.now() course_data.save() paper_data = PAPER( paper_type=str(request.POST.get('paper_type')).lower(), paper_year=str(request.POST.get('paper_year')).lower(), course=course_data) paper_data.save() paper_upload_data = PAPER_UPLOAD(paper=paper_data, uploader=request.user) # 02/01/2019 paper_upload_data.save() # If the form is submitted # This is the API set up thing SCOPES = "https://www.googleapis.com/auth/drive" store = file.Storage('credentials.json') creds = store.get() flags = tools.argparser.parse_args(args=[]) if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store, flags) # since v3 does not support parents, i had to switch back to v2. To use v3, we need to use files.list to get the folder where # we want to upload the file (must be public folder) service = discovery.build('drive', 'v2', http=creds.authorize(Http())) # In settings.py I have added a line FILE_UPLOAD_MAX_MEMORY_SIZE = 0, by this all files added as Temporary files # As in a temporary file is created for each upload # Get the temporary uploaded file, request.FILES contain all the files in the request stream, in the form, the file was named myfile to_upload = request.FILES.get('myfile') file_metadata = { 'title': course_data.code + '_' + paper_data.paper_year + '_' + paper_data.paper_type, 'parents': [{ 'id': '1t2xyHEJ6U7z-e59e6m4Ao4gGTNOc9YHD' }] } # temporary file path and content_type are methods # Temporary files have an attritube temporary_file_path which returns the file path for the temporary file media = MediaFileUpload(to_upload.temporary_file_path(), mimetype=to_upload.content_type) filee = service.files().insert(body=file_metadata, media_body=media, fields='id').execute() # Close the file to_upload.close() file_data = FILE( paper_upload=paper_upload_data, file_url=filee.get('id'), # Retrieve the ID file_name=course_data.code + '_' + paper_data.paper_year + '_' + paper_data.paper_type) file_data.save() return render(request, 'uploadfile/basic.html', {"display": filee.get('id')}) else: return render(request, 'uploadfile/home.html', {})
def allocate(self): _translate = QtCore.QCoreApplication.translate # Connect to Google API store = file.Storage('token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) creds = tools.run_flow(flow, store) service = build('sheets', 'v4', http=creds.authorize(Http())) while self.allow_run: result = service.spreadsheets().values().get(spreadsheetId=self.SPREADSHEET_ID, range = (self.RANGE_NAME_1 + str(self.curr_row_1) + ':' + chr(ord(self.RANGE_NAME_1[-1]) + 2))).execute() values = result.get('values', []) result = service.spreadsheets().values().get(spreadsheetId=self.SPREADSHEET_ID, range = (self.RANGE_NAME_2 + str(self.curr_row_2) + ':B')).execute() done = result.get('values', []) self.curr_row_1 = self.curr_row_1 + len(values) self.curr_row_2 = self.curr_row_2 + len(done) if done: for row in done: if row: self.free[int(row[0][0]) - 1] = 1 self.occupancy[int(row[0][0]) - 1] = [] if not values: print('No data found.') else: #print('Name, Major:') for row in values: if row: # Print columns A and E, which correspond to indices 0 and 4. print('%s, %s, %s' % (row[0], row[1], row[2])) items = row[2].split(', ') for item in items: self.TAs[int(item[0]) - 1].append([row[0].upper(), row[1]]) for i in range(0, self.count): if ((self.free[i] == 1) and (self.TAs[i])): j = 0 while (len(self.TAs[i]) > j) and (self.TAs[i][j][0] in [sublist[0] if sublist else [] for sublist in self.occupancy]): j = j + 1 if (j == len(self.TAs[i])): continue if not (self.TAs[i][j][0] in [sublist[0] if sublist else [] for sublist in self.occupancy]): self.occupancy[i] = self.TAs[i][j] self.TAs[i].pop(j) self.free[i] = 0 print(self.TAs) print(self.free) print([sublist[0] if sublist else [] for sublist in self.occupancy]) for i in range(0, self.count * 3): if (i % 3 == 1): self.labels[i].setText(_translate("MainWindow", str(self.occupancy[i // 3][0] if self.occupancy[i // 3] else ''))) if (i % 3 == 2): self.labels[i].setText(_translate("MainWindow", str(self.occupancy[i // 3][1] if self.occupancy[i // 3] else ''))) for i in range(0, self.count): self.lcds[i].setProperty("intValue", len(self.TAs[i])) time.sleep(4)
def init(argv, name, version, doc, filename, scope=None, parents=[], discovery_filename=None): """A common initialization routine for samples. Many of the sample applications do the same initialization, which has now been consolidated into this function. This function uses common idioms found in almost all the samples, i.e. for an API with name 'apiname', the credentials are stored in a file named apiname.dat, and the client_secrets.json file is stored in the same directory as the application main file. Args: argv: list of string, the command-line parameters of the application. name: string, name of the API. version: string, version of the API. doc: string, description of the application. Usually set to __doc__. file: string, filename of the application. Usually set to __file__. parents: list of argparse.ArgumentParser, additional command-line flags. scope: string, The OAuth scope used. discovery_filename: string, name of local discovery file (JSON). Use when discovery doc not available via URL. Returns: A tuple of (service, flags), where service is the service object and flags is the parsed command-line flags. """ if scope is None: scope = 'https://www.googleapis.com/auth/' + name # Parser command-line arguments. parent_parsers = [tools.argparser] parent_parsers.extend(parents) parser = argparse.ArgumentParser( description=doc, formatter_class=argparse.RawDescriptionHelpFormatter, parents=parent_parsers) flags = parser.parse_args(argv[1:]) # Name of a file containing the OAuth 2.0 information for this # application, including client_id and client_secret, which are found # on the API Access tab on the Google APIs # Console <http://code.google.com/apis/console>. client_secrets = os.path.join(os.path.dirname(filename), 'client_secrets.json') # Set up a Flow object to be used if we need to authenticate. flow = client.flow_from_clientsecrets(client_secrets, scope=scope, message=tools.message_if_missing(client_secrets)) # Prepare credentials, and authorize HTTP object with them. # If the credentials don't exist or are invalid run through the native client # flow. The Storage object will ensure that if successful the good # credentials will get written back to a file. storage = file.Storage(name + '.dat') credentials = storage.get() if credentials is None or credentials.invalid: credentials = tools.run_flow(flow, storage, flags) http = credentials.authorize(http = httplib2.Http()) if discovery_filename is None: # Construct a service object via the discovery service. service = discovery.build(name, version, http=http) else: # Construct a service object using a local discovery document file. with open(discovery_filename) as discovery_file: service = discovery.build_from_document( discovery_file.read(), base='https://www.googleapis.com/', http=http) return (service, flags)
def make_appointment(request): ''' Add a new appointment to the database Also creates a new appointment in the doctors calendar @param request json object with the elements: patient startDate endDate doctor description summary location @return json object with elements: status action id ''' # If modifying these scopes, delete the file token.json. SCOPES = 'https://www.googleapis.com/auth/calendar' store = file.Storage('token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('calendar-config.json', SCOPES) creds = tools.run_flow(flow, store) service = build('calendar', 'v3', http=creds.authorize(Http())) try: patient_id = request.json['patient'] startDate = request.json['startDate'] endDate = request.json['endDate'] doctor_id = request.json['doctor'] description = request.json['description'] summary = request.json['summary'] location = request.json['location'] doctor = Doctor.query.filter_by(id=doctor_id) doctor_result = doctor_schema.dump(doctor).data if len(doctor_result) < 1: raise ValueError doctor_result = doctor_result[0] patient = Patient.query.filter_by(id=patient_id) patient_result = patient_schema.dump(patient).data if len(patient_result) < 1: raise ValueError patient_result = patient_result[0] time_start = "{}".format(startDate) time_end = "{}".format(endDate) new_appointment = Appointment(patient_id, doctor_id, time_start, time_end) db.session.add(new_appointment) db.session.commit() event = { 'summary': summary, 'location': location, 'description': description, 'start': { 'dateTime': time_start, 'timeZone': 'Australia/Melbourne', }, 'end': { 'dateTime': time_end, 'timeZone': 'Australia/Melbourne', }, 'reminders': { 'useDefault': False, 'overrides': [ {'method': 'email', 'minutes': 5}, {'method': 'popup', 'minutes': 10}, ], }, 'attendees': [ { 'email': doctor_result['email'], 'email': patient_result['email'] } ], 'transparency': 'opaque' } calendarID = doctor_result['calendarID'] print(calendarID) event = service.events().insert(calendarId=calendarID, body=event).execute() print('Event created: {}'.format(event.get('htmlLink'))) response = jsonify({"status": "Successful", "action": "make-appointment", "id": patient_id}) response.status_code = 200 except ValueError: response = jsonify({"status": "failed", "action": "make-appointment", "id": patient_id}) response.status_code = 200 finally: return response
def get_availability(request): ''' Return availability of doctors on certain day @param request json object with elements: date doctorID @return json object: availability busy [] ''' # If modifying these scopes, delete the file token.json. SCOPES = 'https://www.googleapis.com/auth/calendar' store = file.Storage('token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('calendar-config.json', SCOPES) creds = tools.run_flow(flow, store) service = build('calendar', 'v3', http=creds.authorize(Http())) try: doctor_id = request.json['doctorID'] date = datetime.strptime(request.json['date'], "%Y-%m-%d") day = date.weekday() doctor_availability = DoctorAvailability.query.filter_by(doctor_id = doctor_id, day = day) doctor_availability_result = doctor_availability_schema.dump(doctor_availability).data if len(doctor_availability_result) < 1: raise ValueError doctor_availability_result = doctor_availability_result[0] startTime = doctor_availability_result['startTime'] endTime = doctor_availability_result['endTime'] doctor = Doctor.query.filter_by(id=doctor_id) doctor_result = doctor_schema.dump(doctor).data if len(doctor_result) < 1: raise ValueError doctor_result = doctor_result[0] dateString = date.strftime("%Y-%m-%d") start_time = "{0}T{1}:00+10:00".format(dateString, startTime) end_time = "{0}T{1}:00+10:00".format(dateString, endTime) freebusy = { "timeMin": start_time, "timeMax": end_time, "items": [ { "id": doctor_result['calendarID'] } ], "timeZone": "Australia/Melbourne" } freebusyResponse = service.freebusy().query(body=freebusy).execute() response = jsonify({"availability": doctor_availability_result, "busy": freebusyResponse['calendars'][doctor_result['calendarID']]['busy']}) response.status_code = 200 except ValueError: response = jsonify({"status": "failed", "action": "get doctor's availability", "id": doctor_id}) response.status_code = 404 finally: return response
CLIENT_SECRET_FILE = 'client_secret.json' # Check https://developers.google.com/gmail/api/auth/scopes for all available scopes OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.compose' # Location of the credentials storage file STORAGE = Storage('gmail.storage') # Start the OAuth flow to retrieve credentials flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=OAUTH_SCOPE) http = httplib2.Http() # Try to retrieve credentials from storage or run the flow to generate them credentials = STORAGE.get() if credentials is None or credentials.invalid: credentials = tools.run_flow(flow, STORAGE, http=http) # Authorize the httplib2.Http object with our credentials http = credentials.authorize(http) # Build the Gmail service from discovery gmail_service = build('gmail', 'v1', http=http) # create a message to send message = MIMEText("Hello sent from GMAIL API 2") message['to'] = "*****@*****.**" message['from'] = "*****@*****.**" message['subject'] = "Mail" encoded_message = message.as_string().encode( ) #base64.b64encode(message.as_string()) body = {'raw': encoded_message}
def send_reminder(): # parser = argparse.ArgumentParser(description='Send reminder email based on spreadsheet') # parser.add_argument('--TEST_MODE', action='store_true', help='whether to run as test (send to personal email)') # parser.add_argument('--LTR', action='store_true', help='send email based on LTR lineup (as opposed to normal lineup)') # args = parser.parse_args() TEST_MODE = False #if not LTR: DAYS = {a: b for (a, b) in zip(range(5), range(5))} # M-F K_LENGTH = 10 COL_END = 'G' K_START = 6 SHEET = 'Daily schedule' #GID = 1189084842 #TO=['*****@*****.**'] GID = 0 # else: # DAYS = {2:0,4:1} # Wednesday/Friday # COL_END = 'F' # K_LENGTH = 16 # K_START = 6 # SHEET = 'LTR Daily Schedule' # #GID = 463043139 # #TO=['*****@*****.**','*****@*****.**', '*****@*****.**'] # GID = 0 TO = ['*****@*****.**'] #TO=['*****@*****.**'] SPREADSHEET_ID = '1yL8V9il2mUJPEoQyS_hzUBkoVe95V-B9_n9bf_nlHAI' SPREADSHEET_LINK = 'https://docs.google.com/spreadsheets/d/{sid}/edit#gid={gid}'.format( sid=SPREADSHEET_ID, gid=GID) def get_cell_range(ts): ''' use the timestamp for the day you want, not for the email day''' idx = DAYS[ts.dayofweek] start = K_START + idx * K_LENGTH ## eg. Monday => dayofweek=0 => answer=A6:H15 end = start + K_LENGTH - 1 return 'A{start}:{col_end}{end}'.format(start=start, col_end=COL_END, end=end) curr_ts = pd.Timestamp.today(tz='EST') row_ts = curr_ts + pd.to_timedelta('1 day') if row_ts.dayofweek not in DAYS.keys(): print('no need to send reminder right now: ', curr_ts) return 0 if row_ts.dayofweek == 1 or row_ts.dayofweek == 3: LTR = True else: LTR = False store = file.Storage('token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets( 'client_secret_241639964710-2c1vfpe75d0tli34iktut2buo1gdi39r.apps.googleusercontent.com.json', SCOPES) creds = tools.run_flow(flow, store) service = build('sheets', 'v4', http=creds.authorize(Http())) cell_range = get_cell_range(row_ts) range_name = '{sheet}!{cell_range}'.format(sheet=SHEET, cell_range=cell_range) result = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID, majorDimension='COLUMNS', range=range_name).execute() values = result.get('values', []) print(values) if not values: print('No data found.') df = process_values(values) stl, tab = render_table(df) if LTR: DAYS = {1: 0, 3: 1} # Tuesday/Thursday COL_END = 'F' K_LENGTH = 16 K_START = 7 SHEET = 'LTR Daily Schedule' def get_cell_range(ts): ''' use the timestamp for the day you want, not for the email day''' idx = DAYS[ts.dayofweek] start = K_START + idx * K_LENGTH ## eg. Monday => dayofweek=0 => answer=A6:H15 end = start + K_LENGTH - 1 return 'A{start}:{col_end}{end}'.format(start=start, col_end=COL_END, end=end) curr_ts = pd.Timestamp.today(tz='EST') row_ts = curr_ts + pd.to_timedelta('1 day') cell_range = get_cell_range(row_ts) range_name = '{sheet}!{cell_range}'.format(sheet=SHEET, cell_range=cell_range) result = service.spreadsheets().values().get( spreadsheetId=SPREADSHEET_ID, majorDimension='COLUMNS', range=range_name).execute() values = result.get('values', []) print(values) if not values: print('No data found.') df = process_values(values) stl_ltr, tab_ltr = render_table(df) if not LTR: template = """ <html> <head> {style} </head> <body> {test_disclaimer}<br/> Hi everyone,<br/><br/> The schedule for tomorrow, {friendly_date}, is below. The full week's schedule can be found here:<br/><br/> {sheet_url}<br/><br/> Everyone listed below should be downstairs in the boathouse by 5:55 am, ready to be on the water at 6am. Please note that this is not a lineup. The coaches will set the lineup in the morning, and may switch people between boats. <br/> <br/> {table} <br/> <br/> Happy rowing and GO TECH!<br/> -Your friendly MITRC bot<br/><br/> This is an auto-generated email. Contact [email protected] if you have trouble viewing this email. Contact [email protected] if you have any questions about the schedule.<br/><br/> MITRC is on Instagram: https://www.instagram.com/mitrowingclub/ and Facebook: https://www.facebook.com/mitrowingclub/ <br/><br/> Useful rowing resources on MITRC website: https://rowingclub.mit.edu <br/><br/> Be friends outside rowing? Join MITRC WhatsApp chat: https://chat.whatsapp.com/5Hvfdpxpcl87V3iARcMCWs </body> </html> """ else: template = """ <html> <head> {style} {stl_ltr} </head> <body> {test_disclaimer}<br/> Hi everyone,<br/><br/> The schedule for tomorrow, {friendly_date}, is below. The full week's schedule can be found here:<br/><br/> {sheet_url}<br/><br/> Everyone listed below should be downstairs in the boathouse by 5:55 am, ready to be on the water at 6am. Please note that this is not a lineup. The coaches will set the lineup in the morning, and may switch people between boats. <br/> <br/> {table_ltr} <br/> <br/> {table} <br/> <br/> Happy rowing and GO TECH!<br/> -Your friendly MITRC bot<br/><br/> This is an auto-generated email. Contact [email protected] if you have trouble viewing this email. Contact [email protected] if you have any questions about the schedule.<br/><br/> MITRC is on Instagram: https://www.instagram.com/mitrowingclub/ and Facebook: https://www.facebook.com/mitrowingclub/ <br/><br/> Useful rowing resources on MITRC website: https://rowingclub.mit.edu <br/><br/> Be friends outside rowing? Join MITRC WhatsApp chat: https://chat.whatsapp.com/5Hvfdpxpcl87V3iARcMCWs </body> </html> """ sheet_url = '{base_link}&range={cell_range}'.format( base_link=SPREADSHEET_LINK, cell_range=cell_range) friendly_date = '{day_name} {month_name} {day_number}'.format( day_name=row_ts.day_name(), month_name=row_ts.month_name(), day_number=row_ts.day) if LTR: message_text = template.format( sheet_url=sheet_url, table=tab, table_ltr=tab_ltr, style=stl, stl_ltr=stl_ltr, friendly_date=friendly_date, test_disclaimer='(this email is a test, pls ignore)' if TEST_MODE else '') else: message_text = template.format( sheet_url=sheet_url, table=tab, style=stl, friendly_date=friendly_date, test_disclaimer='(this email is a test, pls ignore)' if TEST_MODE else '') service = build('gmail', 'v1', http=creds.authorize(Http())) message = MIMEText(message_text, _subtype='html') #to_list = ['*****@*****.**'] if args.TEST_MODE else (TO + ['*****@*****.**']) to_list = ['*****@*****.**'] if TEST_MODE else (TO + ['*****@*****.**']) message['to'] = ','.join(to_list) # message['bcc'] = '*****@*****.**' message[ 'subject'] = '[MITRC] Daily reminder for {friendly_date}{test_mode}'.format( friendly_date=friendly_date, test_mode=' (Test email)' if TEST_MODE else '') ret = { 'raw': "".join( map(chr, base64.urlsafe_b64encode(message.as_string().encode()))) } try: message = (service.users().messages().send(userId='me', body=ret).execute()) print('Message Id: %s' % message['id']) except errors.HttpError as error: print('An error occurred: %s' % error)
def main(): store = file.Storage('token.json') #File generated after google authentication creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) #Credentials from google calendar api creds = tools.run_flow(flow, store) service = build('calendar', 'v3', http=creds.authorize(Http())) events = service.events().list(calendarId=calendarID).execute() driver = webdriver.Firefox() #Designate which browser for selenium to open driver.get(workSite) driver.find_element_by_id(inputUserID).send_keys(userName) driver.find_element_by_id(inputPassID).send_keys(password) driver.find_element_by_id(submitID).click() locales = driver.find_elements_by_xpath("//span[@class='hours']") #Xpath to html element that has the hours for i in range(len(locales)): time = locales[i].text other = locales[i].find_elements_by_xpath("..") other = other[0].find_elements_by_xpath(".//div[1]") #Xpath to get the date for work if len(other) > 0: date = other[0].text #get only first time slot time = time.split('-') endTime = time[1] endTime = endTime[1:] time = time[0] time = time[:-1] #parse times if time[-1:] == 'a': time = time[:-1] mini = time.split(':')[1] if int(mini) < startOffset: leftOver = startOffset - int(mini) mini = 60 - leftOver hrDif = -1 else: mini = int(mini) - startOffset hr = time.split(':')[0] hr = int(hr) + hrDif hr = str(hr) if int(hr) < 10: hr = '0' + hr elif time[-1:] == 'p': time = time[:-1] mini = time.split(':')[1] if int(mini) < 30: leftOver = 30 - int(mini) mini = 60 - leftOver hrDif = -1 else: mini = int(mini) - 30 hr = time.split(':')[0] hr = int(hr) + hrDif hr = int(hr) + 12 if endTime.find('a') > 0: endTime = endTime[:endTime.find('a')] endMini = endTime.split(':')[1] endHr = endTime.split(':')[0] endHr = str(endHr) if int(endHr) < 10: endHr = '0' + endHr elif endTime.find('p') > 0: endTime = endTime[:endTime.find('p')] endMini = endTime.split(':')[1] endHr = endTime.split(':')[0] endHr = int(endHr) + 12 hr = str(hr) mini = str(mini) endHr = str(endHr) endMini = str(endMini) #parse dates month = str(date.split('/')[0]) day = str(date.split('/')[1]) event = { 'summary' : 'Work', 'start' : { 'dateTime' : '2018-' + month + '-' + day + 'T' + hr + ':' + mini + ':00' + timeZoneOffset, 'timeZone': timeZone, }, 'end': { 'dateTime': '2018-' + month + '-' + day + 'T' + endHr + ':' + endMini + ':00' + timeZoneOffset, 'timeZone': timeZone, } } #Ensure that events don't get duplicated upload = True for prevEvent in events['items']: if event['start'] == prevEvent['start']: upload = False #Upload events to calendar if upload: event = service.events().insert(calendarId = calendarID, body=event).execute() driver.close()
# Credit: https://medium.com/@butteredwaffles # Original code found from: https://medium.com/@butteredwaffles/working-with-google-calendar-api-8121d5048597 from googleapiclient.discovery import build from oauth2client import file, client, tools from datetime import datetime import httplib2 # To disable TLS/SSL for testing (security warning! This will temporarily remove the capability of TLS/SSL transport security enforcement) my_http = httplib2.Http(disable_ssl_certificate_validation=True) #my_http = httplib2.Http(ca_certs='./burp.pem') # For self-signed cert, uncomment, and comment the line before this. SCOPES = "https://www.googleapis.com/auth/calendar.readonly" store = file.Storage('token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) creds = tools.run_flow(flow, store, http=my_http) service = build('calendar', 'v3', http=creds.authorize(my_http))
print("Updating event") setEvent(event, calendarId, calendar) try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None SCOPES = 'https://www.googleapis.com/auth/calendar' store = file.Storage('storage.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store, flags) \ if flags else tools.run(flow, store) CAL = build('calendar', 'v3', http=creds.authorize(Http())) GMT_OFF = '-07:00' # PDT/MST/GMT-7 #cases EVENT, calendarId, command = readJson('json/set') #set #EVENT,calendarId,command= readJson('json/cancel') #cancle #EVENT,calendarId,command= readJson('json/rescdule') #reschedule if command == Command.Set: setEvent(EVENT, calendarId, CAL) elif command == Command.Cancel: cancelEvent(EVENT, calendarId, CAL) else:
def events(frame, put): identity_keywords = ["who are you", "who r u", "what is your name"] youtube_keywords = ("play ", "stream ", "queue ") launch_keywords = ["open ", "launch "] search_keywords = ["search "] wikipedia_keywords = ["wikipedia ", "wiki "] location_keywords = ["locate", "spot"] check_keywords = [ "what", "when", "was", "how", "has", "had", "should", "would", "can", "could", "cool", "good" ] #could or cool or good download_music = ("download ", "download music ") search_pc = ("find ", "lookfor ") graph_generation = ("draw graph for ") close_keywords = ("close ", "over ", "stop ", "exit ") pc_locations = ("desktop", "documents", "downloads") put = put.lower() link = put.split() #translate if link[0] == "translate" and link[-2] == "to": translator = Translator() pystring = " ".join(link[1:-2]) lang = detect(pystring) if link[-1] == "english": id = "en" elif link[-1] == "spanish": id = "es" elif link[-1] == "french": id = "fr" elif link[-1] == "german": id = "de" elif link[-1] == "italian": id = "it" elif link[-1] == "portugese" or link[-1] == "portuguese": id = "pt" else: id = "en" translated = translator.translate(pystring, src=lang, dest=id) print(translated.text) try: speak.say("The translated text is " + translated.text) speak.runAndWait() except: print("Error speaking, here is the translated text: {}".format( translated.text)) #Add user for face detection elif link[0] == "face" or link[0] == "phase": name = link[1] path = 'C:/dataset' cam = cv2.VideoCapture(0) ret, img = cam.read() cv2.imwrite(path + "/" + str(name) + ".jpg", img) cam.release() cv2.destroyAllWindows() #Get lyrics elif link[0] == "lyrics": link = '+'.join(link[1:]) link = link.replace('+', ' ') title = link[1:] goog_search = "https://www.google.com/search?q=" + title + "+lyrics" r = requests.get(goog_search) soup = BeautifulSoup(r.text, "html.parser") webbrowser.open(soup.find('cite').text) #Get top 10 tweets elif link[0] == "get" and link[-1] == "tweets": auth = OAuthHandler(twitterCredentials.consumer_key, twitterCredentials.consumer_secret) auth.set_access_token(twitterCredentials.access_token, twitterCredentials.access_secret) api = tweepy.API(auth) if link[-2] == "my": for tweet in tweepy.Cursor(api.user_timeline).items(10): print("\n", json.dumps(tweet.text)) print("on ", tweet.created_at) elif link[1] == "tweets": for status in tweepy.Cursor(api.home_timeline).items(10): print("\n", status.text) print("By ", status.user.screen_name, " at ", status.user.created_at) #Get friends from twitter elif link[-1] == "twitter": if link[-3] == "follow" and link[-1] == "twitter": auth = OAuthHandler(twitterCredentials.consumer_key, twitterCredentials.consumer_secret) auth.set_access_token(twitterCredentials.access_token, twitterCredentials.access_secret) api = tweepy.API(auth) for friend in tweepy.Cursor(api.friends).items(): print("\nName: ", json.dumps(friend.name), " Username: "******"screenshot"): try: pic = pyautogui.screenshot() spath = os.path.expanduser('~') + '/Desktop/screenshot.jpg' pic.save(spath) except: print("Unable to take screenshot.") #Upcoming events elif put.startswith("upcoming events") or put.startswith( "coming events") or put.startswith("events"): try: SCOPES = 'https://www.googleapis.com/auth/calendar.readonly' store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = build('calendar', 'v3', http=creds.authorize(Http())) now = datetime.datetime.utcnow().isoformat( ) + 'z' # 'Z' indicates UTC time root = tk.Tk() root.title("Top 10 Upcoming 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: w = tk.Label(root, text="No upcoming events found.") w.pack() w = tk.Label(root, text="Event Title") w.grid(row=0, column=1) w = tk.Label(root, text="Time And Date Of Event") w.grid(row=0, column=2) i = 1 for event in events: start = event['start'].get('dateTime', event['start'].get('date')) w = tk.Label(root, text=event['summary']) w.grid(row=i, column=1) w = tk.Label(root, text=start) w.grid(row=i, column=2) i = i + 1 root.geometry("400x400") root.mainloop() except: print("Unable to take upcoming events") #Add note elif put.startswith("note") or put.startswith("not") or put.startswith( "node"): try: check = link[1] username = os.getlogin() filename = "Notes.txt" f1 = open( r'''C:\Users\{0}\Desktop\{1}'''.format(username, filename), 'a') link = '+'.join(link[1:]) text = link.replace('+', ' ') text = text[0].capitalize() + text[1:] if check in check_keywords: text += "?" else: text += "." f1.write(text) f1.write("\n") f1.close() speak.say("Note added successfully!") speak.runAndWait() except: print("Could not add the specified note!") #adding an event in google calendar elif link[0] == "add" and link[1] == "event": try: try: import argparse flags = argparse.ArgumentParser( parents=[tools.argparser]).parse_args() except ImportError: flags = None SCOPES = 'https://www.googleapis.com/auth/calendar' CLIENT_SECRET_FILE = 'Client_Secret.json' APPLICATION_NAME = 'GSSOC ' def get_credentials(): home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join( credential_dir, 'calendar-python-quickstart.json') store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets( CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials def main(): credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', 'v3', http=http) summary = link[2] d = link[-3] e = link[-1] date = d + "T00:00:00-07:00" end = e + "T00:00:00-07:00" event = { 'summary': summary, 'start': { 'dateTime': date, }, 'end': { 'dateTime': end, }, 'reminders': { 'useDefault': False, 'overrides': [ { 'method': 'email', 'minutes': 24 * 60 }, { 'method': 'popup', 'minutes': 15 }, ], }, } event = service.events().insert(calendarId='primary', body=event).execute() #print('Event created: %s' % (event.get('htmlLink'))) #webbrowser.open('https://calendar.google.com/calendar/r') if __name__ == '__main__': main() except Exception as e: print(e) #Open a existing folder elif put.startswith(search_pc): try: if any(word in put for word in pc_locations): username = getpass.getuser() location = link[-1] file_name = link[1] path = r"C:\Users\%s\%s\%s" % (username, location, file_name) os.system("start " + path) elif link[-1] == "drive" and link[-3] == "in": drive = link[-2] file_name1 = link[1] if link[2] == link[-3]: file_name2 = '' else: file_name2 = link[2] path = r"%s:\%s %s " % (drive, file_name1, file_name2) os.system("start " + path) elif link[-1] == "drive": drive = link[-2] path = r"%s:\ " % (drive) os.system("start " + path) except Exception as e: print(e) #Screen Recorder elif link[0] == "recorder": try: if len(link) < 2: video = '"UScreenCapture"' audio = '"Microphone (Realtek High Definition Audio)"' elif len(link) < 3: video = link[1] video = video.replace('_', ' ') video = '"' + video + '"' audio = '"Microphone (Realtek High Definition Audio)"' else: video = link[1] video = video.replace('_', ' ') video = '"' + video + '"' audio = link[2] audio = audio.replace('_', ' ') audio = '"' + audio + '"' username = os.getlogin() speak.say("Recording started!") speak.runAndWait() os.chdir(r'''C:\Users\{}\Desktop'''.format(username)) subprocess.call( r'''ffmpeg -rtbufsize 1500M -f dshow -i video={0}:audio={1} -vcodec mpeg4 -vtag xvid -qscale:v 0 -crf 0 -acodec libmp3lame -ab 320k -ac 1 -ar 44100 video.avi''' .format(video, audio), shell=True ) #video = UScreenCapture , audio = Microphone (Realtek High Definition Audio) except: print("Unable to start requested service!") #Voice Recorder elif link[0] == "audio" and link[1] == "recorder": try: if len(link) < 3: audio = '"Microphone (Realtek High Definition Audio)"' else: audio = link[2] audio = audio.replace('_', ' ') audio = '"' + audio + '"' username = os.getlogin() speak.say("Recording started!") speak.runAndWait() os.chdir(r'''C:\Users\{}\Desktop'''.format(username)) subprocess.call( r'''ffmpeg -rtbufsize 1500M -f dshow -i audio={0} -acodec libmp3lame -ab 320k -ac 1 -ar 44100 audio.mp3''' .format(audio), shell=True) except: print("Unable to start requested service!") #Video Recorder elif link[0] == "video" and link[1] == "recorder": try: if len(link) < 3: video = '"UScreenCapture"' else: video = link[2] video = video.replace('_', ' ') video = '"' + video + '"' username = os.getlogin() speak.say("Recording started!") speak.runAndWait() os.chdir(r'''C:\Users\{}\Desktop'''.format(username)) subprocess.call( r'''ffmpeg -rtbufsize 1500M -f dshow -i video={0} -vcodec mpeg4 -vtag xvid -qscale:v 0 -crf 0 video.avi''' .format(video), shell=True) except: print("Unable to start requested service!") #Merge audio and video elif link[0] == "merge": try: username = os.getlogin() os.chdir(r'''C:\Users\{}\Desktop'''.format(username)) video = link[1] audio = link[2] output = link[3] subprocess.call( r'''ffmpeg -i {} -i {} -c:v copy -c:a copy {}'''.format( video, audio, output), shell=True) except: print("Unable to process requested service!") #Convert video elif link[0] == "convert": try: username = os.getlogin() os.chdir(r'''C:\Users\{}\Desktop'''.format(username)) if link[1] == "na": form_in = link[2] video1 = link[3] form_out = link[4] video2 = link[5] if (form_in == "avi" or form_in == "webm" or form_in == "mp4" or form_in == "mkv") and (form_out == "mp4" or form_out == "mkv"): subprocess.call( r'''ffmpeg -i {} -c:v libx264 -an {}'''.format( video1, video2), shell=True) elif (form_in == "avi" or form_in == "mp4" or form_in == "mkv") and form_out == "webm": subprocess.call( r'''ffmpeg -i {} -c:v libvpx-vp9 -b:v 2M -an {}'''. format(video1, video2), shell=True) else: form_in = link[1] video1 = link[2] form_out = link[3] video2 = link[4] if (form_in == "avi" or form_in == "webm" or form_in == "mp4" or form_in == "mkv") and (form_out == "mp4" or form_out == "mkv"): subprocess.call( r'''ffmpeg -i {} -c:v libx264 -acodec aac {}'''.format( video1, video2), shell=True) elif (form_in == "avi" or form_in == "mp4" or form_in == "mkv") and form_out == "webm": subprocess.call( r'''ffmpeg -i {} -c:v libvpx-vp9 -b:v 2M -cpu-used -5 -deadline realtime -c:a libvorbis {}''' .format(video1, video2), shell=True) elif (form_in == "mp4" or form_in == "mkv" or form_in == "webm") and form_out == "avi": subprocess.call( r'''ffmpeg -i {} -c:v mpeg4 -vtag xvid -qscale:v 0 -acodec libmp3lame {}''' .format(video1, video2), shell=True) elif (form_in == "avi" or form_in == "webm" or form_in == "mp4" or form_in == "mkv" or form_in == "mp3" or form_in == "m4a") and (form_out == "m4a" or form_out == "mp3"): subprocess.call(r'''ffmpeg -i {} {}'''.format( video1, video2), shell=True) except: print("Unable to process requested service!") #Closing Benji elif put.startswith(close_keywords): os._exit(0) #Images to video elif put.startswith("images to video "): try: framerate = link[3] username = os.getlogin() os.chdir(r'''C:\Users\{}\Desktop\Images'''.format(username)) subprocess.call( r'''ffmpeg -framerate 1/{} -i img%03d.jpg -vcodec mpeg4 -vtag xvid -qscale:v 0 -crf 0 output.avi''' .format(framerate), shell=True) speak.say("Video created!") speak.runAndWait() except: print("Unable to create video file!") #Open Files elif put.startswith(search_pc): try: name = link[1] rex = regex.compile(name) filepath = link[2] realpath = filepath for root, dirs, files in os.walk(os.path.normpath(filepath)): for f in files: result = rex.search(f) if result: realpath = os.path.join(root, f) print(realpath + "\n") os.startfile(realpath) except: print("Error") #Plotting of graph elif put.startswith(graph_generation): try: formula = link[3] lower_limit = int(link[5]) upper_limit = int(link[7]) x = np.array(range(lower_limit, upper_limit)) y = eval(formula) speak.say("Plotting The Graph") speak.runAndWait() plt.plot(x, y) plt.show() except: print("Error") speak.say("Sorry Graph can not be Plotted") speak.runAndWait() #Box Office Status elif link[-1] == "boxoffice": try: url = "https://in.bookmyshow.com/" + link[0] + "/movies/nowshowing" r = requests.get(url) soup = BeautifulSoup(r.content, 'html.parser') soup_level2 = [] show_status_list = [] shows_list = soup.find_all( 'div', attrs={ 'class': 'card-container wow fadeIn movie-card-container' }) for i in shows_list: start = str(i).index("href=") end = str(i).index("title=") soup_level2.append("https://in.bookmyshow.com" + str(i)[start + 6:end - 2]) show_status_raw = soup.find_all( 'div', attrs={'class': 'popularity sa-data-plugin'}) for i in show_status_raw: start = str(i).index("data-coming-soon=") end = str(i).index('data-event-code') data = str(i)[start + 18:end - 2] if data == "false": show_status_list.append("In Cinemas Now...") if data == "true": show_status_list.append("Coming Soon...") Tags_list = [] Name_list = [] for url in soup_level2: r = requests.get(url) tags = BeautifulSoup(r.content, 'html.parser') Tags_raw = tags.find_all('span', attrs={'class': '__genre-tag'}) tmp_tags = "" for i in Tags_raw: tmp_tags = tmp_tags + str(i)[str(i).index('">') + 2:str(i). index("</span>")] + " - " Tags_list.append(tmp_tags[:-3]) Names_raw = tags.find_all('h1', attrs={'class': '__name'}) for i in Names_raw: Name_list.append( str(i)[str(i).index('">') + 2:str(i).index("</h1>")]) speak.say("Preparing List") speak.runAndWait() cntr = len(Name_list) print("----------------------------------------------") print(link[0].capitalize()) print("----------------------------------------------") print("") for i in range(cntr): print("Name : " + Name_list[i]) print("Tags : " + Tags_list[i]) print("Status : " + show_status_list[i]) print("") print("----------------------------------------------") print("") except: print("Sorry, List Cannot be Prepared...") speak.say("Sorry, List Cannot be Prepared...") speak.runAndWait() # elif put.startswith(search_pc): # process=subprocess.Popen("dir /b/s "+link[1],shell=True,stdout=subprocess.PIPE) # while True: # output = process.stdout.readline() # if output == '' and process.poll() is not None: # break # if output: # print (output.strip()+"\n") # outp=output # try: # os.startfile(outp) # except: # speak.say("Sorry,couldn't open") #Play song on youtube if put.startswith(youtube_keywords): try: link = '+'.join(link[1:]) # print(link) say = link.replace('+', ' ') url = 'https://www.youtube.com/results?search_query=' + link # webbrowser.open('https://www.youtube.com'+link) fhand = urllib.request.urlopen(url).read() soup = BeautifulSoup(fhand, "html.parser") songs = soup.findAll('div', {'class': 'yt-lockup-video'}) hit = songs[0].find('a')['href'] # print(hit) speak.say("playing " + say) speak.runAndWait() webbrowser.open('https://www.youtube.com' + hit) except: print('Sorry Ethan. Looks like its not working!') #Download video if put.startswith("download video "): try: link = '+'.join(link[2:]) say = link.replace('+', ' ') url = 'https://www.youtube.com/results?search_query=' + link fhand = urllib.request.urlopen(url).read() soup = BeautifulSoup(fhand, "html.parser") songs = soup.findAll('div', {'class': 'yt-lockup-video'}) hit = songs[0].find('a')['href'] speak.say("downloading video " + say) speak.runAndWait() username = os.getlogin() os.chdir(r'''C:\Users\{}\Desktop'''.format(username)) YouTube('https://www.youtube.com' + hit).streams.first().download() speak.say("download complete!") speak.runAndWait() except: print('Sorry Ethan. Looks like its not working!') #Download music elif put.startswith(download_music): try: link = '+'.join(link[1:]) # print(link) say = link.replace('+', ' ') url = 'https://www.youtube.com/results?search_query=' + link # webbrowser.open('https://www.youtube.com'+link) fhand = urllib.request.urlopen(url).read() soup = BeautifulSoup(fhand, "html.parser") songs = soup.findAll('div', {'class': 'yt-lockup-video'}) hit = songs[0].find('a')['href'] # print(hit) speak.say("downloading " + say) speak.runAndWait() ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], 'quiet': True, 'restrictfilenames': True, 'outtmpl': 'C:\\Users\\' + os.environ['USERNAME'] + '\\Desktop\\%(title)s.%(ext)s' } ydl = youtube_dl.YoutubeDL(ydl_opts) ydl.download(['https://www.youtube.com' + hit]) speak.say("download completed Check your desktop for the song") speak.runAndWait() except: print("Unable to download requested music!") #Location elif any(word in put for word in location_keywords): try: link = '+'.join(link[1:]) say = link.replace('+', ' ') speak.say("locating " + say) speak.runAndWait() webbrowser.open('https://www.google.nl/maps/place/' + link) except: print('The place seems to be sequestered.') #Who are you? elif any(word in put for word in identity_keywords): try: speak.say( "I am BENJI, a digital assistant declassified for civilian use. Previously I was used by the Impossible Missions Force" ) speak.runAndWait() except: print('Error. Try reading the ReadMe to know about me!') #Open a webpage elif any(word in put for word in launch_keywords): try: link = '+'.join(link[1:]) speak.say("opening " + link) speak.runAndWait() webbrowser.open('http://www.' + link) except: print( 'Sorry Ethan,unable to access it. Cannot hack either-IMF protocol!' ) #Google search elif any(word in put for word in search_keywords): try: link = '+'.join(link[1:]) say = link.replace('+', ' ') speak.say("searching google for " + say) speak.runAndWait() webbrowser.open('https://www.google.com/search?q=' + link) except: print('Nope, this is not working.') #Google Images elif put.startswith("images of "): try: link = '+'.join(link[2:]) say = link.replace('+', ' ') speak.say("searching images of " + say) speak.runAndWait() webbrowser.open('https://www.google.co.in/search?q=' + link + '&source=lnms&tbm=isch') except: print('Could not search for images!') #Gmail elif put.startswith("gmail"): try: speak.say("Opening Gmail!") speak.runAndWait() webbrowser.open('https://www.google.com/gmail') except: print("Could not open Gmail!") #Google Cloud Print elif put.startswith("google cloud print"): try: speak.say("Opening google cloud print!") speak.runAndWait() webbrowser.open('https://www.google.com/cloudprint') except: print("Could not open Google Cloud Print!") #Google Others elif put.startswith("google "): try: say = link[1] speak.say("Opening google " + say) speak.runAndWait() webbrowser.open('https://' + say + '.google.com') except: print("Could not open Google " + say.capitalize() + "!") #Blogger elif put.startswith("blogger"): try: speak.say("Opening blogger!") speak.runAndWait() webbrowser.open('https://www.blogger.com') except: print("Could not open Blogger!") #Wikipedia elif any(word in put for word in wikipedia_keywords): try: link = '+'.join(link[1:]) say = link.replace('+', ' ') wikisearch = wikipedia.page(say) speak.say("Opening wikipedia page for" + say) speak.runAndWait() webbrowser.open(wikisearch.url) except: print( 'Wikipedia could not either find the article or your Third-world connection is unstable' ) #Podcast elif put.startswith("podcast"): try: speak.say("Opening podcast!") speak.runAndWait() webbrowser.open('https://castbox.fm/home') except: print("Could not open podcast!") #Lock the device elif put.startswith('secure ') or put.startswith('lock '): try: speak.say("locking the device") speak.runAndWait() ctypes.windll.user32.LockWorkStation() except: print('Cannot lock device') #News of various press agencies elif put.startswith('news '): try: say = '+'.join(link[1:]) say = say.replace('+', '-') if link[1] == "al" and link[2] == "jazeera": say += "-english" elif link[1] == "bbc": say += "-news" elif link[1] == "espn" and link[2] == "cric": say += "-info" url = ('https://newsapi.org/v1/articles?source=' + say + '&sortBy=latest&apiKey=571863193daf421082a8666fe4b666f3') newsresponce = requests.get(url) newsjson = newsresponce.json() speak.say('Our agents from ' + say + ' report this') speak.runAndWait() print(' =====' + say.upper() + '===== \n') i = 1 for item in newsjson['articles']: print(str(i) + '. ' + item['title'] + '\n') print(item['description'] + '\n') i += 1 except: print('Unable to retrieve data!') #shutdown after specific time elif put.startswith('shutdown after '): try: if link[2].isdigit() and link[4].isdigit(): if link[2] == "zero": link[2] = "0" if link[4] == "zero": link[4] = "0" hours = int(link[2]) minutes = int(link[4]) time_seconds = 60 * minutes time_seconds = time_seconds + hours * 3600 subprocess.call("shutdown /s /t {0}".format(str(time_seconds)), shell=True) speak.say("Shutdown initialized!") speak.runAndWait() except: print("Please shutdown manually!") #shutdown now elif put.startswith("shutdown now"): try: subprocess.call("shutdown /s /t 0", shell=True) except: print("Please shutdown manually!") #abort shutdown elif put.startswith("cancel shutdown"): try: subprocess.call("shutdown /a", shell=True) speak.say("Shutdown cancelled!") speak.runAndWait() except: print("Unable do cancel shutdown!") #restart elif put.startswith("restart now"): try: subprocess.call("shutdown /r /t 0", shell=True) except: print("Unable do restart device!") #Folder elif put.startswith('create ') and link[-1] == "folder": try: username = os.getlogin() filename = '+'.join(link[1:-1]) filename = filename.replace('+', '_').capitalize() path = r'''C:\Users\{0}\Desktop\{1}'''.format(username, filename) os.mkdir(path) speak.say("Folder created!") speak.runAndWait() except: print("Couldn't create specified folder!") #create file elif put.startswith('create ') and link[-1] == "document": try: username = os.getlogin() filename = '+'.join(link[1:-2]) filename = filename.replace('+', '_').capitalize() if link[-2] == "text": filename += ".txt" f1 = open( r'''C:\Users\{0}\Desktop\{1}'''.format(username, filename), 'a') f1.close() elif link[-2] == "word" or link[-2] == "world": filename += ".docx" f1 = open( r'''C:\Users\{0}\Desktop\{1}'''.format(username, filename), 'a') f1.close() elif link[-2] == "powerpoint" or link[-2] == "presentation": filename += ".pptx" prs = Presentation() title_slide_layout = prs.slide_layouts[0] slide = prs.slides.add_slide(title_slide_layout) os.chdir(r'''C:\Users\{0}\Desktop'''.format(username)) prs.save(filename) elif link[-2] == "excel" or link[-2] == "Excel": filename += ".xlsx" wb = Workbook(filename) ws = wb.add_worksheet() os.chdir(r'''C:\Users\{0}\Desktop'''.format(username)) wb.close() elif link[-2] == "visio" or link[-2] == "vizio": filename += ".vsdx" f1 = open( r'''C:\Users\{0}\Desktop\{1}'''.format(username, filename), 'a') f1.close() elif link[-2] == "rich" or link[-2] == "reach": filename += ".rtf" f1 = open( r'''C:\Users\{0}\Desktop\{1}'''.format(username, filename), 'a') f1.close() speak.say("Created" + filename) speak.runAndWait() except: print("Unable to create a file.") #Calculator elif put.startswith('calculator'): try: subprocess.call('calc', shell=True) except: print("Unable to open calculator!") #Exit/Quit elif put.startswith('exit') or put.startswith('quit'): sys.exit()