Skip to content

Commit fe34382

Browse files
committed
TASK: Implement better error handling
That should reduce the message spam coming from the bot.
1 parent 822d49e commit fe34382

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

main.py

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
from threading import Thread
88

99
from telegram import ReplyKeyboardRemove
10+
from telegram.error import (TelegramError, Unauthorized, BadRequest,
11+
TimedOut, ChatMigrated, NetworkError)
1012
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, MessageHandler, Filters
1113
from telegram.inline.inlinekeyboardbutton import InlineKeyboardButton
1214
from telegram.inline.inlinekeyboardmarkup import InlineKeyboardMarkup
@@ -145,10 +147,26 @@ def game_commands(update, context):
145147
def error_callback(update, context):
146148
"""Log Errors caused by Updates."""
147149
error = context.error
148-
if update is None:
150+
logger.error('Update "%s" caused error "%s"', update, error)
151+
try:
152+
raise error
153+
except Unauthorized as e:
154+
logger.error(e.message) # remove update.message.chat_id from conversation list
155+
logger.error(update)
156+
# TODO the unauthorized error indicates that a user blocked the bot.
149157
return
150-
151-
logger.warning('Update "%s" caused error "%s"', update, error)
158+
except BadRequest as e:
159+
logger.error(e.message) # handle malformed requests
160+
return
161+
except TimedOut:
162+
pass # connection issues are ignored for now
163+
return
164+
except NetworkError as e:
165+
logger.error(e.message) # handle other connection problems
166+
except ChatMigrated as e:
167+
logger.error(e.message) # the chat_id of a group has changed, use e.new_chat_id instead
168+
except TelegramError as e:
169+
logger.error(e.message) # handle all other telegram related errors
152170

153171
db = DBwrapper.get_instance()
154172
for admin_id in db.get_admins():
@@ -170,7 +188,7 @@ def admin_check(update, context):
170188
if user.id in db.get_admins():
171189
return func(update, context)
172190
else:
173-
update.message.reply_text('You have not the needed permissions to do that!')
191+
update.message.reply_text('You have not the required permissions to do that!')
174192
logger.warning(
175193
"User {} ({}, @{}) tried to use admin function '{}'!".format(user.id, user.first_name, user.username,
176194
func.__name__))

0 commit comments

Comments
 (0)