Python telethon.tl.types.Message() Examples
The following are 14
code examples of telethon.tl.types.Message().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
telethon.tl.types
, or try the search function
.
Example #1
Source File: backend.py From friendly-telegram with GNU Affero General Public License v3.0 | 7 votes |
def _do_ops(self, ops): try: for r in await asyncio.gather(*ops, return_exceptions=True): if isinstance(r, MessageNotModifiedError): logging.debug("db not modified", exc_info=r) elif isinstance(r, Exception): raise r # Makes more sense to raise even for MessageEditTimeExpiredError elif not isinstance(r, Message): logging.debug("unknown ret from gather, %r", r) except MessageEditTimeExpiredError: logging.debug("Making new channel.") _db = self.db self.db = None await self._client(DeleteChannelRequest(channel=_db)) return True return False
Example #2
Source File: telegram.py From message-analyser with MIT License | 7 votes |
def _retrieve_messages(client, target_entity, num): """Retrieves messages from client's target_entity batch by batch and return them all.""" batch_size = min(3000, num) msgs = [] batch = await client.get_messages(target_entity, limit=batch_size) while len(batch) and len(msgs) < num: offset_id = batch[-1].id msgs.extend([msg for msg in batch if isinstance(msg, Message)]) try: batch = await client.get_messages(target_entity, limit=min(batch_size, num - len(msgs)), offset_id=offset_id) except ConnectionError: log_line("Internet connection was lost.") raise if not len(batch): log_line(f"{len(msgs[:num])} (100%) messages received.") else: log_line(f"{len(msgs[:num])} ({len(msgs[:num])/batch.total*100:.2f}%) messages received.") return msgs[:num][::-1]
Example #3
Source File: client.py From telegram-upload with MIT License | 6 votes |
def download_files(self, entity, messages: Iterable[Message], delete_on_success: bool = False): messages = reversed(list(messages)) for message in messages: filename_attr = next(filter(lambda x: isinstance(x, DocumentAttributeFilename), message.document.attributes), None) filename = filename_attr.file_name if filename_attr else 'Unknown' if message.document.size > free_disk_usage(): raise TelegramUploadNoSpaceError( 'There is no disk space to download "{}". Space required: {}'.format( filename, sizeof_fmt(message.document.size - free_disk_usage()) ) ) progress = get_progress_bar('Downloading', filename, message.document.size) self.download_media(message, progress_callback=progress) if delete_on_success: self.delete_messages(entity, [message]) print()
Example #4
Source File: stickers.py From TG-UserBot with GNU General Public License v3.0 | 6 votes |
def _list_packs() -> Tuple[List[str], types.Message]: async with client.conversation(**conversation_args) as conv: first = await conv.send_message('/cancel') r1 = await conv.get_response() LOGGER.debug("Stickers:" + r1.text) await client.send_read_acknowledge(conv.chat_id) await conv.send_message('/packstats') r2 = await conv.get_response() LOGGER.debug("Stickers:" + r2.text) if r2.text.startswith("You don't have any sticker packs yet."): return [], first await client.send_read_acknowledge(conv.chat_id) buttons = list(itertools.chain.from_iterable(r2.buttons or [])) await conv.send_message('/cancel') r3 = await conv.get_response() LOGGER.debug("Stickers:" + r3.text) await client.send_read_acknowledge(conv.chat_id) return [button.text for button in buttons] if buttons else [], first
Example #5
Source File: backend.py From friendly-telegram with GNU Affero General Public License v3.0 | 5 votes |
def do_download(self): """Attempt to download the database. Return the database (as unparsed JSON) or None""" if not self.db: self.db = await self._find_data_channel() if not self.db: logging.debug("No DB, returning") return None self._client.add_event_handler(self._callback, telethon.events.messageedited.MessageEdited(chats=[self.db])) msgs = self._client.iter_messages( entity=self.db, reverse=True ) data = "" lastdata = "" async for msg in msgs: if isinstance(msg, Message): logger.debug(f"Found text message {msg}") data += lastdata lastdata = msg.message else: logger.debug(f"Found service message {msg}") logger.debug(f"Database contains {data}") return data
Example #6
Source File: backend.py From friendly-telegram with GNU Affero General Public License v3.0 | 5 votes |
def do_upload(self, data): """Attempt to upload the database. Return True or throw""" if not self.db: self.db = await self._find_data_channel() if not self.db: self.db = await self._make_data_channel() self._client.add_event_handler(self._callback, telethon.events.messageedited.MessageEdited(chats=[self.db])) msgs = await self._client.get_messages( entity=self.db, reverse=True ) ops = [] sdata = data newmsg = False for msg in msgs: logger.debug(msg) if isinstance(msg, Message): if len(sdata): logging.debug("editing message " + msg.stringify() + " last is " + msgs[-1].stringify()) if msg.id == msgs[-1].id: newmsg = True if sdata[:4096] != msg.message: ops += [msg.edit("<code>" + utils.escape_html(sdata[:4096]) + "</code>")] sdata = sdata[4096:] else: logging.debug("maybe deleting message") if not msg.id == msgs[-1].id: ops += [msg.delete()] if await self._do_ops(ops): return await self.do_upload(data) while len(sdata): # Only happens if newmsg is True or there was no message before newmsg = True await self._client.send_message(self.db, utils.escape_html(sdata[:4096])) sdata = sdata[4096:] if newmsg: await self._client.send_message(self.db, "Please ignore this chat.") return True
Example #7
Source File: tests.py From telegram-export with Mozilla Public License 2.0 | 5 votes |
def test_dump_msg_entities(self): """Show that entities are correctly parsed and stored""" message = types.Message( id=1, to_id=types.PeerUser(321), date=datetime.now(), message='No entities' ) dumper = Dumper(self.dumper_config) fmt = BaseFormatter(dumper.conn) # Test with no entities dumper.dump_message(message, 123, None, None) dumper.commit() assert not next(fmt.get_messages_from_context(123, order='DESC')).formatting # Test with many entities text, entities = markdown.parse( 'Testing message with __italic__, **bold**, inline ' '[links](https://example.com) and [mentions](@hi), ' 'as well as `code` and ``pre`` blocks.' ) entities[3] = types.MessageEntityMentionName( entities[3].offset, entities[3].length, 123 ) message.id = 2 message.date -= timedelta(days=1) message.message = text message.entities = entities dumper.dump_message(message, 123, None, None) dumper.commit() msg = next(fmt.get_messages_from_context(123, order='ASC')) assert utils.decode_msg_entities(msg.formatting) == message.entities
Example #8
Source File: downloader.py From telegram-export with Mozilla Public License 2.0 | 5 votes |
def _dump_messages(self, messages, target): """ Helper method to iterate the messages from a GetMessageHistoryRequest and dump them into the Dumper, mostly to avoid excessive nesting. Also enqueues any media to be downloaded later by a different coroutine. """ for m in messages: if isinstance(m, types.Message): media_id = self.dumper.dump_media(m.media) if media_id and self._check_media(m.media): self.enqueue_media( media_id, utils.get_peer_id(target), m.from_id, m.date ) self.dumper.dump_message( message=m, context_id=utils.get_peer_id(target), forward_id=self.dumper.dump_forward(m.fwd_from), media_id=media_id ) elif isinstance(m, types.MessageService): if isinstance(m.action, types.MessageActionChatEditPhoto): media_id = self.dumper.dump_media(m.action.photo) self.enqueue_photo(m.action.photo, media_id, target, peer_id=m.from_id, date=m.date) else: media_id = None self.dumper.dump_message_service( message=m, context_id=utils.get_peer_id(target), media_id=media_id )
Example #9
Source File: downloader.py From telegram-export with Mozilla Public License 2.0 | 5 votes |
def download_past_media(self, dumper, target_id): """ Downloads the past media that has already been dumped into the database but has not been downloaded for the given target ID yet. Media which formatted filename results in an already-existing file will be *ignored* and not re-downloaded again. """ # TODO Should this respect and download only allowed media? Or all? target_in = await self.client.get_input_entity(target_id) target = await self.client.get_entity(target_in) target_id = utils.get_peer_id(target) bar = tqdm.tqdm(unit='B', desc='media', unit_divisor=1000, unit_scale=True, bar_format=BAR_FORMAT, total=0, postfix={'chat': utils.get_display_name(target)}) msg_cursor = dumper.conn.cursor() msg_cursor.execute('SELECT ID, Date, FromID, MediaID FROM Message ' 'WHERE ContextID = ? AND MediaID IS NOT NULL', (target_id,)) msg_row = msg_cursor.fetchone() while msg_row: await self._download_media( media_id=msg_row[3], context_id=target_id, sender_id=msg_row[2], date=datetime.datetime.utcfromtimestamp(msg_row[1]), bar=bar ) msg_row = msg_cursor.fetchone()
Example #10
Source File: telegram.py From message-analyser with MIT License | 5 votes |
def _telethon_msg_to_mymessage(msg, target_id, your_name, target_name): """Transforms telethon.tl.types.Message obj to MyMessage obj. Notes: An emoji representation of a sticker adds up to the message's text. Args: msg (telethon.tl.types.Message): A message. target_id (int): Target's dialogue id. your_name (str): Your name. target_name (str): Target's name. Returns: MyMessage obj. """ return MyMessage(msg.message + (msg.sticker.attributes[1].alt if msg.sticker is not None else ''), msg.date.replace(tzinfo=None) + relativedelta(hours=time_offset(msg.date)), target_name if msg.from_id == target_id else your_name, is_forwarded=msg.forward is not None, document_id=msg.document.id if msg.document is not None else None, has_sticker=msg.sticker is not None, has_video=msg.video is not None, has_voice=(msg.voice is not None and msg.document.mime_type == "audio/ogg"), has_audio=(msg.audio is not None and msg.document.mime_type != "audio/ogg"), # let audio != voice has_photo=msg.photo is not None)
Example #11
Source File: custom.py From TG-UserBot with GNU General Public License v3.0 | 5 votes |
def _self_destructor( event: typing.Union[custom.Message, typing.Sequence[custom.Message]], timeout: int or float ) -> typing.Union[custom.Message, typing.Sequence[custom.Message]]: await asyncio.sleep(timeout) if isinstance(event, list): deleted = [] for e in event: deleted.append(await e.delete()) else: deleted = await event.delete() return deleted
Example #12
Source File: stickers.py From TG-UserBot with GNU General Public License v3.0 | 5 votes |
def _delete_sticker_messages( message: types.Message ) -> Sequence[types.messages.AffectedMessages]: messages = [message] async for msg in client.iter_messages( entity="@Stickers", offset_id=message.id, reverse=True ): messages.append(msg) return await client.delete_messages('@Stickers', messages)
Example #13
Source File: stickers.py From TG-UserBot with GNU General Public License v3.0 | 5 votes |
def _resolve_messages( args: list, kwargs: dict, sticker_event: types.Message ) -> Tuple[Union[str, None], str, str, bool]: sticker_name = "sticker.png" pack = None is_animated = False attribute_emoji = None packs = kwargs.pop('pack', []) _emojis = kwargs.pop('emojis', '') if sticker_event.sticker: document = sticker_event.media.document for attribute in document.attributes: if isinstance(attribute, types.DocumentAttributeSticker): attribute_emoji = attribute.alt if document.mime_type == "application/x-tgsticker": sticker_name = 'AnimatedSticker.tgs' is_animated = True for i in args: if re.search(r'[^\w\s,]', i): _emojis += i else: packs.append(i) if len(packs) == 1: pack = packs[0] emojis = _emojis or attribute_emoji or default_emoji return pack, emojis, sticker_name, is_animated
Example #14
Source File: tests.py From telegram-export with Mozilla Public License 2.0 | 4 votes |
def test_formatter_get_messages(self): """ Ensures that the BaseFormatter is able to correctly yield messages. """ dumper = Dumper(self.dumper_config) msg = types.Message( id=1, to_id=123, date=datetime(year=2010, month=1, day=1), message='hi' ) for _ in range(365): dumper.dump_message(msg, 123, forward_id=None, media_id=None) msg.id += 1 msg.date += timedelta(days=1) msg.to_id = 300 - msg.to_id # Flip between two IDs dumper.commit() fmt = BaseFormatter(dumper.conn) # Assert all messages are returned assert len(list(fmt.get_messages_from_context(123))) == 365 # Assert only messages after a date are returned min_date = datetime(year=2010, month=4, day=1) assert all(m.date >= min_date for m in fmt.get_messages_from_context( 123, start_date=min_date )) # Assert only messages before a date are returned max_date = datetime(year=2010, month=4, day=1) assert all(m.date <= max_date for m in fmt.get_messages_from_context( 123, end_date=max_date )) # Assert messages are returned in a range assert all(min_date <= m.date <= max_date for m in fmt.get_messages_from_context( 123, start_date=min_date, end_date=max_date )) # Assert messages are returned in the correct order desc = list(fmt.get_messages_from_context(123, order='DESC')) assert all(desc[i - 1] > desc[i] for i in range(1, len(desc))) asc = list(fmt.get_messages_from_context(123, order='ASC')) assert all(asc[i - 1] < asc[i] for i in range(1, len(asc)))