Attempt at removing cyclic dependencies

This commit is contained in:
Lonami 2016-09-08 16:55:46 +02:00
parent b2425eeea9
commit e9e44795ec
9 changed files with 86 additions and 84 deletions

View File

@ -1,6 +1,5 @@
# This file is based on TLSharp # This file is based on TLSharp
# https://github.com/sochix/TLSharp/blob/master/TLSharp.Core/MTProto/Crypto/AuthKey.cs # https://github.com/sochix/TLSharp/blob/master/TLSharp.Core/MTProto/Crypto/AuthKey.cs
from errors import *
from utils import BinaryWriter, BinaryReader from utils import BinaryWriter, BinaryReader
import utils import utils

View File

@ -1,6 +1,12 @@
import re 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): class InvalidParameterError(Exception):
"""Occurs when an invalid parameter is given, for example, """Occurs when an invalid parameter is given, for example,
when either A or B are required but none is given""" when either A or B are required but none is given"""

122
main.py
View File

@ -1,4 +1,10 @@
import tl_generator 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 tl.telegram_client import TelegramClient
from utils.helpers import load_settings from utils.helpers import load_settings
@ -6,74 +12,70 @@ from datetime import datetime
if __name__ == '__main__': if __name__ == '__main__':
if not tl_generator.tlobjects_exist(): print('Loading interactive example...')
print('Please run `python3 tl_generator.py` first!')
else: # First, initialize our TelegramClient and connect
print('Loading interactive example...') 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 client.connect()
settings = load_settings() input('You should now be connected. Press enter when you are ready to continue.')
client = TelegramClient(session_user_id=settings.get('session_name', 'anonymous'),
layer=55,
api_id=settings['api_id'],
api_hash=settings['api_hash'])
client.connect() # Then, ensure we're authorized and have access
input('You should now be connected. Press enter when you are ready to continue.') if not client.is_user_authorized():
client.send_code_request(str(settings['user_phone']))
# Then, ensure we're authorized and have access code = input('Enter the code you just received: ')
if not client.is_user_authorized(): client.make_auth(settings['user_phone'], code)
client.send_code_request(str(settings['user_phone']))
code = input('Enter the code you just received: ') # Enter a while loop to chat as long as the user wants
client.make_auth(settings['user_phone'], code) 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: while True:
# Retrieve the top dialogs msg = input('Enter a message: ')
dialogs, displays, inputs = client.get_dialogs(8) # Quit
if msg == '!q':
# 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 break
# Retrieve the selected user # History
dialog = dialogs[i] elif msg == '!h':
display = displays[i] # First retrieve the messages and some information
input_peer = inputs[i] 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 # Send chat message
print('You are now sending messages to "{}". Available commands:'.format(display)) else:
print(' !q: Quits the current chat.') client.send_message(input_peer, msg, markdown=True, no_web_page=True)
print(' !h: prints the latest messages (message History) of the chat.')
# And start a while loop to chat print('Thanks for trying the interactive example! Exiting.')
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.')

View File

@ -1,2 +1,3 @@
from .source_builder import SourceBuilder from .source_builder import SourceBuilder
from .tl_parser import TLParser, TLObject from .tl_parser import TLParser
from .tlobject import TLObject

View File

@ -1,5 +1,6 @@
import re import re
from tl import TLObject
from parser.tlobject import TLObject
class TLParser: class TLParser:

View File

@ -91,7 +91,7 @@ class TLObject:
# Some arguments are not valid for being represented, such as the flag indicator or generic definition # Some arguments are not valid for being represented, such as the flag indicator or generic definition
# (these have no explicit values until used) # (these have no explicit values until used)
valid_args = [arg for arg in self.args 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]) args = ', '.join(['{}={{}}'.format(arg.name) for arg in valid_args])
@ -104,8 +104,6 @@ class TLObject:
.format(fullname, hex(self.id), args, args_format)) .format(fullname, hex(self.id), args, args_format))
class TLArg: class TLArg:
def __init__(self, name, type, generic_definition): def __init__(self, name, type, generic_definition):
""" """

View File

@ -1,14 +1,9 @@
import os try:
# Only import most stuff if the TLObjects were generated and there were no errors from .all_tlobjects import tlobjects
if os.path.isfile('tl/all_tlobjects.py'): from .session import Session
try: from .mtproto_request import MTProtoRequest
from .all_tlobjects import tlobjects from .telegram_client import TelegramClient
from .session import Session
from .mtproto_request import MTProtoRequest except ImportError:
from .telegram_client import TelegramClient import errors
except Exception: raise errors.TLGeneratorNotRan()
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

View File

@ -1,12 +1,13 @@
# This file structure is based on TLSharp # This file structure is based on TLSharp
# https://github.com/sochix/TLSharp/blob/master/TLSharp.Core/TelegramClient.cs # https://github.com/sochix/TLSharp/blob/master/TLSharp.Core/TelegramClient.cs
import platform import platform
from parser.markdown_parser import parse_message_entities
import utils import utils
import network.authenticator import network.authenticator
from network import MtProtoSender, TcpTransport
from errors import * from errors import *
from network import MtProtoSender, TcpTransport
from parser.markdown_parser import parse_message_entities
from tl import Session from tl import Session
from tl.types import PeerUser, PeerChat, PeerChannel, InputPeerUser, InputPeerChat, InputPeerChannel, InputPeerEmpty from tl.types import PeerUser, PeerChat, PeerChannel, InputPeerUser, InputPeerChat, InputPeerChannel, InputPeerEmpty

View File

@ -2,8 +2,7 @@ import os
import re import re
import shutil import shutil
from parser.tl_parser import TLParser from parser import SourceBuilder, TLParser
from parser.source_builder import SourceBuilder
def tlobjects_exist(): def tlobjects_exist():