Added ability to both log-out and sign-up

This commit is contained in:
Lonami 2016-09-16 13:35:14 +02:00
parent 9420e15283
commit 6ee93122f2
3 changed files with 52 additions and 10 deletions

View File

@ -49,7 +49,7 @@ class InteractiveTelegramClient(TelegramClient):
code_ok = False code_ok = False
while not code_ok: while not code_ok:
code = input('Enter the code you just received: ') code = input('Enter the code you just received: ')
code_ok = self.make_auth(user_phone, code) code_ok = self.sign_in(user_phone, code)
def run(self): def run(self):
# Listen for updates # Listen for updates
@ -72,9 +72,18 @@ class InteractiveTelegramClient(TelegramClient):
print('{}. {}'.format(i, display)) print('{}. {}'.format(i, display))
# Let the user decide who they want to talk to # Let the user decide who they want to talk to
i = input('Who do you want to send messages to ("!q" to exit)?: ') print()
print('> Who do you want to send messages to?')
print('> Available commands:')
print(' !q: Quits the dialogs window and exits.')
print(' !l: Logs out, terminating this session.')
print()
i = input('Enter dialog ID or a command: ')
if i == '!q': if i == '!q':
return return
if i == '!l':
self.log_out()
return
i = int(i if i else 0) - 1 i = int(i if i else 0) - 1
# Ensure it is inside the bounds, otherwise set to None and retry # Ensure it is inside the bounds, otherwise set to None and retry
@ -90,13 +99,14 @@ class InteractiveTelegramClient(TelegramClient):
# Show some information # Show some information
print_title('Chat with "{}"'.format(display)) print_title('Chat with "{}"'.format(display))
print('Available commands:'.format(display)) 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(' !h: prints the latest messages (message History) of the chat.') print(' !h: prints the latest messages (message History) of the chat.')
print(' !p <path>: sends a Photo located at the given path.') print(' !p <path>: sends a Photo located at the given path.')
print(' !f <path>: sends a File document located at the given path.') print(' !f <path>: sends a File document located at the given path.')
print(' !d <msg-id>: Downloads the given message media (if any).') print(' !d <msg-id>: Downloads the given message media (if any).')
print()
# And start a while loop to chat # And start a while loop to chat
while True: while True:

View File

@ -25,7 +25,7 @@ from tl.types import \
from tl.functions import InvokeWithLayerRequest, InitConnectionRequest from tl.functions import InvokeWithLayerRequest, InitConnectionRequest
from tl.functions.help import GetConfigRequest from tl.functions.help import GetConfigRequest
from tl.functions.auth import SendCodeRequest, SignInRequest from tl.functions.auth import SendCodeRequest, SignInRequest, SignUpRequest, LogOutRequest
from tl.functions.upload import SaveFilePartRequest, GetFileRequest from tl.functions.upload import SaveFilePartRequest, GetFileRequest
from tl.functions.messages import GetDialogsRequest, GetHistoryRequest, SendMessageRequest, SendMediaRequest from tl.functions.messages import GetDialogsRequest, GetHistoryRequest, SendMessageRequest, SendMediaRequest
@ -141,15 +141,15 @@ class TelegramClient:
except InvalidDCError as error: except InvalidDCError as error:
self.reconnect_to_dc(error.new_dc) self.reconnect_to_dc(error.new_dc)
def make_auth(self, phone_number, code): def sign_in(self, phone_number, code):
"""Completes the authorization of a phone number by providing the received code""" """Completes the authorization of a phone number by providing the received code"""
if phone_number not in self.phone_code_hashes: if phone_number not in self.phone_code_hashes:
raise ValueError('Please make sure you have called send_code_request first.') raise ValueError('Please make sure you have called send_code_request first.')
try: try:
request = SignInRequest(phone_number, self.phone_code_hashes[phone_number], code) result = self.invoke(SignInRequest(
self.sender.send(request) phone_number, self.phone_code_hashes[phone_number], code))
self.sender.receive(request)
except RPCError as error: except RPCError as error:
if error.message.startswith('PHONE_CODE_'): if error.message.startswith('PHONE_CODE_'):
print(error) print(error)
@ -158,14 +158,37 @@ class TelegramClient:
raise error raise error
# Result is an Auth.Authorization TLObject # Result is an Auth.Authorization TLObject
self.session.user = request.result.user self.session.user = result.user
self.session.save() self.session.save()
# Now that we're authorized, we can listen for incoming updates # Now that we're authorized, we can listen for incoming updates
self.sender.set_listen_for_updates(True) self.sender.set_listen_for_updates(True)
return True return True
def sign_up(self, phone_number, code, first_name, last_name=''):
"""Signs up to Telegram. Make sure you sent a code request first!"""
result = self.invoke(SignUpRequest(phone_number=phone_number,
phone_code_hash=self.phone_code_hashes[phone_number],
phone_code=code,
first_name=first_name,
last_name=last_name))
self.session.user = result.user
self.session.save()
def log_out(self):
"""Logs out and deletes the current session. Returns True if everything went OK"""
try:
# This request is a bit special. Nothing is received after
self.sender.send(LogOutRequest())
if not self.session.delete():
return False
self.session = None
except:
return False
# endregion # endregion
# region Dialogs ("chats") requests # region Dialogs ("chats") requests

View File

@ -1,4 +1,5 @@
from os.path import isfile as file_exists from os.path import isfile as file_exists
import os
import time import time
import pickle import pickle
import utils import utils
@ -24,6 +25,14 @@ class Session:
with open('{}.session'.format(self.session_user_id), 'wb') as file: with open('{}.session'.format(self.session_user_id), 'wb') as file:
pickle.dump(self, file) pickle.dump(self, file)
def delete(self):
"""Deletes the current session file"""
try:
os.remove('{}.session'.format(self.session_user_id))
return True
except:
return False
@staticmethod @staticmethod
def try_load_or_create_new(session_user_id): def try_load_or_create_new(session_user_id):
"""Loads a saved session_user_id session, or creates a new one if none existed before. """Loads a saved session_user_id session, or creates a new one if none existed before.