How to use the telethon.tl.types function in Telethon

To help you get started, we’ve selected a few Telethon examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github expectocode / telegram-export / telegram_export / tests.py View on Github external
def test_dump_methods(self):
        """Test dumper.dump_* works"""
        dumper = Dumper(self.dumper_config)
        message = types.Message(
            id=777,
            to_id=types.PeerUser(123),
            date=datetime.now(),
            message='Hello',
            out=True,
            via_bot_id=1000,
            fwd_from=types.MessageFwdHeader(
                date=datetime.now() - timedelta(days=1),
                from_id=321
            )
        )
        fwd_id = dumper.dump_forward(message.fwd_from)
        dumper.dump_message(message, 123, forward_id=fwd_id, media_id=None)

        message = types.Message(
            id=778,
github LonamiWebs / Telethon / telethon / utils.py View on Github external
if isinstance(media, types.MessageMediaVenue):
        return types.InputMediaVenue(
            geo_point=get_input_geo(media.geo),
            title=media.title,
            address=media.address,
            provider=media.provider,
            venue_id=media.venue_id,
            venue_type=''
        )

    if isinstance(media, (
            types.MessageMediaEmpty, types.MessageMediaUnsupported,
            types.ChatPhotoEmpty, types.UserProfilePhotoEmpty,
            types.ChatPhoto, types.UserProfilePhoto,
            types.FileLocationToBeDeprecated)):
        return types.InputMediaEmpty()

    if isinstance(media, types.Message):
        return get_input_media(media.media, is_photo=is_photo)

    _raise_cast_fail(media, 'InputMedia')
github LonamiWebs / Telethon / telethon / tl / custom / button.py View on Github external
def _is_inline(button):
        """
        Returns `True` if the button belongs to an inline keyboard.
        """
        return isinstance(button, (
            types.KeyboardButtonCallback,
            types.KeyboardButtonSwitchInline,
            types.KeyboardButtonUrl,
            types.InputKeyboardButtonUrlAuth
        ))
github expectocode / telegram-export / telegram_export / dumper.py View on Github external
row['name'] = attr.file_name

        elif isinstance(media, types.MessageMediaEmpty):
            row['type'] = 'empty'
            return

        elif isinstance(media, types.MessageMediaGame):
            row['type'] = 'game'
            game = media.game
            if isinstance(game, types.Game):
                row['name'] = game.short_name
                row['thumbnail_id'] = self.dump_media(game.photo)
                row['local_id'] = game.id
                row['secret'] = game.access_hash

        elif isinstance(media, types.MessageMediaGeo):
            row['type'] = 'geo'
            geo = media.geo
            if isinstance(geo, types.GeoPoint):
                row['name'] = '({}, {})'.format(repr(geo.lat), repr(geo.long))

        elif isinstance(media, types.MessageMediaGeoLive):
            row['type'] = 'geolive'
            geo = media.geo
            if isinstance(geo, types.GeoPoint):
                row['name'] = '({}, {})'.format(repr(geo.lat), repr(geo.long))

        elif isinstance(media, types.MessageMediaInvoice):
            row['type'] = 'invoice'
            row['name'] = media.title
            row['thumbnail_id'] = self.dump_media(media.photo)
github MaskRay / telegramircd / telegramircd.py View on Github external
webpage = msg.media.webpage
                if isinstance(webpage, tl.types.WebPage):
                    text = '[{}] {} {}'.format(typ, webpage.url.replace('\n', '\\n'), webpage.title)
                elif isinstance(webpage, tl.types.WebPagePending):
                    text = '[WebPagePending] {}'.format(webpage.id)
                    web.webpage_id2sender_to[webpage.id] = (sender, to)
            else:
                typ = 'unknown'
            if typ in ('document', 'photo'):
                media_id = str(len(web.id2media))
                text = '[{}] {}/document/{}{}'.format(typ, options.http_url, media_id, {'photo': '.jpg'}.get(typ, ''))
                if type == 'photo' and isinstance(msg.media.photo, tl.types.Photo):
                    for size in msg.media.photo.sizes:
                        if isinstance(size, tl.types.PhotoCachedSize):
                            text += ' {}x{}'.format(size.w, size.h)
                        elif isinstance(size, tl.types.PhotoSize):
                            text += ' {}x{},{}B'.format(size.w, size.h, size.size)
                web.id2media[media_id] = (msg.media, None)
            elif text is None:
                text = '[{}] {}'.format(type(msg.media).__name__, msg.media.to_dict())
            if getattr(msg.media, 'caption', None):
                text += ' | ' + msg.media.caption.replace('\n', '\\n')
            if msg.message:
                text += ' | ' + msg.message.replace('\n', '\\n')
        else:
            text = msg.message

        self.deliver_message(msg.id, sender, to, msg.date, text, fwd_from=msg.fwd_from, reply_to_msg_id=msg.reply_to_msg_id)
github LonamiWebs / Telethon / telethon / client / uploads.py View on Github external
return None, None  # Can't turn whatever was given into media

        media = None
        file_handle = None
        as_image = utils.is_image(file) and not force_document
        if not isinstance(file, str) or os.path.isfile(file):
            file_handle = await self.upload_file(
                file, progress_callback=progress_callback
            )
        elif re.match('https?://', file):
            if as_image:
                media = types.InputMediaPhotoExternal(file)
            elif not force_document and utils.is_gif(file):
                media = types.InputMediaGifExternal(file, '')
            else:
                media = types.InputMediaDocumentExternal(file)
        else:
            bot_file = utils.resolve_bot_file_id(file)
            if bot_file:
                media = utils.get_input_media(bot_file)

        if media:
            pass  # Already have media, don't check the rest
        elif not file_handle:
            raise ValueError(
                'Failed to convert {} to media. Not an existing file, '
                'an HTTP URL or a valid bot-API-like file ID'.format(file)
            )
        elif as_image:
            media = types.InputMediaUploadedPhoto(file_handle)
        else:
            attributes, mime_type = utils.get_attributes(
github LonamiWebs / Telethon / telethon / client / updates.py View on Github external
def _handle_update(self: 'TelegramClient', update):
        self.session.process_entities(update)
        self._entity_cache.add(update)

        if isinstance(update, (types.Updates, types.UpdatesCombined)):
            entities = {utils.get_peer_id(x): x for x in
                        itertools.chain(update.users, update.chats)}
            for u in update.updates:
                self._process_update(u, update.updates, entities=entities)
        elif isinstance(update, types.UpdateShort):
            self._process_update(update.update, None)
        else:
            self._process_update(update, None)

        self._state_cache.update(update)
github LonamiWebs / Telethon / telethon / client / auth.py View on Github external
sent = await client.send_code_request(phone)
                print(sent)
        """
        result = None
        phone = utils.parse_phone(phone) or self._phone
        phone_hash = self._phone_code_hash.get(phone)

        if not phone_hash:
            try:
                result = await self(functions.auth.SendCodeRequest(
                    phone, self.api_id, self.api_hash, types.CodeSettings()))
            except errors.AuthRestartError:
                return await self.send_code_request(phone, force_sms=force_sms)

            # If we already sent a SMS, do not resend the code (hash may be empty)
            if isinstance(result.type, types.auth.SentCodeTypeSms):
                force_sms = False

            # phone_code_hash may be empty, if it is, do not save it (#1283)
            if result.phone_code_hash:
                self._phone_code_hash[phone] = phone_hash = result.phone_code_hash
        else:
            force_sms = True

        self._phone = phone

        if force_sms:
            result = await self(
                functions.auth.ResendCodeRequest(phone, phone_hash))

            self._phone_code_hash[phone] = result.phone_code_hash
github LonamiWebs / Telethon / telethon / tl / custom / inlineresult.py View on Github external
def url(self):
        """
        The URL present in this inline results. If you want to "click"
        this URL to open it in your browser, you should use Python's
        `webbrowser.open(url)` for such task.
        """
        if isinstance(self.result, types.BotInlineResult):
            return self.result.url
github LonamiWebs / Telethon / telethon / client / dialogs.py View on Github external
async def edit_folder(
            self: 'TelegramClient',
            entity: 'hints.EntitiesLike' = None,
            folder: typing.Union[int, typing.Sequence[int]] = None,
            *,
            unpack=None
    ) -> types.Updates:
        """
        Edits the folder used by one or more dialogs to archive them.

        Arguments
            entity (entities):
                The entity or list of entities to move to the desired
                archive folder.

            folder (`int`):
                The folder to which the dialog should be archived to.

                If you want to "archive" a dialog, use ``folder=1``.

                If you want to "un-archive" it, use ``folder=0``.

                You may also pass a list with the same length as