Python telethon.TelegramClient() Examples

The following are 30 code examples of telethon.TelegramClient(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module telethon , or try the search function .
Example #1
Source File: gui.py    From Telethon with MIT License 9 votes vote down vote up
def main(loop, interval=0.05):
    client = TelegramClient(SESSION, API_ID, API_HASH, loop=loop)
    try:
        await client.connect()
    except Exception as e:
        print('Failed to connect', e, file=sys.stderr)
        return

    app = App(client)
    try:
        while True:
            # We want to update the application but get back
            # to asyncio's event loop. For this we sleep a
            # short time so the event loop can run.
            #
            # https://www.reddit.com/r/Python/comments/33ecpl
            app.update()
            await asyncio.sleep(interval)
    except KeyboardInterrupt:
        pass
    except tkinter.TclError as e:
        if 'application has been destroyed' not in e.args[0]:
            raise
    finally:
        await app.cl.disconnect() 
Example #2
Source File: telegram_bot.py    From pyrobud with MIT License 6 votes vote down vote up
def init_client(self: "Bot") -> None:
        # Get Telegram parameters from config and check types
        session_name = self.tg_config["session_name"]
        if not isinstance(session_name, str):
            raise TypeError("Session name must be a string")

        api_id = self.tg_config["api_id"]
        if not isinstance(api_id, int):
            raise TypeError("API ID must be an integer")

        api_hash = self.tg_config["api_hash"]
        if not isinstance(api_hash, str):
            raise TypeError("API hash must be a string")

        # Initialize Telegram client with gathered parameters
        self.client = tg.TelegramClient(
            session_name, api_id, api_hash, connection_retries=10, retry_delay=5
        ) 
Example #3
Source File: FastTelethon.py    From TG-UserBot with GNU General Public License v3.0 6 votes vote down vote up
def download_file(
    self: TelegramClient, location: TypeLocation,
    out: BinaryIO, progress_callback: callable = None
) -> BinaryIO:
    size = location.size
    dc_id, location = utils.get_input_location(location)
    # We lock the transfers because telegram has connection count limits
    downloader = ParallelTransferrer(self, dc_id)
    downloaded = downloader.download(location, size)
    async for x in downloaded:
        out.write(x)
        if progress_callback:
            r = progress_callback(out.tell(), size)
            if inspect.isawaitable(r):
                await r

    return out 
Example #4
Source File: tests.py    From telegram-export with Mozilla Public License 2.0 6 votes vote down vote up
def setUpClass(cls):
        cls.dumper_config = {'DBFileName': 'test_db', 'OutputDirectory': 'test_work_dir',
                             'MaxSize': 0}
        # TODO test with different configurations

        assert not Path(cls.dumper_config['OutputDirectory']).exists()

        Path(cls.dumper_config['OutputDirectory']).mkdir()

        config = configparser.ConfigParser()
        config.read('config.ini')
        config = config['TelegramAPI']

        cls.client = TelegramClient(None, config['ApiId'], config['ApiHash'])
        login_client(cls.client, gen_username(10))

        dumper = Dumper(cls.dumper_config)
        dumper.check_self_user(cls.client.get_me().id) 
Example #5
Source File: updates.py    From Telethon with MIT License 6 votes vote down vote up
def _process_update(self: 'TelegramClient', update, others, entities=None):
        update._entities = entities or {}

        # This part is somewhat hot so we don't bother patching
        # update with channel ID/its state. Instead we just pass
        # arguments which is faster.
        channel_id = self._state_cache.get_channel_id(update)
        args = (update, others, channel_id, self._state_cache[channel_id])
        if self._dispatching_updates_queue is None:
            task = self._loop.create_task(self._dispatch_update(*args))
            self._updates_queue.add(task)
            task.add_done_callback(lambda _: self._updates_queue.discard(task))
        else:
            self._updates_queue.put_nowait(args)
            if not self._dispatching_updates_queue.is_set():
                self._dispatching_updates_queue.set()
                self._loop.create_task(self._dispatch_queue_updates())

        self._state_cache.update(update) 
Example #6
Source File: FastTelethon.py    From BotHub with Apache License 2.0 6 votes vote down vote up
def upload_file(self: TelegramClient,
                      file: BinaryIO,
                      progress_callback: callable = None) -> TypeInputFile:
    res = (await _internal_transfer_to_telegram(self, file,
                                                progress_callback))[0]
    return res 
Example #7
Source File: FastTelethon.py    From BotHub with Apache License 2.0 6 votes vote down vote up
def download_file(self: TelegramClient,
                        location: TypeLocation,
                        out: BinaryIO,
                        progress_callback: callable = None) -> BinaryIO:
    size = location.size
    dc_id, location = utils.get_input_location(location)
    # We lock the transfers because telegram has connection count limits
    downloader = ParallelTransferrer(self, dc_id)
    downloaded = downloader.download(location, size)
    async for x in downloaded:
        out.write(x)
        if progress_callback:
            r = progress_callback(out.tell(), size)
            if inspect.isawaitable(r):
                await r

    return out 
Example #8
Source File: FastTelethon.py    From TG-UserBot with GNU General Public License v3.0 5 votes vote down vote up
def __init__(
        self, client: TelegramClient, dc_id: Optional[int] = None
    ) -> None:
        self.client = client
        self.loop = self.client.loop
        self.dc_id = dc_id or self.client.session.dc_id
        self.auth_key = (
            None if dc_id and self.client.session.dc_id != dc_id
            else self.client.session.auth_key
        )
        self.senders = None
        self.upload_ticker = 0 
Example #9
Source File: telegramircd.py    From telegramircd with Apache License 2.0 5 votes vote down vote up
def run_telethon(self):
        if self.proc:
            self.proc.disconnect()
        self.proc = TelegramClient(options.tg_session, options.tg_api_id, options.tg_api_hash)
        try:
            self.proc.connect()
        except:
            error('Failed to connect to Telegram server')
            sys.exit(2)
        self.authorized = self.proc.is_user_authorized()
        if not self.authorized and not options.tg_phone:
            error('Not authorized. Please set --tg-phone')
            sys.exit(2)
        self.proc.add_event_handler(server.on_telegram_update) 
Example #10
Source File: FastTelethon.py    From TG-UserBot with GNU General Public License v3.0 5 votes vote down vote up
def _internal_transfer_to_telegram(
    client: TelegramClient, response: BinaryIO, progress_callback: callable
) -> Tuple[TypeInputFile, int]:
    file_id = helpers.generate_random_long()
    file_size = os.path.getsize(response.name)

    hash_md5 = hashlib.md5()
    uploader = ParallelTransferrer(client)
    part_size, part_count, is_large = await uploader.init_upload(
        file_id, file_size
    )
    buffer = bytearray()
    for data in stream_file(response):
        if progress_callback:
            r = progress_callback(response.tell(), file_size)
            if inspect.isawaitable(r):
                await r
        if not is_large:
            hash_md5.update(data)
        if len(buffer) == 0 and len(data) == part_size:
            await uploader.upload(data)
            continue
        new_len = len(buffer) + len(data)
        if new_len >= part_size:
            cutoff = part_size - len(buffer)
            buffer.extend(data[:cutoff])
            await uploader.upload(bytes(buffer))
            buffer.clear()
            buffer.extend(data[cutoff:])
        else:
            buffer.extend(data)
    if len(buffer) > 0:
        await uploader.upload(bytes(buffer))
    await uploader.finish_upload()
    if is_large:
        return InputFileBig(file_id, part_count, "upload"), file_size
    else:
        return (
            InputFile(file_id, part_count, "upload", hash_md5.hexdigest()),
            file_size
        ) 
Example #11
Source File: FastTelethon.py    From TG-UserBot with GNU General Public License v3.0 5 votes vote down vote up
def upload_file(
    self: TelegramClient, file: BinaryIO, progress_callback: callable = None
) -> TypeInputFile:
    res = (
        await _internal_transfer_to_telegram(self, file, progress_callback)
    )[0]
    return res 
Example #12
Source File: telegram_spider.py    From capturer with MIT License 5 votes vote down vote up
def open_client():
    # get api_id and api_hash from https://my.telegram.org/apps
    api_id = None
    api_hash = None

    if not api_id or not api_hash:
        print('Please set api_id and api_hash, you can get it from https://my.telegram.org/apps')
        sys.exit(1)

    # socks5 proxy, can set to be 'None' if no need
    proxy = (socks.SOCKS5, "localhost", 1080)
    return TelegramClient('tg_session', api_id=api_id,
                          api_hash=api_hash, proxy=proxy).start() 
Example #13
Source File: client.py    From BotHub with Apache License 2.0 5 votes vote down vote up
def onMessage(self: TelegramClient,
                  builtin: bool = False,
                  command: str or tuple = None,
                  edited: bool = True,
                  info: str = None,
                  **kwargs) -> callable:
        """Method to register a function without the client"""

        kwargs.setdefault('forwards', False)

        def wrapper(func: callable) -> callable:
            events.register(NewMessage(**kwargs))(func)

            if edited:
                events.register(MessageEdited(**kwargs))(func)

            if self.register_commands and command:
                handlers = events._get_handlers(func)
                category = "misc"
                if isinstance(command, tuple):
                    if len(command) == 2:
                        com, category = command
                    else:
                        raise ValueError
                else:
                    com = command

                UBcommand = Command(func, handlers, info or func.__doc__
                                    or no_info, builtin)
                category = category.lower()
                self.commands.update({com: UBcommand})
                update_dict(self.commandcategories, category, com)
                if builtin:
                    update_dict(self.commandcategories, 'builtin', com)
            return func

        return wrapper 
Example #14
Source File: FastTelethon.py    From BotHub with Apache License 2.0 5 votes vote down vote up
def __init__(self,
                 client: TelegramClient,
                 dc_id: Optional[int] = None) -> None:
        self.client = client
        self.loop = self.client.loop
        self.dc_id = dc_id or self.client.session.dc_id
        self.auth_key = (None if dc_id and self.client.session.dc_id != dc_id
                         else self.client.session.auth_key)
        self.senders = None
        self.upload_ticker = 0 
Example #15
Source File: FastTelethon.py    From BotHub with Apache License 2.0 5 votes vote down vote up
def _internal_transfer_to_telegram(
        client: TelegramClient, response: BinaryIO,
        progress_callback: callable) -> Tuple[TypeInputFile, int]:
    file_id = helpers.generate_random_long()
    file_size = os.path.getsize(response.name)

    hash_md5 = hashlib.md5()
    uploader = ParallelTransferrer(client)
    part_size, part_count, is_large = await uploader.init_upload(
        file_id, file_size)
    buffer = bytearray()
    for data in stream_file(response):
        if progress_callback:
            r = progress_callback(response.tell(), file_size)
            if inspect.isawaitable(r):
                await r
        if not is_large:
            hash_md5.update(data)
        if len(buffer) == 0 and len(data) == part_size:
            await uploader.upload(data)
            continue
        new_len = len(buffer) + len(data)
        if new_len >= part_size:
            cutoff = part_size - len(buffer)
            buffer.extend(data[:cutoff])
            await uploader.upload(bytes(buffer))
            buffer.clear()
            buffer.extend(data[cutoff:])
        else:
            buffer.extend(data)
    if len(buffer) > 0:
        await uploader.upload(bytes(buffer))
    await uploader.finish_upload()
    if is_large:
        return InputFileBig(file_id, part_count, "upload"), file_size
    else:
        return (InputFile(file_id, part_count, "upload",
                          hash_md5.hexdigest()), file_size) 
Example #16
Source File: telegram_client_x.py    From tgcloud with Apache License 2.0 5 votes vote down vote up
def __init__(self, name, client, q_request=None):
            Thread.__init__(self)
            self.name = name
            self.client = TelegramClient(client._session_name, client.api_id, client.api_hash, update_workers=None,
                                         spawn_read_thread=False)
            self.q_request = q_request
            self.result = None 
Example #17
Source File: telegram_client_x.py    From tgcloud with Apache License 2.0 5 votes vote down vote up
def __init__(self, name, client, q_request=None):
            Thread.__init__(self)
            self.name = name
            self.client = TelegramClient(client._session_name, client.api_id, client.api_hash, update_workers=None,
                                         spawn_read_thread=False)
            self.q_request = q_request
            self.result = None 
Example #18
Source File: telegram_async.py    From telegram with MIT License 5 votes vote down vote up
def __init__(self):
        self._client = AsyncTelegram("session", config["api_id"], config["api_hash"]) 
Example #19
Source File: Ping_server.py    From Awesome-Python-Scripts with MIT License 5 votes vote down vote up
def main():
    j
    api_id = #####
    api_hash = '######################'

# Your Account Sid and Auth Token from twilio.com/console
    account_sid = '###############'
    auth_token = '################'
    clients = Client(account_sid, auth_token)


#telegram_Side
    client = TelegramClient('session_name', api_id, api_hash)
    client.start()
#print(client.get_me().stringify())
#updates = client(ImportChatInviteRequest('FDVzKw8BPHTp2wyhwNqT2Q'))
    siteList=[site_list]
    for i in siteList:
        print(i)
        r = requests.head(i)
        if r.status_code == 200:
            message=i +"  returned  200"
            chat = InputPeerChat(chatID)
            client.send_message(chat, message)
            sms= clients.messages.create(to="#####",from_="##########",body="the  "+i+"   is not responding now  ")
            call = clients.calls.create(url='http://demo.twilio.com/docs/voice.xml',to='############',from_='#############')
            print(call.sid)
        else:
            chat = InputPeerChat(chatID)
            message="oops  " + i + "   not available at the moment"
            client.send_message(chat, message) 
Example #20
Source File: paralleltransfer.py    From tgfilestream with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, client: TelegramClient, dc_id: int) -> None:
        self.log = root_log.getChild(f"dc{dc_id}")
        self.client = client
        self.dc_id = dc_id
        self.auth_key = None
        self.connections = []
        self._list_lock = asyncio.Lock()
        self.loop = client.loop
        self.dc = None 
Example #21
Source File: paralleltransfer.py    From tgfilestream with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, client: TelegramClient) -> None:
        self.client = client
        self.loop = self.client.loop
        self._counter = 0
        self.dc_managers = {
            1: DCConnectionManager(client, 1),
            2: DCConnectionManager(client, 2),
            3: DCConnectionManager(client, 3),
            4: DCConnectionManager(client, 4),
            5: DCConnectionManager(client, 5),
        } 
Example #22
Source File: initial_setup.py    From friendly-telegram with GNU Affero General Public License v3.0 5 votes vote down vote up
def send_tg_code(self, request):
        if self.client_data and await self.check_user(request) is None:
            return web.Response(status=302, headers={"Location": "/"})  # They gotta sign in.
        text = await request.text()
        phone = telethon.utils.parse_phone(text)
        if not phone:
            return web.Response(status=400)
        client = telethon.TelegramClient(telethon.sessions.MemorySession(), self.api_token.ID,
                                         self.api_token.HASH, connection_retries=None)
        await client.connect()
        await client.send_code_request(phone)
        self.sign_in_clients[phone] = client
        return web.Response() 
Example #23
Source File: updates.py    From Telethon with MIT License 5 votes vote down vote up
def _run_until_disconnected(self: 'TelegramClient'):
        try:
            # Make a high-level request to notify that we want updates
            await self(functions.updates.GetStateRequest())
            return await self.disconnected
        except KeyboardInterrupt:
            pass
        finally:
            await self.disconnect() 
Example #24
Source File: updates.py    From Telethon with MIT License 5 votes vote down vote up
def on(self: 'TelegramClient', event: EventBuilder):
        """
        Decorator used to `add_event_handler` more conveniently.


        Arguments
            event (`_EventBuilder` | `type`):
                The event builder class or instance to be used,
                for instance ``events.NewMessage``.

        Example
            .. code-block:: python

                from telethon import TelegramClient, events
                client = TelegramClient(...)

                # Here we use client.on
                @client.on(events.NewMessage)
                async def handler(event):
                    ...
        """
        def decorator(f):
            self.add_event_handler(f, event)
            return f

        return decorator 
Example #25
Source File: updates.py    From Telethon with MIT License 5 votes vote down vote up
def list_event_handlers(self: 'TelegramClient')\
            -> 'typing.Sequence[typing.Tuple[callable, EventBuilder]]':
        """
        Lists all registered event handlers.

        Returns
            A list of pairs consisting of ``(callback, event)``.

        Example
            .. code-block:: python

                @client.on(events.NewMessage(pattern='hello'))
                async def on_greeting(event):
                    '''Greets someone'''
                    await event.reply('Hi')

                for callback, event in client.list_event_handlers():
                    print(id(callback), type(event))
        """
        return [(callback, event) for event, callback in self._event_builders] 
Example #26
Source File: updates.py    From Telethon with MIT License 5 votes vote down vote up
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) 
Example #27
Source File: updates.py    From Telethon with MIT License 5 votes vote down vote up
def _dispatch_queue_updates(self: 'TelegramClient'):
        while not self._updates_queue.empty():
            await self._dispatch_update(*self._updates_queue.get_nowait())

        self._dispatching_updates_queue.clear() 
Example #28
Source File: updates.py    From Telethon with MIT License 5 votes vote down vote up
def __init__(self, client: 'TelegramClient', update, others):
        self.client = client
        self.update = update
        self.others = others 
Example #29
Source File: test_client_reference.py    From Telethon with MIT License 5 votes vote down vote up
def test_all_methods_present(docs_dir):
    with (docs_dir / 'quick-references/client-reference.rst').open(encoding='utf-8') as fd:
        present_methods = set(map(str.lstrip, re.findall(r'^ {4}\w+$', fd.read(), re.MULTILINE)))

    assert len(present_methods) > 0
    for name in dir(TelegramClient):
        attr = getattr(TelegramClient, name)
        if callable(attr) and not name.startswith('_'):
            assert name in present_methods 
Example #30
Source File: test_chataction.py    From Telethon with MIT License 5 votes vote down vote up
def get_client():
    return TelegramClient(None, 1, '1')