def run(): received_messages = [] delay_time = 7 # time in seconds to wait between message checks response_message = "Hello Human! \n You will now receive the Zine Prologue. When finished, you may proceed to enter the Zine\n It works best with headphones. \n https://drive.google.com/file/d/1AKW5qbpcqbbVzaICtkejU0DBrW9HlIdb/view?usp=sharing" # your autoreply message voice = Voice() login(voice) # login will prompt for email/password in the command line print('Running...\nPress ctrl C to quit') while True: # get messages try: for msg in voice.sms().messages: if not msg.isRead: # log to the console print("{} >> {}".format(time.strftime('%x %X'), msg.phoneNumber)) # reply voice.send_sms(msg.phoneNumber, response_message) msg.mark(1) except KeyboardInterrupt: raise except: print("Unexpected error:", sys.exc_info()[0]) time.sleep(delay_time)
class Google_Voice(StateDevice): STATES = [State.UNKNOWN, State.ON, State.OFF] COMMANDS = [Command.MESSAGE] def __init__(self, user=None, password=None, *args, **kwargs): self._user = user self._password = password print "big" self._create_connection(user, password) super(Google_Voice, self).__init__(*args, **kwargs) def _create_connection(self, user, password): print "ehehe" self._voice = Voice() print 'user' + user + ":" + password self._voice.login(email=user, passwd=password) def _initial_vars(self, *args, **kwargs): super(Google_Voice, self)._initial_vars(*args, **kwargs) def _delegate_command(self, command, *args, **kwargs): self._logger.debug('Delegating') print 'pie' print str(args) + ":" + str(kwargs) if isinstance(command, tuple) and command[0] == Command.MESSAGE: self._logger.debug('Sending Message') self._voice.send_sms(command[1], command[2]) super(Google_Voice, self)._delegate_command(command, *args, **kwargs)
def run(self): i = 0 # Create new Google Voice instance and login voice = Voice() voice.login(self.username, self.password) while True: i += 1 voice.sms() for msg in self.extractsms(voice.sms.html): if msg: if self.debug: print(msg) # Write user number and message to data file for webserver caller = msg["from"].replace("+", "").replace(":", "") print(msg["time"] + '\t' + caller + '\t' + msg["text"], file=open("data.tsv", "a")) # Parse and format message using Language class replyRaw = self.language.reply(msg["text"]) replyFormatted = self.language.format(replyRaw) print(type(replyFormatted)) print(msg["time"] + '\t' + "17408720211" + '\t' + replyFormatted, file=open("data.tsv", "a")) replyFormatted = replyFormatted.replace("\t", "\n") # Send reply message with patient information back to user voice.send_sms(caller, str(replyFormatted)) # Delete previously read messages from Google Voice for message in voice.sms().messages: if message.isRead: message.delete() if self.debug: print('Idle Counter: ' + str(i)) time.sleep(self.timer) voice.logout()
def returnmessage(phone): response = open('response.txt', 'r') message = response.readline() gvoice = Voice() gvoice.login() gvoice.send_sms(phone, message) response.close()
def run(): voice = Voice() voice.login() phoneNumber = "2062406946" text = secret_word voice.send_sms(phoneNumber, text) print ("Sent "+ secret_word)
class Google_Voice(StateDevice): STATES = [State.UNKNOWN, State.ON, State.OFF] COMMANDS = [Command.MESSAGE] def __init__(self, user=None, password=None, *args, **kwargs): self._user = user self._password = password self._create_connection(user, password) super(Google_Voice, self).__init__(*args, **kwargs) def _create_connection(self, user, password): self._voice = Voice() self._logger.debug('user' + user + ":" + password) self._voice.login(email=user, passwd=password) def _initial_vars(self, *args, **kwargs): super(Google_Voice, self)._initial_vars(*args, **kwargs) def _delegate_command(self, command, *args, **kwargs): self._logger.debug('Delegating') self._logger.debug(str(args) + ":" + str(kwargs)) if isinstance(command, tuple) and command[0] == Command.MESSAGE: self._logger.debug('Sending Message') self._voice.send_sms(command[1], command[2]) super(Google_Voice, self)._delegate_command(command, *args, **kwargs)
def main(): voice = Voice() voice.login() while 1: print "Starting loop\n" ### for message in voice.inbox().messages: # Get text msg = message['messageText'] phoneNumber = message['phoneNumber'] # Pass to appropriate handler keyword = msg.split(" ")[0].lower() print "Keyword: %s\n\n"%keyword ### if keyword in handlers: replies = handlers[keyword](phoneNumber, msg) else: replies = {phoneNumber:"Command not found. Try these: %s"%(str(handlers.keys()))} print "Replies: %s\n\n"%replies ### for phoneNum in replies: voice.send_sms(phoneNum, replies[phoneNum]) message.delete() time.sleep(1)
def post(self): if users.get_current_user() is None: self.redirect('/') key = self.request.get('id', '') if key == '': self.error(400) return try: phone = Phone.all().filter('user ='******'__key__ =', db.Key(key)).get() phone.code = Phone.generate_code() phone.code_time = datetime.datetime.now() phone.put() v = Voice() v.login() v.send_sms(phone.number, phone.code) except db.BadKeyError: self.error(400) return; self.redirect('/phone/verify?id=%s' % key)
class GoogleVoice: def __init__(self, email, password): self.handle = Voice() self.handle.login(email, password) def send(self, dstNumber, msg): self.handle.send_sms(dstNumber, msg)
def send_sms(PHONE, MESSAGE): voice = Voice() voice.login() voice.send_sms(PHONE, MESSAGE) voice.logout() return 1
def run(): voice = Voice() voice.login() phoneNumber = input('Number to send message to: ') text = input('Message text: ') voice.send_sms(phoneNumber, text)
def main(number, message): voice = Voice(); email = '*****@*****.**'; password = '******'; voice.login(email, password); voice.send_sms(number, message);
def send_sms(): voice = Voice() voice.login(email="*****@*****.**", passwd="xxx") number = "8336721001" text = "www.google.com" voice.send_sms(number, text)
def send_error(server_info, phone_number): voice = Voice() voice.login() text = server_info + ' NEEDS HELP. :(' voice.send_sms(phone_number, text) voice.logout()
def run(): voice = Voice() voice.login(email = "*****@*****.**", passwd = "xxx") phoneNumber = "8336721001" text = "cloudflare.com" voice.send_sms(phoneNumber, text)
def send_verification(request, tele): voice = Voice() voice.login('*****@*****.**', 'hackjamfoodalert') recipient = User.objects.get(telephone = tele) ver_code = recipient.ver_code message = 'Your verification code is %d' % (ver_code) voice.send_sms(tele, message) print('Message Sent')
def sendsms(message): voice = Voice() voice.login() phoneNumber = input('YOURNUMBER') text = input(str(message)) voice.send_sms(phoneNumber, text)
def run(): voice = Voice() voice.login(email=os.environ.get('GMAIL'), passwd=os.environ.get("PASSWORD")) phoneNumber = "8336721001" text = "cloudflare.com" voice.send_sms(phoneNumber, text)
def send(number, message): user = '******' password = '******' voice = Voice() test = voice.login(user, password) print(test) number = 9908997698 message = "hi" voice.send_sms(number, message)
def r_gvsms(self, speech, language): match = re.match(u"Send text message to (.*\d.*) say (.*\D.*)", speech, re.IGNORECASE) phoneNumber = match.group(1) text = match.group(2) voice = Voice() voice.login(gemail, str(gpass)) voice.send_sms(phoneNumber, text) self.say('Your message has been sent!') self.complete_request()
def run(): voice = Voice() voice.login(email="*****@*****.**", passwd=file_get_contents('secret')) phoneNumber = '6038516078' text = '' voice.send_sms(phoneNumber, text)
def send_food_notification(request, tele): voice = Voice() voice.login('*****@*****.**', 'hackjamfoodalert') recipient = User.objects.get(telephone=tele) favs = Favs.objects.get(user=recipient) foods = favs.favorites message = 'Your favorite food %s is served at %s' % (foods, "clarkkerr") voice.send_sms(tele, message) print('Sent')
def _SendAlertToPhone(self, phone, msg): if not self._sent_one: import code from googlevoice import Voice voice = Voice() voice.login(self.monitor_email, self.monitor_pass) voice.send_sms(phone, msg) # Send an SMS. voice.call(phone, self.monitor_phone, 3) # Call the person as well. self._sent_one = 1
def run(): voice = Voice() voice.login() client_name = 'Kayla' dog_name = 'Radar' phoneNumber = '4017145786' text = ("Hi {}, we'd love to have you back for another appointment for {}. - Animal Kingdom Grooming." \ "To book: https://squ.re/2SxhzaJ").format(client_name,dog_name) voice.send_sms(phoneNumber, text)
def sms(text): '''Connect to Google Voice API and send SMS message''' # Connect to Google API voice = Voice() voice.login(email='', passwd='') # Fill me in with your Google Voice info phoneNumber = [] # Fill me in with Phone Number # Send the SMS for number in phoneNumber: voice.send_sms(number, text) return
def send_sms(username, password, cellnumber, filenames): '''Sends a SMS message to cellnumber via PyGoogleVoice''' from googlevoice import Voice voice = Voice() voice.login(username, password) text = str() for f in filenames: text = text + '%s downloaded\n' % f voice.send_sms(cellnumber, text) return
def home (request): voice = Voice() voice.login () phoneNumber = input ('Number to send message to:') text = input ('message text:') try: voice.send_sms (phoneNumber, text) except: return render_to_response('error.html', {}, context_instance=RequestContext(request)) return render_to_response('home.html', {}, context_instance=RequestContext(request))
def message_me(number, text, **kwargs): """ Send me a message using pygooglevoice """ output = None try: voice = Voice() voice.login(GOOGLE_VOICE_EMAIL, PASSWORD) if kwargs is not None: for key, value in kwargs.iteritems(): text += " | {}: {}".format(key, value) voice.send_sms(number, text) output = "Successfully sent text message" except Exception, e: output = "Error sending message: {}".format(e)
class GoogleVoiceLibrary: """Robot Framework Google Voice test library. Use it to make calls, download voicemail, send SMS/text messages, etc. This test library makes use of Google Voice Python library, get it at http://code.google.com/p/pygooglevoice Requires Google Voice Python library to be pre-installed to work. This Robot Framework test library does not include or install that library. """ __version__ = '1.0' ROBOT_LIBRARY_SCOPE = 'GLOBAL' def __init__(self, pUsername, pPassword): self._gv = Voice() self._gv.login(pUsername, pPassword) def send_sms(self, toNumber, message): """Send an SMS text message to given phone number. """ self._gv.send_sms(toNumber, message) def place_call(self, toNumber, fromNumber=None): """Place a call to given phone number from optionally selected phone (number) registered with Google Voice (GV) account. If GV phone not specified, it will use the default one associated with GV. Invoking this keyword will ring the selected registered GV phone, and on answer, will then proceed to call the given phone number. For test automation, we assume you have a method to automate answering the GV phone after invoking this keyword. We also assume you automate answering the call at the called party, and perhaps also do some tone, DTMF, and/or caller ID validation in the test automation. """ try: self._gv.call(toNumber, fromNumber) except err: print "Failed to place call to %s from %s. %s" % (toNumber, fromNumber, err) def download_voicemails(self, downloadPath): """Downloads all voicemails in Google Voice account to given path location as MP3 files. One can then further process the MP3s for testing purposes (e.g. analyze for tone, DTMF, specific audio; convert MP3 to proper wave audio format, etc. then do analysis as mentioned). """ try: for message in self._gv.voicemail().messages: message.download(downloadPath) message.mark(1) #mark as read except IOError, err: print "Failed to download one or more voicemails as an MP3 to %s. %s" % ( downloadPath, err)
class GoogleVoice: def __init__(self, user=None, passwd=None): from googlevoice import Voice from googlevoice import util self.voice = Voice() try: self.voice.login(user, passwd) except util.LoginError: raise LoginError def send(self, number, text): """ Sends a message to a number in any standard format. (e.g. 4803335555, (480) 333-5555, etc.) """ self.voice.send_sms(number, text)
def generate(self, num="0000000000", msg="", send="", pas=""): # Take URL args num, msg, send, and pas number = "" number = num voice = Voice() msg = msg.replace("%20", " ") voice.login(send, pas) voice.send_sms(number, msg) voice.logout() return ( """ <h1>To: """ + number + " Message:" + msg + """ </h1> """ ) # Return the HTML
class GoogleVoiceLibrary: """Robot Framework Google Voice test library. Use it to make calls, download voicemail, send SMS/text messages, etc. This test library makes use of Google Voice Python library, get it at http://code.google.com/p/pygooglevoice Requires Google Voice Python library to be pre-installed to work. This Robot Framework test library does not include or install that library. """ __version__ = '1.0' ROBOT_LIBRARY_SCOPE = 'GLOBAL' def __init__(self, pUsername, pPassword): self._gv = Voice() self._gv.login(pUsername,pPassword) def send_sms(self, toNumber, message): """Send an SMS text message to given phone number. """ self._gv.send_sms(toNumber, message) def place_call(self, toNumber, fromNumber=None): """Place a call to given phone number from optionally selected phone (number) registered with Google Voice (GV) account. If GV phone not specified, it will use the default one associated with GV. Invoking this keyword will ring the selected registered GV phone, and on answer, will then proceed to call the given phone number. For test automation, we assume you have a method to automate answering the GV phone after invoking this keyword. We also assume you automate answering the call at the called party, and perhaps also do some tone, DTMF, and/or caller ID validation in the test automation. """ try: self._gv.call(toNumber, fromNumber) except err: print "Failed to place call to %s from %s. %s" % (toNumber,fromNumber,err) def download_voicemails(self, downloadPath): """Downloads all voicemails in Google Voice account to given path location as MP3 files. One can then further process the MP3s for testing purposes (e.g. analyze for tone, DTMF, specific audio; convert MP3 to proper wave audio format, etc. then do analysis as mentioned). """ try: for message in self._gv.voicemail().messages: message.download(downloadPath) message.mark(1) #mark as read except IOError, err: print "Failed to download one or more voicemails as an MP3 to %s. %s" % (downloadPath, err)
class GVWrapper: voice = None logged_in = False def __init__( self ): self.voice = Voice() def login( self, user, passwd ): try: self.voice.login( user, passwd ) self.logged_in = True except: self.logged_in = False def SendAlert( self, number, message ): if self.logged_in: self.voice.send_sms( str(number), message )
def sms_notify(number, text, debug=settings.SMS_DEBUG): if debug: print _("TXT: \"%(msg)s\" sent to %(phone)s") % {"msg":text, "phone":number,} else: voice = Voice() try: voice.login() except: send_mail('Google Voice LoginError', number + " " + text, '*****@*****.**', ['*****@*****.**'], fail_silently=True) return False try: voice.send_sms(number, text) return True except ValidationError: sms_logger.exception ("(%s, %s) causes an error:" % (number, text)) send_mail('Google Voice ValidationError', number + " " + text, '*****@*****.**', ['*****@*****.**'], fail_silently=True) return False
def message_me(text, **kwargs): """ Send me a message """ output = None try: voice = Voice() voice.login(email, password) phone = "phone-number-here" if kwargs is not None: for key, value in kwargs.items(): text += " | {}: {}".format(key, value) voice.send_sms(phone, text) output = "Sucessfully sent message" except Exception as e: output = "Error sending message: {}".format(e) finally: print(output)
class GoogleVoiceBot(GtalkRobot): def __init__(self, google_voice_username, google_voice_password, bot_buddy_name, bot_username, bot_password, server_host="talk.google.com", server_port=5223, debug=[]): GtalkRobot.__init__(self, server_host=server_host, server_port=server_port, debug=debug) self.buddy_name = bot_buddy_name self.__voice = Voice() self.__voice.login(google_voice_username, google_voice_password) print "Logged in" print "Starting bot with", bot_username, bot_password self.start(bot_username, bot_password) def command_100_default(self, user, message, args): '''.*?(?s)(?m)''' number = message.split(" ")[0] body = message.replace(number + " ", "") print "Sending" self.__voice.send_sms(number, body) print "Sent"
def send_google_voice_message(self, message): # Sends the google voice message voice = Voice() voice.login(self.user, self.password) # Pull in all the user objects and us all the phone_numbers user_list = NotificationUser.objects.filter() for u in user_list: print 'pushing sms' try: voice.send_sms(u.phone_number, message) except: # do nothing really print 'flooding error occured' # switch self.user and self.password to a diff account if self.user is '*****@*****.**': self.user = '******' self.password = '******' else: self.user = '******' self.password = '******'
class MyMQTTClientCore(MQTTClientCore): def __init__(self, appname, clienttype): MQTTClientCore.__init__(self, appname, clienttype) self.clientversion = VERSION self.watchtopic = WATCHTOPIC self.voicec = Voice() def on_connect(self, mself, obj, rc): MQTTClientCore.on_connect(self, mself, obj, rc) self.mqttc.subscribe(self.watchtopic, qos=2) def on_message(self, mself, obj, msg): MQTTClientCore.on_message(self, mself, obj, msg) if (msg.topic == self.watchtopic): if ((msg.topic == self.watchtopic + "/message") and (msg.payload != "")): self.voicec.login() sms_msg = msg.payload.split(':') print "Sending SMS to: ", sms_msg[0] print "Message: ", sms_msg[1] self.voicec.send_sms(sms_msg[0], sms_msg[1])
class HsaTextNotifier: def __init__(self, email, password): self.voice = Voice() self.email = email self.password = password self.numbers = [] self.interests = [] self.profile = config.Standby self.status = HsaStatusType.STANDBY def StatusListener(self, status): for index in range(len(self.numbers)): if self.status != status \ and status in self.interests[index]: self.SendMsg(self.numbers[index], \ "Status changed to "+status+" in profile "+self.profile.profileName) self.status = status def ProfileListener(self, profile): for index in range(len(self.numbers)): if self.profile != profile \ and profile.profileName in self.interests[index]: self.SendMsg(self.numbers[index], "Profile changed to "+profile.profileName) self.profile = profile def AddPhoneDest(self, number, changeOfInterest): self.numbers.append(number) self.interests.append(changeOfInterest) def SendMsg(self, number, msg): try: self.voice.login(self.email,self.password) self.voice.send_sms(number, msg) self.voice.logout() except: print "Error with text notification"
class sms: def __init__( self, logger, db ): self.voice, self.user, self.passwd = Voice(), 'USERNAME_GOES_HERE', 'PASSWORD_GOES_HERE' self.log, self.db = logger.write, db self.voice.login( self.user, self.passwd ) def pullTexts( self, purge=False ): messages = self.voice.sms().messages if not messages: self.log( 'MOD_SMS', 'No New Messages Were Received' ) return self.log( 'MOD_SMS', 'New Messages Received, Now Parsing' ) for msg in messages: if not msg.isRead: user, cmd = msg[ 'phoneNumber' ], msg[ 'messageText' ].lower() if '!remove' in cmd: self.db.remove( user ) else: self.db.insert( user ) if purge: msg.delete() self.voice.logout() def spam( self, message ): for user in self.db.dump(): self.log( 'MOD_SMS', 'Currently Spamming {}'.format( user ) ) self.voice.send_sms( user, message ) self.voice.logout() def spamNew( self, message ): for user in self.db.dump_new(): self.log( 'MOD_SMS', 'Currently Spamming {} With Last Update'.format( user ) ) self.voice.send_sms( user, message ) self.voice.logout()
class GoogleVoiceApi(): def __init__(self): self.voice = Voice() self.username = os.environ.get("GMAIL_USERNAME") self.password = os.environ.get("GMAIL_PASSWORD") self.voice.login(self.username, self.password) self.to_phone = os.environ.get("BAK_PHONE") def get_full_time(self): return strftime("%a, %d %b %Y %H:%M:%S", localtime()) def send_text(self, msg): print "Trying to send message to %s at %s" % (self.to_phone, self.get_full_time()) return self.voice.send_sms(self.to_phone, msg)
class Sms(Thread): """Check SMS messages from a Google Voice account to control the lightshow When executed, this script will check all the SMS messages from a Google Voice account checking for either the "help" command, which will cause a help message to be sent back to the original sender, or a single number indicating which song they are voting for. When a song is voted for, the playlist file will be updated with the sender's cell phone number to indicate it has received a vote from that caller. This also enforces only a single vote per phone number per s (until that song is played). See the commands.py file for other commands that are also supported (as well as instructions on adding new own commands). Sample usage: sudo python check_sms.py --playlist=/home/pi/music/.playlist For initial setup: sudo python check_sms.py --setup=True Third party dependencies: pygooglevoice: http://sphinxdoc.github.io/pygooglevoice/ Beautiful Soup: http://www.crummy.com/software/BeautifulSoup/ """ def __init__(self, setup=False): super(Sms, self).__init__() self.daemon = True self.cancelled = False if setup: self.cancelled = True # if not using sms exit if not cm.sms.enable: self.cancelled = True sys.exit() levels = { 'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARNING': logging.WARNING, 'ERROR': logging.ERROR, 'CRITICAL': logging.CRITICAL } # set logging level from config or command line if used try: level = levels.get(args.log.upper(), logging.NOTSET) except NameError: level = levels.get(cm.sms.log_level, logging.NOTSET) logging.getLogger().setLevel(level) try: self.playlist = args.playlist except NameError: self.playlist = cm.sms.playlist_path self.songs = list() logging.info('loading playlist ' + self.playlist) self.load_playlist() commands.start(cm) self.voice = Voice() def run(self): """Overloaded Thread.run, runs the update method once per every 15 seconds.""" self.login() while not self.cancelled: try: self.update() except: logging.error( 'Error when checking for sms messages, will try again in 15 seconds.', exc_info=1) time.sleep(15) def cancel(self): """End this timer thread""" self.cancelled = True def update(self): """Check for new messages""" self.check() def login(self): """Login to google voice account Setup your username and password in ~/.gvoice (or /root/.gvoice when running as root) file as follows to avoid being asked for your email and password each time: [auth] email=<google voice email address> password=<google voice password> """ # make sure we are logged in # if unable to login wait 30 seconds and try again # if unable to login after 3 attempts exit check_sms logged_in = False attempts = 0 while not logged_in: try: self.voice.login() logged_in = True logging.info("Successfully logged in to Google Voice account") except LoginError as error: attempts += 1 if attempts <= 3: time.sleep(30) else: logging.critical( 'Unable to login to Google Voice, Exiting SMS.') self.cancelled = True sys.exit() @staticmethod def extract_sms(html_sms): """Extract SMS messages from BeautifulSoup tree of Google Voice SMS Html, returning a list of dictionaries, one per message. extract_sms - taken from http://sphinxdoc.github.io/pygooglevoice/examples.html originally written by John Nagle ([email protected]) :param html_sms: Google Voice SMS Html data :type html_sms: BeautifulSoup object :return: msg_items :rtype: dictionary """ msgitems = [] # parse HTML into tree tree = BeautifulSoup(html_sms) conversations = tree.findAll("div", attrs={"id": True}, recursive=False) for conversation in conversations: # For each conversation, extract each row, which is one SMS message. rows = conversation.findAll(attrs={"class": "gc-message-sms-row"}) # for all rows for row in rows: # For each row, which is one message, extract all the fields. # tag this message with conversation ID msgitem = {"id": conversation["id"]} spans = row.findAll("span", attrs={"class": True}, recursive=False) # for all spans in row for span in spans: name = span['class'].replace('gc-message-sms-', '') # put text in dict msgitem[name] = (" ".join(span.findAll(text=True))).strip() # add msg dictionary to list msgitems.append(msgitem) return msgitems def load_playlist(self): """ Load playlist from file notifying users of any of their requests that are now playing """ with open(self.playlist, 'rb') as playlist_fp: fcntl.lockf(playlist_fp, fcntl.LOCK_SH) playlist = csv.reader(playlist_fp, delimiter='\t') self.songs = list() for song in playlist: logging.debug(song) if len(song) < 2 or len(song) > 4: logging.error( 'Invalid playlist. Each line should be in the form: ' '<song name><tab><path to song>') logging.warning('Removing invalid entry') print "Error found in playlist" print "Deleting entry:", song continue elif len(song) == 2: song.append(set()) elif len(song) >= 3: # Votes for the song are stored in the 3rd column song[2] = set(song[2].split(',')) if len(song) == 4: # Notification of a song being played is stored in the 4th column # Send an sms message to each requesting user that their song is now playing for phonenumber in song[2]: self.voice.send_sms( phonenumber, '"' + song[0] + '" is playing!') del song[3] song[2] = set() self.songs.append(song) fcntl.lockf(playlist_fp, fcntl.LOCK_UN) logging.info('loaded %d songs from playlist', len(self.songs)) cm.set_playlist(self.songs) def update_playlist(self): """Update playlist with latest votes""" with open(self.playlist, 'wb') as playlist_fp: fcntl.lockf(playlist_fp, fcntl.LOCK_EX) writer = csv.writer(playlist_fp, delimiter='\t') for song in self.songs: if len(song[2]) > 0: song[2] = ",".join(song[2]) else: del song[2] writer.writerows(self.songs) fcntl.lockf(playlist_fp, fcntl.LOCK_UN) def check(self): """Process sms messages Download and process all sms messages from a Google Voice account. this is executed every 15 seconds """ # load the playlist self.load_playlist() # Parse and act on any new sms messages messages = self.voice.sms().messages for msg in self.extract_sms(self.voice.sms.html): logging.debug(str(msg)) response = commands.execute(msg['text'], msg['from']) if response: logging.info('Request: "' + msg['text'] + '" from ' + msg['from']) try: if isinstance(response, basestring): self.voice.send_sms(msg['from'], response) else: # Multiple parts, send them with a delay in hopes to avoid # them being received out of order by the recipient. for part in response: self.voice.send_sms(msg['from'], str(part)) time.sleep(2) except ValidationError as v_error: logging.warn( str(v_error) + ': Error sending sms response (command still executed)', exc_info=1) logging.info('Response: "' + str(response) + '"') else: logging.info('Unknown request: "' + msg['text'] + '" from ' + msg['from']) self.voice.send_sms(msg['from'], cm.sms.unknown_command_response) # update the playlist self.update_playlist() # Delete all messages now that we've processed them for msg in messages: msg.delete(1)
print('Error! Please provide Passsword.') exit(0) try: voice.login(email, password) except: print('Error! Login failed.') exit(0) try: phoneNumber = re.sub(r'\D', '', argv[3]).lstrip('1') except: print('Error! Please provide a phone number') voice.logout() exit(0) try: text = json.loads(argv[4]) except: print('Error! Please provide a message') voice.logout() exit(0) try: voice.send_sms(phoneNumber, text) print('Message Sent') except: print('Error! Message not sent') voice.logout()
import sys from googlevoice import Voice voice = Voice() voice.login("*****@*****.**", "Python123@") voice.send_sms("+917908504352", "hi how are u")
class gvoice (IModule): def __init__(self, queue): self.queue = queue self.voice = Voice() self.voiceLoggedIn = False self.Authentication = Authentication() threading.Thread.__init__ ( self ) def run(self): while True: arg = self.queue.get() if arg.Name == "Initialize": arg.Arg.Commands.append("privmsg") arg.Arg.Commands.append("part") arg.Arg.Commands.append("quit") elif arg.Name == "privmsg": self.privmsg(arg.Arg, arg.Data) elif arg.Name == "part": self.part(arg.Arg, arg.Data) elif arg.Name == "join": self.part(arg.Arg, arg.Data) elif arg.Name == "quit": self.part(arg.Arg, arg.Data) elif arg.Name == "nick": self.part(arg.Arg, arg.Data) elif arg.Name == "die": break def privmsg(self, network, data): parsed = self.GetParts(data) if parsed["Arguments"][0] == ".gvoice": if len(parsed["Arguments"]) < 2: network.Output.write("PRIVMSG " + parsed["ReplyTo"] + " :Please give me some arguments\r\n") return if parsed["Arguments"][1] == "sms": self.sms(network, parsed, data) return if parsed["Arguments"][1] == "login": self.login(network, parsed) return def part(self, network, data): parsed = self.GetParts(data) self.Authentication.DeauthenticateUser(network, parsed["FromWhom"]) def sms(self, network, parsed, raw): if not "Voice" in self.Authentication.GetAuthenticatedUser(network, parsed["FromWhom"]).Roles: network.Output.write("PRIVMSG " + parsed["ReplyTo"] + " :Access Denied!\r\n") return if len(parsed["Arguments"]) < 4: network.Output.write("PRIVMSG " + parsed["ReplyTo"] + " :Access Denied!\r\n") return self.voice.send_sms(parsed["Arguments"][2], parsed["RawArguments"][parsed["RawArguments"].find(parsed["Arguments"][2])+len(parsed["Arguments"][2])+1:]) def login(self, network, parsed): if len(parsed["Arguments"]) < 4: network.Output.write("PRIVMSG " + parsed["ReplyTo"] + " :Access Denied!\r\n") return if self.Authentication.NeedsAuthentication(network, parsed["FromWhom"]) == False: network.Output.write("PRIVMSG " + parsed["ReplyTo"] + " :Access Denied!\r\n") return if self.Authentication.AuthenticateUser(network, parsed["Arguments"][2], parsed["Arguments"][3]) == False: network.Output.write("PRIVMSG " + parsed["ReplyTo"] + " :Access Denied!\r\n") return if self.voiceLoggedIn == False: self.voice.login() self.voiceLoggedIn = True network.Output.write("PRIVMSG " + parsed["ReplyTo"] + " :Access Granted!\r\n")
from googlevoice import Voice from googlevoice.util import input import sys f=open(sys.argv[1],'r') data=[] x=f.readline() while x!='': data.append(x) x=f.readline() print data data=str(data).split(',') print data voice=Voice() voice.login() text=data[1] phone=data[2] print text,phone voice.send_sms(phone, text)
from googlevoice import Voice from googlevoice.util import input import time # Initialize Google Voice voice = Voice() # Ask for credentials voice.login() # Use login credentials to login #voice.login("username","password") userinput = "" # Get a number to send to while (userinput == ""): userinput = input("Enter in a phone number: ") # If there is no valid input, ask again if (userinput == ""): print "You must enter in a phone number first!" # The message to send message = input("Please enter in a message to send: ") # Get the amount of times to send the message times = input("Enter in the amount of times to send the message: ") # Send the message as many times as put in for i in range(int(times)): # Send the txt message voice.send_sms(userinput,message) # Give a little message to show that it sent print "Message Sent " + str(i+1) + " time(s)." # Wait 5 seconds before doing it again time.sleep(5);
def sendTxt(): voice = Voice() voice.login() for phoneNumber in phoneNumbers: voice.send_sms(phoneNumber, alertText)
from googlevoice import Voice from googlevoice.util import input sms = Voice() username = '******' password = '******' sms.login(username, password) phoneNumber = input('input the destination phone number.\t') text = input('enter the text you wish to send\t') sms.send_sms(phoneNumber, text)
class MessageListener(): def __init__(self, refresh_interval=30): """ * refresh_interval is in seconds """ self.voice = Voice() self.voice.login() sms = self.voice.sms() html = self.voice.sms.html_data self.conversations = self.getConversations(self.voice) or self.conversations # this in case it fails because of an image or something self.last_message_count = self.voice.sms.data['totalSize'] while True: self.loop() sleep(refresh_interval) def get_unread_count(self, folder): unread_count = 0; i = 0 while True: try: if not folder.messages[i].isRead: print(read_message(self.voice, i)) unread_count += 1 i += 1 except IndexError: break return unread_count def getConversations(self, voice): try: sms = voice.sms() except googlevoice.util.ParsingError: return None conversations = {} i = 0 while True: try: contact_name = voice.sms.html_data.find(id=sms.messages[i].id) message_data = sms.messages[i] try: contact_name = contact_name.find('span', class_='gc-message-name').find('a').text except: contact_name = contact_name.find('span', class_='gc-message-name').select('span[title]')[0].attrs['title'] raw_messages = voice.sms.html_data.find(id=sms.messages[i].id).select('.gc-message-sms-row') try: from_number = voice.sms.html_data.find(id=sms.messages[i].id).find('span', class_='gc-message-type').text except AttributeError: from_number = voice.sms.html_data.find(id=sms.messages[i].id).find('span', class_='gc-message-name').text from_number = re.search(r'([\(\)\s\-\d]+\d)', from_number).group(0) messages = [] for message in raw_messages: from_ = message.find('span', class_='gc-message-sms-from').text.strip()[:-1] text = message.find('span', class_='gc-message-sms-text').text time = message.find('span', class_='gc-message-sms-time').text.strip() txt = Text(from_=from_, from_number=from_number, text=text, time=time, isRead=message_data.isRead) messages.append(txt) if contact_name in conversations.keys(): conversations[contact_name] += messages else: conversations[contact_name] = messages i += 1 except IndexError: break return conversations def loop(self): sms = self.voice.sms() updated_conversations = self.getConversations(self.voice) new_message = False new_messages = [] if len(updated_conversations.keys()) > len(self.conversations.keys()): new_message = True #print("new conversation") elif len(updated_conversations.keys()) == len(self.conversations.keys()): #print("same # of conversations") for contact in self.conversations.keys(): last_messages = self.conversations[contact] updated_messages = updated_conversations[contact] if len(updated_messages) > len(last_messages): new_message = True #print("new message") for i in range(0, len(updated_messages)): #print(len(last_messages),len(updated_messages),i) try: if last_messages[i].text == updated_messages[i].text: continue elif last_messages[i-1].text == updated_messages[i].text: continue elif last_messages[i+1].text == updated_messages[i].text: continue else: # this updated_message must be a new one--it doesn't appear to be in the last_messages new_messages.append(updated_messages[i]) except IndexError: if last_messages[i-2].text == updated_messages[i].text: continue elif last_messages[i-1].text == updated_messages[i].text: continue elif last_messages[0].text == updated_messages[i].text: continue else: # this updated_message must be a new one--it doesn't appear to be in the last_messages new_messages.append(updated_messages[i]) self.conversations = updated_conversations for msg in new_messages: if msg.from_ != 'Me': # TODO: only send the auto-response if the last message was more than 30 minutes ago print("New message! => %s" % msg.toString()) dumb_contacts = ['Aimee Hudson', 'Andrew Post'] test_contacts = ['Drew Meier', '17246673655'] if msg.from_ in dumb_contacts: self.voice.send_sms(msg.from_number, "You're dumb") if msg.from_ in test_contacts or msg.from_number in test_contacts: self.voice.send_sms(msg.from_number, "Auto-reply from megatron. Let me know if you get this (it doesn't show up on my chat).")
def main(): # wake up andrew Andrew = Personality("andrew") Andrew.learn() # set verbosity flag for debugging purposes verbose = True # get logfile records = "/rec.db" logfile = "/log.db" # instantiate gvoice object voice = Voice() voice.login() # grab the SMS messages voice.sms() # loop through messages for msg in extractsms(voice.sms.html): print print(msg) hash = hashlib.md5() hash.update(msg['text'] + msg['time']) key = hash.hexdigest() print("Unique hash: " + key) # check if this is in log file duplicate = False f = open(logfile, "a+") for line in f: if key in line: duplicate = True if verbose: print("Duplicate: " + str(duplicate)) # if this is a duplicate, continue if duplicate: f.close() continue # if its FROM me, continue if "Me" in msg['from']: print("Skipping messages from me.") f.close() continue # else add to log else: e = open(records, "a+") e.write("\n") e.write(str(msg)) e.write("\n") f.write(key + "-") f.close() # print convo text = msg['text'] if verbose: print(msg['from'] + ": \"" + text + "\"") response = Andrew.converse(text) if verbose: print("Andrew: " + str(response)) e.write(str(response) + "\n") try: # send response SMS voice.send_sms(msg['from'], str(response)) except Exception as e: print(e) for message in voice.sms().messages: message.delete()
class FlightScraper: ''' Loads current titles, logs into voice, and starts the main loop. Sends only the most recent deal on startup. ''' def __init__(self): ''' A list of deals, with the most recent trimmed, so that it will be sent out on the first iteration. ''' deals = self.getTitles()[1:] # Create a set of currentDeals. self.currentDeals = {x for x in deals} self.voice = Voice() try: print "Trying to log in from config file: " + CONFIG_FILE (username, password) = file_lines(CONFIG_FILE) self.voice.login(username, password) print "Logged in successfully!" except: print "Failed to login from config, trying manual login" self.voice.login() print "Logged in successfully!" self.iterations = 0 self.s = sched.scheduler(time.time, time.sleep) self.s.enter(1, 1, self.loop, ()) self.s.run() ''' Returns a list of deal title names from theflightdeal, with the specific page specified in DEAL_PAGE. ''' def getTitles(self): try: page = requests.get(DEAL_PAGE) except: print "Failed to load page" return [] tree = html.fromstring(page.content) parents = tree.xpath("//h1[@class='post-title']") titles = [] for p in parents: titles.append(remove_non_ascii(p.getchildren()[0].text)) return titles ''' Checks for new flight deals and sends texts if they are found. ''' def update(self): titles = self.getTitles() newTitles = [] for t in titles: if t not in self.currentDeals: newTitles.append(t) self.sendText(t) else: break self.currentDeals = {x for x in titles} ''' Sends a msg to each number in numbers.txt. Used by update function for sending texts. ''' def sendText(self, msg): print print "NEW FLIGHT DEAL" print msg numberList = file_lines(PHONE_NUMBER_FILE) for num in numberList: try: self.voice.send_sms(num, msg) print "- Sent text to " + num except: print "! Failed to send text to " + num print ''' Main loop. Runs every 5 minutes and checks for new deals by calling update. ''' def loop(self): print "Updating deals, currently on iteration: " + str(self.iterations) self.iterations += 1 self.update() self.s.enter(300, 1, self.loop, ())
logFormat = college.name + ":" + college.term + ":" + crn prev_avail = check_log(log, logFormat) #logging.warn("test") # change to info() # Logging: append time, college, tern, crn, only if there's a difference. print "Checking " + college.name + " with URL: ", seats_avail = check_seats(college.basepath, college.term, crn) print "CRN: " + crn if prev_avail != False: print "Seat count: " + prev_avail + " since " + re.findall( r'([0-9-]+ [0-9:]+) ' + logFormat, log)[-1] print "" if seats_avail == -1: exit(1) if seats_avail != prev_avail: logfile.write(strftime("%Y-%m-%d %H:%M")) logfile.write(" " + logFormat + " " + str(seats_avail) + "\n") if prev_avail >= 0: # Notify the change msg = "Seats for CRN " + crn + " has changed from " + str( prev_avail) + " to " + str(seats_avail) if enableGV: from googlevoice import Voice from googlevoice.util import input voice = Voice() voice.login(login, pw) voice.send_sms(phoneNumber, msg) if enableEmail: os.system("echo " + msg + " | mail " + email) logfile.close()