Move InteractiveClient to examples/ (and stop shipping it to pip)

This commit is contained in:
Lonami Exo 2017-06-08 14:00:27 +02:00
parent 88f87f6de2
commit a07c7bd0d0
4 changed files with 50 additions and 40 deletions

View File

@ -80,25 +80,28 @@ If you've installed Telethon via pip, launch an interactive python3 session and
.. code:: python .. code:: python
>>> from telethon import InteractiveTelegramClient >>> from telethon import TelegramClient
>>> api_id = 12345
>>> api_hash = '0123456789abcdef0123456789abcdef'
>>> # 'session_id' can be 'your_name'. It'll be saved as your_name.session >>> # 'session_id' can be 'your_name'. It'll be saved as your_name.session
>>> # Also (obviously) replace the api_id and api_hash with your values ... client = TelegramClient('session_id', api_id, api_hash)
>>> client.connect()
True
>>>
>>> if not client.is_user_authorized():
>>> client.send_code_request('+34600000000')
>>> client.sign_in('+34600000000', input('Enter code: '))
... ...
>>> client = InteractiveTelegramClient('session_id', '+34600000000', >>> # Now you can use the connected client as you wish
... api_id=12345, api_hash='0123456789abcdef0123456789abcdef') >>> dialogs, entities = client.get_dialogs(10)
>>> print('\n'.join('{}. {}'.format(i, str(e))
================== ... for i, e in enumerate(entities)))
= Initialization =
==================
Initializing interactive example...
Connecting to Telegram servers...
>>> client.run()
If, on the other hand, you've installed Telethon manually, head to the ``api/`` directory and create a If, on the other hand, you've installed Telethon manually, head to the ``api/`` directory and create a
copy of the ``settings_example`` file, naming it ``settings`` (lowercase!). Then fill the file with the copy of the ``settings_example`` file, naming it ``settings`` (lowercase!). Then fill the file with the
corresponding values (your ``api_id``, ``api_hash`` and phone number in international format). corresponding values (your ``api_id``, ``api_hash`` and phone number in international format).
Then, simply run ``python3 try_telethon.py`` to start the interactive example. Then, simply run ``./try_telethon.py`` to start the interactive example.
.. _Using Telethon: .. _Using Telethon:
@ -106,9 +109,9 @@ Using Telethon
============== ==============
If you really want to learn how to use Telethon, it is **highly advised** that If you really want to learn how to use Telethon, it is **highly advised** that
you take a look to the you take a look to the
`InteractiveTelegramClient <telethon/interactive_telegram_client.py>`_ file `InteractiveTelegramClient <telethon_examples/interactive_telegram_client.py>`_
and check how it works. This file contains everything you'll need to build file and check how it works. This file contains everything you'll need to
your own application, since it shows, among other things: build your own application, since it shows, among other things:
1. Authorizing the user for the first time. 1. Authorizing the user for the first time.
2. Support to enter the 2-steps-verification code. 2. Support to enter the 2-steps-verification code.
@ -122,6 +125,8 @@ disposal, please check the
`official Telethon documentation <https://lonamiwebs.github.io/Telethon>`_. `official Telethon documentation <https://lonamiwebs.github.io/Telethon>`_.
There you'll find a list of all the methods, types and available constructors. There you'll find a list of all the methods, types and available constructors.
More examples are also available under the ``telethon_examples/`` folder.
Common errors Common errors
------------- -------------
@ -228,9 +233,9 @@ Once this is done, pass the proxy settings to the ``TelegramClient`` constructor
.. code:: python .. code:: python
>>> from telethon import InteractiveTelegramClient >>> from telethon import TelegramClient
>>> import socks >>> import socks
>>> client = InteractiveTelegramClient('session_id', '+34600000000', >>> client = TelegramClient('session_id',
... api_id=12345, api_hash='0123456789abcdef0123456789abcdef', ... api_id=12345, api_hash='0123456789abcdef0123456789abcdef',
... proxy=(socks.SOCKS5, 'localhost', 4444)) ... proxy=(socks.SOCKS5, 'localhost', 4444))

View File

@ -1,5 +1,4 @@
from .errors import * from .errors import *
from .telegram_bare_client import TelegramBareClient from .telegram_bare_client import TelegramBareClient
from .telegram_client import TelegramClient from .telegram_client import TelegramClient
from .interactive_telegram_client import InteractiveTelegramClient
from . import tl from . import tl

View File

@ -1,10 +1,10 @@
import shutil import shutil
from getpass import getpass from getpass import getpass
from . import TelegramClient from telethon import TelegramClient
from .errors import RPCError from telethon.errors import RPCError
from .tl.types import UpdateShortChatMessage, UpdateShortMessage from telethon.tl.types import UpdateShortChatMessage, UpdateShortMessage
from .utils import get_display_name from telethon.utils import get_display_name
# Get the (current) number of lines in the terminal # Get the (current) number of lines in the terminal
cols, rows = shutil.get_terminal_size() cols, rows = shutil.get_terminal_size()
@ -40,6 +40,13 @@ def bytes_to_string(byte_count):
class InteractiveTelegramClient(TelegramClient): class InteractiveTelegramClient(TelegramClient):
"""Full featured Telegram client, meant to be used on an interactive
session to see what Telethon is capable off -
This client allows the user to perform some basic interaction with
Telegram through Telethon, such as listing dialogs (open chats),
talking to people, downloading media, and receiving updates.
"""
def __init__(self, session_user_id, user_phone, api_id, api_hash, proxy=None): def __init__(self, session_user_id, user_phone, api_id, api_hash, proxy=None):
print_title('Initialization') print_title('Initialization')
@ -130,14 +137,10 @@ class InteractiveTelegramClient(TelegramClient):
print('Available commands:') print('Available commands:')
print(' !q: Quits the current chat.') print(' !q: Quits the current chat.')
print(' !Q: Quits the current chat and exits.') print(' !Q: Quits the current chat and exits.')
print( print(' !h: prints the latest messages (message History).')
' !h: prints the latest messages (message History) of the chat.') print(' !up <path>: Uploads and sends the Photo from path.')
print( print(' !uf <path>: Uploads and sends the File from path.')
' !up <path>: Uploads and sends a Photo located at the given path.') print(' !dm <msg-id>: Downloads the given message Media (if any).')
print(
' !uf <path>: Uploads and sends a File document located at the given path.')
print(
' !dm <msg-id>: Downloads the given message Media (if any).')
print(' !dp: Downloads the current dialog Profile picture.') print(' !dp: Downloads the current dialog Profile picture.')
print() print()
@ -155,8 +158,10 @@ class InteractiveTelegramClient(TelegramClient):
# First retrieve the messages and some information # First retrieve the messages and some information
total_count, messages, senders = self.get_message_history( total_count, messages, senders = self.get_message_history(
entity, limit=10) entity, limit=10)
# Iterate over all (in reverse order so the latest appears the last in the console)
# and print them in "[hh:mm] Sender: Message" text format # Iterate over all (in reverse order so the latest appear
# the last in the console) and print them with format:
# "[hh:mm] Sender: Message"
for msg, sender in zip( for msg, sender in zip(
reversed(messages), reversed(senders)): reversed(messages), reversed(senders)):
# Get the name of the sender if any # Get the name of the sender if any
@ -165,16 +170,18 @@ class InteractiveTelegramClient(TelegramClient):
# Format the message content # Format the message content
if getattr(msg, 'media', None): if getattr(msg, 'media', None):
self.found_media.add(msg) self.found_media.add(msg)
content = '<{}> {}'.format( # The media may or may not have a caption # The media may or may not have a caption
msg.media.__class__.__name__, caption = getattr(msg.media, 'caption', '')
getattr(msg.media, 'caption', '')) content = '<{}> {}'.format(
type(msg.media).__name__, caption)
elif hasattr(msg, 'message'): elif hasattr(msg, 'message'):
content = msg.message content = msg.message
elif hasattr(msg, 'action'): elif hasattr(msg, 'action'):
content = str(msg.action) content = str(msg.action)
else: else:
# Unknown message, simply print its class name # Unknown message, simply print its class name
content = msg.__class__.__name__ content = type(msg).__name__
# And print it to the user # And print it to the user
sprint('[{}:{}] (ID={}) {}: {}'.format( sprint('[{}:{}] (ID={}) {}: {}'.format(

View File

@ -1,8 +1,8 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import traceback import traceback
from telethon.interactive_telegram_client import (InteractiveTelegramClient, from telethon_examples.interactive_telegram_client \
print_title) import InteractiveTelegramClient
def load_settings(path='api/settings'): def load_settings(path='api/settings'):
@ -40,6 +40,5 @@ if __name__ == '__main__':
type(e), e, traceback.format_exc())) type(e), e, traceback.format_exc()))
finally: finally:
print_title('Exit')
print('Thanks for trying the interactive example! Exiting...')
client.disconnect() client.disconnect()
print('Thanks for trying the interactive example! Exiting...')