Update old interactive example (#546)

This commit is contained in:
Lonami Exo 2018-01-16 18:36:50 +01:00
parent 49f204c955
commit fde0d60f72
2 changed files with 27 additions and 39 deletions

View File

@ -728,7 +728,6 @@ class TelegramClient(TelegramBareClient):
# Add a few extra attributes to the Message to make it friendlier. # Add a few extra attributes to the Message to make it friendlier.
messages.total = total_messages messages.total = total_messages
for m in messages: for m in messages:
# TODO Better way to return a total without tuples?
m.sender = (None if not m.from_id else m.sender = (None if not m.from_id else
entities[utils.get_peer_id(m.from_id)]) entities[utils.get_peer_id(m.from_id)])

View File

@ -84,9 +84,9 @@ class InteractiveTelegramClient(TelegramClient):
update_workers=1 update_workers=1
) )
# Store all the found media in memory here, # Store {message.id: message} map here so that we can download
# so it can be downloaded if the user wants # media known the message ID, for every message having media.
self.found_media = set() self.found_media = {}
# Calling .connect() may return False, so you need to assert it's # Calling .connect() may return False, so you need to assert it's
# True before continuing. Otherwise you may want to retry as done here. # True before continuing. Otherwise you may want to retry as done here.
@ -204,27 +204,21 @@ class InteractiveTelegramClient(TelegramClient):
# History # History
elif msg == '!h': elif msg == '!h':
# First retrieve the messages and some information # First retrieve the messages and some information
total_count, messages, senders = \ messages = self.get_message_history(entity, limit=10)
self.get_message_history(entity, limit=10)
# Iterate over all (in reverse order so the latest appear # Iterate over all (in reverse order so the latest appear
# the last in the console) and print them with format: # the last in the console) and print them with format:
# "[hh:mm] Sender: Message" # "[hh:mm] Sender: Message"
for msg, sender in zip( for msg in reversed(messages):
reversed(messages), reversed(senders)): # Note that the .sender attribute is only there for
# Get the name of the sender if any # convenience, the API returns it differently. But
if sender: # this shouldn't concern us. See the documentation
name = getattr(sender, 'first_name', None) # for .get_message_history() for more information.
if not name: name = get_display_name(msg.sender)
name = getattr(sender, 'title')
if not name:
name = '???'
else:
name = '???'
# Format the message content # Format the message content
if getattr(msg, 'media', None): if getattr(msg, 'media', None):
self.found_media.add(msg) self.found_media[msg.id] = msg
# The media may or may not have a caption # The media may or may not have a caption
caption = getattr(msg.media, 'caption', '') caption = getattr(msg.media, 'caption', '')
content = '<{}> {}'.format( content = '<{}> {}'.format(
@ -257,8 +251,7 @@ class InteractiveTelegramClient(TelegramClient):
elif msg.startswith('!d '): elif msg.startswith('!d '):
# Slice the message to get message ID # Slice the message to get message ID
deleted_msg = self.delete_messages(entity, msg[len('!d '):]) deleted_msg = self.delete_messages(entity, msg[len('!d '):])
print('Deleted. {}'.format(deleted_msg)) print('Deleted {}'.format(deleted_msg))
# Download media # Download media
elif msg.startswith('!dm '): elif msg.startswith('!dm '):
@ -275,12 +268,11 @@ class InteractiveTelegramClient(TelegramClient):
'Profile picture downloaded to {}'.format(output) 'Profile picture downloaded to {}'.format(output)
) )
else: else:
print('No profile picture found for this user.') print('No profile picture found for this user!')
# Send chat message (if any) # Send chat message (if any)
elif msg: elif msg:
self.send_message( self.send_message(entity, msg, link_preview=False)
entity, msg, link_preview=False)
def send_photo(self, path, entity): def send_photo(self, path, entity):
"""Sends the file located at path to the desired entity as a photo""" """Sends the file located at path to the desired entity as a photo"""
@ -304,23 +296,20 @@ class InteractiveTelegramClient(TelegramClient):
downloads it. downloads it.
""" """
try: try:
# The user may have entered a non-integer string! msg = self.found_media[int(media_id)]
msg_media_id = int(media_id) except (ValueError, KeyError):
# ValueError when parsing, KeyError when accessing dictionary
print('Invalid media ID given or message not found!')
return
# Search the message ID print('Downloading media to usermedia/...')
for msg in self.found_media: os.makedirs('usermedia', exist_ok=True)
if msg.id == msg_media_id: output = self.download_media(
print('Downloading media to usermedia/...') msg.media,
os.makedirs('usermedia', exist_ok=True) file='usermedia/',
output = self.download_media( progress_callback=self.download_progress_callback
msg.media, )
file='usermedia/', print('Media downloaded to {}!'.format(output))
progress_callback=self.download_progress_callback
)
print('Media downloaded to {}!'.format(output))
except ValueError:
print('Invalid media ID given!')
@staticmethod @staticmethod
def download_progress_callback(downloaded_bytes, total_bytes): def download_progress_callback(downloaded_bytes, total_bytes):