Python script stops at error instead of carrying on - python

I am using Telethon for a telegram bot.
I've got a list of phone numbers. If the phone number is valid then to run a script, if it is invalid I want it to check another number.
This is the part of script which is causing me issues.
from telethon.sync import TelegramClient
from telethon.errors.rpcerrorlist import PhoneNumberBannedError
api_id = xxx # Your api_id
api_hash = 'xxx' # Your api_hash
try:
c = TelegramClient('{number}', api_id, api_hash)
c.start(number)
print('Login successful')
c.disconnect()
break
except ValueError:
print('invalid number')
If the number is invalud then I would expect the script to print 'invalid number' and then carry on. Except it is throwing error 'telethon.errors.rpcerrorlist.PhoneNumberInvalidError: The phone number is invalid (caused by SendCodeRequest)', then ending the script.
How can I carry on the script when this error is thrown?
Thanks

The exception you're catching is ValueError, but the error being thrown is telethon.errors.rpcerrorlist.PhoneNumberInvalidError.
So you need to catch that exception instead:
from telethon.errors.rpcerrorlist import PhoneNumberInvalidError
try:
# your code
except PhoneNumberInvalidError:
print('invalid number')
You can also combine error types if needed:
except (PhoneNumberInvalidError, ValueError):
# handle these types the same way
except TypeError:
# or add another 'except <type>' line to handle this error separately
This is especially useful when you're running a lot of code in your try and so a lot of different errors could occur.
Your last options is to catch every error using
try:
# code
except Exception:
print("exception!")
and while this might seem to be useful it will make debugging a lot harder as this will catch ANY error (which can easily hide unexpected errors) or it will handle them in the wrong way (you don't want to print 'invalid number' if it was actually a TypeError or KeyboardInterrupt for example).

Related

How can i make an exception on "caused by SendMultiMediaRequest"?

How can i make an exception on "A wait of 61 seconds is required (caused by SendMultiMediaRequest)" ? I can't find anything in the official documentation.
The fact is that when sending photos to some users, this error pops up.
Basically sends well, but sometimes there are users who simply do not send (throws an exception "Exception"), although they exist and, in principle, you can send a message to them. I need to trace this exception
from telethon import TelegramClient, errors
client = TelegramClient('session', api_id=API_ID, api_hash=API_HASH)
message = "Hello"
files = ['img/11.jpg', 'img/22.jpg', 'img/33.jpg', 'img/44.jpg', 'img/55.jpg']
async def main():
for user in db.get_users(name_table=table):
try:
if db.check_invited(name_table=table, user_name=user) != "TRUE":
await client.send_message(entity=user, message=message, file=files)
print('Ok')
except errors.BadRequestError as e:
print(e)
except Exception as e:
print(e)

How to change Prometheus error message if token is invalid?

I have a python file called main.py and I am trying to make a Prometheus connection with a specific token. However, if the token is expired, instead of the error message printing out prometheus_api_client.exceptions.PrometheusApiClientException, how can I get the error message to print our like status_code: 500, reason: Invalid token using a try and except block.
Code:
#token="V0aksn-as9ckcnblqc6bi3ans9cj1nsk" #example, expired token
token ="c0ams7bnskd9dk1ndk7aKNYTVOVRBajs" #example, valid token
pc = PrometheusConnect(url = url, headers={"Authorization": "bearer {}".format(token)}, disable_ssl=True)
try:
#Not entirely sure what to put here and the except block
except:
I've tested out a couple code in the try and except blocks and could not get rid of the long error from Prometheus. Any suggestions?
How about putting your pc variable in try and PrometheusApiClientException for the exception. If that doesn't work, go to the source file and use whatever exception developers used while making authorization.
This is how you catch that exception in a try/except block
try:
# Interact with prometheus here
pass
except prometheus_api_client.exceptions.PrometheusApiClientException as e:
print('status_code: 500, reason: Invalid token')

Detect failed edit of channel in discord.py

I am making a discord bot which lets users edit a voicechannel name. My code is something like this:
channel = client.get_channel(id)
try:
await channel.edit(name="new name")
except:
raise
And it raises fine if the name is invalid but not if the name is valid and the change was not successful due to Discords rate limit of I guess 2 edits every 10 minutes.
I think the problem is that there is no error on my end, Discord is just waiting with the response. Is there a way to give my request a timeout of about 5 seconds and raise if it takes too long?
I would check for both an error and a None response. Better yet, why not just check that the name after the change is what it should be?
I don't think you can add in a timeout directly into the function call but this is the type of thing you might want to loop and add a asyncio.sleep into. Ignoring the first part, you might have something like this:
NEW_NAME = "new name"
while True:
e = None
try:
await channel.edit(name=NEW_NAME)
except Exception as e: pass
# "channel.name" is pseudo-code.
# Use whatever method to check the name.
if <channel.name> != NEW_NAME:
print ("Exception: %s ...(whatever else you want to print)" % e)
await asyncio.sleep(60) # or whatever you think reasonable
else:
break

Error handling Telegram bot

I am trying to avoid a telegram error. This error occurs when a message is not modified:
telegram.error.BadRequest: Message is not modified
I would like to make a function to print a message when this error occurs instead the original error message telegram prints. I have tried something like this but does not work:
def error_callback(bot, update, error):
try:
raise error
except BadRequest:
# handle malformed requests - read more below!
print('Same message')
First of all, if there are no evident bugs, this error could be happen if a user if clicking too fast on a button. In this case it can be easily ignored.
Assuming you are using python-telegram-bot library looking at your code, you can follow 2 approaches:
1. Ignore the error globally:
def error(bot, update, error):
if not (error.message == "Message is not modified"):
logger.warning('Update "%s" caused error "%s"' % (update, error))
but you will still receive on the console:
2017-11-03 17:16:41,405 - telegram.ext.dispatcher - WARNING - A TelegramError was raised while processing the Update
the only thing you can do is to disable that string for any error of any type doing this:
updater.dispatcher.logger.addFilter((lambda s: not s.msg.endswith('A TelegramError was raised while processing the Update')))
in your main(). credits
2. Ignore the error in the method you are calling:
You can ignore the error in the method you are calling doing:
try:
# the method causing the error
except TelegramError as e:
if str(e) != "Message is not modified": print(e)
This second approach will ignore the error completely on the console without modifying the error callback function, but you have to use it in every single method causing that exception.
Printing 'text' instead of ignoring:
i suggest you to ignore the error, but if you want to print a string as you said: you can very easily modify those 2 approaches to print the string.
Example for the first approach:
def error(bot, update, error):
if error.message == "Message is not modified":
# print your string
return
logger.warning('Update "%s" caused error "%s"' % (update, error))
Example of the second approach:
try:
# the method causing the error
except TelegramError as e:
if str(e) == "Message is not modified": print(your_string)

Error handling in python with ldap

I have this bit of code below, it is part of a python script iv been working on(piecing it together blocks at a time as learning curve). This bit binds to an ldap directory to query, so the rest of the script can to the queries.
When successful, it will print the below message in the block. When not successful it will throw an error- or at least i want to control the error.
If im not domain bound/vpn it will throw this message:
{'desc': "Can't contact LDAP server"}
if incorrect credentials :
Invalid credentials
nowhere in my script is it defined for the error message, how can i find where its fetching what to print that messsage- and possibly create or customize it?
(for what its worth i am using PyCharm)
try:
l = ldap.open(server)
l.simple_bind_s(user, pwd)
#if connection is successful print:
print "successfully bound to %s.\n" %server
l.protocol_version = ldap.VERSION3
except ldap.LDAPError, e:
print e
thanks
you can do something like this to provide a specific message for a specific exception.
try:
foo = 'hi'
bar = 'hello'
#do stuff
except ValueError:
raise ValueError("invalid credientials: {},{}".format(foo, bar))
so in your example it could become
except ldap.LDAPError:
raise ldap.LDAPError("invalid credientials: {},{}".format(user, pwd))
or if you literally just want to print it
except ldap.LDAPError:
print("invalid credientials: {},{}".format(user, pwd))

Categories