def post_tweet(text): if profile.data['twitter']['consumer_key'] == "xxxx" \ or profile.data['twitter']['consumer_secret'] == "xxxx" \ or profile.data['twitter']['access_token'] == "xxxx" \ or profile.data['twitter']['access_token_secret'] == "xxxx": msg = 'twitter requires a consumer key and secret, and an access token and token secret.' print msg tts(msg) return; words_of_message = text.split() words_of_message.remove('tweet') cleaned_message = ' '.join(words_of_message).capitalize() auth = tweepy.OAuthHandler( profile.data['twitter']['consumer_key'], profile.data['twitter']['consumer_secret']) auth.set_access_token( profile.data['twitter']['access_token'], profile.data['twitter']['access_token_secret']) api = tweepy.API(auth) api.update_status(status=cleaned_message) tts('Your tweet has been posted')
def test_pyvona(self, mock_sys, mock_subprocess): """test pyvona.""" random_gender = get_random_string(exclude_list=('female', 'male')) mock_access_key = mock.Mock() mock_secret_key = mock.Mock() for gender in ('male', 'female', random_gender): mock_profile.data = { 'va_gender': gender, 'tts': 'ivona', 'ivona': { 'access_key': mock_access_key, 'secret_key': mock_secret_key, } } with mock.patch('melissa.tts.pyvona') as mock_pyvona: tts(self.message) # test voice name assert len(mock_pyvona.mock_calls) == 2 # test voice name if gender == 'female': assert mock_pyvona.create_voice().voice_name == 'Salli' elif gender == 'male': assert mock_pyvona.create_voice().voice_name == 'Joey' else: assert mock_pyvona.create_voice().voice_name == 'Joey' create_voice_call = mock.call.create_voice( mock_access_key, mock_secret_key) assert create_voice_call in mock_pyvona.mock_calls engine_speak_call = mock.call.create_voice().speak( self.message) assert engine_speak_call in mock_pyvona.mock_calls
def test_pyvona(self, mock_sys, mock_subprocess): """test pyvona.""" random_gender = get_random_string( exclude_list=('female', 'male') ) mock_access_key = mock.Mock() mock_secret_key = mock.Mock() for gender in ('male', 'female', random_gender): mock_profile.data = { 'va_gender': gender, 'tts': 'ivona', 'ivona': { 'access_key': mock_access_key, 'secret_key': mock_secret_key, } } with mock.patch('melissa.tts.pyvona') as mock_pyvona: tts(self.message) # test voice name assert len(mock_pyvona.mock_calls) == 2 # test voice name if gender == 'female': assert mock_pyvona.create_voice().voice_name == 'Salli' elif gender == 'male': assert mock_pyvona.create_voice().voice_name == 'Joey' else: assert mock_pyvona.create_voice().voice_name == 'Joey' create_voice_call = mock.call.create_voice( mock_access_key, mock_secret_key ) assert create_voice_call in mock_pyvona.mock_calls engine_speak_call = mock.call.create_voice().speak( self.message ) assert engine_speak_call in mock_pyvona.mock_calls
def test_random_platform(self, mock_sys, mock_subprocess): """test random platform.""" mock_sys.platform = get_random_string(exclude_list=('linux', 'darwin', 'win32')) tts(self.message) # empty list/mock_subprocess not called assert not mock_subprocess.mock_calls
def post_tweet(text): if profile.data['twitter']['consumer_key'] == "xxxx" \ or profile.data['twitter']['consumer_secret'] == "xxxx" \ or profile.data['twitter']['access_token'] == "xxxx" \ or profile.data['twitter']['access_token_secret'] == "xxxx": msg = "twitter requires a consumer key and secret," \ " and an access token and token secret." print msg tts(msg) return words_of_message = text.split() words_of_message.remove('tweet') cleaned_message = ' '.join(words_of_message).capitalize() auth = tweepy.OAuthHandler(profile.data['twitter']['consumer_key'], profile.data['twitter']['consumer_secret']) auth.set_access_token(profile.data['twitter']['access_token'], profile.data['twitter']['access_token_secret']) api = tweepy.API(auth) api.update_status(status=cleaned_message) tts('Your tweet has been posted')
def test_default_mock(self, mock_sys, mock_subprocess): """test using default mock obj.""" tts(self.message) # NOTE: the default for linux/win32 with gender male. # ( see non-exitent 'ven+f3' flag) mock_call = mock.call.call(['espeak', '-s170', self.message]) assert mock_call in mock_subprocess.mock_calls assert len(mock_subprocess.mock_calls) == 1
def who_are_you(text): va_name = profile.data['va_name'] messages = [ 'I am ' + va_name + ', your lovely personal assistant.', va_name + ', didnt I tell you before?', 'You ask that so many times! I am ' + va_name ] tts(random.choice(messages))
def test_random_platform(self, mock_sys, mock_subprocess): """test random platform.""" mock_sys.platform = get_random_string( exclude_list=('linux', 'darwin', 'win32') ) tts(self.message) # empty list/mock_subprocess not called assert not mock_subprocess.mock_calls
def how_am_i(text): replies = [ 'You are goddamn handsome!', 'My knees go weak when I see you.', 'You are sexy!', 'You look like the kindest person that I have met.' ] tts(random.choice(replies))
def go_to_sleep(text): replies = ['See you later!', 'Just call my name and I\'ll be there!'] tts(random.choice(replies)) if profile.data['hotword_detection'] == 'on': print('\nListening for Keyword...') print('Press Ctrl+C to exit') quit()
def show_all_notes(text, bot, chat_id): conn = sqlite3.connect(profile.data['memory_db']) tts('Your notes are as follows:') cursor = conn.execute("SELECT notes FROM notes") for row in cursor: tts(row[0], bot, chat_id) conn.close()
def show_all_notes(text): conn = sqlite3.connect(profile.data['memory_db']) tts('Your notes are as follows:') cursor = conn.execute("SELECT notes FROM notes") for row in cursor: tts(row[0]) conn.close()
def play_shuffle(text): try: mp3gen() random.shuffle(music_listing) for i in range(0, len(music_listing)): music_player(music_listing[i]) except IndexError as e: tts('No music files found.') print("No music files found: {0}".format(e))
def show_all_uploads(text): conn = sqlite3.connect(profile.data['memory_db']) cursor = conn.execute("SELECT * FROM image_uploads") for row in cursor: print(row[0] + ': (' + row[1] + ') on ' + row[2]) tts('Requested data has been printed on your terminal') conn.close()
def play_random(text): try: mp3gen() music_playing = random.choice(music_listing) song_name = os.path.splitext(basename(music_playing[1]))[0] tts("Now playing: " + song_name) music_player(music_playing) except IndexError as e: tts('No music files found.') print("No music files found: {0}".format(e))
def system_status(text): os, name, version, _, _, _ = platform.uname() version = version.split('-')[0] cores = psutil.cpu_count() cpu_percent = psutil.cpu_percent() memory_percent = psutil.virtual_memory()[2] response = "I am currently running on %s version %s. " %(os, version) response += "This system is named %s and has %s CPU cores. " %(name, cores) response += "Current CPU utilization is %s percent. " %cpu_percent response += "Current memory utilization is %s percent." %memory_percent tts(response)
def note_something(speech_text): conn = sqlite3.connect(profile.data['memory_db']) words_of_message = speech_text.split() words_of_message.remove('note') cleaned_message = ' '.join(words_of_message) conn.execute("INSERT INTO notes (notes, notes_date) VALUES (?, ?)", (cleaned_message, datetime.strftime(datetime.now(), '%d-%m-%Y'))) conn.commit() conn.close() tts('Your note has been saved.')
def system_status(text): os, name, version, _, _, _ = platform.uname() version = version.split('-')[0] cores = psutil.cpu_count() cpu_percent = psutil.cpu_percent() memory_percent = psutil.virtual_memory()[2] response = "I am currently running on %s version %s. " % (os, version) response += "This system is named %s and has %s CPU cores. " % (name, cores) response += "Current CPU utilization is %s percent. " % cpu_percent response += "Current memory utilization is %s percent." % memory_percent tts(response)
def weather(text): weather_com_result = pywapi.get_weather_from_weather_com(profile.data['city_code']) temperature = float(weather_com_result['current_conditions']['temperature']) degrees_type = 'celcius' if profile.data['degrees'] == 'fahrenheit': temperature = (temperature * 9/5) + 32 degrees_type = 'fahrenheit' weather_result = "Weather.com says: It is " + weather_com_result['current_conditions']['text'].lower() + " and " + str(temperature) + "degrees "+ degrees_type +" now in " + profile.data['city_name'] tts(weather_result)
def tell_joke(text): jokes = [ 'What happens to a frogs car when it breaks down? It gets toad away.', 'Why was six scared of seven? Because seven ate nine.', 'Why are mountains so funny? Because they are hill areas.', 'Have you ever tried to eat a clock? I hear it is very time consuming.', 'What happened when the wheel was invented? A revolution.', 'What do you call a fake noodle? An impasta!', 'Did you hear about that new broom? It is sweeping the nation!', 'What is heavy forward but not backward? Ton.', 'No, I always forget the punch line.' ] tts(random.choice(jokes))
def tell_joke(text): jokes = [ 'What happens to a frogs car when it breaks down? It gets toad away.', 'Why was six scared of seven? Because seven ate nine.', 'Why are mountains so funny? Because they are hill areas.', 'Have you ever tried to eat a clock?' 'I hear it is very time consuming.', 'What happened when the wheel was invented? A revolution.', 'What do you call a fake noodle? An impasta!', 'Did you hear about that new broom? It is sweeping the nation!', 'What is heavy forward but not backward? Ton.', 'No, I always forget the punch line.' ] tts(random.choice(jokes))
def find_iphone(text): try: api = PyiCloudService(ICLOUD_USERNAME, ICLOUD_PASSWORD) except PyiCloudFailedLoginException: tts("Invalid Username & Password") return # All Devices devices = api.devices # Just the iPhones iphones = [] for device in devices: current = device.status() if "iPhone" in current['deviceDisplayName']: iphones.append(device) # The one to ring phone_to_ring = None if len(iphones) == 0: tts("No iPhones found in your account") return elif len(iphones) == 1: phone_to_ring = iphones[0] phone_to_ring.play_sound() tts("Sending ring command to the phone now") elif len(iphones) > 1: for phone in iphones: phone_to_ring = phone phone_to_ring.play_sound() tts("Sending ring command to the phone now")
def main(): tts('Welcome ' + profile.data['name'] + ', how can I help you?') while True: if sys.platform == 'darwin': subprocess.call(['afplay', 'data/snowboy_resources/ding.wav']) elif sys.platform.startswith('linux') or sys.platform == 'win32': subprocess.call(['mpg123', 'data/snowboy_resources/ding.wav']) text = stt() if text is None: continue else: query(text)
def main(): data = load_profile(True) tts('Welcome ' + data['name'] + ', how can I help you?') while True: if sys.platform == 'darwin': subprocess.call(['afplay', 'data/snowboy_resources/ding.wav']) elif sys.platform.startswith('linux') or sys.platform == 'win32': subprocess.call(['mpg123', 'data/snowboy_resources/ding.wav']) text = stt() if text is None: continue else: query(text)
def weather(text): weather_com_result = pywapi.get_weather_from_weather_com( profile.data['city_code']) temperature = float( weather_com_result['current_conditions']['temperature']) degrees_type = 'celcius' if profile.data['degrees'] == 'fahrenheit': temperature = (temperature * 9 / 5) + 32 degrees_type = 'fahrenheit' weather_result = "Weather.com says: It is " + weather_com_result[ 'current_conditions']['text'].lower() + " and " + str( temperature ) + "degrees " + degrees_type + " now in " + profile.data['city_name'] tts(weather_result)
def test_darwin_platform(self, mock_sys, mock_subprocess): """test darwin platform.""" random_gender = get_random_string(exclude_list=('female', 'male')) # tuple contain (gender, mock_call) data = ( (None, lambda x: mock.call.call(['say', x])), (random_gender, lambda x: mock.call.call(['say', x])), ('female', lambda x: mock.call.call(['say', x])), ('male', lambda x: mock.call.call(['say', '-valex', x])), ) mock_sys.platform = 'darwin' for gender, mock_call in data: if gender is not None: DEFAULT_PROFILE_DATA['va_gender'] = gender mock_profile.data = DEFAULT_PROFILE_DATA tts(self.message) # NOTE: the default for macos with gender female. # (it don't have 'valex' flag) assert mock_call(self.message) in mock_subprocess.mock_calls assert len(mock_subprocess.mock_calls) == 1 mock_subprocess.reset_mock()
def image_uploader(speech_text): if profile.data['imgur']['client_id'] == "xxxx" \ or profile.data['imgur']['client_secret'] == "xxxx": msg = 'upload requires a client id and secret' print msg tts(msg) return; words_of_message = speech_text.split() words_of_message.remove('upload') cleaned_message = ' '.join(words_of_message) if len(cleaned_message) == 0: tts('upload requires a picture name') return; image_listing = img_list_gen() client = ImgurClient(profile.data['imgur']['client_id'], profile.data['imgur']['client_secret']) for i in range(0, len(image_listing)): if cleaned_message in image_listing[i]: result = client.upload_from_path(image_listing[i], config=None, anon=True) conn = sqlite3.connect(profile.data['memory_db']) conn.execute("INSERT INTO image_uploads (filename, url, upload_date) VALUES (?, ?, ?)", (image_listing[i], result['link'], datetime.strftime(datetime.now(), '%d-%m-%Y'))) conn.commit() conn.close() print result['link'] tts('Your image has been uploaded')
def define_subject(speech_text): words_of_message = speech_text.split() words_of_message.remove('define') cleaned_message = ' '.join(words_of_message).rstrip() if len(cleaned_message) == 0: msg = 'define requires subject words' print msg tts(msg) return try: wiki_data = wikipedia.summary(cleaned_message, sentences=5) regEx = re.compile(r'([^\(]*)\([^\)]*\) *(.*)') m = regEx.match(wiki_data) while m: wiki_data = m.group(1) + m.group(2) m = regEx.match(wiki_data) wiki_data = wiki_data.replace("'", "") tts(wiki_data) except wikipedia.exceptions.DisambiguationError as e: tts('Can you please be more specific? You may choose something' + 'from the following.') print("Can you please be more specific? You may choose something" + "from the following; {0}".format(e))
def iphone_battery(text): try: api = PyiCloudService(ICLOUD_USERNAME, ICLOUD_PASSWORD) except PyiCloudFailedLoginException: tts("Invalid Username & Password") return # All Devices devices = api.devices # Just the iPhones iphones = [] for device in devices: current = device.status() if "iPhone" in current['deviceDisplayName']: iphones.append(device) for phone in iphones: status = phone.status() battery = str(int(float(status['batteryLevel']) * 100)) tts(battery + 'percent battery left in ' + status['name'])
def test_linux_win32_platform(self, mock_sys, mock_subprocess): """test linux and win32 platform.""" random_gender = get_random_string(exclude_list=('female', 'male')) # tuple contain (gender, mock_call) def gender_mock_call(language=None): """mock_call func for testing.""" if language is None: return lambda x: mock.call.call(['espeak', '-s170', x]) else: return lambda x: mock.call.call( ['espeak', language, '-s170', x] ) male_mock_call = gender_mock_call() female_mock_call = gender_mock_call(language='-ven+f3') data = ( (None, male_mock_call), (random_gender, male_mock_call), ('female', female_mock_call), ('male', male_mock_call), ) for gender, gmock_call in data: if gender is not None: mock_profile.data['va_gender'] = gender for platform in ['linux', 'win32']: mock_sys.platform = platform tts(self.message) last_mock_call = gmock_call(self.message) test_rep = 'platform:[{}], gender:[{}]'.format( platform, gender ) assert last_mock_call in mock_subprocess.mock_calls, test_rep assert len(mock_subprocess.mock_calls) == 1 # reset mock_subprocess mock_subprocess.reset_mock()
def test_linux_win32_platform(self, mock_sys, mock_subprocess): """test linux and win32 platform.""" random_gender = get_random_string(exclude_list=('female', 'male')) # tuple contain (gender, mock_call) def gender_mock_call(language=None): """mock_call func for testing.""" if language is None: return lambda x: mock.call.call(['espeak', '-s170', x]) else: return lambda x: mock.call.call( ['espeak', language, '-s170', x]) male_mock_call = gender_mock_call() female_mock_call = gender_mock_call(language='-ven+f3') data = ( (None, male_mock_call), (random_gender, male_mock_call), ('female', female_mock_call), ('male', male_mock_call), ) for gender, gmock_call in data: if gender is not None: mock_profile.data['va_gender'] = gender for platform in ['linux', 'win32']: mock_sys.platform = platform tts(self.message) last_mock_call = gmock_call(self.message) test_rep = 'platform:[{}], gender:[{}]'.format( platform, gender) assert last_mock_call in mock_subprocess.mock_calls, test_rep assert len(mock_subprocess.mock_calls) == 1 # reset mock_subprocess mock_subprocess.reset_mock()
def ip_address(text): tts("Here are my available I.P. addresses.") for ifaceName in interfaces(): addresses = [ i['addr'] for i in ifaddresses(ifaceName).setdefault( AF_INET, [{'addr': None}])] if None in addresses: addresses.remove(None) if addresses and ifaceName != "lo": updated_addresses = [re.sub(r"\.", r" dot ", address) for address in addresses] tts('%s: %s' % ("interface: " + ifaceName +", I.P. Address ", ', '.join(updated_addresses))) tts("Those are all my I.P. addresses.")
def ip_address(text, bot, chat_id): tts("Here are my available I.P. addresses.") for ifaceName in interfaces(): addresses = [ i['addr'] for i in ifaddresses(ifaceName).setdefault( AF_INET, [{'addr': None}])] if None in addresses: addresses.remove(None) if addresses and ifaceName != "lo": updated_addresses = [re.sub(r"\.", r" dot ", address) for address in addresses] tts('%s: %s' % ("interface: " + ifaceName + ", I.P. Address ", ', '.join(updated_addresses)), bot, chat_id) tts("Those are all my I.P. addresses.", bot, chat_id)
def go_to_sleep(text): tts('Goodbye! Have a great day!') quit()
def feeling_creative(text): subprocess.call(['blink1-tool', '--magenta']) tts('So good to hear that!')
def feeling_lazy(text): subprocess.call(['blink1-tool', '--yellow']) tts('Rise and shine dear!')
def very_dark(text): subprocess.call(['blink1-tool', '--white']) tts('Better now?')
def feeling_angry(text): subprocess.call(['blink1-tool', '--cyan']) tts('Calm down dear!')
def repeat_text(text): text = text.split(' ', 1)[1] tts(text)
def spell_text(text, bot, chat_id): text = list(text.split(' ', 1)[1]) spelling = ' '.join(text) tts(spelling, bot, chat_id)
def self_destruct(text): tts('Self destruction mode engaged, over and out.') subprocess.call(['sudo', 'rm', '-r', '../Melissa-Core']) quit()
def tell_joke(text): tts(random.choice(jokeAPIRegister)())
def system_uptime(text): boot_time = datetime.datetime.fromtimestamp(psutil.boot_time()) running_since = boot_time.strftime("%A %d. %B %Y") response = 'System has been running since ' + running_since tts(response)