Reputation: 21
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
Upvotes: 0
Views: 1241
Reputation: 390
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.
Upvotes: 1