Handling Errors in PRAW (Reddit) - python

I'm playing around with making an auto reply bot that scanns r/All submission comments for a given command eg. !command
When it detects this command it replies to the comment with a string:
eg. "Hello"
The error I get is that there is a limit on new accounts where they can only comment once every 10 minutes. And when the bot comments and moves to the next comment to reply to it gets this error:
raise APIException(*errors[0])
praw.exceptions.APIException: RATELIMIT: 'you are doing that too much.
try again in 2 minutes.' on field 'ratelimit'
How can I detect this type of error so the code knows what to do, at the moment the whole script that stops and I have to run it again after 10 minutes.
Had a read of https://praw.readthedocs.io/en/latest/code_overview/exceptions.html but still not getting it

An Exception is raised here, which you can handle using a try..except
try:
the_api_call()
except APIException as e:
print "Handling exception like a baus"
P.S. you would need to import APIException as it's not a in-built exception.

As Samaksh Jain said,
used try..catch
imported APIexception using the following
import django
from rest_framework.exceptions import APIException

Related

verify if bloomberg-anywhere pdblp session is valid

I want to implement a check if import pdblp is active and if not exit the session.
I note from this link (Bloomberg Anywhere + pdblp or xbbg + not logged in) that a session:
remains logged in for 3 days.
is logged out if a session is opened on another pc.
Therefore, i want to implement a try-execpt block like this:
import pdblp
# check if connected
try:
con = pdblp.BCon(timeout=5000)
con.start()
except Exception as e:
print('not logged in:', e)
my question is, would the above be sufficient to validate the connection ?
(ie. would the above throw an error, e).
TL;DR
Use the newer blp package instead of blpapi, which is no longer supported by the creator.
pip install blp
try:
from blp import blp
con = blp.BlpQuery().start()# change debug to true to see issues
except:
print('NO BLOOMBERG')
Yes, your try-except is sufficient. The except statement will throw you the error to know that the Bloomberg connection is not working (the link you included to the other SO article correctly noted that the python API will only work under the same conditions that the Excel API does for Bloomberg).
However, it was troublesome for me that con = pdblp.BCon(timeout=5000) con.start() would try to connect for nearly 1 minute. The new blp package will kick out an error in 17 seconds. Just change your con to the new .start()

Telethon, TelegramClient.connect how do I set authentication code programmatically

I am using telethon to automate some tasks on Telegram.
I am trying to create an API where third party users can provide phone number and enter code through an api. I have got the phone number part working, As I allow users to input their phone number through a webservice, this gets wrote to a file, then I am opening that file and fetching the phone number in python which is {number}, I then connect to the client using below.
client = TelegramClient(f'{number}', API_ID, API_KEY)
try:
await client.connect()
except Exception as e:
print('Failed to connect', e, file=sys.stderr)
return
Once the code is run the user enters the verification code (not in the python app) which gets wrote to a file.
And in python the following is returned
Please enter the code you received:
I can open the file which contains the verification code which as {code}
but how do I use {code} to reply to 'Please enter the code you received:'
Thanks
I think that you get the code on telegram and not in the file
It is possible, but this will be very complex as the code is sent to another device. You can write custom Telegram client that will send this code to your program, but it is too complex and in 99.9% of cases you won't need it.
Edit:
If you already have this code, let's say in code variable, you can try to use method sign_in() instead of connect()
try:
await client.sign_in(number, code)
except Exception as e:
print('Failed to connect', e, file=sys.stderr)
return
Reference for sign_in() in docs

Python continue on gaierror using the requests library

I'm using the requests library for python and I would like the code to continue whenever this ('Connection aborted.', gaierror(-2, 'Name or service not known')) error occurs. For some reason my try catch is being ignored and the error causes the application to exit anyway.
My code:
try:
self.doSomething();
except requests.exceptions.ConnectionError as e:
self.logger.error("A connection error occured.");
self.logger.error(str(e) + "\n");
except Exception as e:
self.logger.error("An error occured.");
self.logger.error(str(e) + "\n");
If the error is a socket.gaierror, which is a subclass of OSError which is a subclass of Exception, then the except Exception clause should be executed.
Try/except is a powerful tool in Python, however, if not used carefully, it can easily hide errors. Sometimes the best approach is to remove the try/except and read the full traceback. Another approach that works pretty well is to log the full traceback, unfortunately for the Python newcomer, there are ubiquitous examples of this done wrong. To get the full traceback, you need to either remove the try/except, or use
import traceback
try:
risky_call()
except Exception:
print(traceback.print_exc())
Or, if you have a logger configured
import logging
try:
risky_call()
except Exception:
logging.exception('')

Python requests causing error on certain urls

For some reason when I try to get and process the following url with python-requests I receive an error causing my program to fail. Other similar urls seems to work fine
import requests
test = requests.get('http://t.co/Ilvvq1cKjK')
print test.url, test.status_code
What could be causing this URL to fail instead of just producing a 404 status code?
The requests library has an exception hierarchy as listed here
So wrap your GET request in a try/except block:
import requests
try:
test = requests.get('http://t.co/Ilvvq1cKjK')
print test.url, test.status_code
except requests.exceptions.ConnectionError as e:
print e.request.url, "*connection failed*"
That way you end up with similar behaviour to what you're doing now (so you get the redirected url), but cater for not being able to connect rather than print the status code.

python Django custom error msg for any error (apart from try,except)

in django, whenever an error is occured , if we dont keep in try block, an error will be raised . At that point of time(during error), if it is not in try block, instead of the error page, can we display a msg .
What I am actually saying is, is there anything in django(like signals) that gets activated during error and prints that msg . In my case, it is an ajax request, so what i want is, when something is not inside try block, and still if it raises error, then it should atleast send back an error msg(to another server which made ajax call to our server) saying "error occured" .
In Django, if an error occurs, it isn't actually propagated to the user automatically. Rather, if you have an error occur, it returns a 500 error page. If Django is in debug mode, it will give a traceback. If the other server is intelligent, it will realized that there is a 500 error message instead of a 200 message. In Django you can then define a "500.html" in your root directory to handle the errors (or use the default Django template). GLHF
As far as I know, there is no way to globally override the default exception handling in Python. You can use try/except blocks to catch errors, execute some code, then re-raise the exception though.
Put your code in a try block, and in the except block print your message, then call raise to re-raise the caught exception.
Ex:
try:
raise Exception("This is an exception")
except Exception:
print ("Exception raised, notify server")
#re-raise exception
raise
This will print something like:
Exception raised, notify server
Traceback (most recent call last):
File "[file]", line [line], in [module]
Exception: This is an exception

Categories