-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathalexa.py
78 lines (73 loc) · 2.78 KB
/
alexa.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
def talk(text):
engine.say(text)
engine.runAndWait()
def take_instruction():
command = ''
instruction = "Sorry, I couldn't understand that. Please repeat your command."
try:
with sr.Microphone() as source:
print('Listening...')
voice = listener.listen(source, timeout=5, phrase_time_limit=10)
command = listener.recognize_google(voice)
command = command.lower()
if 'alexa' in command:
command = command.replace('alexa', '')
print('User Command:', command)
instruction = '' # Reset instruction if a valid command is recognized
except sr.UnknownValueError:
pass
except sr.RequestError as e:
print(f"Could not request results from Google Speech Recognition service; {e}")
except sr.WaitTimeoutError:
print("Timed out while waiting for speech")
return command, instruction
def my_alexa():
command, instruction = take_instruction()
print('Processed Command:', command)
if any(keyword in command for keyword in ['play', 'music', 'song']):
# Extract the song name from the command
song = command.replace('play', '').replace('music', '').replace('song', '')
try:
pywhatkit.playonyt(song.strip())
except Exception as e:
print(f"Could not play song: {e}")
talk("I'm sorry, I couldn't play that song")
elif 'time' in command:
current_time = datetime.datetime.now().strftime('%I:%M %p')
talk('Current time is ' + current_time)
elif 'date' in command:
current_date = datetime.datetime.now().strftime('%Y-%m-%d')
talk('Today is ' + current_date)
elif 'who the heck is' in command:
person = command.replace('who the heck is', '')
try:
info = wikipedia.summary(person, 1)
print('Wikipedia Summary:', info)
talk(info)
except Exception as e:
print(f"Could not get information about {person}: {e}")
talk("I'm sorry, I couldn't find information about that person")
elif 'are you single' in command:
talk("I'm in a committed relationship with technology. We make a great couple!")
elif 'joke' in command:
try:
joke = pyjokes.get_joke()
print('Joke:', joke)
talk(joke)
except Exception as e:
print(f"Could not get joke: {e}")
talk("I'm sorry, I couldn't tell a joke right now")
else:
talk(instruction)
while True:
my_alexa()