當前位置: 首頁>>代碼示例>>Python>>正文


Python telegram.TelegramError方法代碼示例

本文整理匯總了Python中telegram.TelegramError方法的典型用法代碼示例。如果您正苦於以下問題:Python telegram.TelegramError方法的具體用法?Python telegram.TelegramError怎麽用?Python telegram.TelegramError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在telegram的用法示例。


在下文中一共展示了telegram.TelegramError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: botupdated_message

# 需要導入模塊: import telegram [as 別名]
# 或者: from telegram import TelegramError [as 別名]
def botupdated_message(bot, job):
    """
    Defining a command to notify the user and tell them what updates have been released
    It is called at every execution ONLY if there are documents in a specific db collection
    """

    messages = list(DATABASE.messages.find())
    DATABASE.messages.remove()

    invalid_chatid = []

    for message in messages:
        for chat_id in USERS['telegramID']:
            try:
                bot.sendMessage(chat_id, parse_mode='HTML',
                                text=message['text'])
            except TelegramError:
                invalid_chatid.append(chat_id)

    for chat_id in invalid_chatid:
        USERS['telegramID'].remove(chat_id)
        unsubscribe_user(chat_id, 'telegramID') 
開發者ID:giacomocerquone,項目名稱:UnivaqBot,代碼行數:24,代碼來源:utils.py

示例2: error

# 需要導入模塊: import telegram [as 別名]
# 或者: from telegram import TelegramError [as 別名]
def error(update, context, **kwargs):
    """ Error handling """
    error = context.error

    try:
        if isinstance(error, TelegramError) and (
            error.message == "Unauthorized"
            or error.message == "Have no rights to send a message"
            or "PEER_ID_INVALID" in error.message
        ):
            chats = db.get("chats")
            chats.remove(update.message.chat_id)
            db.set("chats", chats)
            logger.info("Removed chat_id %s from chat list" % update.message.chat_id)
        else:
            logger.error("An error (%s) occurred: %s" % (type(error), error.message))
    except:
        pass 
開發者ID:jh0ker,項目名稱:welcomebot,代碼行數:20,代碼來源:bot.py

示例3: _check_ssl_cert

# 需要導入模塊: import telegram [as 別名]
# 或者: from telegram import TelegramError [as 別名]
def _check_ssl_cert(self, cert, key):
        # Check SSL-Certificate with openssl, if possible
        try:
            exit_code = subprocess.call(
                ["openssl", "x509", "-text", "-noout", "-in", cert],
                stdout=open(os.devnull, 'wb'),
                stderr=subprocess.STDOUT)
        except OSError:
            exit_code = 0
        if exit_code is 0:
            try:
                self.httpd.socket = ssl.wrap_socket(
                    self.httpd.socket, certfile=cert, keyfile=key, server_side=True)
            except ssl.SSLError as error:
                self.logger.exception('Failed to init SSL socket')
                raise TelegramError(str(error))
        else:
            raise TelegramError('SSL Certificate invalid') 
開發者ID:cbrgm,項目名稱:telegram-robot-rss,代碼行數:20,代碼來源:updater.py

示例4: respondToMessageQuery

# 需要導入模塊: import telegram [as 別名]
# 或者: from telegram import TelegramError [as 別名]
def respondToMessageQuery(self, message):
        senderId = message.from_user.id
        chatId = message.chat.id
        messageId = message.message_id
        expression = message.text
        
        errorMessage = None
        try:
            imageStream, pdfStream = self._latexConverter.convertExpressionToPng(expression, senderId, str(messageId)+str(senderId), returnPdf=True)
            self._bot.sendDocument(chatId, pdfStream, filename="expression.pdf")
            self._bot.sendPhoto(chatId, imageStream)
        except ValueError as err:
            errorMessage = self.getWrongSyntaxResult(expression, err.args[0])
        except TelegramError as err:
            errorMessage = self._resourceManager.getString("telegram_error")+str(err)
            self.logger.warn(errorMessage)
        finally:
            if not errorMessage is None:
                self._bot.sendMessage(chatId, errorMessage)
            self.logger.debug("Answered to message from %d, chatId %d, expression: %s", 
                                                        senderId, chatId, expression) 
開發者ID:vdrhtc,項目名稱:InLaTeXbot,代碼行數:23,代碼來源:MessageQueryResponseDispatcher.py

示例5: broadcast

# 需要導入模塊: import telegram [as 別名]
# 或者: from telegram import TelegramError [as 別名]
def broadcast(bot: Bot, update: Update):
    to_send = update.effective_message.text.split(None, 1)
    if len(to_send) >= 2:
        chats = sql.get_all_chats() or []
        failed = 0
        for chat in chats:
            try:
                bot.sendMessage(int(chat.chat_id), to_send[1])
                sleep(0.1)
            except TelegramError:
                failed += 1
                LOGGER.warning("Couldn't send broadcast to %s, group name %s", str(chat.chat_id), str(chat.chat_name))

        update.effective_message.reply_text("Broadcast complete. {} groups failed to receive the message, probably "
                                            "due to being kicked.".format(failed)) 
開發者ID:skittles9823,項目名稱:SkittBot,代碼行數:17,代碼來源:users.py

示例6: makepack_internal

# 需要導入模塊: import telegram [as 別名]
# 或者: from telegram import TelegramError [as 別名]
def makepack_internal(msg, user, png_sticker, emoji, bot, packname, packnum):
    name = user.first_name
    name = name[:50]
    try:
        extra_version = ""
        if packnum > 0:
            extra_version = " " + str(packnum)
        success = bot.create_new_sticker_set(user.id, packname, f"{name}s kang pack" + extra_version,
                                             png_sticker=png_sticker,
                                             emojis=emoji)
    except TelegramError as e:
        print(e)
        if e.message == "Sticker set name is already occupied":
            msg.reply_text("Your pack can be found [here](t.me/addstickers/%s)" % packname,
                           parse_mode=ParseMode.MARKDOWN)
        elif e.message == "Peer_id_invalid":
            msg.reply_text("Contact me in PM first.", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(
                text="Start", url=f"t.me/{bot.username}")]]))
        elif e.message == "Internal Server Error: created sticker set not found (500)":
                msg.reply_text("Sticker pack successfully created. Get it [here](t.me/addstickers/%s)" % packname,
                       parse_mode=ParseMode.MARKDOWN)
        return

    if success:
        msg.reply_text("Sticker pack successfully created. Get it [here](t.me/addstickers/%s)" % packname,
                       parse_mode=ParseMode.MARKDOWN)
    else:
        msg.reply_text("Failed to create sticker pack. Possibly due to blek mejik.") 
開發者ID:skittles9823,項目名稱:SkittBot,代碼行數:30,代碼來源:stickers.py

示例7: restr_members

# 需要導入模塊: import telegram [as 別名]
# 或者: from telegram import TelegramError [as 別名]
def restr_members(bot, chat_id, members, messages=False, media=False, other=False, previews=False):
    for mem in members:
        if mem.user in SUDO_USERS:
            pass
        try:
            bot.restrict_chat_member(chat_id, mem.user,
                                     can_send_messages=messages,
                                     can_send_media_messages=media,
                                     can_send_other_messages=other,
                                     can_add_web_page_previews=previews)
        except TelegramError:
            pass


# NOT ASYNC 
開發者ID:skittles9823,項目名稱:SkittBot,代碼行數:17,代碼來源:locks.py

示例8: unrestr_members

# 需要導入模塊: import telegram [as 別名]
# 或者: from telegram import TelegramError [as 別名]
def unrestr_members(bot, chat_id, members, messages=True, media=True, other=True, previews=True):
    for mem in members:
        try:
            bot.restrict_chat_member(chat_id, mem.user,
                                     can_send_messages=messages,
                                     can_send_media_messages=media,
                                     can_send_other_messages=other,
                                     can_add_web_page_previews=previews)
        except TelegramError:
            pass 
開發者ID:skittles9823,項目名稱:SkittBot,代碼行數:12,代碼來源:locks.py

示例9: snipe

# 需要導入模塊: import telegram [as 別名]
# 或者: from telegram import TelegramError [as 別名]
def snipe(bot: Bot, update: Update, args: List[str]):
    try:
        chat_id = str(args[0])
        del args[0]
    except TypeError as excp:
        update.effective_message.reply_text("Please give me a chat to echo to!")
    to_send = " ".join(args)
    if len(to_send) >= 2:
        try:
            bot.sendMessage(int(chat_id), str(to_send))
        except TelegramError:
            LOGGER.warning("Couldn't send to group %s", str(chat_id))
            update.effective_message.reply_text("Couldn't send the message. Perhaps I'm not part of that group?") 
開發者ID:skittles9823,項目名稱:SkittBot,代碼行數:15,代碼來源:special.py

示例10: restricted

# 需要導入模塊: import telegram [as 別名]
# 或者: from telegram import TelegramError [as 別名]
def restricted(func=None, strict=False, silent=False):
    if func is None:
        # If called without method, we've been called with optional arguments.
        # We return a decorator with the optional arguments filled in.
        return partial(restricted, strict=strict, silent=silent)

    @wraps(func)
    def wrapped(bot, update, *args, **kwargs):
        chat_id = update.effective_user.id

        if chat_id not in settings.MODERATORS:
            try:
                print("Unauthorized access denied for {}.".format(chat_id))
                if not silent:
                    bot.sendPhoto(chat_id, open(appglobals.ROOT_DIR + '/assets/img/go_away_noob.png', 'rb'),
                                  caption="Moderator Area. Unauthorized.")
                return
            except (TelegramError, AttributeError):
                return

        if strict and chat_id not in settings.ADMINS:
            if not silent:
                bot.sendMessage(chat_id, "This function is restricted to the channel creator.")
            return

        return func(bot, update, *args, **kwargs)

    return wrapped 
開發者ID:JosXa,項目名稱:BotListBot,代碼行數:30,代碼來源:util.py

示例11: broadcast

# 需要導入模塊: import telegram [as 別名]
# 或者: from telegram import TelegramError [as 別名]
def broadcast(update, context):
    to_send = update.effective_message.text.split(None, 1)
    if len(to_send) >= 2:
        chats = sql.get_all_chats() or []
        failed = 0
        for chat in chats:
            try:
                context.bot.sendMessage(int(chat.chat_id), to_send[1])
                sleep(0.1)
            except TelegramError:
                failed += 1
                LOGGER.warning("Couldn't send broadcast to %s, group name %s", str(chat.chat_id), str(chat.chat_name))

        send_message(update.effective_message, "Siaran selesai. {} grup gagal menerima pesan, mungkin "
                                            "karena ditendang.".format(failed)) 
開發者ID:AyraHikari,項目名稱:EmiliaHikari,代碼行數:17,代碼來源:users.py

示例12: restr_members

# 需要導入模塊: import telegram [as 別名]
# 或者: from telegram import TelegramError [as 別名]
def restr_members(bot, chat_id, members, messages=False, media=False, other=False, previews=False):
	for mem in members:
		if mem.user in SUDO_USERS:
			pass
		try:
			bot.restrict_chat_member(chat_id, mem.user,
									 can_send_messages=messages,
									 can_send_media_messages=media,
									 can_send_other_messages=other,
									 can_add_web_page_previews=previews)
		except TelegramError:
			pass


# NOT ASYNC 
開發者ID:AyraHikari,項目名稱:EmiliaHikari,代碼行數:17,代碼來源:locks.py

示例13: unrestr_members

# 需要導入模塊: import telegram [as 別名]
# 或者: from telegram import TelegramError [as 別名]
def unrestr_members(bot, chat_id, members, messages=True, media=True, other=True, previews=True):
	for mem in members:
		try:
			bot.restrict_chat_member(chat_id, mem.user,
									 can_send_messages=messages,
									 can_send_media_messages=media,
									 can_send_other_messages=other,
									 can_add_web_page_previews=previews)
		except TelegramError:
			pass 
開發者ID:AyraHikari,項目名稱:EmiliaHikari,代碼行數:12,代碼來源:locks.py

示例14: __init__

# 需要導入模塊: import telegram [as 別名]
# 或者: from telegram import TelegramError [as 別名]
def __init__(self, data):
        self.data = data
        self.boundary = choose_boundary()

        for t in FILE_TYPES:
            if t in data:
                self.input_name = t
                self.input_file = data.pop(t)
                break
        else:
            raise TelegramError('Unknown inputfile type')

        if hasattr(self.input_file, 'read'):
            self.filename = None
            self.input_file_content = self.input_file.read()
            if 'filename' in data:
                self.filename = self.data.pop('filename')
            elif hasattr(self.input_file, 'name'):
                # on py2.7, pylint fails to understand this properly
                # pylint: disable=E1101
                self.filename = os.path.basename(self.input_file.name)

            try:
                self.mimetype = self.is_image(self.input_file_content)
                if not self.filename or '.' not in self.filename:
                    self.filename = self.mimetype.replace('/', '.')
            except TelegramError:
                if self.filename:
                    self.mimetype = mimetypes.guess_type(
                        self.filename)[0] or DEFAULT_MIME_TYPE
                else:
                    self.mimetype = DEFAULT_MIME_TYPE 
開發者ID:cbrgm,項目名稱:telegram-robot-rss,代碼行數:34,代碼來源:inputfile.py

示例15: is_image

# 需要導入模塊: import telegram [as 別名]
# 或者: from telegram import TelegramError [as 別名]
def is_image(stream):
        """Check if the content file is an image by analyzing its headers.

        Args:
            stream (:obj:`str`): A str representing the content of a file.

        Returns:
            :obj:`str`: The str mime-type of an image.

        """
        image = imghdr.what(None, stream)
        if image:
            return 'image/%s' % image

        raise TelegramError('Could not parse file content') 
開發者ID:cbrgm,項目名稱:telegram-robot-rss,代碼行數:17,代碼來源:inputfile.py


注:本文中的telegram.TelegramError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。