def checkbalance(): client = textmagic.client.TextMagicClient(username, password) balance = client.account()['balance'] print balance if balance < credits: client.send("WARNING - Textmagic credit balance below threshold, please top the account", owner) else: sys.exit()
def checktemp(): output = subprocess.Popen(["/usr/local/bin/pcsensor"], stdout=subprocess.PIPE).communicate()[0] output2 = output.split()[4] temp = output2[:2] if int(temp) > threshold: for phonebook in fileinput.input("/usr/local/bin/phonebook.txt"): client = textmagic.client.TextMagicClient(username, password) client.send("WARNING - Server room temperature above threshold!!! PLEASE CHECK!!!", phonebook) else: sys.exit()
def send_sms(account, recipients, body_text, debug=False ): if debug: print "Loaded account, starting SMS session" if len(body_text) > 155: print "Warning: Body text will be truncated" body_text = body_text[:160] client = textmagic.client.TextMagicClient( account[keys.sms_account.username], account[keys.sms_account.api_password]) result = client.send(body_text, recipients) message_ids = result['message_id'].keys() return message_ids
while True: print 'Receiving data from TextMagic...', try: sms_in = client.receive(0) except: print 'Failed' else: print 'Done' print 'Notifying Michael of the crash...', try: info = str(sms_in['messages'][0]['from'])+' | "'+str(sms_in['messages'][0]['text'])+'"' except: info = 'Internal Issues' try: client.send('Piabetes crashed | '+info,'17042306940') except Exception,exc: print 'Failed' print 'Reason: '+str(exc) time.sleep(10) else: print 'Done' break print 'Deleting message that made Piabetes crash...' if len(sms_in['messages'])>0: client.delete_reply(sms_in['messages'][0]['message_id']) print 'Done' else: print 'No message to delete'
def sending_txt(txt, number): #sending result = client.send(txt, number) #uniqque id for a txt message message_id = result['message_id'].keys()[0] return message_id
def sending_txt(txt, number): # sending result = client.send(txt, number) # uniqque id for a txt message message_id = result['message_id'].keys()[0] return message_id
import textmagic.client # Use your username and API password to create a client client = textmagic.client.TextMagicClient('your_username', 'your_api_password') # Send a message and store its message id result = client.send("Hello, World!", "1234567890") message_id = result['message_id'].keys()[0] # Now you can retrieve the delivery status using the message id response = client.message_status(message_id) status = response[message_id]['status'] # Replies to your outgoing messages are delivered to your TextMagic Inbox # This is how you receive messages from your Inbox received_messages = client.receive(0) messages_info = received_messages['messages'] for message_info in messages_info: print "%(text)s received from %(from)s" % message_info # Delete a message from your Inbox client.delete_reply(message_info['message_id']) # Get your account balance balance = client.account()['balance'] # Find the country and cost of a telephone number response = client.check_number('44123456789') info = response['44123456789'] country = info['country'] credits = info['price']
import textmagic.client # Use your username and API password to create a client client = textmagic.client.TextMagicClient('your_username', 'your_api_password') # Send a message and store its message id result = client.send("Hello, World!", "1234567890") message_id = list(result['message_id'].keys())[0] # Now you can retrieve the delivery status using the message id response = client.message_status(message_id) status = response[message_id]['status'] # Replies to your outgoing messages are delivered to your TextMagic Inbox # This is how you receive messages from your Inbox received_messages = client.receive(0) messages_info = received_messages['messages'] for message_info in messages_info: print("%(text)s received from %(from)s" % message_info) # Delete a message from your Inbox client.delete_reply(message_info['message_id']) # Get your account balance balance = client.account()['balance'] # Find the country and cost of a telephone number response = client.check_number('44123456789') info = response['44123456789'] country = info['country'] credits = info['price']
def parse_command(toparse): global local_dir global whitelist global sms_in global info global client global regex_filename global regex_fileurl global dev_mode global dev_number global do_libupdate global manual_libupdate global uptime_start global uptime if toparse[:12] == '--whitelist ': whitelist.append(toparse[12:]) save_whitelist() if not dev_mode: client.send('You have been added to the Piabetes whitelist',toparse[12:]) print timestamp()+'Added '+toparse[12:]+' to the whitelist' if toparse[:12] == '--blacklist ': whitelist.remove(toparse[12:]) save_whitelist() print timestamp()+'Removed '+toparse[12:]+' from the whitelist' if toparse == '--info': print timestamp()+'Info requested from '+sms_in['messages'][0]['from'] if sms_in['messages'][0]['from'] in whitelist: if dev_mode: print info else: client.send(info,sms_in['messages'][0]['from']) print timestamp()+'Whitelist authenticated, reply sent' else: print timestamp()+'Whitelist authentification failed' if toparse == '--restart': print timestamp()+'Restart command received' if sms_in['messages'][0]['from'] in whitelist: print timestamp()+'Whitelist authenticated' fileout = open(local_dir+'Reboot.nt','w') fileout.write(sms_in['messages'][0]['from']) fileout.close() if dev_mode: print 'Piabetes will notify you when the restart is complete' else: client.send('Piabetes will notify you when the restart is complete',sms_in['messages'][0]['from']) os.remove(local_dir+'crashcom.nt') system('sudo shutdown -r now') else: print timestamp()+'Whitelist authentification failed' if toparse == '--shutdown': print timestamp()+'Shutdown command received' if sms_in['messages'][0]['from'] in whitelist: print timestamp()+'Whitelist authenticated' os.remove(local_dir+'crashcom.nt') system('sudo shutdown -h now') else: print timestamp()+'Whitelist authentification failed' if toparse[:9] == '--update ': url = toparse[9:] print timestamp()+sms_in['messages'][0]['from']+' requested to update' print timestamp()+url if not sms_in['messages'][0]['from'] in whitelist: print timestamp()+sms_in['messages'][0]['from']+' is not whitelisted' return False if get_update(url): print 'Successfully downloaded update' print 'The system will now restart' if not dev_mode: client.delete_reply(int(sms_in['messages'][0]['message_id'])) os.remove(local_dir+'crashcom.nt') time.sleep(3) system('sudo shutdown -r now') if toparse[:9] == '--upload ': url = re.search(regex_fileurl,toparse) name = re.search(regex_filename,toparse) url = url.group(1) name = name.group(1) print timestamp()+sms_in['messages'][0]['from']+' is attempting a file upload' if not sms_in['messages'][0]['from'] in whitelist: print timestamp()+sms_in['messages'][0]['from']+' is not whitelisted' return False if get_file(name,url): print 'The file was successfully downloaded' if toparse == '--exit': os.remove(local_dir+'crashcom.nt') print timestamp()+'Exit request received - Quitting...' if not dev_mode: client.delete_reply(int(sms_in['messages'][0]['message_id'])) sys.exit(0) if toparse == '--nolibupdate': do_libupdate = False print timestamp()+'Automatic library updating was disabled' if toparse == '--libupdate': do_libupdate = True print timestamp()+'Automatic library updating was enabled' if toparse == '--dolibupdate': print timestamp()+'The library will now be updated manually' update_library() if toparse == '--uptime': print timestamp()+sms_in['messages'][0]['from']+' requested the uptime' if not sms_in['messages'][0]['from'] in whitelist: print timestamp()+sms_in['messages'][0]['from']+' is not whitelisted' return False else: uptime_string = str(uptime['days'])+' days\n'+str(uptime['hours'])+' hours\n'+str(uptime['minutes'])+' minutes\n'+str(uptime['seconds'])+' seconds' if dev_mode: print uptime_string else: client.send(uptime_string,sms_in['messages'][0]['from']) print timestamp()+sms_in['messages'][0]['from']+' whitelisted, uptime sent ('+uptime_string.replace('\n',', ')+')' if toparse == '--integrity': print timestamp()+sms_in['messages'][0]['from']+' requested an integrity check' if dev_mode == True: integrity_check() else: print timestamp()+'Integrity checks not available via text message' if sms_in['messages'][0]['from'] in whitelist: client.send('Integrity checks not available via text message',sms_in['messages'][0]['from']) print timestamp()+'They have been notified of this' else: print timestamp()+'No matter, they\'re not whitelisted anyway' if toparse == '--flushlib': print timestamp()+sms_in['messages'][0]['from']+' requested a library flush' if sms_in['messages'][0]['from'] in whitelist: print timestamp()+'Authenticated '+sms_in['messages'][0]['from']+' with the whitelist' print timestamp()+'Flushing the library...', if not os.path.isdir(local_dir+'Library'): print 'Failed' else: lib_files = os.listdir(local_dir+'Library') for filename in lib_files: if not filename[:1] == '.': os.remove(local_dir+'Library/'+filename) print 'Done' print timestamp()+'The library was successfully flushed' if toparse == '--addlib': print timestamp()+sms_in['messages'][0]['from']+' requested a manual addition to the library' if not sms_in['messages'][0]['from'] in whitelist: print timestamp()+sms_in['messages'][0]['from']+' is not on the whitelist' return if not dev_mode: print timestamp()+'Library additions are not allowed via text message' client.send('Library additions cannot be made via text message',sms_in['messages'][0]['from']) name = raw_input('Name of food: ') amount = raw_input('Quantity of food: ') carbs = raw_input('Carbs in amount given: ') fiber = raw_input('Dietary fiber in amount given: ') try: fileout = open(local_dir+'Library/'+str(amount)+':'+str(name),'w') except: print 'Error occured when attempting to open the file' return fileout.write(name+'\nQty: '+str(amount)+'\nCarbs: '+str(carbs)+'\nDietary Fiber: '+str(fiber)) fileout.close() print timestamp()+'Library file successfully created'
print credit_amount load_whitelist() # # # # # #Misc. Setup if os.path.isfile(local_dir+'Reboot.nt'): filein = open(local_dir+'Reboot.nt') totext = filein.read() filein.close() if dev_mode: print 'Piabetes is back online' else: client.send('Piabetes is back online',totext) os.remove(local_dir+'Reboot.nt') print timestamp()+'Reboot file detected | administering notification to '+totext try: import RPI.GPIO as gpio except ImportError: print 'No GPIO Found' print 'Indicator LEDs will be unavailable' gpio_avail = False else: print 'GPIO imported' print 'Indicator LEDs are now running (if they\'re plugged in)' gpio_avail = True gpio.setup(14,gpio.OUT) gpio.setup(15,gpio.OUT)
def envioSMS(self): import textmagic.client remitente = '*****@*****.**' fecha = datetime.datetime.now() #- datetime.timedelta(days=5,hours=3) #el delta para testar tantes = (fecha - datetime.timedelta(hours=4)) client = textmagic.client.TextMagicClient('infinityloopsis', 'uTM0EwZF026AQCN') hoy = fecha diasemana = hoy.weekday() hora = hoy.now() listaempresas = Empresas.objects.filter(habilitar=True, fechabaja__isnull=True) print listaempresas.count() for emp in listaempresas: listobjreg = DetallesRegistros.objects.filter( tracksondas__isnull=False, empresa_id=emp.id) if listobjreg: for objreg in listobjreg: #Detalle Registros #Conseguir consignas de limites. consigna = objreg.tplimitcrit.valormax #Revision temperatura rango temp = objreg.tracksondas.tempMin(fecha, 15) sondalarm = { 'tracksonda_id': objreg.tracksondas.id, 'dateaviso': fecha, 'valor': temp['Temperature__avg'], } if temp['Temperature__avg'] is not None: if temp['Temperature__avg'] > consigna: listaenvios = DetalleConfiguracion.objects.filter( configuracion__empresa__id=emp.id, habilitar='S', accion__in=('S', 'Z')) for envio in listaenvios: #Listas parametros envios if envio.dias == 'L': DIAS = [0, 1, 2, 3, 4] elif envio.dias == 'F': DIAS = [5, 6] elif envio.dias == 'A': DIAS = [0, 1, 2, 3, 4, 5, 6] else: DIAS = [envio.dias] if DIAS: if diasemana in DIAS: #Comprueba que estamos en el dia de alarma listaturnos = HorarioTurnos.objects.filter( tpturnos=envio.turnos) if listaturnos: for objturno in listaturnos: #Recorre Turnos horavalida = ( objturno.fhora >= hora and objturno.ihora <= hora ) #Verifica que se encuentra en hora de aviso else: #Sin horario, por defecto todas las horas son validas horavalida = True if horavalida: no_avisos = TrackSondasAlarmas.objects.filter( tracksonda_id=objreg. tracksondas.id, dateaviso__gte=tantes).count() if no_avisos is None: TrackSondasAlarmas.objects.create( **sondalarm) elif no_avisos in (13, 21, 34): listapersonas = Personal.objects.filter( detalleconfiguracion__id= envio.id, emailnotifica__isnull=False, telefonosms__isnull=False) if listapersonas != []: email = [] titulo = objreg.denominacion( ) mensaje = "Alarma %s excede valor %s, valor actual ** %s ** " % ( titulo, consigna, temp[ 'Temperature__avg'] ) for direccion in listapersonas: #Listas Personas if envio.accion == 'S' or envio.accion == 'Z': result = client.send( unicode( mensaje, 'utf8'), direccion. telefonosms) messager_id = result[ 'message_id'].keys( )[0] print "Envia Mensajes %s" % mensaje objtrack = TrackSondasAlarmas.objects.filter( tracksonda_id= objreg. tracksondas.id, dateaviso__gte= tantes, idavisosms__isnull =True).update( idavisosms= messager_id ) if envio.accion == 'Z': email.append( direccion. emailnotifica) if envio.accion == 'Z': send_mail( "Urgente - Alarmas de fecha %s" % hoy, mensaje, remitente, email) TrackSondasAlarmas.objects.create( **sondalarm) else: TrackSondasAlarmas.objects.create( **sondalarm)
def enviosdelegados(listaenvios, temp, objreg, sondalarm, hora, diasemana, tantes, consigna, hoy): import textmagic.client logger.debug("Imprime informacion de sonda alarm %s " % sondalarm) logger.debug("Lista de envios %s " % listaenvios) remitente = '*****@*****.**' client = textmagic.client.TextMagicClient('infinityloopsis', 'uTM0EwZF026AQCN') for envio in listaenvios: #Listas parametros envios logger.debug("Envios %s %s " % (envio.dias, envio.turnos)) DIAS = normalizadias(envio.dias) if DIAS: if diasemana in DIAS: # Comprueba que estamos en el dia de alarma listaturnos = HorarioTurnos.objects.filter( tpturnos=envio.turnos) if listaturnos: for objturno in listaturnos: #Recorre Turnos horavalida = ( objturno.fhora >= hora and objturno.ihora <= hora ) #Verifica que se encuentra en hora de aviso else: #Sin horario, por defecto todas las horas son validas horavalida = True if horavalida: no_avisos = TrackSondasAlarmas.objects.filter( tracksonda_id=objreg.tracksondas.id, dateaviso__gte=tantes).count() logger.debug("Cuenta no de aviso %s" % no_avisos) if no_avisos is None: TrackSondasAlarmas.objects.create(**sondalarm) elif no_avisos in (13, 21, 34): listapersonas = Personal.objects.filter( detalleconfiguracion__id=envio.id, emailnotifica__isnull=False, telefonosms__isnull=False) if listapersonas != []: email = [] titulo = objreg.denominacion() mensaje = "Alarma %s excede valor %s, valor actual ** %s ** " % ( titulo, consigna, temp['Temperature__avg']) for direccion in listapersonas: #Listas Personas if envio.accion == 'S' or envio.accion == 'Z': result = client.send( unicode(mensaje, 'utf8'), direccion.telefonosms) messager_id = result['message_id'].keys( )[0] logger.debug("Envia Mensajes %s" % mensaje) objtrack = TrackSondasAlarmas.objects.filter( tracksonda_id=objreg.tracksondas.id, dateaviso__gte=tantes, idavisosms__isnull=True).update( idavisosms=messager_id) if envio.accion == 'Z': email.append(direccion.emailnotifica) if envio.accion == 'Z': send_mail( "Urgente - Alarmas de fecha %s" % hoy, mensaje, remitente, email) logger.debug("Envia email a %s " % email) TrackSondasAlarmas.objects.create(**sondalarm) else: TrackSondasAlarmas.objects.create(**sondalarm) logger.debug(sondalarm)