This question already has answers here:
python dictionary keyError
(5 answers)
Closed 11 days ago.
This post was edited and submitted for review 11 days ago and failed to reopen the post:
Original close reason(s) were not resolved
my code on line 152 is giving me KeyError. I suspect it to be an error from radar API or from the os module. API key may also be in question. Please help!
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
import webbrowser
import tkinter as tk
from tkinter import *
import turtle
from playsound import playsound
#pip install playsound==1.2.2, pyfiglet, SpeechRecognition, PyAudio, pyttsx3,termcolor
#Wish Happy New Year 2023
import pyfiglet
import time
from termcolor import colored,cprint
wish =['Welcome','To','The','AI','Assistant']
count=0
colors=['green','yellow','magenta','cyan','orange']
playsound('C:/Users/anish/Start_up.mp3',False)
for i in range(1,6):
if(count>4):
count=0
cprint('*'*60,'red')
else:
color=colors[count]
msg = pyfiglet.figlet_format(wish[count],
font='starwars',
width = 150)
cprint(msg,color)
count = count + 1
time.sleep(0.7)
# CODE FOR PROGRAM:
listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
newVoiceRate = 145
engine.setProperty('rate',newVoiceRate)
def talk(text):
engine.say(text)
engine.runAndWait()
def take_command():
try:
with sr.Microphone() as source:
talk("Talk after the tune!")
playsound("C:/Users/anish/correct-2-46134.mp3",False)
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'alexa' in command:
command = command.replace('alexa', '')
print(command)
except:
pass
return command
def run_alexa():
command = take_command()
print(command)
if 'play' in command:
song = command.replace('play', '')
talk('playing ' + song)
pywhatkit.playonyt(song)
elif 'time' in command:
time = datetime.datetime.now().strftime('%I:%M %p')
talk('Current time is ' + time)
elif 'who is' in command:
person = command.replace('who the heck is', '')
info = wikipedia.summary(person, 1)
print(info)
talk(info)
elif 'date' in command:
talk('sorry, I have a headache')
elif 'are you single' in command:
talk('I am in a relationship with wifi')
elif 'joke' in command:
y = pyjokes.get_joke()
print(y)
talk(y)
elif 'shut up' in command:
LOL = "Haha, you cannot stop me! But, I will stop now. Bye!"
print(LOL)
talk(LOL)
playsound('C:/Users/anish/goodbye-until-next-time-29143.mp3', False)
wish = ['Made', 'By', ' ', 'Me!', 'Thank You!']
count = 0
colors = ['green', 'yellow', 'magenta', 'cyan', 'orange']
for i in range(1, 6):
if (count > 4):
count = 0
cprint('*' * 60, 'red')
else:
color = colors[count]
msg = pyfiglet.figlet_format(wish[count],
font='starwars',
width=150)
cprint(msg, color)
count = count + 1
import time
time.sleep(0.7)
exit()
elif "stop" in command:
STO_P = "Ok, I will stop. Bye!"
print(STO_P)
talk(STO_P)
playsound('C:/Users/anish/goodbye-until-next-time-29143.mp3',False)
wish = ['Made', 'By', ' ', 'Me!', 'Thank You!']
count = 0
colors = ['green', 'yellow', 'magenta', 'cyan', 'orange']
for i in range(1, 6):
if (count > 4):
count = 0
cprint('*' * 60, 'red')
else:
color = colors[count]
msg = pyfiglet.figlet_format(wish[count],
font='starwars',
width=150)
cprint(msg, color)
count = count + 1
import time
time.sleep(0.7)
time.sleep(2)
result = pyfiglet.figlet_format("Built using Python", font="digital")
print(result)
time.sleep(4)
exit()
elif "open" in command:
ope_n = command.replace("open",'')
talk('opening' + ope_n)
from AppOpener import open
open(ope_n)
elif"website" in command:
url = command.replace("website",'')
x = "Opening Website"
chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
webbrowser.register('chrome', None,webbrowser.BackgroundBrowser(chrome_path))
webbrowser.get('chrome').open(url)
print("Okay, just a minute!")
talk(x)
elif "where is" in command:
import os
from radar import RadarClient
# initialize client
radar = RadarClient(os.environ["RADAR_SECRET_KEY"])
# get a geofence by id
geofence = radar.geofences.get(id='123')
# list geofences
radar.geofences.list()
else:
talk('Please say the command again.')
while True:
run_alexa()
I tried changing my radar api key, but not working. Also checked my code!
Maybe it is either the api key, or something wrong with the os module.
I am actually working on a small project, but as one def function controls it, had to paste the entire code.
Inconvenience regretted!
I hope we can solve this as soon as we can!
I have switched to OpenStreetMaps now, but bould still love to know about the issue, ThankYou!!!
Related
I have two Python files, I want to access variable from while loop while True.
Print it to another python file
main.py
#main.py
import speech_recognition as sr
import pyttsx3
import pywhatkit
import subprocess
import os
import sys
def restart_program():
python = sys.executable
print(python)
os.execl(python, python, *sys.argv)
def speak(text):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
said = ""
try:
said = r.recognize_google(audio)
print(said)
except Exception as e:
print("cancle")
print("Exception: " + str(e))
# return Task()
return said.lower()
def Task():
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
said = ""
try:
# audio = r.listen(source, timeout=3)
print("listening...")
said = r.recognize_google(audio)
said = said.lower()
# said = "alexa play a song"
# said = "alexa navigate me"
if 'alexa' in said:
command = said.replace("alexa", "")
print(command)
else:
command = "null"
except:
command = "null"
return command
def process_command(command):
print(command)
if ('cancel' in command or 'nevermind' in command or 'forget it' in command):
speak("Sorry.")
SONG_STRS = ["play a song", "sing"]
for phrase in SONG_STRS:
if phrase in command:
speak("What would you like to play?")
song = get_audio()
if ('cancel' in song or 'nevermind' in song or 'forget it' in song):
speak("Sorry.")
else:
pywhatkit.playonyt(song)
speak("I've done that.")
NAV_STRS = ["navigate me to", "start navigate", "let's go to"]
for phrase in NAV_STRS:
if phrase in command:
speak("Where would you like Go?")
place = get_audio()
if ('cancel' in song or 'nevermind' in song or 'forget it' in song):
speak("Sorry.")
else:
speak("okay, let's go to." + place)
if 'restart' in command or 'reload' in command:
speak("Cake and grief counseling will be available at the conclusion of the test.")
restart_program()
print(place) #and also print here
while True:
command = Task()
process_command(command)
And also print place in main.py.
value.py:
#value.py
x = place #this is variable from main.py --> def process_command
print(x)
i am coding a virtual assistant, everything is fine it listens to my audio input and responses correctly, but when i run the programme it only takes my command one time and the programme ends. I can't figure out where should I use the while loop so that the programme continues until i ask it to end. I tries addding while loops in different function but none seem to work.
import speech_recognition
import pyttsx3 as tts
import subprocess
import datetime
import webbrowser
import time
now = datetime.datetime.now()
recognizer = speech_recognition.Recognizer()
speaker = tts.init()
x = speaker.getProperty('voices')
speaker.setProperty('voice', x[1].id)
y = speaker.getProperty('rate')
speaker.setProperty('rate' , 175)
def record_audio(ask = False):
with speech_recognition.Microphone() as mic:
if ask:
tts.speak(ask)
print("listening")
recognizer.adjust_for_ambient_noise(mic , 0.05)
audio = recognizer.listen(mic)
try:
voice_data = recognizer.recognize_google(audio , language = "en-IN")
except speech_recognition.UnknownValueError:
tts.speak('Sorry, I did not understand what you just said. Please try again.')
except speech_recognition.RequestError:
tts.speak("Sorry, my speech service is down for the time being. Please try again later.")
return voice_data
def responses(command):
if 'hello' in command:
tts.speak("hello sir, how can I help you.")
elif 'what is your name' in command:
tts.speak("My name is Otto Octavius")
elif 'time' in command:
tts.speak(now.strftime("%I:%M:%S"))
elif 'date' in command:
tts.speak(now.strftime("%Y-%m-%d"))
elif 'open' and 'telegram' in command:
tts.speak("opening telegram")
subprocess.Popen("D:\My Folder\My Softwares\Telegram Desktop\Telegram.exe")
elif 'close' and 'telegram' and 'window' in command:
tts.speak("closing telegram")
subprocess.call(["taskkill","/F","/IM","Telegram.exe"])
elif 'open' and 'binance' in command:
tts.speak("opening binance")
subprocess.Popen("D:\My Folder\My Softwares\Binance\Binance.exe")
elif 'close' and 'binance' in command:
tts.speak('closing binance')
subprocess.call(["taskkill" , "/F" , "IM" , 'Binance.exe'])
elif 'file explorer' in command:
tts.speak("opening file explorer")
webbrowser.open('C:/Users/arfee/Downloads')
elif 'my folder' in command:
tts.speak('opening my folder')
webbrowser.open("D:\My Folder")
elif 'search' in command:
search_object = record_audio("What do you want me to search for?")
url = ("https://www.google.com/search?q=" + search_object)
tts.speak('Searching for ' + search_object)
webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open_new_tab(url)
tts.speak("Welcome, how can I help you")
command = record_audio()
responses(command)
Try putting this in an infinite loop -
while True:
command = record_audio()
responses(command)
I am making a voice assistant it used to be so slow so I Wanted to Use Some functions from an other python file because the code will become larger which might make the program much much slower so i decided to ship some features which are more that seven lines into a another file Named Features.py and i also added all the features into a class so that it might become faster And now some features are not working so i searched google alot but i didn't find answer i am hoping for an good answer
Main.py Code
import datetime
import os # os module is used to open files and run commands on the cmd and a lot of other features installation:deafult by python
import webbrowser
import cv2
import pyautogui
import pyttsx3 # pyttsx3 is module for text to speech installation:pip install pyttsx3
import requests
# speechrecogntion is the module which is used for recognizing audio and converting into text installation:pip install speechrecogntion
import speech_recognition as sr
from pyttsx3.drivers import sapi5
import functools
hour = datetime.datetime.now().hour
class HoverAssist():
#functools.lru_cache()
def __init__(self) -> None:
self.hour = int(datetime.datetime.now().hour)
self.engine = pyttsx3.init()
self.voices = self.engine.getProperty('voices')
self.engine.setProperty('voice', self.voices[0].id)
#functools.lru_cache()
def speak(self, audio):
self.engine.say(audio)
print(" ")
print(f"Hover Said: {audio}")
self.engine.runAndWait()
#functools.lru_cache()
def listen(self):
while 1:
listener = sr.Recognizer()
try:
with sr.Microphone() as source:
audio = listener.listen(source, timeout=1.0)
response = listener.recognize_google(audio)
response = response.lower()
if "hawa" in response or "how" in response:
self.speak("How can I help you?")
self.Analyze()
else:
pass
except sr.WaitTimeoutError:
pass
except sr.UnknownValueError:
pass
except sr.RequestError:
print("Network error.")
#functools.lru_cache()
def takecommand(self):
listener = sr.Recognizer()
command = ""
try:
with sr.Microphone() as source:
voice = listener.listen(source, phrase_time_limit=4)
command = listener.recognize_google(voice)
print(f"User Said: {command}")
print(" ")
except sr.WaitTimeoutError:
pass
except sr.UnknownValueError:
pass
except sr.RequestError:
print("Network error.")
return command.lower()
#functools.lru_cache()
def wish(self, hour):
if hour > 0 and hour < 12:
self.speak('Good Morning')
elif hour > 12 and hour > 15:
self.speak('Good Afternoon')
else:
self.speak('Good Evening')
#functools.lru_cache()
def Analyze(self):
query = self.takecommand().lower()
if query == "open notepad":
os.system("notepad")
elif "what is the time" in query:
min = datetime.datetime.now().strftime("%I:%M %p")
self.speak(f"It is {min}")
elif 'browser' in query:
self.speak("opening Browser ")
webbrowser.open("https://www.google.com")
elif 'open cmd' in query or 'open command prompt' in query:
self.speak('Opening CMD')
os.system("start cmd")
elif 'open camera' in query:
self.capture = cv2.VideoCapture(0)
while True:
ret, img = self.capture.read()
cv2.imshow('Camera', img)
k = cv2.waitKey(27)
if k == 27:
break
elif 'close camera' in query:
self.capture.release()
self.capture.destroyAllWindows()
elif 'ip address' in query:
ip = requests.get('https://api.ipify.org').text
self.speak(f"your ip is {ip}")
elif 'wikipedia' in query:
self.speak('Searching Wikipedia')
import wikipedia
query = query.replace('wikipedia', '')
results = wikipedia.summary(query, sentences=3)
self.speak('Accoding to wikipedia'+results)
elif 'open youtube' in query:
self.speak("Opening Youtube")
webbrowser.open('www.youtube.com')
elif 'open stack overflow' in query:
self.speak("Opening Stackoverflow")
webbrowser.open('www.stackoverflow.com')
elif 'search' in query:
self.speak("Searching The Internet")
search = query.replace("search", "")
webbrowser.open(f'www.google.com/search?q={search}')
elif 'i am going' in query:
self.speak(
"ok i will open ..security camera. to secure your device")
from Feature import Security_Cam
Security_Cam()
elif 'open' in query.lower():
from Feature import Webopener
query = query.replace("open", "")
query = query.replace("chrome", "")
self.speak(f"Opening {query} ")
Webopener.webopen(query=query)
elif "weather" in query:
from Feature import Weather
w = Weather()
self.speak(w)
elif 'how' in query:
import pywikihow
how = pywikihow.search_wikihow(query, max_results=1)
assert len(how) == 1
self.speak(how[0].summary)
elif 'shutdown' in query or 'shut down' in query:
self.speak('Shutting Down Windows')
os.system("shutdown /s /t 00")
elif 'switch the window' in query:
self.speak("I'll switch the window for you")
pyautogui.hotkey("Alt", "Tab")
elif 'take a screenshot' in query:
self.speak("taking screenshot buddy")
pyautogui.hotkey("Win", "prtsc")
elif "volume up" in query:
pyautogui.press("volumeup")
elif "volume down" in query:
pyautogui.press("volumedown")
elif "remind me" in query:
import threading
self.speak("What should i remind you for")
name = self.takecommand()
self.speak("When Should I Remind You")
time = self.takecommand()
from Feature import Reminder
tt = time
tt = tt.replace(".", "")
tt = tt.upper()
h = threading.Thread(target=lambda: Reminder(tt, name))
elif "play" in query:
import pywhatkit
query = query.replace("play", "")
self.speak(f"Playing {query}")
pywhatkit.playonyt(query)
elif "note" in query:
from Feature import Takenote
Takenote()
elif "alarm" in query:
self.speak(
"Sir Please Tell Me The Time to set alarm. For Example, Set Alarm to 5:30 A.M")
tt = self.takecommand()
tt = tt.replace("set alarm to ", "")
tt = tt.replace(".", "")
tt = tt.upper()
import threading
from Feature import Alarm
m = threading.Thread(target=lambda: Alarm(tt)).start()
elif "timer" in query:
import threading
from Feature import Timer
query = query.replace("set a timer for ", "")
query = query.replace("minutes", "")
query = query.replace("minute", "")
t = threading.Thread(target=lambda: Timer(int(query))).start()
else:
pass
Hover = HoverAssist()
Hover.wish(hour=hour)
Hover.listen()
Feature.py
import pyttsx3
import threading
import speech_recognition as sr
import datetime
import os
import cv2
import webbrowser
import requests
import wikipedia
import winsound
import webbrowser
import pyautogui
from pyttsx3.drivers import sapi5
import pywhatkit
import pywikihow
from googlesearch import search
import webbrowser
hour = int(datetime.datetime.now().hour)
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
def speak(audio):
engine.say(audio)
print(" ")
print(f"Hover Said: {audio}")
engine.runAndWait()
def takecommand():
try:
listener = sr.Recognizer()
with sr.Microphone() as source:
voice = listener.listen(source)
command = listener.recognize_google(voice)
print(command)
except sr.WaitTimeoutError:
pass
except sr.UnknownValueError:
pass
except sr.RequestError:
print("Network error.")
return command.lower()
def Security_Cam():
speak("ok i will open ..security camera. to secure your device")
cam = cv2.VideoCapture(0)
while cam.isOpened():
ret, frame1 = cam.read()
ret, frame2 = cam.read()
diff = cv2.absdiff(frame1, frame2)
gray = cv2.cvtColor(diff, cv2.COLOR_RGB2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
_, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)
dilated = cv2.dilate(thresh, None, iterations=3)
contours, _ = cv2.findContours(
dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
if cv2.contourArea(c) < 20000:
continue
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(frame1, (x, y), (x+w, y+h), (0, 255, 0), 2)
winsound.PlaySound('alert.wav', winsound.SND_ASYNC)
if cv2.waitKey(10) == ord('q'):
break
cv2.imshow('Secure Cam', frame1)
def Webopener():
USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0"
def webopen(query):
# scraping data
urls = []
for j in search(query=query, tld="co.in", num=1, stop=1, pause=1):
webbrowser.open(j)
print("done")
def Alarm(Timing):
altime = str(datetime.datetime.now().strptime(Timing, "%I:%M %p"))
altime = altime[11:-3]
Horeal = altime[:2]
Horeal = int(Horeal)
Mireal = altime[3:5]
Mireal = int(Mireal)
speak(f"Done Set an Reminder for {Timing}")
while True:
if Horeal == datetime.datetime.now().hour:
if Mireal == datetime.datetime.now().minute:
print("The alarm has been completed")
winsound.PlaySound('alert.wav', winsound.SND_FILENAME)
elif Mireal<datetime.datetime.now().minute:
break
def Weather():
from bs4 import BeautifulSoup
import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
res = requests.get(f'https://www.google.com/search?q=weather&oq=weather&aqs=chrome.0.35i39l2j0l4j46j69i60.6128j1j7&sourceid=chrome&ie=UTF-8',headers=headers)
soup = BeautifulSoup(res.text,'html.parser')
location = soup.select('#wob_loc')[0].getText().strip()
info = soup.select('#wob_dc')[0].getText().strip()
weather = soup.select('#wob_tm')[0].getText().strip()
precipitation = soup.select('#wob_pp')[0].getText().strip()
humidity = soup.select('#wob_hm')[0].getText().strip()
windspeed =soup.select('#wob_ws')[0].getText().strip()
information = f"It is {weather}°F There are {precipitation} % chances of rainfall It is {info}.the wind is blowing in a speed of {windspeed}. The humidity is {humidity} % in {location} "
return information
def Takenote():
speak("What is The Name of the Note")
name = takecommand()
speak("Please Tell Me What Should I Take Note Of")
hnote = open(name, "a")
note = takecommand()
hnote.write(f"{note}\n")
hnote.close()
def Reminder(Timing,reminder):
import datetime
import winsound
altime = str(datetime.datetime.now().strptime(Timing, "%I:%M %p"))
altime = altime[11:-3]
Horeal = altime[:2]
Horeal = int(Horeal)
Mireal = altime[3:5]
Mireal = int(Mireal)
speak(f"Done Set an Reminder for {Timing} and {reminder}")
while True:
if Horeal == datetime.datetime.now().hour:
if Mireal == datetime.datetime.now().minute:
print(reminder)
winsound.PlaySound('alert.wav', winsound.SND_FILENAME)
elif Mireal<datetime.datetime.now().minute:
break
def Timer(mins):
import time
secs = mins*60
time.sleep(secs)
mins = f"{mins}minutes"
speak(f"The {mins} Timer has been completed")
winsound.PlaySound('alert.wav', winsound.SND_FILENAME)
Thanks
If they are in the same directory, you can simply import the features.py as
import features
though a bit code will be helpful.
you should try
from Feature import function_name
I am a student and I am making a virtual assistant on Python 3.9. I want my assistant answer my questions when I say "google" in command, but I don't know why its not working. I tried so many ways but it still doesn't work and I don't know how to fix it, so I hope you guys can help me to fix it.
Thanks for any help!
Here is my code:
import speech_recognition
import pyttsx3
robot_ear = speech_recognition.Recognizer()
robot_mouth = pyttsx3.init()
voices = robot_mouth.getProperty('voices')
robot_mouth.setProperty('voice', voices[1].id)
def robot_brain(robot_brain):
print("Jarvis: " + robot_brain)
robot_mouth.say(robot_brain)
robot_mouth.runAndWait()
def take_command():
try:
with speech_recognition.Microphone() as mic:
print("Jarvis: I'm Listening")
audio = robot_ear.listen(mic,timeout=6 )
print("Jarvis: ...")
you = robot_ear.recognize_google(audio)
you = you.lower()
if "google" in you:
you = you.replace("google", "")
print(you)
except:
pass
you = ""
print("Boss: " + you)
return you
def run_google():
you = take_command()
print(you)
if "hello" in you:
robot_brain = "hello"
elif "bye" in you:
robot_brain = "bye"
print("Jarvis: " + robot_brain)
robot_mouth.say(robot_brain)
robot_mouth.runAndWait()
else:
robot_brain = "I can't hear you, try again"
while True:
run_google()
please make sure you have all the necessary modules installed.
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_command():
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'google' in command:
command = command.replace('google', '')
print(command)
except:
pass
return command
def run_google():
command = take_command()
print(command)
if 'play' in command:
song = command.replace('play', '')
talk('playing ' + song)
pywhatkit.playonyt(song)
elif 'time' in command:
time = datetime.datetime.now().strftime('%I:%M %p')
talk('Current time is ' + time)
elif 'who the heck is' in command:
person = command.replace('who the heck is', '')
info = wikipedia.summary(person, 1)
print(info)
talk(info)
elif 'date' in command:
talk('sorry, I have a headache')
elif 'are you single' in command:
talk('I am in a relationship with wifi')
elif 'joke' in command:
talk(pyjokes.get_joke())
else:
talk('Please say the command again.')
while True:
run_google()
I have been looking for a way to record streams whilst not at home as past broadcasts are unsatisfactory to me with all their muted sections. I had a found one site to help get me started but when i went to check for replies to after commenting asking for help and including images of my script i see that my posting got deleted rather than answered. But i digress.
I know how to manually start livestreamer from the command prompt when the stream is live but as aforementioned i am looking for a solution for when i'm not home.
I am sharing what i have in the hopes that someone would be able to identify what is wrong and help me rectify all issues to get this working.
#This script checks if a user on twitch is currently streaming and then records the stream via livestreamer
from urllib.request import urlopen
from urllib.error import URLError
from threading import Timer
import time
import datetime
import json
import sys
import subprocess
import datetime
import os
import configparser
def check_user(user):
""" returns 0: online, 1: offline, 2: not found, 3: error """
global info
url = 'https://api.twitch.tv/kraken/streams/' + user +"/?client_id=###"
try:
info = json.loads(urlopen(url, timeout = 15).read().decode('utf-8'))
if info['stream'] == None:
status = 1
else:
status = 0
except URLError as e:
if e.reason == 'Not Found' or e.reason == 'Unprocessable Entity':
status = 2
else:
status = 3
return status
def format_filename(fname):
# Removes invalid characters from filename
fname = fname.replace("/","")
fname = fname.replace("?","")
fname = fname.replace(":","-")
fname = fname.replace("\\","")
fname = fname.replace("<","")
fname = fname.replace(">","")
fname = fname.replace("*","")
fname = fname.replace("\"","")
fname = fname.replace("|","")
fname = fname.replace(" ","")
return fname
def loopcheck():
while True:
status = check_user(user)
if status == 2:
print("username not found. invalid username?")
elif status == 3:
print(datetime.datetime.now().strftime("%Hh%Mm%Ss")," ","unexpected error. will try again in 5 minutes.")
time.sleep(300)
elif status == 1:
print(user,"currently offline, checking again in",refresh,"seconds")
time.sleep(refresh) # 15 seconds
elif status == 0:
print(user,"online. stop.")
filename = user+" - "+datetime.datetime.now().strftime("%Y-%m-%d %Hh%Mm%Ss")+" - "+(info['stream']).get("channel").get("status")+".mp4"
filename = format_filename(filename)
str1="livestreamer --twitch-oauth-token ### twitch.tv/"+user+" "+quality+" -o "+directory+filename
subprocess.call(str1)
print("Stream is done. Going back to checking..")
time.sleep(15)
def main():
global refresh
global user
global quality
global directory
print("Usage: check.py [refresh] [user] [quality]")
print("Usage: TwitchChecker.py [refresh] [user] [quality]")
refresh = 15.0
str1=""
refresh = 15.0
user = "###"
quality = "best"
directory = "C:\Users\###\Videos\###\\"
if(refresh<15):
print("Check interval should not be lower than 15 seconds")
refresh=15
print("Checking for",user,"every",refresh,"seconds. Record with",quality,"quality.")
loopcheck()
if __name__ == "__main__":
# execute only if run as a script
main()
set /p DUMMY=Hit ENTER to continue...
For the batch file i have:
#echo
C:\Python\python C:\Users\xxx\Videos\xxx\xxx.py
#echo off
All that happens when i click on either of the 2 files is that the command prompt window flashes quickly.
Thankies for any and all help!