当前位置: 首页>>代码示例>>Python>>正文


Python telegram.error方法代码示例

本文整理汇总了Python中telegram.error方法的典型用法代码示例。如果您正苦于以下问题:Python telegram.error方法的具体用法?Python telegram.error怎么用?Python telegram.error使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在telegram的用法示例。


在下文中一共展示了telegram.error方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: error_handler

# 需要导入模块: import telegram [as 别名]
# 或者: from telegram import error [as 别名]
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) 
开发者ID:ekeih,项目名称:OmNomNom,代码行数:20,代码来源:frontend.py

示例2: get_tw_user

# 需要导入模块: import telegram [as 别名]
# 或者: from telegram import error [as 别名]
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 
开发者ID:franciscod,项目名称:telegram-twitter-forwarder-bot,代码行数:22,代码来源:bot.py

示例3: active_check

# 需要导入模块: import telegram [as 别名]
# 或者: from telegram import error [as 别名]
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 
开发者ID:charslab,项目名称:TranscriberBot,代码行数:22,代码来源:bot.py

示例4: signalHandler

# 需要导入模块: import telegram [as 别名]
# 或者: from telegram import error [as 别名]
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) 
开发者ID:scaidermern,项目名称:piCamBot,代码行数:17,代码来源:piCamBot.py

示例5: check_requirements

# 需要导入模块: import telegram [as 别名]
# 或者: from telegram import error [as 别名]
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 
开发者ID:MA3STR0,项目名称:kimsufi-crawler,代码行数:9,代码来源:telegram_notifier.py

示例6: notify

# 需要导入模块: import telegram [as 别名]
# 或者: from telegram import error [as 别名]
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) 
开发者ID:MA3STR0,项目名称:kimsufi-crawler,代码行数:8,代码来源:telegram_notifier.py

示例7: webhook

# 需要导入模块: import telegram [as 别名]
# 或者: from telegram import error [as 别名]
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({}) 
开发者ID:JungDev,项目名称:django-telegrambot,代码行数:37,代码来源:views.py

示例8: menu

# 需要导入模块: import telegram [as 别名]
# 或者: from telegram import error [as 别名]
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) 
开发者ID:ekeih,项目名称:OmNomNom,代码行数:47,代码来源:frontend.py

示例9: warn_user

# 需要导入模块: import telegram [as 别名]
# 或者: from telegram import error [as 别名]
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 "" 
开发者ID:AyraHikari,项目名称:EmiliaHikari,代码行数:49,代码来源:warns.py

示例10: reset_warns

# 需要导入模块: import telegram [as 别名]
# 或者: from telegram import error [as 别名]
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 "" 
开发者ID:AyraHikari,项目名称:EmiliaHikari,代码行数:49,代码来源:warns.py

示例11: catch_telegram_errors

# 需要导入模块: import telegram [as 别名]
# 或者: from telegram import error [as 别名]
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 
开发者ID:Steffo99,项目名称:greed,代码行数:46,代码来源:utils.py


注:本文中的telegram.error方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。