How to use the telethon.tl.functions.messages 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 LonamiWebs / Telethon / telethon / client / dialogs.py View on Github external
async def _init(
            self, offset_date, offset_id, offset_peer, ignore_pinned, ignore_migrated, folder
    ):
        self.request = functions.messages.GetDialogsRequest(
            offset_date=offset_date,
            offset_id=offset_id,
            offset_peer=offset_peer,
            limit=1,
            hash=0,
            exclude_pinned=ignore_pinned,
            folder_id=folder
        )

        if self.limit <= 0:
            # Special case, get a single dialog and determine count
            dialogs = await self.client(self.request)
            self.total = getattr(dialogs, 'count', len(dialogs.dialogs))
            raise StopAsyncIteration

        self.seen = set()
github LonamiWebs / Telethon / telethon / client / uploads.py View on Github external
await self._parse_message_text(caption, parse_mode)

        file_handle, media, image = await self._file_to_media(
            file, force_document=force_document,
            progress_callback=progress_callback,
            attributes=attributes,  allow_cache=allow_cache, thumb=thumb,
            voice_note=voice_note, video_note=video_note,
            supports_streaming=supports_streaming
        )

        # e.g. invalid cast from :tl:`MessageMediaWebPage`
        if not media:
            raise TypeError('Cannot use {!r} as file'.format(file))

        markup = self.build_reply_markup(buttons)
        request = functions.messages.SendMediaRequest(
            entity, media, reply_to_msg_id=reply_to, message=caption,
            entities=msg_entities, reply_markup=markup, silent=silent,
            schedule_date=schedule
        )
        msg = self._get_response_message(request, await self(request), entity)
        await self._cache_media(msg, file, file_handle, image=image)

        return msg
github LonamiWebs / Telethon / telethon / client / chats.py View on Github external
async def __aenter__(self):
        self._chat = await self._client.get_input_entity(self._chat)

        # Since `self._action` is passed by reference we can avoid
        # recreating the request all the time and still modify
        # `self._action.progress` directly in `progress`.
        self._request = functions.messages.SetTypingRequest(
            self._chat, self._action)

        self._running = True
        self._task = self._client.loop.create_task(self._update())
        return self
github LonamiWebs / Telethon / telethon / tl / custom / inlinebuilder.py View on Github external
if voice_note:
                type = 'voice'
            else:
                type = 'document'

        fh = await self._client.upload_file(file)
        if not isinstance(fh, types.InputDocument):
            attributes, mime_type = utils.get_attributes(
                file,
                mime_type=mime_type,
                attributes=attributes,
                force_document=force_document,
                voice_note=voice_note,
                video_note=video_note
            )
            r = await self._client(functions.messages.UploadMediaRequest(
                types.InputPeerSelf(), media=types.InputMediaUploadedDocument(
                    fh,
                    mime_type=mime_type,
                    attributes=attributes,
                    nosound_video=None,
                    thumb=None
            )))
            fh = utils.get_input_document(r.document)

        result = types.InputBotInlineResultDocument(
            id=id or '',
            type=type,
            document=fh,
            send_message=await self._message(
                text=text, parse_mode=parse_mode, link_preview=link_preview,
                geo=geo, period=period,
github LonamiWebs / Telethon / telethon / tl / custom / inlinebuilder.py View on Github external
try:
            fh = utils.get_input_document(file)
        except TypeError:
            _, media, _ = await self._client._file_to_media(
                file,
                mime_type=mime_type,
                attributes=attributes,
                force_document=True,
                voice_note=voice_note,
                video_note=video_note,
                allow_cache=use_cache
            )
            if isinstance(media, types.InputDocument):
                fh = media
            else:
                r = await self._client(functions.messages.UploadMediaRequest(
                    types.InputPeerSelf(), media=media
                ))
                fh = utils.get_input_document(r.document)

        result = types.InputBotInlineResultDocument(
            id=id or '',
            type=type,
            document=fh,
            send_message=await self._message(
                # Empty string for text if there's media but text is None.
                # We may want to display a document but send text; however
                # default to sending the media (without text, i.e. stickers).
                text=text or '',
                parse_mode=parse_mode,
                link_preview=link_preview,
                geo=geo,
github LonamiWebs / Telethon / telethon / client / uploads.py View on Github external
captions = []
        for c in reversed(caption):  # Pop from the end (so reverse)
            captions.append(await self._parse_message_text(c or '', parse_mode))

        reply_to = utils.get_message_id(reply_to)

        # Need to upload the media first, but only if they're not cached yet
        media = []
        for file in files:
            # Albums want :tl:`InputMedia` which, in theory, includes
            # :tl:`InputMediaUploadedPhoto`. However using that will
            # make it `raise MediaInvalidError`, so we need to upload
            # it as media and then convert that to :tl:`InputMediaPhoto`.
            fh, fm, _ = await self._file_to_media(file)
            if isinstance(fm, types.InputMediaUploadedPhoto):
                r = await self(functions.messages.UploadMediaRequest(
                    entity, media=fm
                ))
                self.session.cache_file(
                    fh.md5, fh.size, utils.get_input_photo(r.photo))

                fm = utils.get_input_media(r.photo)

            if captions:
                caption, msg_entities = captions.pop()
            else:
                caption, msg_entities = '', None
            media.append(types.InputSingleMedia(
                fm,
                message=caption,
                entities=msg_entities
                # random_id is autogenerated
github LonamiWebs / Telethon / telethon / client / chats.py View on Github external
.. code-block:: python

                # Kick some user from some chat
                await client.kick_participant(chat, user)

                # Leaving chat
                await client.kick_participant(chat, 'me')
        """
        entity = await self.get_input_entity(entity)
        user = await self.get_input_entity(user)
        if helpers._entity_type(user) != helpers._EntityType.USER:
            raise ValueError('You must pass a user entity')

        ty = helpers._entity_type(entity)
        if ty == helpers._EntityType.CHAT:
            await self(functions.messages.DeleteChatUserRequest(entity.chat_id, user))
        elif ty == helpers._EntityType.CHANNEL:
            if isinstance(user, types.InputPeerSelf):
                await self(functions.channels.LeaveChannelRequest(entity))
            else:
                await self(functions.channels.EditBannedRequest(
                    channel=entity,
                    user_id=user,
                    banned_rights=types.ChatBannedRights(until_date=None, view_messages=True)
                ))
                await asyncio.sleep(0.5)
                await self(functions.channels.EditBannedRequest(
                    channel=entity,
                    user_id=user,
                    banned_rights=types.ChatBannedRights(until_date=None)
                ))
        else:
github MaskRay / telegramircd / telegramircd.py View on Github external
def message_get(self, id):
        messages = self.proc(tl.functions.messages.GetMessagesRequest([id])).messages
        return messages[0] if messages else None
github kandnub / TG-UserBot / userbot / plugins / misc.py View on Github external
continue

                if isinstance(chat, types.User):
                    text = f"**ID:** `{chat.id}`"
                    if chat.username:
                        text += f"\n**Username:** @{chat.username}"
                    text += f"\n{await get_chat_link(chat)}"

                if isinstance(chat, types.ChatForbidden):
                    text += f"\n`Not allowed to view {chat.title}.`"
                elif isinstance(chat, types.ChatEmpty):
                    text += "\n`The chat is empty.`"
                elif isinstance(chat, types.Chat):
                    text = f"**Chat:** @{valid}"
                    result = await client(
                        functions.messages.GetFullChatRequest(
                            chat_id=chat
                        )
                    )
                    text += await misc.resolve_chat(event.client, result)

                if isinstance(chat, types.ChannelForbidden):
                    text += f"\n`Not allowed to view {chat.title}.`"
                elif isinstance(chat, types.Channel):
                    text = f"**Channel:** @{valid}"
                    result = await client(
                        functions.channels.GetFullChannelRequest(
                            channel=chat
                        )
                    )
                    text += await misc.resolve_channel(event.client, result)
    await event.answer(text, link_preview=False)
github Terrance / IMMP / immp / plug / telegram.py View on Github external
# mentions and forwards).  Narrow down the list by excluding chats we can't access.
        log.debug("Finding chats to blacklist")
        lookup = []
        for chat in self._client.session.get_chat_entities():
            if chat[0] in self._blacklist:
                continue
            if str(chat[0]).startswith("-100"):
                try:
                    await self._client(tl.functions.channels.GetChannelsRequest([abs(chat[0])]))
                except ChannelPrivateError:
                    log.debug("Blacklisting channel %d", chat[0])
                    self._blacklist.add(chat[0])
            else:
                lookup.append(abs(chat[0]))
        if lookup:
            chats = await self._client(tl.functions.messages.GetChatsRequest(lookup))
            gone = [-chat.id for chat in chats.chats if isinstance(chat, tl.types.ChatForbidden)]
            if gone:
                log.debug("Blacklisting chats %s", ", ".join(str(id_) for id_ in gone))
                self._blacklist.update(gone)
        log.debug("Done blacklisting chats")