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


Python error.Unauthorized方法代码示例

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


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

示例1: donate

# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import Unauthorized [as 别名]
def donate(bot: Bot, update: Update):
    user = update.effective_message.from_user
    chat = update.effective_chat  # type: Optional[Chat]

    if chat.type == "private":
        update.effective_message.reply_text(DONATE_STRING, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)

        if OWNER_ID != 254318997 and DONATION_LINK:
            update.effective_message.reply_text("You can also donate to the person currently running me "
                                                "[here]({})".format(DONATION_LINK),
                                                parse_mode=ParseMode.MARKDOWN)

    else:
        try:
            bot.send_message(user.id, DONATE_STRING, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)

            update.effective_message.reply_text("I've PM'ed you about donating to my creator!")
        except Unauthorized:
            update.effective_message.reply_text("Contact me in PM first to get donation information.") 
开发者ID:skittles9823,项目名称:SkittBot,代码行数:21,代码来源:__main__.py

示例2: notify

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

示例3: donate

# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import Unauthorized [as 别名]
def donate(update, context):
    user = update.effective_message.from_user
    chat = update.effective_chat  # type: Optional[Chat]

    if chat.type == "private":
        update.effective_message.reply_text(tl(update.effective_message, DONATE_STRING), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)

        if OWNER_ID != 388576209 and DONATION_LINK:
            update.effective_message.reply_text(tl(update.effective_message, "Anda juga dapat menyumbang kepada orang yang saat ini menjalankan saya "
                                                "[disini]({})").format(DONATION_LINK),
                                                parse_mode=ParseMode.MARKDOWN)

    else:
        try:
            context.bot.send_message(user.id, tl(update.effective_message, DONATE_STRING), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)

            update.effective_message.reply_text(tl(update.effective_message, "Saya sudah PM Anda tentang donasi untuk pencipta saya!"))
        except Unauthorized:
            update.effective_message.reply_text(tl(update.effective_message, "Hubungi saya di PM dulu untuk mendapatkan informasi donasi."))




# Avoid memory dead 
开发者ID:AyraHikari,项目名称:EmiliaHikari,代码行数:26,代码来源:__main__.py

示例4: loggable

# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import Unauthorized [as 别名]
def loggable(func):
        @wraps(func)
        def log_action(update, context, *args, **kwargs):
            result = func(update, context, *args, **kwargs)
            chat = update.effective_chat  # type: Optional[Chat]
            message = update.effective_message  # type: Optional[Message]
            if result:
                if chat.type == chat.SUPERGROUP and chat.username:
                    result += "\n<b>Link:</b> " \
                              "<a href=\"http://telegram.me/{}/{}\">klik disini</a>".format(chat.username,
                                                                                           message.message_id)
                log_chat = sql.get_chat_log_channel(chat.id)
                if log_chat:
                    try:
                        send_log(context.bot, log_chat, chat.id, result)
                    except Unauthorized:
                        sql.stop_chat_logging(chat.id)
            elif result == "":
                pass
            else:
                LOGGER.warning("%s was set as loggable, but had no return statement.", func)

            return result

        return log_action 
开发者ID:AyraHikari,项目名称:EmiliaHikari,代码行数:27,代码来源:log_channel.py

示例5: distribute_tasks

# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import Unauthorized [as 别名]
def distribute_tasks(bot, session):
    """Distribute tasks under idle maintenance chats."""
    idle_maintenance_chats = (
        session.query(Chat)
        .filter(Chat.is_maintenance)
        .filter(Chat.current_task_id.is_(None))
        .all()
    )

    for chat in idle_maintenance_chats:
        try:
            tg_chat = call_tg_func(bot, "get_chat", args=[chat.id])
        except BadRequest as e:
            if e.message == "Chat not found":  # noqa
                session.delete(chat)
                continue

            raise e

        try:
            check_maintenance_chat(session, tg_chat, chat, job=True)
        except (Unauthorized, ChatMigrated):
            session.delete(chat)
            session.commit() 
开发者ID:Nukesor,项目名称:sticker-finder,代码行数:26,代码来源:maintenance.py

示例6: active_check

# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import Unauthorized [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

示例7: push_simple

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

示例8: run_job_queue

# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import Unauthorized [as 别名]
def run_job_queue(bot):
    try:
        redix = redis.Redis(host=REDIS_HOST, port=REDIS_PORT)
        while True:
            # get job from redis
            _, job = redix.brpop(TELEGRAM_WORKER_QUEUE)
            job = json.loads(job)
            message = "Hello this is your periodic star reminder and these are the lucky repos:\n"
            for repo in job["repos"]:
                message = "{}\n--\t[{}]({})".format(message, repo["name"], repo["url"])
            message = "{}".format(message)
            try:
                bot.send_message(int(job['to']), message, parse_mode="Markdown", disable_web_page_preview=True)
            except error.BadRequest as e:
                logger.error("{}, UserID: {}".format(e, job["to"]))
            except error.Unauthorized as e:
                logger.error("{}, UserID: {}".format(e, job["to"]))
            # report job done.
    except KeyboardInterrupt:
        raise KeyboardInterrupt 
开发者ID:alirizakeles,项目名称:ab-2018,代码行数:22,代码来源:bot.py

示例9: send_notifications_for_poll

# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import Unauthorized [as 别名]
def send_notifications_for_poll(context, session, poll, message_key):
    """Send the notifications for a single poll depending on the remaining time."""
    locale = poll.locale
    for notification in poll.notifications:
        try:
            # Get the chat and send the notification
            tg_chat = context.bot.get_chat(notification.chat_id)
            tg_chat.send_message(
                i18n.t(message_key, locale=locale, name=poll.name),
                parse_mode="markdown",
                reply_to_message_id=notification.poll_message_id,
            )

        except BadRequest as e:
            if e.message == "Chat not found":
                session.delete(notification)
        # Bot was removed from group
        except Unauthorized:
            session.delete(notification) 
开发者ID:Nukesor,项目名称:ultimate-poll-bot,代码行数:21,代码来源:job.py

示例10: error_callback

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

示例11: setlog

# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import Unauthorized [as 别名]
def setlog(bot: Bot, update: Update):
        message = update.effective_message  # type: Optional[Message]
        chat = update.effective_chat  # type: Optional[Chat]
        if chat.type == chat.CHANNEL:
            message.reply_text("Now, forward the /setlog to the group you want to tie this channel to!")

        elif message.forward_from_chat:
            sql.set_chat_log_channel(chat.id, message.forward_from_chat.id)
            try:
                message.delete()
            except BadRequest as excp:
                if excp.message == "Message to delete not found":
                    pass
                else:
                    LOGGER.exception("Error deleting message in log channel. Should work anyway though.")

            try:
                bot.send_message(message.forward_from_chat.id,
                                 "This channel has been set as the log channel for {}.".format(
                                     chat.title or chat.first_name))
            except Unauthorized as excp:
                if excp.message == "Forbidden: bot is not a member of the channel chat":
                    bot.send_message(chat.id, "Successfully set log channel!")
                else:
                    LOGGER.exception("ERROR in setting the log channel.")

            bot.send_message(chat.id, "Successfully set log channel!")

        else:
            message.reply_text("The steps to set a log channel are:\n"
                               " - add bot to the desired channel\n"
                               " - send /setlog to the channel\n"
                               " - forward the /setlog to the group\n") 
开发者ID:skittles9823,项目名称:SkittBot,代码行数:35,代码来源:log_channel.py

示例12: setlog

# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import Unauthorized [as 别名]
def setlog(update, context):
        message = update.effective_message  # type: Optional[Message]
        chat = update.effective_chat  # type: Optional[Chat]
        if chat.type == chat.CHANNEL:
            send_message(update.effective_message, tl(update.effective_message, "Sekarang, teruskan /setlog ke grup yang Anda ingin ikat saluran ini!"))

        elif message.forward_from_chat:
            sql.set_chat_log_channel(chat.id, message.forward_from_chat.id)
            try:
                message.delete()
            except BadRequest as excp:
                if excp.message == "Message to delete not found":
                    pass
                else:
                    LOGGER.exception("Error deleting message in log channel. Should work anyway though.")
                    
            try:
                context.bot.send_message(message.forward_from_chat.id,
                             tl(update.effective_message, "Saluran ini telah ditetapkan sebagai saluran log untuk {}.").format(
                                 chat.title or chat.first_name))
            except Unauthorized as excp:
                if excp.message == "Forbidden: bot is not a member of the channel chat":
                    context.bot.send_message(chat.id, tl(update.effective_message, "Gagal menyetel saluran log!\nSaya mungkin bukan admin di channel tersebut."))
                    sql.stop_chat_logging(chat.id)
                    return
                else:
                    LOGGER.exception("ERROR in setting the log channel.")
                    
            context.bot.send_message(chat.id, tl(update.effective_message, "Berhasil mengatur saluran log!"))

        else:
            send_message(update.effective_message, tl(update.effective_message, "Langkah-langkah untuk mengatur saluran log adalah:\n"
                               " - tambahkan bot ke saluran yang diinginkan\n"
                               " - Kirimkan /setlog ke saluran\n"
                               " - Teruskan /setlog ke grup\n")) 
开发者ID:AyraHikari,项目名称:EmiliaHikari,代码行数:37,代码来源:log_channel.py

示例13: _bootstrap

# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import Unauthorized [as 别名]
def _bootstrap(self, max_retries, clean, webhook_url, allowed_updates, cert=None):
        retries = 0
        while 1:

            try:
                if clean:
                    # Disable webhook for cleaning
                    self.bot.delete_webhook()
                    self._clean_updates()
                    sleep(1)

                self.bot.set_webhook(
                    url=webhook_url, certificate=cert, allowed_updates=allowed_updates)
            except (Unauthorized, InvalidToken):
                raise
            except TelegramError:
                msg = 'error in bootstrap phase; try={0} max_retries={1}'.format(retries,
                                                                                 max_retries)
                if max_retries < 0 or retries < max_retries:
                    self.logger.warning(msg)
                    retries += 1
                else:
                    self.logger.exception(msg)
                    raise
            else:
                break
            sleep(1) 
开发者ID:cbrgm,项目名称:telegram-robot-rss,代码行数:29,代码来源:updater.py

示例14: message_markdown

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

示例15: remove_old_references

# 需要导入模块: from telegram import error [as 别名]
# 或者: from telegram.error import Unauthorized [as 别名]
def remove_old_references(session, bot, poll, user):
    """Remove old references in private chats."""
    references = (
        session.query(Reference)
        .filter(Reference.poll == poll)
        .filter(Reference.user == user)
        .all()
    )

    for reference in references:
        try:
            bot.delete_message(
                chat_id=reference.user_id, message_id=reference.message_id
            )
        except Unauthorized:
            session.delete(reference)
        except BadRequest as e:
            if (
                e.message.startswith("Message_id_invalid")
                or e.message.startswith("Message can't be edited")
                or e.message.startswith("Message to edit not found")
                or e.message.startswith("Chat not found")
                or e.message.startswith("Can't access the chat")
            ):
                session.delete(reference)

        session.commit() 
开发者ID:Nukesor,项目名称:ultimate-poll-bot,代码行数:29,代码来源:poll.py


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