def enviar(self): # Unir con el metodo de envio de GoogleSheet """ Funcion que recibe la informacion y escribe en la hoja de pagos. """ for pack in self.datos: GoogleSheet.enviar_datos_formulario(pack) pprint(pack) QMessageBox.warning(QWidget(), "Listo", "Datos enviados e ingresados!")
def test_messageManager_individual(self): G = MessageManager.gmail('2018/10/25','credentials_gmail1') print('There are '+str(len(G._messages))+' unread individual/corporate agreement') #print(G.getAllIDs()) #print(G.getAllMessages()['166c584b592ae544']) # ============================================================================= labels = G.getService().users().labels().list(userId='me').execute().get('labels', []) for label in labels: print(label['name']+ " "+label['id']) # ============================================================================= GS = GoogleSheet.googleSheet() for i in GS.ReadProcessedID(): #ID = '166c584b592ae544' mess = MessageManager.emailMessage(i,G) mess.MarkAsRead() # ============================================================================= print(mess._content) mess.downloadAttachment() print(mess.getLastName()) print(mess.getFirstName()) print(mess.getFolderName()) print(mess.getNationality()) print(mess.getPlatform()) print(mess.getCountryName()) print(mess.getID()) print(mess.getSubject()) #print(mess._content) print(mess.getTradingKnowledge())
def main(): baseDir = 'C:/Users/Administrator/Documents/Individual Agreements/' filemanager = FileManager.fileManager(baseDir) Drive = DriveManager.driveManager() GS = GoogleSheet.googleSheet() ProcessedID = GS.ReadProcessedID() while True: ########################################################################### Gmail = MessageManager.gmail('2018/10/28','credentials_gmail1') ########################################################################### UnreadID = Gmail.getAllIDs() Process = set(UnreadID)-set(ProcessedID) for I in Process: print(I) mess = MessageManager.emailMessage(I,Gmail) try: ia = IndividualAgreement.individualAgreement( Gmail, filemanager, Drive,I) li= ia.ReportResult() except: try: ia = IndividualAgreement.individualAgreement( Gmail, filemanager, Drive,I) li= ia.ReportResult() except: li = [I,mess.getSubject(),mess.getFullName(),mess.getEmailAddress(),mess.getCountryName(), None, None, None,None,None,mess.getPlatform()] print('failed') print(li) GS.updateInformation([li]) ProcessedID.append(I)
def test_googlesheet(self): values = [['1', 'dsafgsef', 'awetgae', 'ergaer']] GS = GoogleSheet.googleSheet() GS.updateInformation(values) print(GS.ReadProcessedID())
def RiskMatrix(self): self._Drive.CopyRiskMatrix(self._FullName) RiskMatrixID = self._Drive.getFileID(self._FullName+" RiskMatrix") self._RiskMatrix = GoogleSheet.googleSheet(RiskMatrixID) self._RiskMatrix._service.spreadsheets().values().update(spreadsheetId=RiskMatrixID,range ='A4',valueInputOption='RAW', body={'values': [[self._FullName]]}).execute() self._RiskMatrix._service.spreadsheets().values().update(spreadsheetId=RiskMatrixID,range ='B26',valueInputOption='RAW', body={'values': [[time.strftime("%Y-%m-%d", time.gmtime())]]}).execute() #RiskMatrix['A4'] = self._FullName if self._Country in HighRiskCountry: #RiskMatrix['B7'] = 3 self._RiskMatrix._service.spreadsheets().values().update(spreadsheetId=RiskMatrixID,range ='B7',valueInputOption='RAW', body={'values': [[3]]}).execute() else: #RiskMatrix['B7'] = 1 self._RiskMatrix._service.spreadsheets().values().update(spreadsheetId=RiskMatrixID,range ='B7',valueInputOption='RAW',body={'values': [[1]]}).execute() if 'Corporate' in self._message.getSubject(): #RiskMatrix['B8'] = 1 self._RiskMatrix._service.spreadsheets().values().update(spreadsheetId=RiskMatrixID,range ='B8',valueInputOption='RAW', body={'values': [[1]]}).execute() else: #RiskMatrix['B8'] = 3 self._RiskMatrix._service.spreadsheets().values().update(spreadsheetId=RiskMatrixID,range ='B8',valueInputOption='RAW', body={'values': [[3]]}).execute() if self._message.getManagementAccount() == 'Third party manager': #RiskMatrix['B9'] = 5 self._RiskMatrix._service.spreadsheets().values().update(spreadsheetId=RiskMatrixID,range ='B9',valueInputOption='RAW', body={'values': [[5]]}).execute() else: #RiskMatrix['B9'] = 1 self._RiskMatrix._service.spreadsheets().values().update(spreadsheetId=RiskMatrixID,range ='B9',valueInputOption='RAW', body={'values': [[1]]}).execute() if self._message.getTradingKnowledge() == 'N': #RiskMatrix['B12']=5 self._RiskMatrix._service.spreadsheets().values().update(spreadsheetId=RiskMatrixID,range ='B12',valueInputOption='RAW', body={'values': [[5]]}).execute() elif self._message.getTradingKnowledge() == 0: #RiskMatrix['B12'] = 3 self._RiskMatrix._service.spreadsheets().values().update(spreadsheetId=RiskMatrixID,range ='B12', valueInputOption='RAW',body={'values': [[3]]}).execute() elif self._message.getTradingKnowledge() == 2: #RiskMatrix['B12'] = 2 self._RiskMatrix._service.spreadsheets().values().update(spreadsheetId=RiskMatrixID,range ='B12',valueInputOption='RAW', body={'values': [[2]]}).execute() else: #RiskMatrix['B12'] = 1 self._RiskMatrix._service.spreadsheets().values().update(spreadsheetId=RiskMatrixID,range ='B12', valueInputOption='RAW',body={'values': [[1]]}).execute()
def GetFile(self, configuration, section, entry, nodownload): filespecifier = configuration.get(section, entry) if filespecifier: self.Log('Laden van ' + filespecifier) gs = GoogleSheet(configuration.cachedir, filespecifier) if nodownload: errormsg = 'Bestand wordt niet gedownload' else: errormsg = gs.LoadFromGoogle() if errormsg: self.Log(errormsg, error=True) if gs.cachedcsv and os.path.isfile(gs.cachedcsv): self.Log('Gebruik het bestand uit de cache: ' + gs.cachedcsv) return gs.cachedcsv self.Log('Geen bestand aanwezig in de cache', error=True) else: if gs.documentname: self.Log('Ontvangen: ' + gs.documentname) return gs.cachedcsv
def cargar_base_de_datos(self): """ Funcion que genera un archivo .txt que almacena la base de datos. :return: """ BASE_DE_DATOS = GoogleSheet.obtener_datos(GoogleSheet.URL_BASE_DATOS) with open("Base de Datos.txt", "w", encoding="utf-8") as file: for dato in BASE_DE_DATOS: cadena = str.join(";", dato) file.write(cadena) file.write("\n") QMessageBox.warning(QWidget(), "Listo", "Base de datos actualizada!") return BASE_DE_DATOS
def iniciar_nueva_hoja(self, nombre, link_formulario, link_historial): """ :param nombre: Nombre de la hoja que se desea trabajar :param link_formulario: Link de la hoja que se desea trabajar :return: """ # Se comprueba si hay que abrir/crear una hoja para el pago GoogleSheet.comprobar_hoja(nombre, link_formulario) GoogleSheet.comprobar_hoja(nombre.replace("Formulario", "Actividades"), link_historial) # Se almacena el nombre de la sheet self.hoja_formulario = nombre self.hoja_historial = nombre.replace("Formulario", "Actividades") # Se crea la lista que almacenará toda la informacion para ser enviada # a cada hoja self.datos = list() # Se genera la instacia del form y se oculta la bienvenida self.form = Form() self.form.show() self.bienvenida.hide() # Se setea el nombre de la hoja self.form.setWindowTitle(self.hoja_formulario) # Se da forma a la instancia del form self.nombres_completos, self.rut_completos, self.correos_uc = GoogleSheet.ordenar_informacion( self.cargar()) self.form.nombre_completo.addItems(self.nombres_completos) self.form.actividad.addItems(PARAMETROS_SIMBOLOGIA_2018.keys()) # Se conectan las señales self.form.sheet_formulario.clicked.connect( lambda: GoogleSheet.abrir_formulario_google()) self.form.sheet_historial.clicked.connect( lambda: GoogleSheet.abrir_historial_google()) self.form.cambiar_pago.clicked.connect(lambda: self.cambiar_pago()) self.form.enviar.clicked.connect(lambda: self.enviar()) self.form.agregar.clicked.connect(lambda: self.agregar()) self.form.eliminar.clicked.connect(lambda: self.eliminar())
def __init__(self): self.vk_session = vk_api.VkApi(token = /Токен/) self.session_api = self.vk_session.get_api() self.longpoll = VkLongPoll(self.vk_session) try: self.googleSheet = GoogleSheet.GoogleSheet() except Exception as e: self.sender(/Айди/, "Что-то не вышло с гугл файлами, вот текст исключения: " + str(e) + "\nЯ, кстати, упал", None) self.keyboard = VkKeyboard.Keyboard() self.eventsList = self.googleSheet.getEventsList() self.controlKeyBoard = self.keyboard.getControlKeyBoard() self.eventKeyBoard = self.keyboard.getEventsKeyBoard(self.eventsList) self.yesKeyBoard = self.keyboard.getYesKeyBoard() self.confirmationKeyBoard = self.keyboard.getConfirmationKeyboard() #adminPart self.testPassword = /пароль/ self.clearAdminValues() self.adminActions = { 'начать рассылку': self.confirmationBeforeMailing, 'разослать запрос на подтверждение': self.startConfirmationMailing, 'сменить текст рассылки': self.setMailing, 'просмотреть количество зарегистрированных участников': self.showRegisteredUsers } #adminPart self.userSessions = {} self.confirmationList = {} self.threadPool = ThreadPool(20) nightTime = self.getNightDatetime() self.inactiveUserDeleter = threading.Timer(self.getSecondsToDate(nightTime), self.deleteInactiveUsers) self.inactiveUserDeleter.start()
''' Created on Jan 4, 2013 @author: jslowik ''' import GoogleSheet import CPULoad import DiskLoad import MemoryLoad import CPUTemp import NetworkLoad CPULOAD = CPULoad.getCpuLoad()*100.0 MEMTOTAL, MEMFREE = MemoryLoad.getMemory() MEMUSED = MEMTOTAL-MEMFREE DISKLOAD = DiskLoad.getDiskLoad("sda1") TEMP = CPUTemp.getCPUtemperature('F') RX,TX = NetworkLoad.getNetworkLoad("eth0:") result = GoogleSheet.send(CPULOAD,MEMUSED,MEMFREE,MEMTOTAL,DISKLOAD,TEMP,RX,TX)
def main(): """Shows basic usage of the Sheets API. Prints values from a sample spreadsheet. """ creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server() # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) # list files in google drive print('google drive') service2 = build('drive', 'v3', credentials=creds) results = service2.files().list( pageSize=10, fields="nextPageToken, files(id, name, parents, capabilities)").execute() items = results.get('files', []) FitnessChallengeFolderID = '' if not items: print('No files found.') else: for item in items: if (item['name'] == 'FitnessChallenge'): FitnessChallengeFolderID = item['id'] leaderBoardInfo = {} userFolders = [] userFiles = [] if FitnessChallengeFolderID: # get all file id's in FitnessChallenge directory for item in items: parents = item.get('parents') if parents and (FitnessChallengeFolderID in parents): if (item['name'] == 'LeaderBoard'): # save the LeaderBoard sheet to update later leaderBoardInfo = item elif item['capabilities']['canListChildren']: # if this is a directory then it is a user's folder userFolders.append(item) else: userFiles.append(item) # build a map of user folders to its sub files directoryStructureMap = {} for userFolder in userFolders: directoryStructureMap[userFolder['id']] = {'self': userFolder, 'children': []} for userFile in userFiles: for parent in userFile['parents']: if parent in directoryStructureMap.keys(): directoryStructureMap[parent]['children'].append(userFile) break # create service for sheets service = build('sheets', 'v4', credentials=creds) # Generate the leader board try: leaderBoard = LeaderBoard.LeaderBoard(leaderBoardInfo, service) except Exception as e: print('Error when retrieving the leader board') raise # get the spread sheet for each new file users = [] for userFolderID in directoryStructureMap.keys(): userFolder = directoryStructureMap[userFolderID] # create the user user = User.User(userFolder['self']) # create this user's GoogleSheet objects for userFile in userFolder['children']: googleSheet = GoogleSheet.GoogleSheet(userFile, values) user.addChildSheet(googleSheet) users.append(user) # Now we have a list of users with their child sheets for user in users: print (user.getName())