Basic Voice Assistance with Python - python

I am a newbie in Python and I am developing a basic Voice Assistance with my teachers on Raspberry Pi 3. The code in this project is collected and fixed by me. However, as a newbie there are many questions I cant answer. Can you help me, please?
I want to develop an assistance which can search on Google, Play music on YouTube and show out the weather forecast. The AI.py is my main file, Google_Search.py is used for searching and YouTube_Search.py is used for playing music.
When I ask for searching the AI.py will import the Google_Search.py file to search for my requests. It is similar with YouTube file.
The problem is the Google_Search.py and YouTube_search.py just keep running and don't stop or allow me to keep working with the AI.py file. I want to run these two files while I still can run with the AI.py file to stop or re-open them again. These are the code, Please help me out. Thanks so much.
This is AI.py file
import speech_recognition
import pyaudio
import pyttsx3
import time
import os
import webbrowser, sys, imp
import requests, json
import vlc
import pafy
from datetime import date
from datetime import datetime
from googlesearch import search
robot_ear = speech_recognition.Recognizer()
robot_mouth = pyttsx3.init()
robot_brain = ""
api_key = "82328b3addcd3f984da6c1e74cf4c7c9"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
city_name = "Melbourne,au"
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
response = requests.get(complete_url)
x = response.json()
while True:
with speech_recognition.Microphone() as mic:
print("Robot: I'm Listening")
audio = robot_ear.adjust_for_ambient_noise(mic)
audio = robot_ear.listen(mic, phrase_time_limit=3)
print("Robot: ...")
try:
you = robot_ear.recognize_google(audio, language = "en")
except:
you = ""
print("You: " + you)
if you == "":
robot_brain = "I can't hear you, please try again"
elif "hello" in you:
robot_brain = "Hello Minh"
elif "play some music" in you:
import YouTube_Search
robot_brain = "Music is playing"
elif "stop music" in you:
os.system("pkill YouTube_Search")
robot_brain = "Music is stoped"
elif "search something" in you:
robot_brain = "What do you want me to search for?"
import Google_Search
imp.reload(Google_Search)
time.sleep(5)
elif "stop searching" in you:
os.system("pkill chromium")
robot_brain = "Google search is closed"
elif "weather today" in you:
if x["cod"] != "404":
y = x["main"]
current_pressure = y["pressure"]
current_humidiy = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
robot_brain = (" Temperature: " +
str(current_temperature) + " °F" +
"\n atmospheric pressure: " +
str(current_pressure) + " hPa" +
"\n humidity: " +
str(current_humidiy) + " %" +
"\n weather today: " +
str(weather_description))
elif "bye" in you:
robot_brain = "Bye Minh"
print("Robot: " + robot_brain)
robot_mouth.say(robot_brain)
robot_mouth.runAndWait()
break
else:
robot_brain = "I'm learning"
print("Robot: " + robot_brain)
robot_mouth.say(robot_brain)
robot_mouth.runAndWait()
This is the Google_Search.py file
import speech_recognition
import os, sys
import webbrowser
robot_brain = ""
robot_ear = speech_recognition.Recognizer()
with speech_recognition.Microphone() as mic:
#print("Robot: What do you want me to search for?")
audio = robot_ear.adjust_for_ambient_noise(mic)
audio = robot_ear.listen(mic, phrase_time_limit=2)
try:
you = robot_ear.recognize_google(audio, language = 'en-US')
except:
you = ""
search_terms = [you]
# ... construct your list of search terms ...
for term in search_terms:
url = "https://www.google.com/search?q={}".format(term)
webbrowser.open_new_tab(url)
robot_brain = ("Here is what I found for") + (" ") + str(you)
print("Robot: " + robot_brain)
os.system("pkill Google_Search")
This is the YouTube_Search.py
import vlc
import pafy
import time
import urllib.request
import urllib.parse
import re
import speech_recognition
robot_ear = speech_recognition.Recognizer()
with speech_recognition.Microphone() as mic:
print("Robot: What do you want me to search for?")
audio = robot_ear.adjust_for_ambient_noise(mic)
audio = robot_ear.listen(mic, phrase_time_limit=2)
try:
you = robot_ear.recognize_google(audio, language = 'en-US')
except:
you = ""
search = you
query_string = urllib.parse.urlencode({"search_query" : search})
html_content = urllib.request.urlopen("http://www.youtube.com/results?search_query="+query_string)
search_results = re.findall(r"watch\?v=(\S{11})", html_content.read().decode())
#print("http://www.youtube.com/watch?v=" + search_results[0])
url = "http://www.youtube.com/watch?v=" + search_results[0]
video = pafy.new(url)
best = video.getbest()
playurl = best.url
Instance = vlc.Instance()
player = Instance.media_player_new()
Media = Instance.media_new(playurl)
Media.get_mrl()
player.set_media(Media)
player.play()

The import keyword in Python is used to load other Python source code files in to the current interpreter session.
When you import a file, that file will be run first. If you want to call the program in your imported file, you should use a function and call that. For example:
test.py
def myFunction():
print("Hello")
main.py
import test
test.myFunction()

Related

Open AI davinci does not produce any output (text or audio)

I have the following piece of code:
import openai
import pyttsx3
import speech_recognition as sr
from api_key import API_KEY
openai.api_key = API_KEY
engine = pyttsx3.init()
r = sr.Recognizer()
mic = sr.Microphone(device_index=1)
print(sr.Microphone.list_microphone_names())
conversation = ""
user_name = "Josode"
while True:
with mic as source:
print("\nlistening... speak clearly into mic.")
r.adjust_for_ambient_noise(source, duration=0.2)
audio = r.listen(source)
print("no longer listening.\n")
try:
user_input = r.recognize_google(audio)
except:
continue
prompt = user_name + ": " + user_input + "\n Ava:"
conversation += prompt
response = openai.Completion.create(engine="text-davinci-002", prompt=conversation, max_tokens=100)
response_str = response["choices"][0]["text"].replace("\n", "")
response_str = response_str.split(user_name + ": ", 1)[0].split("Ava: ", 1)[0]
conversation += response_str + "\n"
print(response_str)
engine.say(response_str)
engine.runAndWait()
When I run the file, I get just listening... speak clearly into mic.
no longer listening. with no output from davinci.
Also, the mic print is ['LG FULL HD', 'Ari Chan’s AirPods', 'Ari Chan’s AirPods', 'MacBook Pro Microphone', 'MacBook Pro Speakers']. I am using index 1
API key is correct and imported. I have an account at Open AI and can use playground without a problem.
Do you see something that I don't see? It should work
Most probably you are getting an exception in r.recognize_google(audio) so it forces continue again and again without any output, try to add something like this to debug it:
import traceback
...
try:
user_input = r.recognize_google(audio)
except:
print(traceback.format_exc())
continue

How to fix "UnboundLocalError: local variable 'open' referenced before assignment" in write file?

I am doing an assistant and I want it to write file all the conversations I have spoken but this happens when I run it "UnboundLocalError: local variable 'open' referenced before assignment" and I try many ways to fix it but I could not fix it. Hope anyone can help me to fix it.
Thank you for any help
Here is my code
#import
import datetime
import os
import pyautogui
import pyjokes
import pyttsx3
import pywhatkit
import requests
import smtplib
import speech_recognition as sr
import webbrowser as we
from email.message import EmailMessage
from datetime import date
from newsapi import NewsApiClient
import random
import os
import wikipedia
from subprocess import run
from typing import Text
import time
user = "Tom" #your name
assistant= "Jarvis" # Iron man Fan
Jarvis_mouth = pyttsx3.init()
Jarvis_mouth.setProperty("rate", 165)
voices = Jarvis_mouth.getProperty("voices")
# For Mail voice AKA Jarvis
Jarvis_mouth.setProperty("voice", voices[1].id)
def Jarvis_brain(audio):
robot = Jarvis_brain
print("Jarvis: " + audio)
Jarvis_mouth.say(audio)
Jarvis_mouth.runAndWait()
#Jarvis speech
#Jarvis_ear = listener
#Jarvis_brain = speak
#Jarvis_mouth = engine
#you = command
def inputCommand():
# you = input() # For getting input from CLI
Jarvis_ear = sr.Recognizer()
you = ""
with sr.Microphone(device_index=1) as mic:
print("Listening...")
Jarvis_ear.pause_threshold = 1
try:
you = Jarvis_ear.recognize_google(Jarvis_ear.listen(mic, timeout=3), language="en-IN")
except Exception as e:
Jarvis_brain(" ")
except:
you = ""
print("You: " + you)
return you
print("Jarvis AI system is booting, please wait a moment")
Jarvis_brain("Start the system, your AI personal assistant Jarvis")
def greet():
hour=datetime.datetime.now().hour
if hour>=0 and hour<12:
Jarvis_brain(f"Hello, Good Morning {user}")
print("Hello,Good Morning")
elif hour>=12 and hour<18:
Jarvis_brain(f"Hello, Good Afternoon {user}")
print("Hello, Good Afternoon")
else:
Jarvis_brain(f"Hello, Good Evening {user}")
print("Hello,Good Evening")
greet()
def main():
while True:
with open ("Jarvis.txt", "a") as Jarvis:
Jarvis.write("Jarvis: " + str(Jarvis_brain) + "\n" + "You: " + str(you) + "\n")
# Getting input from the user
you = inputCommand().lower()
#General question.
if ("hello" in you) or ("Hi" in you):
Jarvis_brain(random.choice(["how may i help you, sir.","Hi,sir"]))
elif ("time" in you):
now = datetime.datetime.now()
robot_brain = now.strftime("%H hour %M minutes %S seconds")
Jarvis_brain(robot_brain)
elif ("date" in you):
today = date.today()
robot_brain = today.strftime("%B %d, %Y")
Jarvis_brain(robot_brain)
elif ("joke" in you):
Jarvis_brain(pyjokes.get_joke())
elif "president of America" in you:
Jarvis_brain("Donald Trump")
#open application
elif ("play" in you):
song = you.replace('play', '')
Jarvis_brain('playing ' + song)
pywhatkit.playonyt(song)
elif ("open youtube" in you):
Jarvis_brain("opening YouTube")
we.open('https://www.youtube.com/')
elif ("open google" in you):
Jarvis_brain("opening google")
we.open('https://www.google.com/')
elif "information" in you:
you = you.replace("find imformation", "")
Jarvis_brain("what news you what to know about")
topic=inputCommand()
Jarvis_brain("open " + topic)
we.open("https://www.google.com/search?q=" + topic)
elif ("open gmail" in you):
Jarvis_brain("opening gmail")
we.open('https://mail.google.com/mail/u/2/#inbox')
elif "vietnamese translate" in you:
Jarvis_brain("opening Vietnamese Translate")
we.open('https://translate.google.com/?hl=vi')
elif "english translate" in you:
Jarvis_brain("opening English Translate")
we.open('https://translate.google.com/?hl=vi&sl=en&tl=vi&op=translate')
elif ("open internet") in you:
Jarvis_brain("opening internet")
open = "C:\Program Files (x86)\BraveSoftware\Brave-Browser\Application\Brave.exe"
os.startfile(open)
elif "wikipedia" in you:
you = you.replace("wikipedia", "")
Jarvis_brain("what topic you need to listen to")
topic=inputCommand()
results = wikipedia.summary(topic, sentences=2, auto_suggest=False, redirect=True)
print(results)
Jarvis_brain(results)
#New&Covid-19
elif ("news" in you):
newsapi = NewsApiClient(api_key='d4eb31a4b9f34011a0c243d47b9aed4d')
Jarvis_brain("What topic you need the news about")
topic = inputCommand()
data = newsapi.get_top_headlines(
q=topic, language="en", page_size=5)
newsData = data["articles"]
for y in newsData:
Jarvis_brain(y["description"])
elif ("covid-19" in you):
r = requests.get('https://coronavirus-19-api.herokuapp.com/all').json()
Jarvis_brain(f'Confirmed Cases: {r["cases"]} \nDeaths: {r["deaths"]} \nRecovered {r["recovered"]}')
else:
if "goodbye" in you:
hour = datetime.datetime.now().hour
if (hour >= 21) and (hour < 5):
Jarvis_brain(f"Good Night {user}! Have a nice Sleep")
else:
Jarvis_brain(f"Bye {user}")
quit()
main()
Here is my terminal
Traceback (most recent call last):
File "c:\Users\PC\Documents\Code\assistant\Jarvis.py", line 181, in <module>
main()
File "c:\Users\PC\Documents\Code\assistant\Jarvis.py", line 86, in main
with open ("Jarvis.txt", "a") as Jarvis:
UnboundLocalError: local variable 'open' referenced before assignment
Thanks for any help
This is because you have defined the open command, which is one of the main Python commands, as a variable.
At this point, it looks like you put this string in with and try to open a file using a string, which causes an error.
open = "C:\Program Files (x86)\BraveSoftware\Brave-Browser\Application\Brave.exe"
Rename the open variable you defined on line 146 to another name like open_ to fix your problem.

How to fix "wikipedia.exceptions.PageError: Page id " rowan atkinson" does not match any pages. Try another id!"

My name is Tom! I am doing a Python3.9 project and when I run it, all the commands and functions work very well except the line 137 "wikipedia" when I say "wikipedia with the command" it will appear an error.
"wikipedia.exceptions.PageError: Page id " rowan atkinson" does not match any pages. Try another id!"
I tried to fix it many different ways but the error still there. Hope anyone can help me to fix this error.
Thank you very much!
Here is my code.
#import
import datetime
import os
import pyautogui
import pyjokes
import pyttsx3
import pywhatkit
import requests
import smtplib
import speech_recognition as sr
import webbrowser as we
from email.message import EmailMessage
from datetime import date
from newsapi import NewsApiClient
import random
import os
import wikipedia
from subprocess import run
from typing import Text
user = "Tom" #your name
assistant= "Jarvis" # Iron man Fan
Jarvis_mouth = pyttsx3.init()
Jarvis_mouth.setProperty("rate", 170)
voices = Jarvis_mouth.getProperty("voices")
# For Mail voice AKA Jarvis
Jarvis_mouth.setProperty("voice", voices[1].id)
def Jarvis_brain(audio):
print("Jarvis: " + audio)
Jarvis_mouth.say(audio)
Jarvis_mouth.runAndWait()
#Jarvis speech
#Jarvis_ear = listener
#Jarvis_brain = speak
#Jarvis_mouth = engine
#you = command
def inputCommand():
# you = input() # For getting input from CLI
Jarvis_ear = sr.Recognizer()
you = ""
with sr.Microphone(device_index=1) as mic:
print("Listening...")
Jarvis_ear.pause_threshold = 1
try:
you = Jarvis_ear.recognize_google(Jarvis_ear.listen(mic, timeout=3), language="en-IN")
except Exception as e:
Jarvis_brain(" ")
except:
you = ""
print("You: " + you)
return you
print("Jarvis AI system is booting, please wait a moment")
Jarvis_brain("Start the system, your AI personal assistant Jarvis")
def greet():
hour=datetime.datetime.now().hour
if hour>=0 and hour<12:
Jarvis_brain(f"Hello, Good Morning {user}")
print("Hello,Good Morning")
elif hour>=12 and hour<18:
Jarvis_brain(f"Hello, Good Afternoon {user}")
print("Hello, Good Afternoon")
else:
Jarvis_brain(f"Hello, Good Evening {user}")
print("Hello,Good Evening")
greet()
while True:
# Getting input from the user
you = inputCommand().lower()
#General question.
if ("hello" in you) or ("Hi" in you):
Jarvis_brain(random.choice(["how may i help you, sir.","Hi,sir"]))
elif ("time" in you):
now = datetime.datetime.now()
robot_brain = now.strftime("%H hour %M minutes %S seconds")
Jarvis_brain(robot_brain)
elif ("date" in you):
today = date.today()
robot_brain = today.strftime("%B %d, %Y")
Jarvis_brain(robot_brain)
elif ("joke" in you):
Jarvis_brain(pyjokes.get_joke())
elif "president of America" in you:
Jarvis_brain("Donald Trump")
#open application
elif ("play" in you):
song = you.replace('play', '')
Jarvis_brain('playing ' + song)
pywhatkit.playonyt(song)
elif ("open youtube" in you):
Jarvis_brain("opening YouTube")
we.open('https://www.youtube.com/')
elif ("open google" in you):
Jarvis_brain("opening google")
we.open('https://www.google.com/')
elif ("open gmail" in you):
Jarvis_brain("opening gmail")
we.open('https://mail.google.com/mail/u/2/#inbox')
elif "vietnamese translate" in you:
Jarvis_brain("opening Vietnamese Translate")
we.open('https://translate.google.com/?hl=vi')
elif "english translate" in you:
Jarvis_brain("opening English Translate")
we.open('https://translate.google.com/?hl=vi&sl=en&tl=vi&op=translate')
elif ("open internet") in you:
Jarvis_brain("opening internet")
open = "C:\Program Files (x86)\BraveSoftware\Brave-Browser\Application\Brave.exe"
os.startfile(open)
elif ("wikipedia") in you:#can't use wikipedia
you = you.replace("wikipedia", "")
results = wikipedia.summary(you, sentences=2)
Jarvis_brain(results)
print(results)
#New&Covid-19
elif ("news" in you):
newsapi = NewsApiClient(api_key='5840b303fbf949c9985f0e1016fc1155')
Jarvis_brain("What topic you need the news about")
topic = inputCommand()
data = newsapi.get_top_headlines(
q=topic, language="en", page_size=5)
newsData = data["articles"]
for y in newsData:
Jarvis_brain(y["description"])
elif ("covid-19" in you):
r = requests.get('https://coronavirus-19-api.herokuapp.com/all').json()
Jarvis_brain(f'Confirmed Cases: {r["cases"]} \nDeaths: {r["deaths"]} \nRecovered {r["recovered"]}')
#can not use wikipedia!
elif ("wikipedia") in you:
you = you.replace("wikipedia", "")
results = wikipedia.summary(you, sentences=2)
Jarvis_brain(results)
print(results)
else:
if "goodbye" in you:
hour = datetime.datetime.now().hour
if (hour >= 21) and (hour < 5):
Jarvis_brain(f"Good Night {user}! Have a nice Sleep")
else:
Jarvis_brain(f"Bye {user}")
quit()
I will paste my error here.
Listening...
You: Wikipedia Rowan Atkinson
Traceback (most recent call last):
File "c:\Users\PC\Desktop\assistant\abc.py", line 138, in <module>
results = wikipedia.summary(you, sentences=2)
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\wikipedia\util.py", line 28, in __call__
ret = self._cache[key] = self.fn(*args, **kwargs)
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\wikipedia\wikipedia.py", line 231, in summary
page_info = page(title, auto_suggest=auto_suggest, redirect=redirect)
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\wikipedia\wikipedia.py", line 276, in page
return WikipediaPage(title, redirect=redirect, preload=preload)
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\wikipedia\wikipedia.py", line 299, in __init__
self.__load(redirect=redirect, preload=preload)
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\wikipedia\wikipedia.py", line 345, in __load
raise PageError(self.title)
wikipedia.exceptions.PageError: Page id "roman atkinson" does not match any pages. Try another id!
Thanks for any help!

Python Speech Recognition not working when the file is converted to exe with pyinstaller

I created a Voice Assistant using speech recognition and GTTS modules in Python. The code works perfectly fine when run from script. But when I converted it using pyinstaller --onefile Speak.py(The name of the file) it stopped working. It is using my microphone but its not responding to anything. Suppose if I say hey google which is the wake up keyword it simply doesnt respond. I tried after a while but of no use. Can anyone please help me???
Code:
"from gtts import gTTS
import speech_recognition as sr
import os
import playsound
from datetime import datetime
import webbrowser
keeprunning = True
WAKING = "HEY GOOGLE"
def chec(cond, tex):
if cond in tex:
return True
else:
return False
def speak(text):
speaker = gTTS(text = text, lang = "en")
speaker.save("Voice.mp3")
playsound.playsound("voice.mp3")
os.remove("Voice.mp3")
def cleanify(text, wtremove, wtremove2=""):
try:
text = text.replace(wtremove)
except:
if not wtremove2 == "":
text = text.replace(wtremove2, "")
return text
#Main controlling part here(Oof!)
def Control(comnd):
if chec("SEARCH", comnd) or chec("GOOGLE", comnd):
comnd = cleanify(comnd, "SEARCH", "GOOGLE")
webbrowser.open(f"https://google.com/search?q={comnd.lower()}")
elif chec("WHO ARE YOU", comnd):
speak("I am your virtual assistant, google")
keepcontrol()
elif chec("TIME", comnd):
t = datetime.now()
t = time.strptime(t.strftime("%H:%S"), "%H:%M")
tt = time.strftime( "%I:%M %p", t )
speak(f"The current time is {tt}")
elif chec("NOTE", comnd) or chec("REMEMBER", comnd) or chec("JOT", comnd):
try:
text = comnd.replace("NOTE")
except:
try:
text = text.replace("REMEMBER")
except:
text = text.replace("JOT")
try:
with open("This_File_Name_Is_Very_Big_Because_I_dont_Want_to_overwrite_anyother_files_so_forgive_me_plz.txt", "rt") as file:
previous = file.read()
except:
with open("This_File_Name_Is_Very_Big_Because_I_dont_want_to_overwrite_any_other_files_so_forgive_me_plz.txt", "wt") as file:
ttw = f"""
•{text.lower()}
"""
file.write(previous + ttw)
previous = ""
with open("Notes.txt", "wt") as file:
ttw = previous + " •" + text
file.write(ttw)
speak("Got it! I noted it down")
elif chec("OPEN", comnd):
web = cleanify(comnd, "OPEN")
bruh = cleanify(web, ".com")
speak(f"Opening {bruh}")
print(comnd)
web = cleanify(comnd, "OPEN")
if web == "":
web = listen()
else:
if "https://" in web:
webbrowser.open(web.lower())
else:
web = "https://" + web
webbrowser.open(web.lower())
keepcontrol()
#Main controlling part ends
def listen():
r = sr.Recognizer()
with sr.Microphone() as source:
listen = r.listen(source)
try:
text = r.recognize_google(listen)
return text.upper()
except Exception as e:
if not e == "":
return ""
keepcontrol()
else:
speak("Sorry we couldnt catch that, please try again")
keepcontrol()
def keepcontrol():
while keeprunning:
text = listen()
if not text == None:
if text.count(WAKING) == 1:
speak("I am listening..")
text = listen()
if not text == None and not text == "":
Control(text)
else:
speak("Sorry i did not get that. Try again in a few seconds")
keepcontrol()
elif chec("QUIT", text):
exit()
elif chec("", text):
keepcontrol()
else:
speak("Sorry we didnt get that right. Please try again.")
speak("I am booting up...")
keepcontrol()
"
When you have converted it into exe,I think you have forgot to put files that you have used to build the assistant in the folder.
When your exe get converted, just simply copy those files(the files you have used) in the same folder in which you have kept your exe.
Hope it will work.

Python script for detecting if servers go down

So here is my code:
from os import system
from datetime import datetime
import time
import os
import subprocess
import sys
def status(ip_addr):
return os.system('ping ' + ip_addr + '> nul') == 0
statut[]
print("##################################")
print("Current time: ", str(datetime.now()))
print(" ")
with open('data.txt', 'r+') as adds:
add = [addrs.strip() for addrs in adds.readlines()]
for website in add:
stat = status(website)
if stat == 1:
stats = " is up!"
statut[website] = 1
else:
stats = " is down!"
statut[website] = 0
print(website, stats)
print("##################################")
while True:
print("Current time: ", str(datetime.now()))
print(" ")
with open('data.txt', 'r+') as adds:
add = [addrs.strip() for addrs in adds.readlines()]
for website in add:
stat = status(website)
if stat != statut[website]:
stats = " is up!"
statut[website] = stat
print(website, stats)
print("##################################")
time.sleep(240)
What I want to make out of it is to firstly learn if a server is up/down and after that, check at every 240 sec if it went the other way around - I can't however use boolean array "statut" like I intended. I would really apreciate some help with how I could make it work.
If you are just looking for a state change you could do something like this:
from os import system
from datetime import datetime
import time
def server_status(ip_addr):
if system('ping ' + ip_addr + '> nul') == 0:
return 'up'
else:
return 'down'
status_history = {}
print("##################################")
print("Current time: ", str(datetime.now()))
print(" ")
with open('data.txt', 'r+') as adds:
ipaddress = [addrs.strip() for addrs in adds.readlines()]
# Set inital state
for server in ipaddress:
status_history[server] = server_status(server)
print(f"{server} is {status_history[server]}")
print("##################################")
while True:
print("Current time: ", str(datetime.now()))
print(" ")
for server in ipaddress:
if server_status(server) != status_history[server]:
status_history[server] = server_status(server)
print(f"{server} has switched state to {status_history[server]}")
else:
print(f"{server} is still {status_history[server]}")
print("##################################")
time.sleep(10)
I would put a timeout on the while loop just in case and possible make some parts more configurable, such as the sleep.

Categories

Resources