How to fix "BaseException is not allowed" - python-3.x

I am trying to make this script get what im saying and print it out on terminal but im getting this error
TypeError: catching classes that do not inherit from BaseException is not allowed
for this I followed a tutorial and his worked just fine im running version 3.9.5 I have tried to look this up but nothing I found was helpful if you know please let me know
import speech_recognition
import pyttsx3
recognizer = speech_recognition.Recognizer()
while True:
try:
with speech_recognition.Microphone() as mic:
recognizer.adjust_for_ambient_noise(mic, duration=0.2)
audio = recognizer.listen(mic)
text = recognizer.recognize_google(audio)
text = text.lower()
print(f"Recognized {text}")
except speech_recognition.UnknownValueError():
recognizer = speech_recognition.Recognizer()
continue

Your
except speech_recognition.UnknownValueError():
should be
except speech_recognition.UnknownValueError:
i.e. it should name the type, not call it and use the return value.

Related

APIError(code=-1099): Not found, unauthenticated, or unauthorized

I hope that you are having a good day.
I am working with the Binance api trough the Python-Binance.
My bot runs fine most of the time but for some reason after a while it randomly stops and gives me this error message. "APIError(code=-1099): Not found, unauthenticated, or unauthorized".
The error seems to happen at the same line of code everytime.
from binance.client import Client
import time
from datetime import datetime
import pandas as pd
class LastPrice():
def __init__(self, symbol):
self.symbol = symbol
self.api_key = "my key"
self.secret_key = "my secret"
def get_client(self):
try:
client = Client(self.api_key, self.secret_key)
except Exception as e:
print(e)
pass
return client
def get_last_price(self):
last_price_string = self.get_client().get_ticker(symbol=self.symbol)['lastPrice']
last_price = float(last_price_string)
return last_price_string
def get_last_price_and_time(self):
last_price_string = self.get_client().get_ticker(symbol=self.symbol)['lastPrice']
close_time = self.get_client().get_ticker(symbol=self.symbol)['closeTime']
last_price = float(last_price_string)
price_and_time = [close_time, last_price]
return price_and_time
error message
I Have included a screenshot of my error message i get. Despite using the same code to generate the client everytime i only get the error in that specific code. My code stops because the client is referenced before assignement but I am looking for the cause of the precedent APIError.
Any idea what that error meassage means in the context of my code ? Thanks in advance !

os.startfile strange behaviour

I'm receiving a string from a web extension. The string is a local file path, and I'm trying to open the filepath using the default OS setting for whatever that may be.
edit: Sorry! The question is: how can I successfully open the given path with the OS default app?
The filepath is initially a string formatted as below:
'file:///C:/Test/File/Path.docx'
WEIRD THINGS!
If Word is already open, it works fine.
If Word isn't already open, the blue Word "launching" screen shows for a split second then disappears (crashes, as subsequent attempts show the "start word in safe mode?" dialog for a split second instead).
It won't work at all unless I use "os.startfile" twice specifically as written. One outside a try statement, one inside. Any other combo won't work.
From IDLE, it works 100% of the time with just one "os.startfile" call.
I've also tried to use subprocess.check_call, but that fails to launch anything at all.
Here is the script:
#!/usr/bin/env python
import sys
import json
import struct
import re, subprocess, os
def read_thread_func(queue):
while 1:
text_length_bytes = sys.stdin.buffer.read(4)
if len(text_length_bytes) == 0:
sys.exit(0)
text_length = struct.unpack("i", text_length_bytes)[0]
text = sys.stdin.read(text_length)
data = json.loads(text)
fileStr = data['url']
filePath = re.sub('file:\/{1,3}','',fileStr)
filePath = filePath.replace("/","\\")
filePath = os.path.normpath(filePath)
os.startfile(filePath)
try:
os.startfile(filePath)
except AttributeError:
"nothing to see here"
sys.exit(0)
def Main():
read_thread_func(None)
sys.exit(0)
if __name__ == '__main__':
Main()

program keeps executing first if condition

I'm trying to build a speech recognition app in python,everything works fine but,when I'm executing program the first If condition always executes no matter what the input is.
import speech_recognition as sr
from gtts import gTTS
import os
from google_speech import Speech
import webbrowser
def speech():
while True:
try:
with sr.Microphone() as source:
r = sr.Recognizer()
audio = r.listen(source,timeout=3, phrase_time_limit=3)
x = r.recognize_google(audio)
print(x)
if 'hello' or 'Hello' or 'Hi' in x:
speech=Speech('Hello,How are you?','en')
speech.play()
print('Input: ',x)
print('output: Hello,How are you?',)
elif 'omkara' or 'Omkara' in x:
speech=Speech('Playing Omkara song on Youtube','en')
speech.play()
webbrowser.get('/usr/bin/google-chrome').open('https://youtu.be/NoPAKchuhxE?t=21')
except sr.UnknownValueError:
print("No clue what you said, listening again... \n")
speech()
if __name__ == '__main__':
print('Executine Voice based commands \n')
speech()
here is my code I have used while to continuously repeat the program but,In first if condition,it should only be executed when there is 'Hello','Hi' in input. First time I say 'Hi',if is valid then,but when the program loops again with another input like 'how are you' it still executes first IF condition,can anyone please help me with this.Thank you.
You use or in wrong way there. Try to use this code:
if any(check in x for check in ('hello', 'Hello', 'Hi')):
The problem occurs because if 'Hello' becomes True instantly. Once you have a condition which is true, it will always go to if condition.
You can try to check this using bool('Hello'). The solution is to check each string separately.
if ('hello' in x) or ('Hello' in x) or ('Hi' in x):
something

How to call any other event in the Slack API besides [message]?

I'm playing around with trying to make a bot in the slack channel so that I can understand how the whole process works. I have 2 questions. [1st question solved]First, I know how to send a message if someone said anything but I can't figure out how to check what was specifically said. Here's my code:
import os
import time
from slackclient import SlackClient
BOT_TOKEN = os.getenv('SLACK_BOT_USER_TOKEN')
print(BOT_TOKEN)
CH_NM = "bot_testing"
def main():
sc = SlackClient(BOT_TOKEN)
SM = sc.rtm_send_message
if sc.rtm_connect():
print("Bot running")
SM(CH_NM, "Started")
while True:
for slack_message in sc.rtm_read():
message = slack_message.get("text")
user = slack_message.get("user")
if 'hello' in message:
SM(CH_NM, "Hey, <#{}>!".format(user))
if not message or not user:
continue
SM(CH_NM, """<#{}> wrote something...""".format(user))
time.sleep(.5)
if __name__ == '__main__':
main()
The main line I'm having trouble with is
if 'hello' in message:
SM(CH_NM, "Hey, <#{}>!".format(user))
because I can't iterate through 'message' since it is 'NoneType'. How then would I go about checking if it contained a specific string?
Second question, I see that there are all sorts of event types, but mine only seems to work for the "message" type of events. If I wanted to return something every time a specific user started typing for example what would I add to make that work? I already tried adding typing = slack_message.get("user_typing") but understandably it doesn't work since 'user_typing' is an event type, not part of the message event type I'm pulling 'text' and 'user' out of.
So you know, I'm using python 3.6, Windows 10, powershell.
The issue was that I had my if not message or not user: continue line below the if 'hello' in message: line, so it would error out due to any other event that is happening that isn't a message. 1st Issue solved.

QComboBox.currentText() -- PySide vs PyQt4

I've got a python script using PySide and it works fine.
But then I thought to check if it gonna work with PyQt4.
And after changing the import strings to PyQt4, things went wrong.
The error points to the subject, as follows:
File "./my_file.py", line 93, in showit
curr_query = '.'.join(curr_query)
TypeError: sequence item 0: expected string, QString found
From the docs I can see that PySide subject method returns 'unicode' string,
but the PyQt4 one returns QString object.
Playing with the str(), str() etc did not seem to do the job.
Here's the function code:
def showit(self, idx):
curr_query = []
for i in xrange(idx+1):
>> x = self.combo[i].currentText()
>> if x:
curr_query.append(x)
else:
break
curr_query = '.'.join(curr_query)
This reads text of a set of QCombobox'es to build up a dot-sepated string presentation that I use later.
The marked '>>' lines is where the issue occurs - the 'x' object is never an empty string, suddenly, as it was while using PySide library. But it is expected to be empty, if there's an empty self.combo[i] .
I've searched the SO archive and found this answer but not able to use it.
Please advice how to fix this.
You need to convert your x values to a string of sorts. Something like
curr_query.append(str(x))
should do the trick.

Resources