当前位置: 首页>>代码示例>>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;未经允许,请勿转载。