Python telegram.error.TimedOut() Examples
The following are 26
code examples of telegram.error.TimedOut().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
telegram.error
, or try the search function
.
Example #1
Source File: core.py From CindicatorArbitrageBot with GNU General Public License v3.0 | 6 votes |
def notify(bot, job): """ Send notification to user Args: :param bot: <telegram.Bot> bot instance :param job: <telegram.ext.jobqueue.Job> user's job instance """ res = crawl(job.context['chat_id']) if len(res) > 0: try: bot.send_message(chat_id=job.context['chat_id'], text=_generate_string(res), parse_mode=messages.MARKDOWN) except Unauthorized: job.schedule_removal() mq.update_setting(job.context['chat_id'], setting=base_config.NOTIFICATIONS, value=False) except TimedOut: logger.warning('chat_id: {}; error: {}'.format(job.context['chat_id'], 'Time out while sending notification')) except Exception as e: logger.warning('chat_id: {}; error: {}\n' '{}'.format(job.context['chat_id'], str(e), format_exc()))
Example #2
Source File: ezstickerbot.py From ez-sticker-bot with MIT License | 6 votes |
def download_file(file_id): try: # download file file = bot.get_file(file_id=file_id, timeout=30) ext = '.' + file.file_path.split('/')[-1].split('.')[1] download_path = os.path.join(temp_dir(), (file_id + ext)) file.download(custom_path=download_path) return download_path except TimedOut: raise TimedOut # _____ _ _ _ _ _ # | ____| __ __ ___ _ __ | |_ | | | | __ _ _ __ __| | | | ___ _ __ ___ # | _| \ \ / / / _ \ | '_ \ | __| | |_| | / _` | | '_ \ / _` | | | / _ \ | '__| / __| # | |___ \ V / | __/ | | | | | |_ | _ | | (_| | | | | | | (_| | | | | __/ | | \__ \ # |_____| \_/ \___| |_| |_| \__| |_| |_| \__,_| |_| |_| \__,_| |_| \___| |_| |___/
Example #3
Source File: test_handle_callback.py From AmbroBot with GNU General Public License v3.0 | 6 votes |
def test_handle_callback_with_timeout_sends_message(mocker, sample_movie, caplog): bot, update = mocker.MagicMock(), mocker.MagicMock() update.callback_query.data = NEXT_YTS mocker.patch('commands.yts.utils.InputMediaPhoto', side_effect=TimedOut) chat_data = { 'context': { 'data': [sample_movie, sample_movie], 'movie_number': 0, 'movie_count': 1, 'command': 'yts', 'edit_original_text': True, } } caplog.set_level(logging.INFO) handle_callback(bot, update, chat_data) assert bot.send_message.call_count == 1 assert ( bot.send_message.call_args[1]['text'] == 'Request for new photo timed out. Try again.' ) assert "Could not build InputMediaPhoto from url" in caplog.text
Example #4
Source File: decorators.py From tnt-village-bot with MIT License | 6 votes |
def failwithmessage(func): @wraps(func) def wrapped(update: Update, context: CallbackContext, *args, **kwargs): try: return func(update, context, *args, **kwargs) except TimedOut: logger.error('TimedOut error') # memo: timed out errors break conversation handlers because the new state isn't returned except Exception as e: logger.error('unexpected error while running handler callback: %s', str(e), exc_info=True) text = 'An error occurred while processing the message: <code>{}</code>'.format(html_escape(str(e))) if update.callback_query: update.callback_query.message.reply_html(text) else: update.message.reply_html(text) return wrapped
Example #5
Source File: common.py From NanoWalletBot with BSD 3-Clause "New" or "Revised" License | 6 votes |
def push_simple(bot, chat_id, message): try: bot.sendMessage(chat_id=chat_id, text=message) except BadRequest as e: bot.sendMessage(chat_id=chat_id, text=replace_unsafe(message)) except RetryAfter as e: sleep(240) bot.sendMessage(chat_id=chat_id, text=message) except TimedOut as e: sleep(60) bot.sendMessage(chat_id=chat_id, text=message) except Unauthorized as e: sleep(0.25) except NetworkError as e: sleep(30) bot.sendMessage(chat_id=chat_id, text=message) except Exception as e: sleep(1) bot.sendMessage(chat_id=chat_id, text=message)
Example #6
Source File: __main__.py From SkittBot with GNU General Public License v3.0 | 5 votes |
def error_callback(bot, update, error): try: raise error except Unauthorized: print("no nono1") print(error) # remove update.message.chat_id from conversation list except BadRequest: print("no nono2") print("BadRequest caught") print(error) # handle malformed requests - read more below! except TimedOut: print("no nono3") # handle slow connection problems except NetworkError: print("no nono4") # handle other connection problems except ChatMigrated as err: print("no nono5") print(err) # the chat_id of a group has changed, use e.new_chat_id instead except TelegramError: print(error) # handle all other telegram related errors
Example #7
Source File: telegram-bot.py From Deep-Reinforcement-Learning-Hands-On with MIT License | 5 votes |
def error(self, bot, update, error): try: raise error except TimedOut: log.info("Timed out error")
Example #8
Source File: __main__.py From tgbot with GNU General Public License v3.0 | 5 votes |
def error_callback(bot, update, error): try: raise error except Unauthorized: print("no nono1") print(error) # remove update.message.chat_id from conversation list except BadRequest: print("no nono2") print("BadRequest caught") print(error) # handle malformed requests - read more below! except TimedOut: print("no nono3") # handle slow connection problems except NetworkError: print("no nono4") # handle other connection problems except ChatMigrated as err: print("no nono5") print(err) # the chat_id of a group has changed, use e.new_chat_id instead except TelegramError: print(error) # handle all other telegram related errors
Example #9
Source File: __main__.py From Marie-2.0-English with GNU General Public License v3.0 | 5 votes |
def error_callback(bot, update, error): try: raise error except Unauthorized: print("no nono1") print(error) # remove update.message.chat_id from conversation list except BadRequest: print("no nono2") print("BadRequest caught") print(error) # handle malformed requests - read more below! except TimedOut: print("no nono3") # handle slow connection problems except NetworkError: print("no nono4") # handle other connection problems except ChatMigrated as err: print("no nono5") print(err) # the chat_id of a group has changed, use e.new_chat_id instead except TelegramError: print(error) # handle all other telegram related errors
Example #10
Source File: message_utils.py From python-aria-mirror-bot with GNU General Public License v3.0 | 5 votes |
def editMessage(text: str, message: Message): try: bot.edit_message_text(text=text, message_id=message.message_id, chat_id=message.chat.id, parse_mode='HTMl') except TimedOut as e: LOGGER.error(str(e)) pass
Example #11
Source File: sentry.py From ultimate-poll-bot with MIT License | 5 votes |
def __init__(self): """Construct new sentry wrapper.""" if config["logging"]["sentry_enabled"]: self.initialized = True self.sentry = Client( config["logging"]["sentry_token"], ignore_exceptions=[TimedOut], )
Example #12
Source File: session.py From ultimate-poll-bot with MIT License | 5 votes |
def ignore_job_exception(exception): """Check whether we can safely ignore this exception.""" if isinstance(exception, TimedOut): return True return False
Example #13
Source File: common.py From NanoWalletBot with BSD 3-Clause "New" or "Revised" License | 5 votes |
def text_reply(update, text): try: update.message.reply_text(text) except TimedOut as e: sleep(60) update.message.reply_text(text) except NetworkError as e: sleep(30) update.message.reply_text(text) except Exception as e: sleep(1) update.message.reply_text(text)
Example #14
Source File: common.py From NanoWalletBot with BSD 3-Clause "New" or "Revised" License | 5 votes |
def message_markdown(bot, chat_id, message): try: bot.sendMessage(chat_id=chat_id, text=message, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except BadRequest: bot.sendMessage(chat_id=chat_id, text=replace_unsafe(message), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except RetryAfter: sleep(240) bot.sendMessage(chat_id=chat_id, text=message, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except TimedOut as e: sleep(60) bot.sendMessage(chat_id=chat_id, text=message, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except Unauthorized as e: sleep(0.25) except NetworkError as e: sleep(30) bot.sendMessage(chat_id=chat_id, text=message, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except Exception as e: sleep(1) bot.sendMessage(chat_id=chat_id, text=message, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
Example #15
Source File: raiwalletbot.py From NanoWalletBot with BSD 3-Clause "New" or "Revised" License | 5 votes |
def custom_keyboard(bot, chat_id, buttons, text): reply_markup = ReplyKeyboardMarkup(buttons, resize_keyboard = True) try: bot.sendMessage(chat_id=chat_id, text=text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=reply_markup) except BadRequest: bot.sendMessage(chat_id=chat_id, text=replace_unsafe(text), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=reply_markup) except RetryAfter: sleep(240) bot.sendMessage(chat_id=chat_id, text=text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=reply_markup) except TimedOut: sleep(10) bot.sendMessage(chat_id=chat_id, text=text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=reply_markup) except: sleep(1) bot.sendMessage(chat_id=chat_id, text=text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=reply_markup)
Example #16
Source File: sticker_set.py From sticker-finder with MIT License | 5 votes |
def extract_text(tg_sticker): """Extract the text from a telegram sticker.""" text = None logger = logging.getLogger() try: # Get Image and preprocess it tg_file = call_tg_func(tg_sticker, "get_file") image_bytes = call_tg_func(tg_file, "download_as_bytearray") with Image.open(io.BytesIO(image_bytes)).convert("RGB") as image: image = preprocess_image(image) # Extract text text = image_to_string(image).strip().lower() # Only allow chars and remove multiple spaces to single spaces text = re.sub("[^a-zA-Z\ ]+", "", text) text = re.sub(" +", " ", text) text = text.strip() if text == "": text = None except TimedOut: logger.info(f"Finally failed on file {tg_sticker.file_id}") pass except BadRequest: logger.info(f"Failed to get image of {tg_sticker.file_id}") pass except OSError: logger.info(f"Failed to open image {tg_sticker.file_id}") pass except: sentry.captureException() pass return text
Example #17
Source File: test_handle_callback.py From AmbroBot with GNU General Public License v3.0 | 5 votes |
def test_get_photo_returns_none_on_timeout(mocker, caplog): caplog.set_level(logging.INFO) mocker.patch('commands.yts.utils.InputMediaPhoto', side_effect=TimedOut) assert get_photo('url_img') is None assert 'Retry Failed.' in caplog.text
Example #18
Source File: test_handle_callback.py From AmbroBot with GNU General Public License v3.0 | 5 votes |
def test_get_photo_retry_works(mocker, caplog): caplog.set_level(logging.INFO) mocker.patch( 'commands.yts.utils.InputMediaPhoto', side_effect=[TimedOut, 'photo_url'] ) assert get_photo('url_img') == 'photo_url' assert 'Retrying..' in caplog.text
Example #19
Source File: utils.py From AmbroBot with GNU General Public License v3.0 | 5 votes |
def get_photo(image_url): """Build InputMediaPhoto from image url""" try: return InputMediaPhoto(image_url) except TimedOut: logger.info('Request for photo from %s timed out.', image_url) logger.info('Retrying..') try: return InputMediaPhoto(image_url) except TimedOut: logger.info('Retry Failed.') return None
Example #20
Source File: clean_cmd.py From channel-helper-bot with GNU General Public License v3.0 | 5 votes |
def get_invalid_channel_access(bot): configs = helper_database.get_all_channel_config() invalid_list = [] for config in configs: channel_id = int(config[0]) admin_id = int(config[5]) try: chat_members = bot.get_chat_administrators(chat_id=channel_id).result() except TimedOut: pass except NetworkError: pass except: invalid_list.append(config) return invalid_list
Example #21
Source File: common.py From NanoWalletBot with BSD 3-Clause "New" or "Revised" License | 4 votes |
def push(bot, chat_id, message): try: bot.sendMessage(chat_id=chat_id, text=message, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except BadRequest as e: try: bot.sendMessage(chat_id=chat_id, text=replace_unsafe(message), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except BadRequest: bot.sendMessage(chat_id=chat_id, text=message.replace("_", "\_"), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except RetryAfter as e: sleep(240) bot.sendMessage(chat_id=chat_id, text=replace_unsafe(message), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except TimedOut as e: sleep(60) bot.sendMessage(chat_id=chat_id, text=replace_unsafe(message), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except Unauthorized as e: sleep(0.25) except NetworkError as e: sleep(30) bot.sendMessage(chat_id=chat_id, text=replace_unsafe(message), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except Exception as e: sleep(1) try: bot.sendMessage(chat_id=chat_id, text=message, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) except: sleep(2.5) bot.sendMessage(chat_id=chat_id, text=message, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
Example #22
Source File: telegram.py From sticker-finder with MIT License | 4 votes |
def call_tg_func( tg_object: object, function_name: str, args: list = None, kwargs: dict = None ): """Call a tg object member function. We need to handle those calls in case we get rate limited. """ current_try = 1 tries = 4 exception = None while current_try < tries: try: args = args if args else [] kwargs = kwargs if kwargs else {} breadcrumbs.record( data={"action": f"Starting: {datetime.now()}"}, category="info" ) retrieved_object = getattr(tg_object, function_name)(*args, **kwargs) return retrieved_object except (TimedOut, NetworkError) as e: # Can't update message. just ignore it if "Message to edit not found" in str( e ) or "Message is not modified" in str(e): raise e timeout = 2 * current_try breadcrumbs.record( data={"action": f"Exception: {datetime.now()}"}, category="info" ) logger = logging.getLogger() logger.info( f"Try {current_try}: Got telegram exception waiting {timeout} secs." ) logger.info(e.message) if config["logging"]["debug"]: sentry.captureException() time.sleep(timeout) current_try += 1 exception = e pass raise exception
Example #23
Source File: session.py From ultimate-poll-bot with MIT License | 4 votes |
def ignore_exception(exception): """Check whether we can safely ignore this exception.""" if isinstance(exception, BadRequest): if ( exception.message.startswith("Query is too old") or exception.message.startswith("Have no rights to send a message") or exception.message.startswith("Message_id_invalid") or exception.message.startswith("Message identifier not specified") or exception.message.startswith("Schedule_date_invalid") or exception.message.startswith("Message to edit not found") or exception.message.startswith( "Message is not modified: specified new message content" ) ): return True if isinstance(exception, Unauthorized): if exception.message.lower() == "forbidden: bot was blocked by the user": return True if exception.message.lower() == "forbidden: message_author_required": return True if ( exception.message.lower() == "forbidden: bot is not a member of the supergroup chat" ): return True if exception.message.lower() == "forbidden: user is deactivated": return True if exception.message.lower() == "forbidden: bot was kicked from the group chat": return True if ( exception.message.lower() == "forbidden: bot was kicked from the supergroup chat" ): return True if exception.message.lower() == "forbidden: chat_write_forbidden": return True if isinstance(exception, TimedOut): return True if isinstance(exception, RetryAfter): return True return False
Example #24
Source File: __main__.py From EmiliaHikari with GNU General Public License v3.0 | 4 votes |
def error_callback(update, context): # add all the dev user_ids in this list. You can also add ids of channels or groups. devs = [OWNER_ID] # we want to notify the user of this problem. This will always work, but not notify users if the update is an # callback or inline query, or a poll update. In case you want this, keep in mind that sending the message # could fail if update.effective_message: text = "Hey. I'm sorry to inform you that an error happened while I tried to handle your update. " \ "My developer(s) will be notified." update.effective_message.reply_text(text) # This traceback is created with accessing the traceback object from the sys.exc_info, which is returned as the # third value of the returned tuple. Then we use the traceback.format_tb to get the traceback as a string, which # for a weird reason separates the line breaks in a list, but keeps the linebreaks itself. So just joining an # empty string works fine. trace = "".join(traceback.format_tb(sys.exc_info()[2])) # lets try to get as much information from the telegram update as possible payload = "" # normally, we always have an user. If not, its either a channel or a poll update. if update.effective_user: payload += f' with the user {mention_html(update.effective_user.id, update.effective_user.first_name)}' # there are more situations when you don't get a chat if update.effective_chat: payload += f' within the chat <i>{update.effective_chat.title}</i>' if update.effective_chat.username: payload += f' (@{update.effective_chat.username})' # but only one where you have an empty payload by now: A poll (buuuh) if update.poll: payload += f' with the poll id {update.poll.id}.' # lets put this in a "well" formatted text text = f"Hey.\n The error <code>{context.error}</code> happened{payload}. The full traceback:\n\n<code>{trace}" \ f"</code>" # and send it to the dev(s) for dev_id in devs: context.bot.send_message(dev_id, text, parse_mode=ParseMode.HTML) # we raise the error again, so the logger module catches it. If you don't use the logger module, use it. try: raise context.error except Unauthorized: # remove update.message.chat_id from conversation list LOGGER.exception('Update "%s" caused error "%s"', update, context.error) except BadRequest: # handle malformed requests - read more below! LOGGER.exception('Update "%s" caused error "%s"', update, context.error) except TimedOut: # handle slow connection problems LOGGER.exception('Update "%s" caused error "%s"', update, context.error) except NetworkError: # handle other connection problems LOGGER.exception('Update "%s" caused error "%s"', update, context.error) except ChatMigrated as e: # the chat_id of a group has changed, use e.new_chat_id instead LOGGER.exception('Update "%s" caused error "%s"', update, context.error) except TelegramError: # handle all other telegram related errors LOGGER.exception('Update "%s" caused error "%s"', update, context.error)
Example #25
Source File: utils.py From AmbroBot with GNU General Public License v3.0 | 4 votes |
def error_handler(bot, update, error): try: raise error except Unauthorized: logger.info("User unauthorized") except BadRequest as e: msg = getattr(error, 'message', None) if msg is None: raise if msg == 'Query_id_invalid': logger.info("We took too long to answer.") elif msg == 'Message is not modified': logger.info( "Tried to edit a message but text hasn't changed." " Probably a button in inline keyboard was pressed but it didn't change the message" ) return else: logger.info("Bad Request exception: %s", msg) except TimedOut: logger.info("Request timed out") bot.send_message( chat_id=update.effective_message.chat_id, text='The request timed out ⌛️' ) except TelegramError: logger.exception("A TelegramError occurred") finally: try: text = update.effective_message.text user = update.effective_user.name chat = update.effective_chat error_msg = (f"User: {user}\nText: {text}\n" f"Chat: {chat.id, chat.type, chat.username}\n" f"Error: {repr(error)} - {str(error)}") logger.info(f"Conflicting update: {error_msg}") except Exception: error_msg = f'Error found: {error}. Update: {update}' logger.error(error_msg, exc_info=True) send_message_to_admin(bot, error_msg)
Example #26
Source File: ezstickerbot.py From ez-sticker-bot with MIT License | 4 votes |
def image_received(update: Update, context: CallbackContext): message = update.message user_id = message.from_user.id # check spam filter cooldown_info = user_on_cooldown(user_id) if cooldown_info[0]: minutes = int(config['spam_interval'] / 60) message_text = get_message(user_id, 'spam_limit_reached').format(config['spam_max'], minutes, cooldown_info[1], cooldown_info[2]) message.reply_markdown(message_text) return # get file id if message.document: # check that document is image document = message.document if document.mime_type.lower() in ('image/png', 'image/jpeg', 'image/webp'): photo_id = document.file_id else: # feedback to show bot is processing bot.send_chat_action(user_id, 'typing') message.reply_markdown(get_message(user_id, 'doc_not_img')) return else: photo_id = message.photo[-1].file_id # feedback to show bot is processing bot.send_chat_action(user_id, 'upload_document') try: download_path = download_file(photo_id) image = Image.open(download_path) create_sticker_file(message, image, context) # delete local file os.remove(download_path) except TimedOut: message.reply_text(get_message(user_id, "send_timeout")) except FileNotFoundError: # if file does not exist ignore pass