Difference between revisions of "SMS and Email Responder"

From Unallocated Space
Jump to navigation Jump to search
(Created page with "Here is the code for the sensor responder using gmail and google voice -Textile <pre> #!/usr/bin/python2.6 import imaplib,smtplib,re,urllib,urllib2,time from email.mime.text imp...")
 
Line 2: Line 2:
 
-Textile
 
-Textile
  
<pre>
+
<pre>#!/usr/bin/python2.6
#!/usr/bin/python2.6
+
import imaplib,smtplib,re,urllib,urllib2,time,socket
import imaplib,smtplib,re,urllib,urllib2,time
 
 
from email.mime.text import MIMEText
 
from email.mime.text import MIMEText
import pdb
+
import pdb,os
 +
class actions:
 +
    def __init__(self):
 +
        pass
 +
 
 +
    def status(self,X=None):
 +
        f = open('/tmp/status','r')
 +
        stat = f.read()
 +
        f.close()
 +
        return stat
 +
 
 +
    def address(self,X=None):
 +
        return "512 Shaw Court suite 105\nSevern, MD 21122"
 +
   
 +
    def sign(self,data):
 +
data=data.replace('"','')
 +
data=data.replace("'",'')
 +
try:
 +
if data=="":
 +
message='The last sign update read as: '+open('/tmp/sign','r').read()
 +
                else:
 +
                        if '<FO>' in data:
 +
                                message="<FO> is not allowed"
 +
                        else:
 +
                                s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 +
                                s.connect(('127.0.0.1',9001))
 +
                                s.sendall(data)
 +
                                message=s.recv(1024)
 +
                                s.close()
 +
if "Updating sign to " in message:
 +
os.system("echo 'Mobile update to sign: "+data+"' > /uas/irc/irc")
 +
        except socket.error:
 +
                message="Failed to update sign"
 +
        return message
 +
       
 
class emailResponder:
 
class emailResponder:
def __init__(self):
+
        def __init__(self):
#list of trigger words
+
            cmd = actions()
self.trigger = ['status','address']
+
            self.trigger = {'status':cmd.status,'address':cmd.address,'sign':cmd.sign}
 +
            self.msg = None
  
def parse(self):
+
        def parse(self):
fromaddy = None
+
            fromaddy = None
subject = None
+
            subject = None
self.body.reverse()
+
            self.body.reverse()
for field in self.body:
+
            for field in self.body:
if field[:5] == 'From:':
+
                if field[:5] == 'From:':
fromaddy = field.split('<')[-1][:-1]
+
                    fromaddy = field.split('<')[-1][:-1]
elif field[:8] == 'Subject:':
+
                elif field[:8] == 'Subject:':
subject = field.split(' ')[1].strip().lower()
+
                    subject = field.split(' ')[1].strip().lower()
if subject not in self.trigger:
+
                    self.msg = ' '.join(field.split(' ')[1:])
subject = None
+
                    if subject not in self.trigger.keys():
if fromaddy and subject != None:
+
                        subject = None
return (fromaddy,subject)
+
            if fromaddy and subject != None:
else: return False
+
                return (fromaddy,subject)
+
            else: return False
def getMessage(self,msg):
+
       
if msg == 'status':
+
        def getMessage(self,msg):
f = open('/tmp/status','r')
+
            if msg in self.trigger.keys():
stat = f.read()
+
                return self.trigger[msg](self.msg) #call function
f.close()
+
            else:
return stat
+
                return "Invalid Command"
elif msg == 'address':
 
return "512 Shaw Court suite 105\nSevern, MD 21122"
 
 
  
def getUnread(self):
+
        def getUnread(self):
"""
+
            """
get unread messages and return subject and from address
+
            get unread messages and return subject and from address
"""
+
            """
self.messages = {}
+
            self.messages = {}
mbox = imaplib.IMAP4_SSL('imap.gmail.com', 993)
+
            mbox = imaplib.IMAP4_SSL('imap.gmail.com', 993)
mbox.login(*****,*****)
+
            mbox.login(######################,################)
status, count = mbox.select('EmailResponder')
+
            status, count = mbox.select('EmailResponder')
#print count #number of total messages
+
            #print count #number of total messages
typ, data = mbox.search(None, 'UNSEEN')
+
            typ, data = mbox.search(None, 'UNSEEN')
for num in data[0].split():
+
            for num in data[0].split():
typ, data = mbox.fetch(num, '(RFC822)')
+
                typ, data = mbox.fetch(num, '(RFC822)')
self.body = data[0][1].split('\r\n')
+
                self.body = data[0][1].split('\r\n')
data = self.parse()
+
                data = self.parse()
if data is not False:
+
                if data is not False:
self.messages[data[0]] = {"subject":data[1],"from":data[0]}
+
                    self.messages[data[0]] = {"subject":data[1],"from":data[0]}
mbox.close()
+
            mbox.close()
mbox.logout()
+
            mbox.logout()
  
def sendRespond(self,responce,toaddy):
+
        def sendRespond(self,responce,toaddy):
server = smtplib.SMTP("smtp.gmail.com",587)
+
            server = smtplib.SMTP("smtp.gmail.com",587)
server.ehlo('x')
+
            server.ehlo('x')
server.starttls()
+
            server.starttls()
server.ehlo('x')
+
            server.ehlo('x')
server.login(*****,*****)
+
            server.login(######################,################)
server.sendmail('*****@gmail.com',toaddy,responce)
+
            server.sendmail('uasstatus@gmail.com',toaddy,responce)
  
def status(self,toaddy):
+
        def status(self,toaddy):
"""
+
            """
format the responce from the sensor into an email message and return it
+
            format the responce from the sensor into an email message and return it
"""
+
            """
stat = self.getMessage(self.messages[toaddy]['subject'])
+
            stat = self.getMessage(self.messages[toaddy]['subject'])
msg = MIMEText(stat+"\n\nTeach, Learn, Party")
+
            msg = MIMEText(stat+"\n\nTeach, Learn, Party")
msg['Subject'] = stat
+
            msg['Subject'] = stat
msg['From'] = "*****@gmail.com"
+
            msg['From'] = "uasstatus@gmail.com"
msg['To'] = toaddy
+
            msg['To'] = toaddy
return str(msg)
+
            return str(msg)
+
       
def respond(self):
+
        def respond(self):
self.getUnread()
+
            self.getUnread()
if len(self.messages) == 0:
+
            if len(self.messages) == 0:
return
+
                return
else:
+
            else:
for key in self.messages.keys():
+
                for key in self.messages.keys():
toaddy = self.messages[key]['from']
+
                    toaddy = self.messages[key]['from']
self.sendRespond(
+
                    self.sendRespond(
self.status(toaddy),toaddy)
+
                        self.status(toaddy),toaddy)
  
 
class textResponder:
 
class textResponder:
def __init__(self):
+
        def __init__(self):
#list of trigger words
+
            cmd = actions()
self.trigger = ['status','address']
+
            self.trigger = {'status':cmd.status,'address':cmd.address,'sign':cmd.sign}
 +
            self.msg = None
 +
            self.fromaddy = None
 +
 
 +
        def getUnread(self):
 +
            """
 +
            get unread messages and return subject and from address
 +
            """
 +
            self.messages = {}
 +
            mbox = imaplib.IMAP4_SSL('imap.gmail.com', 993)
 +
            mbox.login(######################,################)
 +
            status, count = mbox.select('TXTMESSAGE')
 +
            #print count #number of total messages
 +
            typ, data = mbox.search(None, 'UNSEEN')
 +
            for num in data[0].split():
 +
                typ, data = mbox.fetch(num, '(RFC822)')
 +
                self.body = data[0][1].split('\r\n')
 +
                data = self.parse()
 +
                if data is not False:
 +
                    #we do this so multiple text messages are not sent to the same user based on email history
 +
                    #its a hack but it works
 +
                    self.messages[data[0]] = {"from":data[0],"msg":data[1]}
 +
            mbox.close()
 +
            mbox.logout()
  
def getUnread(self):
+
        def parse(self):
"""
+
            fromaddy = None
get unread messages and return subject and from address
+
            msg = None
"""
+
            self.body.reverse()
self.messages = {}
+
            for field in self.body:
mbox = imaplib.IMAP4_SSL('imap.gmail.com', 993)
+
                if field[:5] == 'From:':
mbox.login(*****,*****)
+
                    fromaddy = field.split('<')[-1][:-1].split('.')[1]
status, count = mbox.select('TXTMESSAGE')
+
                    self.fromaddy = fromaddy
#print count #number of total messages
+
                elif field.lower().split(' ')[0] in self.trigger.keys():
typ, data = mbox.search(None, 'UNSEEN')
+
                    msg = field.lower().split(' ')[0]
for num in data[0].split():
+
                    self.msg = ' '.join(field.lower().split(' ')[1:])
typ, data = mbox.fetch(num, '(RFC822)')
+
            if fromaddy and msg != None:
self.body = data[0][1].split('\r\n')
+
                return (fromaddy,msg)
data = self.parse()
+
            else: return False
if data is not False:
+
       
#we do this so multiple text messages are not sent to the same user
+
        def getMessage(self,msg):
#its a hack but it works
+
            if msg in self.trigger.keys():
self.messages[data[0]] = {"from":data[0],"msg":data[1]}
+
return self.trigger[msg](self.msg) #call function
mbox.close()
+
            else:
mbox.logout()
+
                return "Invalid Command"
  
def parse(self):
+
        def respond(self):
fromaddy = None
+
            self.getUnread()
msg = None
+
            #check to see if there are any messages to be sent and return
self.body.reverse()
+
            if len(self.messages) == 0:
for field in self.body:
+
                return  
if field[:5] == 'From:':
+
            gv = GoogleVoiceLogin(######################,################)
fromaddy = field.split('<')[-1][:-1].split('.')[1]
+
            if not gv.logged_in:
elif field.lower() in self.trigger:
+
                print "voice login failed"
msg = field.lower()
+
                return
if fromaddy and msg != None:
+
            for number in self.messages.keys():
return (fromaddy,msg)
+
                text_sender = TextSend(gv.opener, gv.key)
else: return False
+
                text_sender.text = self.getMessage(self.messages[number]['msg'])
+
                text_sender.send_text(number)
def getMessage(self,msg):
+
                #following 5 lines are used for debug
if msg == 'status':
+
                #if text_sender.responce:
f = open('/tmp/status','r')
+
                #   print text_sender.responce
stat = f.read()
+
                #   print "success"
f.close()
+
                #else:
return stat
+
                #   print "failed"
elif msg == 'address':
+
                #sleep so as not to have google think we are trying to txt message spam
return "512 Shaw Court suite 105\nSevern, MD 21122"
+
                time.sleep(3)
+
               
def respond(self):
 
self.getUnread()
 
#check to see if there are any messages to be sent and return
 
if len(self.messages) == 0:
 
return  
 
gv = GoogleVoiceLogin(*****,*****)
 
if not gv.logged_in:
 
print "voice login failed"
 
return
 
for number in self.messages.keys():
 
text_sender = TextSend(gv.opener, gv.key)
 
text_sender.text = self.getMessage(self.messages[number]['msg'])
 
text_sender.send_text(number)
 
#following 5 lines are used for debug
 
#if text_sender.responce:
 
# print text_sender.responce
 
# print "success"
 
#else:
 
# print "failed"
 
#sleep so as not to have google think we are trying to txt message spam
 
time.sleep(3)
 
 
 
class TextSend():
 
class TextSend():
"""
+
    """
text send coded taken from here
+
    text send coded taken from here
http://everydayscripting.blogspot.com/2009/08/python-google-voice-mass-sms-and-mass.html
+
    http://everydayscripting.blogspot.com/2009/08/python-google-voice-mass-sms-and-mass.html
"""
+
    """
def __init__(self, opener, key):
+
    def __init__(self, opener, key):
self.opener = opener
+
        self.opener = opener
self.key = key
+
        self.key = key
self.sms_url = "https://www.google.com/voice/sms/send/"
+
        self.sms_url = "https://www.google.com/voice/sms/send/"
self.text = ''
+
        self.text = ''
  
def send_text(self, phone_number):
+
    def send_text(self, phone_number):
sms_params = urllib.urlencode({
+
        sms_params = urllib.urlencode({
'_rnr_se': self.key,
+
        '_rnr_se': self.key,
'phoneNumber': phone_number,
+
        'phoneNumber': phone_number,
'text': self.text
+
        'text': self.text
})
+
        })
#send the text
+
        #send the text
self.responce = self.opener.open(self.sms_url, sms_params).read()
+
        self.responce = self.opener.open(self.sms_url, sms_params).read()
  
 
class GoogleVoiceLogin:
 
class GoogleVoiceLogin:
"""
+
    """
gvoice code from here
+
    gvoice code from here
http://everydayscripting.blogspot.com/2009/08/python-google-voice-mass-sms-and-mass.html
+
    http://everydayscripting.blogspot.com/2009/08/python-google-voice-mass-sms-and-mass.html
"""
+
    """
def __init__(self, email, password):
+
    def __init__(self, email, password):
# Set up our opener
+
        # Set up our opener
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
+
        self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(self.opener)
+
        urllib2.install_opener(self.opener)
+
                       
# Define URLs
+
        # Define URLs
self.loing_page_url = 'https://www.google.com/accounts/ServiceLogin'
+
        self.loing_page_url = 'https://www.google.com/accounts/ServiceLogin'
self.authenticate_url = 'https://www.google.com/accounts/ServiceLoginAuth'
+
        self.authenticate_url = 'https://www.google.com/accounts/ServiceLoginAuth'
self.gv_home_page_url = 'https://www.google.com/voice/#inbox'
+
        self.gv_home_page_url = 'https://www.google.com/voice/#inbox'
+
                                                   
# Load sign in page
+
        # Load sign in page
login_page_contents = self.opener.open(self.loing_page_url).read()
+
        login_page_contents = self.opener.open(self.loing_page_url).read()
  
# Find GALX value
+
        # Find GALX value
galx_match_obj = re.search(r'name="GALX"\s*value="([^"]+)"', login_page_contents, re.IGNORECASE)
+
        galx_match_obj = re.search(r'name="GALX"\s*value="([^"]+)"', login_page_contents, re.IGNORECASE)
+
                                                                               
galx_value = galx_match_obj.group(1) if galx_match_obj.group(1) is not None else ''
+
        galx_value = galx_match_obj.group(1) if galx_match_obj.group(1) is not None else ''
# Set up login credentials
+
        # Set up login credentials
login_params = urllib.urlencode( {
+
        login_params = urllib.urlencode( {
'Email' : email,
+
            'Email' : email,
'Passwd' : password,
+
            'Passwd' : password,
'continue' : 'https://www.google.com/voice/account/signin',
+
            'continue' : 'https://www.google.com/voice/account/signin',
'GALX': galx_value
+
            'GALX': galx_value
})
+
            })
# Login
+
        # Login
self.opener.open(self.authenticate_url, login_params)
+
        self.opener.open(self.authenticate_url, login_params)
  
# Open GV home page
+
        # Open GV home page
gv_home_page_contents = self.opener.open(self.gv_home_page_url).read()
+
        gv_home_page_contents = self.opener.open(self.gv_home_page_url).read()
# Fine _rnr_se value
+
        # Fine _rnr_se value
key = re.search('name="_rnr_se".*?value="(.*?)"', gv_home_page_contents)
+
        key = re.search('name="_rnr_se".*?value="(.*?)"', gv_home_page_contents)
if not key:
+
        if not key:
self.logged_in = False
+
            self.logged_in = False
else:
+
        else:
self.logged_in = True
+
            self.logged_in = True
self.key = key.group(1)
+
            self.key = key.group(1)
  
 
if __name__ == "__main__":
 
if __name__ == "__main__":
emailResponder().respond()
+
    emailResponder().respond()
textResponder().respond()
+
    textResponder().respond()
 +
 
 
</pre>
 
</pre>

Revision as of 14:05, 6 September 2011

Here is the code for the sensor responder using gmail and google voice -Textile

#!/usr/bin/python2.6
import imaplib,smtplib,re,urllib,urllib2,time,socket
from email.mime.text import MIMEText
import pdb,os
class actions:
    def __init__(self):
        pass

    def status(self,X=None):
        f = open('/tmp/status','r')
        stat = f.read()
        f.close()
        return stat

    def address(self,X=None):
        return "512 Shaw Court suite 105\nSevern, MD 21122"
    
    def sign(self,data):
	data=data.replace('"','')
	data=data.replace("'",'')
	try:
		if data=="":
			message='The last sign update read as: '+open('/tmp/sign','r').read()
                else:	
                        if '<FO>' in data:
                                message="<FO> is not allowed"
                        else:
                                s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
                                s.connect(('127.0.0.1',9001))
                                s.sendall(data)
                                message=s.recv(1024)
                                s.close()
				if "Updating sign to " in message:
					os.system("echo 'Mobile update to sign: "+data+"' > /uas/irc/irc")
        except socket.error:
                message="Failed to update sign"
        return message
        
class emailResponder:
        def __init__(self):
            cmd = actions()
            self.trigger = {'status':cmd.status,'address':cmd.address,'sign':cmd.sign}
            self.msg = None

        def parse(self):
            fromaddy = None
            subject = None
            self.body.reverse()
            for field in self.body:
                if field[:5] == 'From:':
                    fromaddy = field.split('<')[-1][:-1]
                elif field[:8] == 'Subject:':
                    subject = field.split(' ')[1].strip().lower()
                    self.msg = ' '.join(field.split(' ')[1:])
                    if subject not in self.trigger.keys():
                        subject = None
            if fromaddy and subject != None:
                return (fromaddy,subject)
            else: return False
        
        def getMessage(self,msg):
            if msg in self.trigger.keys():
                return self.trigger[msg](self.msg) #call function
            else:
                return "Invalid Command"

        def getUnread(self):
            """
            get unread messages and return subject and from address
            """
            self.messages = {}
            mbox = imaplib.IMAP4_SSL('imap.gmail.com', 993)
            mbox.login(######################,################)
            status, count = mbox.select('EmailResponder')
            #print count #number of total messages
            typ, data = mbox.search(None, 'UNSEEN')
            for num in data[0].split():
                typ, data = mbox.fetch(num, '(RFC822)')
                self.body = data[0][1].split('\r\n')
                data = self.parse()
                if data is not False:
                    self.messages[data[0]] = {"subject":data[1],"from":data[0]}
            mbox.close()
            mbox.logout()

        def sendRespond(self,responce,toaddy):
            server = smtplib.SMTP("smtp.gmail.com",587)
            server.ehlo('x')
            server.starttls()
            server.ehlo('x')
            server.login(######################,################)
            server.sendmail('uasstatus@gmail.com',toaddy,responce)

        def status(self,toaddy):
            """
            format the responce from the sensor into an email message and return it
            """
            stat = self.getMessage(self.messages[toaddy]['subject'])
            msg = MIMEText(stat+"\n\nTeach, Learn, Party")
            msg['Subject'] = stat
            msg['From'] = "uasstatus@gmail.com"
            msg['To'] = toaddy
            return str(msg)
        
        def respond(self):
            self.getUnread()
            if len(self.messages) == 0:
                return
            else:
                for key in self.messages.keys():
                    toaddy = self.messages[key]['from']
                    self.sendRespond(
                        self.status(toaddy),toaddy)

class textResponder:
        def __init__(self):
            cmd = actions()
            self.trigger = {'status':cmd.status,'address':cmd.address,'sign':cmd.sign}
            self.msg = None
            self.fromaddy = None

        def getUnread(self):
            """
            get unread messages and return subject and from address
            """
            self.messages = {}
            mbox = imaplib.IMAP4_SSL('imap.gmail.com', 993)
            mbox.login(######################,################)
            status, count = mbox.select('TXTMESSAGE')
            #print count #number of total messages
            typ, data = mbox.search(None, 'UNSEEN')
            for num in data[0].split():
                typ, data = mbox.fetch(num, '(RFC822)')
                self.body = data[0][1].split('\r\n')
                data = self.parse()
                if data is not False:
                    #we do this so multiple text messages are not sent to the same user based on email history
                    #its a hack but it works
                    self.messages[data[0]] = {"from":data[0],"msg":data[1]}
            mbox.close()
            mbox.logout()

        def parse(self):
            fromaddy = None
            msg = None
            self.body.reverse()
            for field in self.body:
                if field[:5] == 'From:':
                    fromaddy = field.split('<')[-1][:-1].split('.')[1]
                    self.fromaddy = fromaddy
                elif field.lower().split(' ')[0] in self.trigger.keys():
                    msg = field.lower().split(' ')[0]
                    self.msg = ' '.join(field.lower().split(' ')[1:])
            if fromaddy and msg != None:
                return (fromaddy,msg)
            else: return False
        
        def getMessage(self,msg):
            if msg in self.trigger.keys():
		return self.trigger[msg](self.msg) #call function
            else:
                return "Invalid Command"

        def respond(self):
            self.getUnread()
            #check to see if there are any messages to be sent and return
            if len(self.messages) == 0:
                return 
            gv = GoogleVoiceLogin(######################,################)
            if not gv.logged_in:
                print "voice login failed"
                return
            for number in self.messages.keys():
                text_sender = TextSend(gv.opener, gv.key)
                text_sender.text = self.getMessage(self.messages[number]['msg'])
                text_sender.send_text(number)
                #following 5 lines are used for debug
                #if text_sender.responce:
                #   print text_sender.responce
                #   print "success"
                #else:
                #   print "failed"
                #sleep so as not to have google think we are trying to txt message spam
                time.sleep(3)
                
class TextSend():
    """
    text send coded taken from here
    http://everydayscripting.blogspot.com/2009/08/python-google-voice-mass-sms-and-mass.html
    """
    def __init__(self, opener, key):
        self.opener = opener
        self.key = key
        self.sms_url = "https://www.google.com/voice/sms/send/"
        self.text = ''

    def send_text(self, phone_number):
        sms_params = urllib.urlencode({
        '_rnr_se': self.key,
        'phoneNumber': phone_number,
        'text': self.text
        })
        #send the text
        self.responce = self.opener.open(self.sms_url, sms_params).read()

class GoogleVoiceLogin:
    """
    gvoice code from here
    http://everydayscripting.blogspot.com/2009/08/python-google-voice-mass-sms-and-mass.html
    """
    def __init__(self, email, password):
        # Set up our opener
        self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
        urllib2.install_opener(self.opener)
                        
        # Define URLs
        self.loing_page_url = 'https://www.google.com/accounts/ServiceLogin'
        self.authenticate_url = 'https://www.google.com/accounts/ServiceLoginAuth'
        self.gv_home_page_url = 'https://www.google.com/voice/#inbox'
                                                    
        # Load sign in page
        login_page_contents = self.opener.open(self.loing_page_url).read()

        # Find GALX value
        galx_match_obj = re.search(r'name="GALX"\s*value="([^"]+)"', login_page_contents, re.IGNORECASE)
                                                                                
        galx_value = galx_match_obj.group(1) if galx_match_obj.group(1) is not None else ''
        # Set up login credentials  
        login_params = urllib.urlencode( {
            'Email' : email,
            'Passwd' : password,
            'continue' : 'https://www.google.com/voice/account/signin',
            'GALX': galx_value
            })
        # Login
        self.opener.open(self.authenticate_url, login_params)

        # Open GV home page
        gv_home_page_contents = self.opener.open(self.gv_home_page_url).read()
        # Fine _rnr_se value
        key = re.search('name="_rnr_se".*?value="(.*?)"', gv_home_page_contents)
        if not key:
            self.logged_in = False
        else:
            self.logged_in = True
            self.key = key.group(1)

if __name__ == "__main__":
    emailResponder().respond()
    textResponder().respond()