Python telegram.error() Examples

The following are 11 code examples of telegram.error(). 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 , or try the search function .
Example #1
Source File: frontend.py    From OmNomNom with GNU Affero General Public License v3.0 7 votes vote down vote up
def error_handler(_, update, error):
    """
    Handle errors in the dispatcher and decide which errors are just logged and which errors are important enough to
    trigger a message to the admin.
    """
    # noinspection PyBroadException
    try:
        raise error
    except telegram.error.BadRequest:
        frontend_logger.error(error)
        log_error.delay(str(error), 'frontend', 'badrequest')
    except telegram.error.TimedOut:
        frontend_logger.error(error)
        log_error.delay(str(error), 'frontend', 'timeout')
    except:
        error_message = '*Some Frontend Error*\n\n*Update*\n```\n%s\n```\n*Error*\n```\n%s\n```' % (update, error)
        send_message_to_admin.delay(error_message)
        frontend_logger.error(error) 
Example #2
Source File: bot.py    From telegram-twitter-forwarder-bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_tw_user(self, tw_username):
        try:
            tw_user = self.tw.get_user(tw_username)
        except tweepy.error.TweepError as err:
            self.logger.error(err)
            return None

        db_user, _created = TwitterUser.get_or_create(
            screen_name=tw_user.screen_name,
            defaults={
                'name': tw_user.name,
            },
        )

        if not _created:
            if db_user.name != tw_user.name:
                db_user.name = tw_user.name
                db_user.save()

        return db_user 
Example #3
Source File: bot.py    From TranscriberBot with GNU General Public License v3.0 6 votes vote down vote up
def active_check(self, fn, *args, **kwargs):
      err = None
      res = None

      try:
        res = fn(*args, **kwargs)
      except Unauthorized as e:
        pprint.pprint(e)
        logger.error(e)
        err = e

      if err is not None:
        chat_id = kwargs['chat_id']
        if chat_id not in self.active_chats_cache or self.active_chats_cache[chat_id] == 1:
          logger.debug("Marking chat {} as inactive".format(chat_id))
          self.active_chats_cache[chat_id] = 0
          TBDB.set_chat_active(chat_id, self.active_chats_cache[chat_id])
        raise err

      return res 
Example #4
Source File: piCamBot.py    From piCamBot with GNU General Public License v3.0 5 votes vote down vote up
def signalHandler(self, signal, frame):
        # always disable buzzer
        if self.config['buzzer']['enable']:
            gpio = self.config['buzzer']['gpio']
            self.GPIO.output(gpio, 0)
            self.GPIO.cleanup()

        msg = 'Caught signal %d, terminating now.' % signal
        self.logger.error(msg)
        for owner_id in self.config['telegram']['owner_ids']:
            try:
                self.bot.sendMessage(chat_id=owner_id, text=msg)
            except Exception as e:
                pass
        sys.exit(1) 
Example #5
Source File: telegram_notifier.py    From kimsufi-crawler with MIT License 5 votes vote down vote up
def check_requirements(self):
        try:
            self.bot.get_me()
            self.bot.send_message(chat_id=self.chat_id, text="Kimsufi Crawler started")
        except TelegramError as te:
            _logger.error("Telegram validation failed: {error}".format(error=te.message))
            raise 
Example #6
Source File: telegram_notifier.py    From kimsufi-crawler with MIT License 5 votes vote down vote up
def notify(self, title, text, url=None):
        try:
            self.bot.send_message(chat_id=self.chat_id, text=text)
        except TelegramError as te:
            _logger.error("Something went wrong sending the message to Telegram:")
            _logger.error(te) 
Example #7
Source File: views.py    From django-telegrambot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def webhook (request, bot_token):

    #verifico la validità del token
    bot = DjangoTelegramBot.getBot(bot_id=bot_token, safe=False)
    if bot is None:
        logger.warn('Request for not found token : {}'.format(bot_token))
        return JsonResponse({})

    try:
        data = json.loads(request.body.decode("utf-8"))

    except:
        logger.warn('Telegram bot <{}> receive invalid request : {}'.format(bot.username, repr(request)))
        return JsonResponse({})

    dispatcher = DjangoTelegramBot.getDispatcher(bot_token, safe=False)
    if dispatcher is None:
        logger.error('Dispatcher for bot <{}> not found : {}'.format(bot.username, bot_token))
        return JsonResponse({})

    try:
        update = telegram.Update.de_json(data, bot)
        dispatcher.process_update(update)
        logger.debug('Bot <{}> : Processed update {}'.format(bot.username, update))
    # Dispatch any errors
    except TelegramError as te:
        logger.warn("Bot <{}> : Error was raised while processing Update.".format(bot.username))
        dispatcher.dispatchError(update, te)

    # All other errors should not stop the thread, just print them
    except:
        logger.error("Bot <{}> : An uncaught error was raised while processing an update\n{}".format(bot.username, sys.exc_info()[0]))

    finally:
        return JsonResponse({}) 
Example #8
Source File: frontend.py    From OmNomNom with GNU Affero General Public License v3.0 4 votes vote down vote up
def menu(bot, update):
    """
    Process the message and reply with the menu or error messages.

    Todo:
        Reduce complexity!
    """
    frontend_logger.debug('menu called')
    if update.message.text:
        message = update.message.text.lower().replace('@%s' % bot.username.lower(), '')
        requested_canteen, requested_date = get_canteen_and_date(message)
        frontend_logger.info('Requested Canteen: %s (%s)' % (requested_canteen, requested_date))
        if requested_date:
            reply = cache.hget(requested_date, requested_canteen)
            if not reply or reply.strip() == '':
                possible_canteens = []
                for canteen, canteen_menu in cache.hscan_iter(requested_date, '*%s*' % requested_canteen):
                    possible_canteens.append((canteen, canteen_menu))
                if len(possible_canteens) == 1:
                    reply = possible_canteens.pop()[1]
                    update.message.reply_text(text=reply, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
                    message_logger.debug('Out: %s' % reply)
                elif len(possible_canteens) > 1:
                    reply = 'Meintest du vielleicht:\n'
                    for canteen in possible_canteens:
                        reply += '\n /%s' % canteen[0]
                    update.message.reply_text(text=reply)
                    message_logger.debug('Out: %s' % reply)
                else:
                    error_message = "\n*Chat*\n```\n%s\n```\n*Message*\n```\n%s\n```\n*User*\n```\n%s\n```" % \
                                    (update.effective_chat, update.effective_message, update.effective_user)
                    send_message_to_admin.delay(error_message)
                    reply = 'Leider kenne ich keinen passenden Speiseplan. ' \
                            'Wenn das ein Fehler ist, wende dich an @ekeih.'
                    update.message.reply_text(text=reply, parse_mode=ParseMode.MARKDOWN)
                    message_logger.debug('Out: %s' % reply)
            else:
                update.message.reply_text(text=reply, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
                message_logger.debug('Out: %s' % reply)
        else:
            reply = 'Sorry, leider habe ich das Datum nicht verstanden. Probier es doch einmal mit `/%s morgen`, ' \
                    '`/%s dienstag`, `/%s yesterday` oder `/%s next friday`.' % (requested_canteen, requested_canteen,
                                                                                 requested_canteen, requested_canteen)
            update.message.reply_text(text=reply, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
            message_logger.debug('Out: %s' % reply) 
Example #9
Source File: warns.py    From EmiliaHikari with GNU General Public License v3.0 4 votes vote down vote up
def warn_user(update, context):
    message = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    warner = update.effective_user  # type: Optional[User]
    user = update.effective_user
    args = context.args

    user_id, reason = extract_user_and_text(message, args)
    if user_id == "error":
        send_message(update.effective_message, tl(update.effective_message, reason))
        return ""

    conn = connected(context.bot, update, chat, user.id, need_admin=True)
    if conn:
        chat = dispatcher.bot.getChat(conn)
        chat_id = conn
        chat_name = dispatcher.bot.getChat(conn).title
    else:
        if update.effective_message.chat.type == "private":
            send_message(update.effective_message, tl(update.effective_message, "Anda bisa lakukan command ini pada grup, bukan pada PM"))
            return ""
        chat = update.effective_chat
        chat_id = update.effective_chat.id
        chat_name = update.effective_message.chat.title

    check = context.bot.getChatMember(chat_id, context.bot.id)
    if check.status == 'member' or check['can_restrict_members'] == False:
        if conn:
            text = tl(update.effective_message, "Saya tidak bisa membatasi orang di {}! Pastikan saya sudah menjadi admin.").format(chat_name)
        else:
            text = tl(update.effective_message, "Saya tidak bisa membatasi orang di sini! Pastikan saya sudah menjadi admin.")
        send_message(update.effective_message, text, parse_mode="markdown")
        return ""

    if user_id:
        if conn:
            warning = warn(chat.get_member(user_id).user, chat, reason, message, warner, conn=True)
            send_message(update.effective_message, tl(update.effective_message, "Saya sudah memperingatinya pada grup *{}*").format(chat_name), parse_mode="markdown")
            return warning
        else:
            if message.reply_to_message and message.reply_to_message.from_user.id == user_id:
                return warn(message.reply_to_message.from_user, chat, reason, message.reply_to_message, warner)
            else:
                return warn(chat.get_member(user_id).user, chat, reason, message, warner)
    else:
        send_message(update.effective_message, tl(update.effective_message, "Tidak ada pengguna yang ditunjuk!"))
    return "" 
Example #10
Source File: warns.py    From EmiliaHikari with GNU General Public License v3.0 4 votes vote down vote up
def reset_warns(update, context):
    message = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    args = context.args

    user_id = extract_user(message, args)

    conn = connected(context.bot, update, chat, user.id, need_admin=True)
    if conn:
        chat = dispatcher.bot.getChat(conn)
        chat_id = conn
        chat_name = dispatcher.bot.getChat(conn).title
    else:
        if update.effective_message.chat.type == "private":
            send_message(update.effective_message, tl(update.effective_message, "Anda bisa lakukan command ini pada grup, bukan pada PM"))
            return ""
        chat = update.effective_chat
        chat_id = update.effective_chat.id
        chat_name = update.effective_message.chat.title

    check = context.bot.getChatMember(chat_id, context.bot.id)
    if check.status == 'member' or check['can_restrict_members'] == False:
        if conn:
            text = tl(update.effective_message, "Saya tidak bisa membatasi orang di {}! Pastikan saya sudah menjadi admin.").format(chat_name)
        else:
            text = tl(update.effective_message, "Saya tidak bisa membatasi orang di sini! Pastikan saya sudah menjadi admin.")
        send_message(update.effective_message, text, parse_mode="markdown")
        return ""
    
    if user_id and user_id != "error":
        sql.reset_warns(user_id, chat.id)
        if conn:
            send_message(update.effective_message, tl(update.effective_message, "Peringatan telah disetel ulang pada *{}*!").format(chat_name), parse_mode="markdown")
        else:
            send_message(update.effective_message, tl(update.effective_message, "Peringatan telah disetel ulang!"))
        warned = chat.get_member(user_id).user
        return "<b>{}:</b>" \
               "\n#RESETWARNS" \
               "\n<b>Admin:</b> {}" \
               "\n<b>User:</b> {} (<code>{}</code>)".format(html.escape(chat.title),
                                                            mention_html(user.id, user.first_name),
                                                            mention_html(warned.id, warned.first_name),
                                                            warned.id)
    else:
        send_message(update.effective_message, tl(update.effective_message, "Tidak ada pengguna yang ditunjuk!"))
    return "" 
Example #11
Source File: utils.py    From greed with GNU Affero General Public License v3.0 4 votes vote down vote up
def catch_telegram_errors(func):
    """Decorator, can be applied to any function to retry in case of Telegram errors."""

    def result_func(*args, **kwargs):
        while True:
            try:
                return func(*args, **kwargs)
            # Bot was blocked by the user
            except telegram.error.Unauthorized:
                log.debug(f"Unauthorized to call {func.__name__}(), skipping.")
                break
            # Telegram API didn't answer in time
            except telegram.error.TimedOut:
                log.warning(f"Timed out while calling {func.__name__}(),"
                            f" retrying in {config['Telegram']['timed_out_pause']} secs...")
                time.sleep(int(config["Telegram"]["timed_out_pause"]))
            # Telegram is not reachable
            except telegram.error.NetworkError as error:
                log.error(f"Network error while calling {func.__name__}(),"
                          f" retrying in {config['Telegram']['error_pause']} secs...\n"
                          f"Full error: {error.message}")
                time.sleep(int(config["Telegram"]["error_pause"]))
            # Unknown error
            except telegram.error.TelegramError as error:
                if error.message.lower() in ["bad gateway", "invalid server response"]:
                    log.warning(f"Bad Gateway while calling {func.__name__}(),"
                                f" retrying in {config['Telegram']['error_pause']} secs...")
                    time.sleep(int(config["Telegram"]["error_pause"]))
                elif error.message.lower() == "timed out":
                    log.warning(f"Timed out while calling {func.__name__}(),"
                                f" retrying in {config['Telegram']['timed_out_pause']} secs...")
                    time.sleep(int(config["Telegram"]["timed_out_pause"]))
                else:
                    log.error(f"Telegram error while calling {func.__name__}(),"
                              f" retrying in {config['Telegram']['error_pause']} secs...\n"
                              f"Full error: {error.message}")
                    # Send the error to the Sentry server
                    if sentry_client is not None:
                        sentry_client.captureException(exc_info=sys.exc_info())
                    else:
                        traceback.print_exception(*sys.exc_info())
                    time.sleep(int(config["Telegram"]["error_pause"]))

    return result_func