diff --git a/crypto/auth_key.py b/crypto/auth_key.py index da4827c6..d6d60edd 100755 --- a/crypto/auth_key.py +++ b/crypto/auth_key.py @@ -1,6 +1,5 @@ # This file is based on TLSharp # https://github.com/sochix/TLSharp/blob/master/TLSharp.Core/MTProto/Crypto/AuthKey.cs -from errors import * from utils import BinaryWriter, BinaryReader import utils diff --git a/errors.py b/errors.py index 5029b9f6..cdbe4017 100644 --- a/errors.py +++ b/errors.py @@ -1,6 +1,12 @@ import re +class TLGeneratorNotRan(Exception): + """Occurs when you should've ran `tl_generator.py`, but you haven't""" + def __init__(self): + super().__init__(self, 'You must run `python3 tl_generator.py` first. #ReadTheDocs!') + + class InvalidParameterError(Exception): """Occurs when an invalid parameter is given, for example, when either A or B are required but none is given""" diff --git a/main.py b/main.py index 08807323..b2a55694 100755 --- a/main.py +++ b/main.py @@ -1,4 +1,10 @@ import tl_generator +if not tl_generator.tlobjects_exist(): + import errors + raise errors.TLGeneratorNotRan() +else: + del tl_generator + from tl.telegram_client import TelegramClient from utils.helpers import load_settings @@ -6,74 +12,70 @@ from datetime import datetime if __name__ == '__main__': - if not tl_generator.tlobjects_exist(): - print('Please run `python3 tl_generator.py` first!') + print('Loading interactive example...') - else: - print('Loading interactive example...') + # First, initialize our TelegramClient and connect + settings = load_settings() + client = TelegramClient(session_user_id=settings.get('session_name', 'anonymous'), + layer=55, + api_id=settings['api_id'], + api_hash=settings['api_hash']) - # First, initialize our TelegramClient and connect - settings = load_settings() - client = TelegramClient(session_user_id=settings.get('session_name', 'anonymous'), - layer=55, - api_id=settings['api_id'], - api_hash=settings['api_hash']) + client.connect() + input('You should now be connected. Press enter when you are ready to continue.') - client.connect() - input('You should now be connected. Press enter when you are ready to continue.') + # Then, ensure we're authorized and have access + if not client.is_user_authorized(): + client.send_code_request(str(settings['user_phone'])) - # Then, ensure we're authorized and have access - if not client.is_user_authorized(): - client.send_code_request(str(settings['user_phone'])) + code = input('Enter the code you just received: ') + client.make_auth(settings['user_phone'], code) - code = input('Enter the code you just received: ') - client.make_auth(settings['user_phone'], code) + # Enter a while loop to chat as long as the user wants + while True: + # Retrieve the top dialogs + dialogs, displays, inputs = client.get_dialogs(8) - # Enter a while loop to chat as long as the user wants + # Display them so the user can choose + for i, display in enumerate(displays): + i += 1 # 1-based index for normies + print('{}. {}'.format(i, display)) + + # Let the user decide who they want to talk to + i = int(input('Who do you want to send messages to (0 to exit)?: ')) - 1 + if i == -1: + break + + # Retrieve the selected user + dialog = dialogs[i] + display = displays[i] + input_peer = inputs[i] + + # Show some information + print('You are now sending messages to "{}". Available commands:'.format(display)) + print(' !q: Quits the current chat.') + print(' !h: prints the latest messages (message History) of the chat.') + + # And start a while loop to chat while True: - # Retrieve the top dialogs - dialogs, displays, inputs = client.get_dialogs(8) - - # Display them so the user can choose - for i, display in enumerate(displays): - i += 1 # 1-based index for normies - print('{}. {}'.format(i, display)) - - # Let the user decide who they want to talk to - i = int(input('Who do you want to send messages to (0 to exit)?: ')) - 1 - if i == -1: + msg = input('Enter a message: ') + # Quit + if msg == '!q': break - # Retrieve the selected user - dialog = dialogs[i] - display = displays[i] - input_peer = inputs[i] + # History + elif msg == '!h': + # First retrieve the messages and some information + total_count, messages, senders = client.get_message_history(input_peer, 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 + for msg, sender in zip(reversed(messages), reversed(senders)): + name = sender.first_name if sender else '???' + date = datetime.fromtimestamp(msg.date) + print('[{}:{}] {}: {}'.format(date.hour, date.minute, name, msg.message)) - # Show some information - print('You are now sending messages to "{}". Available commands:'.format(display)) - print(' !q: Quits the current chat.') - print(' !h: prints the latest messages (message History) of the chat.') + # Send chat message + else: + client.send_message(input_peer, msg, markdown=True, no_web_page=True) - # And start a while loop to chat - while True: - msg = input('Enter a message: ') - # Quit - if msg == '!q': - break - - # History - elif msg == '!h': - # First retrieve the messages and some information - total_count, messages, senders = client.get_message_history(input_peer, 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 - for msg, sender in zip(reversed(messages), reversed(senders)): - name = sender.first_name if sender else '???' - date = datetime.fromtimestamp(msg.date) - print('[{}:{}] {}: {}'.format(date.hour, date.minute, name, msg.message)) - - # Send chat message - else: - client.send_message(input_peer, msg, markdown=True, no_web_page=True) - - print('Thanks for trying the interactive example! Exiting.') + print('Thanks for trying the interactive example! Exiting.') diff --git a/parser/__init__.py b/parser/__init__.py index d29930ed..6fa3c3ac 100755 --- a/parser/__init__.py +++ b/parser/__init__.py @@ -1,2 +1,3 @@ from .source_builder import SourceBuilder -from .tl_parser import TLParser, TLObject +from .tl_parser import TLParser +from .tlobject import TLObject diff --git a/parser/tl_parser.py b/parser/tl_parser.py index 694a0d92..a23b1117 100755 --- a/parser/tl_parser.py +++ b/parser/tl_parser.py @@ -1,5 +1,6 @@ import re -from tl import TLObject + +from parser.tlobject import TLObject class TLParser: diff --git a/tl/tlobject.py b/parser/tlobject.py similarity index 98% rename from tl/tlobject.py rename to parser/tlobject.py index adf9e7f1..970bb1cd 100755 --- a/tl/tlobject.py +++ b/parser/tlobject.py @@ -91,7 +91,7 @@ class TLObject: # Some arguments are not valid for being represented, such as the flag indicator or generic definition # (these have no explicit values until used) valid_args = [arg for arg in self.args - if not arg.flag_indicator and not arg.generic_definition] + if not arg.flag_indicator and not arg.generic_definition] args = ', '.join(['{}={{}}'.format(arg.name) for arg in valid_args]) @@ -104,8 +104,6 @@ class TLObject: .format(fullname, hex(self.id), args, args_format)) - - class TLArg: def __init__(self, name, type, generic_definition): """ diff --git a/tl/__init__.py b/tl/__init__.py index 43bf14fb..0cd67cc1 100755 --- a/tl/__init__.py +++ b/tl/__init__.py @@ -1,14 +1,9 @@ -import os -# Only import most stuff if the TLObjects were generated and there were no errors -if os.path.isfile('tl/all_tlobjects.py'): - try: - from .all_tlobjects import tlobjects - from .session import Session - from .mtproto_request import MTProtoRequest - from .telegram_client import TelegramClient - except Exception: - print('Please fix `tl_generator.py` and run it again') -else: - print('Please run `python3 tl_generator.py` first') -del os -from .tlobject import TLObject, TLArg +try: + from .all_tlobjects import tlobjects + from .session import Session + from .mtproto_request import MTProtoRequest + from .telegram_client import TelegramClient + +except ImportError: + import errors + raise errors.TLGeneratorNotRan() diff --git a/tl/telegram_client.py b/tl/telegram_client.py index e5a721eb..241eddc3 100644 --- a/tl/telegram_client.py +++ b/tl/telegram_client.py @@ -1,12 +1,13 @@ # This file structure is based on TLSharp # https://github.com/sochix/TLSharp/blob/master/TLSharp.Core/TelegramClient.cs import platform -from parser.markdown_parser import parse_message_entities import utils import network.authenticator -from network import MtProtoSender, TcpTransport + from errors import * +from network import MtProtoSender, TcpTransport +from parser.markdown_parser import parse_message_entities from tl import Session from tl.types import PeerUser, PeerChat, PeerChannel, InputPeerUser, InputPeerChat, InputPeerChannel, InputPeerEmpty diff --git a/tl_generator.py b/tl_generator.py index cb3dad9e..bbaa2177 100755 --- a/tl_generator.py +++ b/tl_generator.py @@ -2,8 +2,7 @@ import os import re import shutil -from parser.tl_parser import TLParser -from parser.source_builder import SourceBuilder +from parser import SourceBuilder, TLParser def tlobjects_exist():