Python语音助手:聊天响应与命令执行重叠问题求助
Python语音助手响应重叠问题:命令与通用聊天响应同时播报
背景
我正在开发一款带有聊天机器人功能的Python语音助手,但遇到了一个令人困扰的问题:响应重叠。有时当我请求讲笑话时,笑话命令的响应和通用聊天响应会同时播报,造成尴尬且混乱的体验。
问题描述
- 该问题偶发,难以确定确切原因。
- 触发特定命令(如"joke")时,预期响应正常工作,但聊天响应似乎会在之后激活,导致与命令输出重叠。
代码示例
if __name__ == "__main__": clear = lambda: os.system("cls") # This Function will clean any # command before the execution of this python file clear() mystical_greet() while True: query = takeCommand().lower() if "wikipedia" in query: speak("Searching Wikipedia...") query = query.replace("wikipedia", "") try: results = wikipedia.summary(query, sentences=5) except wikipedia.DisambiguationError as e: speak("There are multiple options. Please specify.") for i, option in enumerate(e.options, start=1): speak(f"{i}. {option}") choice = int(input("Enter the number of your choice: ")) results = wikipedia.summary(e.options[choice - 1], sentences=5) except Exception as error: pass speak("According to Wikipedia") speak(results) elif "open youtube" in query: speak("Here you go to Youtube") webbrowser.open("https://www.youtube.com") elif "youtube" in query: search_query = query.replace("youtube", "").strip() url_search = quote(search_query) webbrowser.open( f"https://www.youtube.com/results?search_query={url_search}" ) elif "open google" in query: speak("Here you go to Google\n") webbrowser.open("google.com") elif "open stackoverflow" in query: speak("Here you go to Stack Over flow.Happy coding") webbrowser.open("stackoverflow.com") # rest of commands elif "joke" in query: joke = get_joke() speak(joke) # rest of the commands elif "news" in query: user_preference = get_user_preference() if "world" in user_preference: get_news("world") elif "national" in user_preference: get_news( "general" ) # You can customize this to a specific category for Indian news elif "headlines" in user_preference: get_news("top-headlines") else: speak("Sorry, I couldn't understand your preference. Please try again.") elif "where is" in query: query = query.replace("where is", "") location = query speak("User asked to Locate") speak(location) webbrowser.open("https://www.google.nl / maps / place/" + location + "") # rest of commands else: text = quote(query) botname = quote(assistant_name) url = f"https://api.popcat.xyz/chatbot?msg={text}&owner=Pranjal+Prakarsh&botname={botname}" try: request = requests.get(url) data = request.json() output = data["response"] speak(output) except: speak("Sorry, I don't understand that")
期望行为
我希望个人助手仅在必要时响应:
- 当我明确向聊天机器人提问时。
- 当其他已定义命令均未被识别时作为备选方案。
- 聊天响应不得干扰其他命令的执行。
内容的提问来源于stack exchange,提问作者Infinotiver
相关产品推荐
相关产品推荐

