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
# https://github.com/sochix/TLSharp/blob/master/TLSharp.Core/MTProto/Crypto/AuthKey.cs
from errors import *
from utils import BinaryWriter, BinaryReader
import utils

View File

@ -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"""

122
main.py
View File

@ -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.')

View File

@ -1,2 +1,3 @@
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
from tl import TLObject
from parser.tlobject import TLObject
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
# (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):
"""

View File

@ -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()

View File

@ -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

View File

@ -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():