Python telegram.error.NetworkError() Examples
The following are 13
code examples of telegram.error.NetworkError().
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: 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 #2
Source File: bismillah.py From BismillahBot with GNU Affero General Public License v3.0 | 6 votes |
def main(): global update_id bot = telegram.Bot(token=TOKEN) try: update_id = bot.get_updates()[0].update_id except IndexError: update_id = None interface = telegram.ReplyKeyboardMarkup( [["Arabic", "Audio", "English", "Tafsir"], ["Previous", "Random", "Next"]], resize_keyboard=True) data = { "english": Quran("translation"), "tafsir": Quran("tafsir"), "index": make_index(), "interface": interface } data["default_query_results"] = get_default_query_results(data["english"]) while True: try: serve(bot, data) except NetworkError: sleep(1) except Unauthorized: # user has removed or blocked the bot update_id += 1 except TelegramError as e: if "Invalid server response" in str(e): sleep(3) else: raise e
Example #3
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 #4
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 #5
Source File: piCamBot.py From piCamBot with GNU General Public License v3.0 | 5 votes |
def fetchTelegramUpdates(self): self.logger.info('Setting up telegram thread') while True: try: # request updates after the last update_id # timeout: how long to poll for messages for update in self.bot.getUpdates(offset=self.update_id, timeout=10): # skip updates without a message if not update.message: continue # chat_id is required to reply to any message chat_id = update.message.chat_id self.update_id = update.update_id + 1 message = update.message # skip messages from non-owner if message.from_user.id not in self.config['telegram']['owner_ids']: self.logger.warn('Received message from unknown user "%s": "%s"' % (message.from_user, message.text)) message.reply_text("I'm sorry, Dave. I'm afraid I can't do that.") continue self.logger.info('Received message from user "%s": "%s"' % (message.from_user, message.text)) self.performCommand(message) except NetworkError as e: time.sleep(1) except Exception as e: self.logger.warn(str(e)) self.logger.warn(traceback.format_exc()) time.sleep(1)
Example #6
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 #7
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 #8
Source File: echobot.py From bale-bot-samples with Apache License 2.0 | 5 votes |
def main(): """Run the bot.""" global update_id # Telegram Bot Authorization Token bot = telegram.Bot(token='TOKEN', base_url="https://tapi.bale.ai/") # get the first pending update_id, this is so we can skip over it in case # we get an "Unauthorized" exception. try: bot.delete_webhook() update_id = bot.get_updates()[0].update_id except IndexError: update_id = None # Enable logging logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG) while True: try: echo(bot) sleep(2) except NetworkError: sleep(1) except Unauthorized: # The user has removed or blocked the bot. update_id += 1
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: __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 #11
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 #12
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 #13
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)