python类TelegramError()的实例源码

inputfile.py 文件源码 项目:mobot 作者: JokerQyou 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def __init__(self, data):
        self.data = data
        self.boundary = choose_boundary()

        if 'audio' in data:
            self.input_name = 'audio'
            self.input_file = data.pop('audio')
        elif 'document' in data:
            self.input_name = 'document'
            self.input_file = data.pop('document')
        elif 'photo' in data:
            self.input_name = 'photo'
            self.input_file = data.pop('photo')
        elif 'sticker' in data:
            self.input_name = 'sticker'
            self.input_file = data.pop('sticker')
        elif 'video' in data:
            self.input_name = 'video'
            self.input_file = data.pop('video')
        elif 'voice' in data:
            self.input_name = 'voice'
            self.input_file = data.pop('voice')
        elif 'certificate' in data:
            self.input_name = 'certificate'
            self.input_file = data.pop('certificate')
        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:
                self.mimetype = mimetypes.guess_type(self.filename)[0] or DEFAULT_MIME_TYPE
updater.py 文件源码 项目:mobot 作者: JokerQyou 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _start_polling(self, poll_interval, timeout, read_latency, bootstrap_retries, clean,
                       allowed_updates):
        """
        Thread target of thread 'updater'. Runs in background, pulls
        updates from Telegram and inserts them in the update queue of the
        Dispatcher.

        """
        cur_interval = poll_interval
        self.logger.debug('Updater thread started')

        self._bootstrap(bootstrap_retries, clean=clean, webhook_url='', allowed_updates=None)

        while self.running:
            try:
                updates = self.bot.getUpdates(
                    self.last_update_id,
                    timeout=timeout,
                    read_latency=read_latency,
                    allowed_updates=allowed_updates)
            except RetryAfter as e:
                self.logger.info(str(e))
                cur_interval = 0.5 + e.retry_after
            except TelegramError as te:
                self.logger.error("Error while getting Updates: {0}".format(te))

                # Put the error into the update queue and let the Dispatcher
                # broadcast it
                self.update_queue.put(te)

                cur_interval = self._increase_poll_interval(cur_interval)
            else:
                if not self.running:
                    if len(updates) > 0:
                        self.logger.debug('Updates ignored and will be pulled '
                                          'again on restart.')
                    break

                if updates:
                    for update in updates:
                        self.update_queue.put(update)
                    self.last_update_id = updates[-1].update_id + 1

                cur_interval = poll_interval

            sleep(cur_interval)
utils.py 文件源码 项目:teamSpeakTelegram 作者: jossalgon 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def assign_user_alias_step2(bot, update, chat_data):
    message = update.effective_message
    chat_id = update.effective_chat.id
    markup = []

    first_message = bool(update.message)
    page = chat_data[message.message_id]['pages'] if not first_message else 1

    user_ids = get_user_ids()

    start = 10 * (page - 1) if page > 1 else 0
    end = start + 10 if start + 10 < len(user_ids) else len(user_ids)
    for i in range(start, end, 2):
        j = i + 1
        try:
            user1 = bot.get_chat_member(chat_id=user_ids[i], user_id=user_ids[i]).user
            username1 = '@' + user1.username if user1.username else user1.first_name
        except TelegramError:
            username1 = 'ID: ' + str(user_ids[i])
        row = [InlineKeyboardButton(username1, callback_data='USER_ALIAS_%s' % str(user_ids[i]))]
        if j < len(user_ids):
            try:
                user2 = bot.get_chat_member(chat_id=user_ids[j], user_id=user_ids[j]).user
                username2 = '@' + user2.username if user2.username else user2.first_name
            except TelegramError:
                username2 = 'ID: ' + str(user_ids[j])
            row.append(InlineKeyboardButton(username2, callback_data='USER_ALIAS_%s' % str(user_ids[j])))
        markup.append(row)

    markup = markup_append_pagination(bot, update, user_ids, markup, page, 'USER_ALIAS')
    markup.append([InlineKeyboardButton('?? ' + _('Skip'), callback_data='USER_ALIAS_%s' % str(0))])

    reply_markup = InlineKeyboardMarkup(markup)
    text = '?? ' + _('Ok, is this user on Telegram?')

    if not first_message:
        msg = bot.edit_message_text(text, chat_id=chat_id, message_id=message.message_id, reply_markup=reply_markup,
                                    parse_mode='Markdown')
    elif len(user_ids) == 0:
        msg = bot.send_message(chat_id, _('No results'))
    else:
        msg = bot.send_message(chat_id, text, disable_notification=True, reply_markup=reply_markup,
                               parse_mode='Markdown')
        chat_data[msg.message_id] = dict()
        chat_data[msg.message_id]['pages'] = page

    if message.reply_to_message:
        cldbid = chat_data['alias_cldbid'][str(message.reply_to_message.message_id)][1]
        del chat_data['alias_cldbid'][str(message.reply_to_message.message_id)]
        bot.delete_message(chat_id=chat_id, message_id=message.reply_to_message.message_id)
        chat_data['alias_cldbid'][str(msg.message_id)] = message.text, cldbid
news.py 文件源码 项目:UnivaqBot 作者: giacomocerquone 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def notify_news(bot, job):
    """Defining method that will be repeated over and over"""

    translation = {
        'disim': 'Disim',
        'univaq': 'Univaq',
        'discab_general': 'Discab',
        'discab_biotechnology': 'Biotecnologie',
        'discab_medical': 'Discab Medicina',
        'discab_motor_science': 'Scienze Motorie',
        'discab_psychology': 'Psicologia',
        'mesva_general': 'Mesva',
        'mesva_medical': 'Mesva Medicina',
        'mesva_environmental_science': 'Scienze Ambientali',
        'mesva_biological_science': 'Scienze Biologiche'
    }

    checked = check_news()
    unread_news = checked['unread_news']
    pulled_news = checked['pulled_news']
    invalid_chatid = []

    for section in unread_news:
        if unread_news[section]:
            news_to_string = "<b>"+translation[section]+"</b>\n\n"

            utils.NEWS = pulled_news
            utils.store_news(pulled_news)

            for item in unread_news[section]:
                news_to_string += ('- <a href="{link}">{title}</a>\n'
                                   '\t<i>{description}</i>\n\n').format(**item)

            for chat_id in utils.USERS[section]:
                try:
                    bot.sendMessage(chat_id, parse_mode='HTML', disable_web_page_preview=True,
                                    text=news_to_string)
                except TelegramError:
                    invalid_chatid.append(chat_id)

            for chat_id in invalid_chatid:
                utils.USERS[section].remove(chat_id)
                utils.unsubscribe_user(chat_id, section)
locks.py 文件源码 项目:tgbot 作者: PaulSonOfLars 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def lock(bot, update, args):
    chat = update.effective_chat
    message = update.effective_message
    if can_delete(chat, bot.id):
        if len(args) >= 1:
            if args[0] in LOCK_TYPES:
                sql.update_lock(chat.id, args[0], locked=True)
                message.reply_text("Locked {} messages for all non-admins!".format(args[0]))

            elif args[0] in RESTRICTION_TYPES:
                sql.update_restriction(chat.id, args[0], locked=True)
                message.reply_text("locked {}".format(args[0]))
                members = users_sql.get_chat_members(chat.id)
                if args[0] == "messages":
                    for mem in members:
                        try:
                            bot.restrict_chat_member(chat.id, mem.user,
                                                     can_send_messages=True)
                        except TelegramError:
                            pass
                elif args[0] == "media":
                    for mem in members:
                        try:
                            bot.restrict_chat_member(chat.id, mem.user,
                                                     can_send_messages=True,
                                                     can_send_media_messages=True)
                        except TelegramError:
                            pass
                elif args[0] == "other":
                    for mem in members:
                        try:
                            bot.restrict_chat_member(chat.id, mem.user,
                                                     can_send_messages=True,
                                                     can_send_media_messages=True,
                                                     can_send_other_messages=True)
                        except TelegramError:
                            pass
                elif args[0] == "previews":
                    for mem in members:
                        try:
                            bot.restrict_chat_member(chat.id, mem.user,
                                                     can_send_messages=True,
                                                     can_send_media_messages=True,
                                                     can_add_web_page_previews=True)
                        except TelegramError:
                            pass

    else:
        message.reply_text("I'm not an administrator, or haven't got delete rights.")
cli.py 文件源码 项目:HashDigestBot 作者: wagnerluis1982 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def config(token, db_url, op_name, values):
        operation, name = op_name

        try:
            digestbot = hdbot.HDBot(token, db_url)
            cfg = digestbot.get_config()
            logging.info("Using configuration at %s", db_url)
        except Exception as e:
            raise CLIError(e)

        with contextlib.closing(digestbot):
            if operation == '--add' and name == 'chat':
                # validation
                if len(values) < 2:
                    raise CLIError("Not enough arguments for --add chat")

                # get values
                name = values[0]
                email = values[1]
                # validations
                util.validate_username(name, exception=CLIError)
                util.validate_email_address(email, exception=CLIError)

                # get extra values if provided
                try:
                    extra = dict(v.split('=') for v in values[2:])
                except ValueError:
                    raise CLIError("Bad format in extra values for --add chat")

                # ensure the format @groupname
                name = '@'+name if name[0] != '@' else name

                # get chat_id
                try:
                    tgchat = digestbot.get_chat(name)
                except TelegramError:
                    raise CLIError("chat '%s' not found" % name)

                # add this chat to the config database
                try:
                    if cfg.has_chat(tgchat.id):
                        if confirm("Chat %s already in config, you are about to update it.\n"
                                   "Do you want to continue?" % name, default=True):
                            whatdone = 'updated'
                        else:
                            raise CLIError("Configuration aborted by user")
                    else:
                        whatdone = 'added'
                    cfg.add_chat(chat_id=tgchat.id, name=name[1:], sendto=email, **extra)
                    print("config: chat %s was %s" % (name, whatdone))
                except TypeError as e:
                    raise CLIError(e)
updater.py 文件源码 项目:deluge-telegramer 作者: noam09 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def _start_polling(self, poll_interval, timeout, read_latency, bootstrap_retries, clean,
                       allowed_updates):
        # """
        # Thread target of thread 'updater'. Runs in background, pulls
        # updates from Telegram and inserts them in the update queue of the
        # Dispatcher.
        # """

        cur_interval = poll_interval
        self.logger.debug('Updater thread started')

        self._bootstrap(bootstrap_retries, clean=clean, webhook_url='', allowed_updates=None)

        while self.running:
            try:
                updates = self.bot.get_updates(
                    self.last_update_id,
                    timeout=timeout,
                    read_latency=read_latency,
                    allowed_updates=allowed_updates)
            except RetryAfter as e:
                self.logger.info(str(e))
                cur_interval = 0.5 + e.retry_after
            except TelegramError as te:
                self.logger.error("Error while getting Updates: {0}".format(te))

                # Put the error into the update queue and let the Dispatcher
                # broadcast it
                self.update_queue.put(te)

                cur_interval = self._increase_poll_interval(cur_interval)
            else:
                if not self.running:
                    if len(updates) > 0:
                        self.logger.debug('Updates ignored and will be pulled '
                                          'again on restart.')
                    break

                if updates:
                    for update in updates:
                        self.update_queue.put(update)
                    self.last_update_id = updates[-1].update_id + 1

                cur_interval = poll_interval

            sleep(cur_interval)
dispatcher.py 文件源码 项目:deluge-telegramer 作者: noam09 项目源码 文件源码 阅读 41 收藏 0 点赞 0 评论 0
def process_update(self, update):
        """Processes a single update.

        Args:
            update (:obj:`str` | :class:`telegram.Update` | :class:`telegram.TelegramError`):
                The update to process.

        """
        # An error happened while polling
        if isinstance(update, TelegramError):
            try:
                self.dispatch_error(None, update)
            except Exception:
                self.logger.exception('An uncaught error was raised while handling the error')
            return

        for group in self.groups:
            try:
                for handler in (x for x in self.handlers[group] if x.check_update(update)):
                    handler.handle_update(update, self)
                    break

            # Stop processing with any other handler.
            except DispatcherHandlerStop:
                self.logger.debug('Stopping further handlers due to DispatcherHandlerStop')
                break

            # Dispatch any error.
            except TelegramError as te:
                self.logger.warning('A TelegramError was raised while processing the Update')

                try:
                    self.dispatch_error(update, te)
                except DispatcherHandlerStop:
                    self.logger.debug('Error handler stopped further handlers')
                    break
                except Exception:
                    self.logger.exception('An uncaught error was raised while handling the error')

            # Errors should not stop the thread.
            except Exception:
                self.logger.exception('An uncaught error was raised while processing the update')


问题


面经


文章

微信
公众号

扫码关注公众号