How to use Telethon - 10 common examples

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 / downloads.py View on Github external
#
                # telethon.sync must be imported for this to work,
                # and you must not be inside an "async def".
                stream = client.iter_download(media, request_size=32)
                header = next(stream)
                stream.close()
                assert len(header) == 32

                # Fetching only the header, inside of an ``async def``
                async def main():
                    stream = client.iter_download(media, request_size=32)
                    header = await stream.__anext__()
                    await stream.close()
                    assert len(header) == 32
        """
        info = utils._get_file_info(file)
        if info.dc_id is not None:
            dc_id = info.dc_id

        if file_size is None:
            file_size = info.size

        file = info.location

        if chunk_size is None:
            chunk_size = request_size

        if limit is None and file_size is not None:
            limit = (file_size + chunk_size - 1) // chunk_size

        if stride is None:
            stride = chunk_size
github expectocode / telegram-export / telegram_export / tests.py View on Github external
def test_dump_msg_entities(self):
        """Show that entities are correctly parsed and stored"""
        message = types.Message(
            id=1,
            to_id=types.PeerUser(321),
            date=datetime.now(),
            message='No entities'
        )
        dumper = Dumper(self.dumper_config)
        fmt = BaseFormatter(dumper.conn)

        # Test with no entities
        dumper.dump_message(message, 123, None, None)
        dumper.commit()
        assert not next(fmt.get_messages_from_context(123, order='DESC')).formatting

        # Test with many entities
        text, entities = markdown.parse(
            'Testing message with __italic__, **bold**, inline '
            '[links](https://example.com) and [mentions](@hi), '
            'as well as `code` and ``pre`` blocks.'
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 blueset / efb-telegram-master / tests / integration / helper / helper.py View on Github external
# Telethon client to use
        self.client: TelegramClient = TelegramClient(
            StringSession(session), api_id, api_hash, proxy=proxy, loop=loop,
            sequential_updates=True
        )

        # Queue for incoming messages
        self.queue: "asyncio.queues.Queue[EventCommon]" = asyncio.queues.Queue()

        # Collect mappings from message ID to its chat (as Telegram API is not sending them)
        self.message_chat_map: Dict[int, TypeInputPeer] = dict()

        self.chats = list(map(abs, chats))
        self.client.parse_mode = "html"
        self.client.add_event_handler(self.new_message_handler,
                                      NewMessage(chats=self.chats, incoming=True, from_users=[bot_id]))
        # self.client.add_event_handler(self.new_message_handler,
        #                               NewMessage(incoming=True))
        self.client.add_event_handler(self.deleted_message_handler, MessageDeleted())
        self.client.add_event_handler(self.update_handler, UserUpdate(chats=self.chats))
        self.client.add_event_handler(self.update_handler, MessageEdited(chats=self.chats))
        self.client.add_event_handler(self.update_handler, ChatAction(chats=self.chats))

        self.logger = logging.getLogger(__name__)
github blueset / efb-telegram-master / tests / integration / test_update_info.py View on Github external
with link_chats(channel, (chat,), bot_group):
        await client.send_message(bot_group, "/update_info")
        title = (await helper.wait_for_event(in_chats(bot_group) & new_title)).new_title
        if alias:
            assert chat.alias in title
        else:
            assert chat.name in title

        if avatar:
            await helper.wait_for_event(in_chats(bot_group) & new_photo)

        if chat_type == "GroupChat":
            # Get group description
            bot_group_t, peer_type = resolve_id(bot_group)
            if peer_type == PeerChannel:
                group: ChatFull = await client(GetFullChannelRequest(bot_group_t))
            else:
                group: ChatFull = await client(GetFullChatRequest(bot_group_t))
            desc = group.full_chat.about

            chats_found = sum(int(
                (i.name in desc) and  # Original name is found, and
                (i.alias is None or i.alias in desc)  # alias is found too if available
            ) for i in chat.members)

            assert len(chat.members) >= 5
            assert chats_found >= 5, f"At least 5 members shall be found in the description: {desc}"
github expectocode / telegram-export / telegram_export / tests.py View on Github external
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,
            to_id=types.PeerUser(321),
            date=datetime.now(),
            message='Hello',
            out=False,
            via_bot_id=1000,
            media=types.MessageMediaPhoto(
                caption='Hi',
                ttl_seconds=40,
                photo=types.Photo(
                    id=2357,
                    access_hash=-123456789,
                    date=datetime.now(),
                    sizes=[
                        types.PhotoSize(
                            type='X',
github LonamiWebs / Telethon / telethon / client / messageparse.py View on Github external
if isinstance(update, types.UpdateMessageID):
                random_to_id[update.random_id] = update.id

            elif isinstance(update, (
                    types.UpdateNewChannelMessage, types.UpdateNewMessage)):
                update.message._finish_init(self, entities, input_chat)
                id_to_message[update.message.id] = update.message

            elif (isinstance(update, types.UpdateEditMessage)
                  and helpers._entity_type(request.peer) != helpers._EntityType.CHANNEL):
                if request.id == update.message.id:
                    update.message._finish_init(self, entities, input_chat)
                    return update.message

            elif (isinstance(update, types.UpdateEditChannelMessage)
                  and utils.get_peer_id(request.peer) ==
                  utils.get_peer_id(update.message.to_id)):
                if request.id == update.message.id:
                    update.message._finish_init(self, entities, input_chat)
                    return update.message

            elif isinstance(update, types.UpdateNewScheduledMessage):
                update.message._finish_init(self, entities, input_chat)
                sched_to_message[update.message.id] = update.message

            elif isinstance(update, types.UpdateMessagePoll):
                if request.media.poll.id == update.poll_id:
                    m = types.Message(
                        id=request.id,
                        to_id=utils.get_peer(request.peer),
                        media=types.MessageMediaPoll(
                            poll=update.poll,
github Dark-Princ3 / X-tra-Telegram / userbot / plugins / ukinti.py View on Github external
return
    input_str = event.pattern_match.group(1)
    if input_str:
        logger.info("TODO: Not yet Implemented")
    else:
        if event.is_private:
            return False
        await event.edit("Searching Participant Lists.")
        p = 0
        async for i in borg.iter_participants(event.chat_id, filter=ChannelParticipantsKicked, aggressive=True):
            rights = ChatBannedRights(
                until_date=0,
                view_messages=False
            )
            try:
                await borg(functions.channels.EditBannedRequest(event.chat_id, i, rights))
            except FloodWaitError as ex:
                logger.warn("sleeping for {} seconds".format(ex.seconds))
                sleep(ex.seconds)
            except Exception as ex:
                await event.edit(str(ex))
            else:
                p += 1
        await event.edit("{}: {} unbanned".format(event.chat_id, p))
github LonamiWebs / Telethon / telethon / client / chats.py View on Github external
async def _init(
            self, entity, offset, max_id
    ):
        entity = await self.client.get_input_entity(entity)
        ty = helpers._entity_type(entity)
        if ty == helpers._EntityType.USER:
            self.request = functions.photos.GetUserPhotosRequest(
                entity,
                offset=offset,
                max_id=max_id,
                limit=1
            )
        else:
            self.request = functions.messages.SearchRequest(
                peer=entity,
                q='',
                filter=types.InputMessagesFilterChatPhotos(),
                min_date=None,
                max_date=None,
                offset_id=0,
                add_offset=offset,
                limit=1,
                max_id=max_id,
github LonamiWebs / Telethon / telethon_examples / replier.py View on Github external
# We can also use client methods from here
    client = event.client

    # If we sent the message, we are replying to someone,
    # and we said "save pic" in the message
    if event.out and event.reply_to_msg_id and 'save pic' in event.raw_text:
        reply_msg = await event.get_reply_message()
        replied_to_user = await reply_msg.get_input_sender()

        message = await event.reply('Downloading your profile photo...')
        file = await client.download_profile_photo(replied_to_user)
        await message.edit('I saved your photo in {}'.format(file))


client = TelegramClient(
    os.environ.get('TG_SESSION', 'replier'),
    get_env('TG_API_ID', 'Enter your API ID: ', int),
    get_env('TG_API_HASH', 'Enter your API hash: '),
    proxy=None
)

with client:
    # This remembers the events.NewMessage we registered before
    client.add_event_handler(handler)

    print('(Press Ctrl+C to stop this)')
    client.run_until_disconnected()