How to log errors from the Telegram bot console - python

From time to time, errors appear in the telegram bot, and I would like to log them. In all "try:except" I set logging, but for some reason these errors pop up in the console and I cannot find a place to grab them
I need to find not the cause of the problem, but how to log it from the console
(__init__.py:445 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. The server returned HTTP 400 Bad Request. Response body:
[b'{"ok":false,"error_code":400,"description":"Bad Request: message can\'t be edited"}']"
At the end of the file I have such a construction, but for some reason it does not capture the error that I indicated above
while True:
try:
bot.polling(none_stop=True, interval=1, timeout=20)
except Exception as E:
log(E)

python-telegram-bot has his own Exception Handling;
Example;
from telegram.error import (TelegramError, Unauthorized, BadRequest,
TimedOut, ChatMigrated, NetworkError)
def error_callback(update, context):
try:
raise context.error
except Unauthorized:
# remove update.message.chat_id from conversation list
except BadRequest:
# handle malformed requests - read more below!
except TimedOut:
# handle slow connection problems
except NetworkError:
# handle other connection problems
except ChatMigrated as e:
# the chat_id of a group has changed, use e.new_chat_id instead
except TelegramError:
# handle all other telegram related errors
dispatcher.add_error_handler(error_callback)
Any other errors will be caught and logged by the Dispatcher. (As described in on there git page).
Small example of configuring the dispatcher;
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)

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 define Exception Handling for Dead-Letter-Queue Strategy

For my Data Pipeline where I am scraping data out of the web and send it to Kafka, I am using the Dead-Letter-Queue Strategy for professional Error Handling. I was wondering how I can define the except-Statement if I don't know what Exception might occur. I am sending the exception to an error topic in which I want to extract the Error details. Atm it looks like this:
from setup import producer as p
def scraper():
try:
# ... scraping data
except Exception as e:
# Send NaN-Value to topic
p.produce(topic, NaN-message, callback=delivery_report)
p.flush()
# Send error message to error topic
error_message = json.dumps({
"topic": topic,
"error": repr(e),
"error_type": str(type(e)),
"timestamp": str(datetime.datetime.now())
})
p.produce(error_topic, error_message, callback=delivery_report)
p.flush()
Anyone an idea on how to improve the error handling that it takes whatever Exception occurs?

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')

Flask-restful - During handling of the above exception, another exception occurred

As part a Flask-restful API I have a login Resource:
class LoginApi(Resource):
def post(self):
try:
body = request.get_json()
user = User.objects.get(email=body.get('email'))
authorized = user.check_password(body.get('password'))
if not authorized:
raise UnauthorizedError
expires = datetime.timedelta(days=7)
access_token = create_access_token(identity=str(user.id), expires_delta=expires)
return {'token': access_token}, 200
except DoesNotExist:
raise UnauthorizedError
except Exception as e:
raise InternalServerError
There are 4 scenarios for login route:
Email and Password are correct
Email does not exist in the database - in this case the UnauthorizedError is raised correctly.
Email exists but password is incorrect - in this case I have an issue (described below)
Some other Error - InternalServerError is raised correctly.
So for number 3 - instead of getting an UnauthorizedError, I am getting an InternalServerError.
The if not authorized: statement is working correctly (If i put a print in there I can see it work). However for some reason I am getting the following when trying to raise the error:
During handling of the above exception, another exception occurred:
I came across this PEP article which seems to suggest changing to raise UnauthorizedError from None but the issue persists. Does anyone know how I can implement this successfully? Ideally I would like the same error to be raised from scenarios 2 and 3, otherwise there is a potential for someone to know whether or not an email exists in the database, from the errors they get back.
The if statement is raising UnAuthorized, but that happens in the excepts, you have to raise DoesNotExist to make it so that UnAuthorized can be raised in the except.

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)

Categories