Allow passing entities instead input_peers and more*

Some fixes to the interactive client (not handling
invalid options, errors when uploading files)
This commit is contained in:
Lonami Exo 2017-01-17 20:22:47 +01:00
parent 8e48455cdc
commit 9ca4471bcd
3 changed files with 36 additions and 32 deletions

View File

@ -3,7 +3,7 @@ from getpass import getpass
from telethon import RPCError, TelegramClient
from telethon.tl.types import UpdateShortChatMessage, UpdateShortMessage
from telethon.utils import get_display_name, get_input_peer
from telethon.utils import get_display_name
# Get the (current) number of lines in the terminal
cols, rows = shutil.get_terminal_size()
@ -106,11 +106,10 @@ class InteractiveTelegramClient(TelegramClient):
i = None
except ValueError:
pass
i = None
# Retrieve the selected user (or chat, or channel)
entity = entities[i]
input_peer = get_input_peer(entity)
# Show some information
print_title('Chat with "{}"'.format(get_display_name(entity)))
@ -141,7 +140,7 @@ class InteractiveTelegramClient(TelegramClient):
elif msg == '!h':
# First retrieve the messages and some information
total_count, messages, senders = self.get_message_history(
input_peer, 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
for msg, sender in zip(
@ -166,17 +165,17 @@ class InteractiveTelegramClient(TelegramClient):
# Send photo
elif msg.startswith('!up '):
# Slice the message to get the path
self.send_photo(path=msg[len('!p '):], peer=input_peer)
self.send_photo(path=msg[len('!up '):], entity=entity)
# Send file (document)
elif msg.startswith('!uf '):
# Slice the message to get the path
self.send_document(path=msg[len('!f '):], peer=input_peer)
self.send_document(path=msg[len('!uf '):], entity=entity)
# Download media
elif msg.startswith('!dm '):
# Slice the message to get message ID
self.download_media(msg[len('!d '):])
self.download_media(msg[len('!dm '):])
# Download profile photo
elif msg == '!dp':
@ -193,24 +192,24 @@ class InteractiveTelegramClient(TelegramClient):
# Send chat message (if any)
elif msg:
self.send_message(
input_peer, msg, markdown=True, no_web_page=True)
entity, msg, markdown=True, no_web_page=True)
def send_photo(self, path, peer):
def send_photo(self, path, entity):
print('Uploading {}...'.format(path))
input_file = self.upload_file(
path, progress_callback=self.upload_progress_callback)
# After we have the handle to the uploaded file, send it to our peer
self.send_photo_file(input_file, peer)
self.send_photo_file(input_file, entity)
print('Photo sent!')
def send_document(self, path, peer):
def send_document(self, path, entity):
print('Uploading {}...'.format(path))
input_file = self.upload_file(
path, progress_callback=self.upload_progress_callback)
# After we have the handle to the uploaded file, send it to our peer
self.send_document_file(input_file, peer)
self.send_document_file(input_file, entity)
print('Document sent!')
def download_media(self, media_id):

View File

@ -33,8 +33,8 @@ from telethon.tl.types import (
InputMediaUploadedDocument, InputMediaUploadedPhoto, InputPeerEmpty,
MessageMediaContact, MessageMediaDocument, MessageMediaPhoto,
UserProfilePhotoEmpty)
from telethon.utils import (find_user_or_chat, get_appropiate_part_size,
get_extension)
from telethon.utils import (find_user_or_chat, get_input_peer,
get_appropiate_part_size, get_extension)
class TelegramClient:
@ -282,11 +282,11 @@ class TelegramClient:
# region Message requests
def send_message(self,
input_peer,
entity,
message,
markdown=False,
no_web_page=False):
"""Sends a message to the given input peer and returns the sent message ID"""
"""Sends a message to the given entity (or input peer) and returns the sent message ID"""
if markdown:
msg, entities = parse_message_entities(message)
else:
@ -295,7 +295,7 @@ class TelegramClient:
msg_id = utils.generate_random_long()
self.invoke(
SendMessageRequest(
peer=input_peer,
peer=get_input_peer(entity),
message=msg,
random_id=msg_id,
entities=entities,
@ -303,7 +303,7 @@ class TelegramClient:
return msg_id
def get_message_history(self,
input_peer,
entity,
limit=20,
offset_date=None,
offset_id=0,
@ -311,9 +311,9 @@ class TelegramClient:
min_id=0,
add_offset=0):
"""
Gets the message history for the specified InputPeer
Gets the message history for the specified entity
:param input_peer: The InputPeer from whom to retrieve the message history
:param entity: The entity (or input peer) from whom to retrieve the message history
:param limit: Number of messages to be retrieved
:param offset_date: Offset date (messages *previous* to this date will be retrieved)
:param offset_id: Offset message ID (only messages *previous* to the given ID will be retrieved)
@ -326,7 +326,7 @@ class TelegramClient:
"""
result = self.invoke(
GetHistoryRequest(
input_peer,
get_input_peer(entity),
limit=limit,
offset_date=offset_date,
offset_id=offset_id,
@ -349,7 +349,7 @@ class TelegramClient:
return total_messages, result.messages, users
def send_read_acknowledge(self, input_peer, messages=None, max_id=None):
def send_read_acknowledge(self, entity, messages=None, max_id=None):
"""Sends a "read acknowledge" (i.e., notifying the given peer that we've
read their messages, also known as the "double check ✅✅").
@ -367,7 +367,7 @@ class TelegramClient:
else:
max_id = messages.id
return self.invoke(ReadHistoryRequest(peer=input_peer, max_id=max_id))
return self.invoke(ReadHistoryRequest(peer=get_input_peer(entity), max_id=max_id))
# endregion
@ -445,15 +445,15 @@ class TelegramClient:
name=file_name,
md5_checksum=hash_md5.hexdigest())
def send_photo_file(self, input_file, input_peer, caption=''):
def send_photo_file(self, input_file, entity, caption=''):
"""Sends a previously uploaded input_file
(which should be a photo) to an input_peer"""
(which should be a photo) to the given entity (or input peer)"""
self.send_media_file(
InputMediaUploadedPhoto(input_file, caption), input_peer)
InputMediaUploadedPhoto(input_file, caption), entity)
def send_document_file(self, input_file, input_peer, caption=''):
def send_document_file(self, input_file, entity, caption=''):
"""Sends a previously uploaded input_file
(which should be a document) to an input_peer"""
(which should be a document) to the given entity (or input peer)"""
# Determine mime-type and attributes
# Take the first element by using [0] since it returns a tuple
@ -473,13 +473,13 @@ class TelegramClient:
mime_type=mime_type,
attributes=attributes,
caption=caption),
input_peer)
entity)
def send_media_file(self, input_media, input_peer):
"""Sends any input_media (contact, document, photo...) to an input_peer"""
def send_media_file(self, input_media, entity):
"""Sends any input_media (contact, document, photo...) to the given entiy"""
self.invoke(
SendMediaRequest(
peer=input_peer,
peer=get_input_peer(entity),
media=input_media,
random_id=utils.generate_random_long()))

View File

@ -44,6 +44,11 @@ def get_extension(media):
def get_input_peer(entity):
"""Gets the input peer for the given "entity" (user, chat or channel).
Returns None if it was not found"""
if (isinstance(entity, InputPeerUser) or
isinstance(entity, InputPeerChat) or
isinstance(entity, InputPeerChannel)):
return entity
if isinstance(entity, User):
return InputPeerUser(entity.id, entity.access_hash)
if isinstance(entity, Chat):