Python telethon.utils.get_display_name() Examples
The following are 14
code examples of telethon.utils.get_display_name().
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.utils
, or try the search function
.
Example #1
Source File: quart_login.py From Telethon with MIT License | 6 votes |
def format_message(message): if message.photo: content = '<img src="data:image/png;base64,{}" alt="{}" />'.format( base64.b64encode(await message.download_media(bytes)).decode(), message.raw_text ) else: # client.parse_mode = 'html', so bold etc. will work! content = (message.text or '(action message)').replace('\n', '<br>') return '<p><strong>{}</strong>: {}<sub>{}</sub></p>'.format( utils.get_display_name(message.sender), content, message.date ) # Connect the client before we start serving with Quart
Example #2
Source File: print_messages.py From Telethon with MIT License | 5 votes |
def handler(event): sender = await event.get_sender() name = utils.get_display_name(sender) print(name, 'said', event.text, '!')
Example #3
Source File: interactive_telegram_client.py From Telethon with MIT License | 5 votes |
def message_handler(self, event): """Callback method for received events.NewMessage""" # Note that message_handler is called when a Telegram update occurs # and an event is created. Telegram may not always send information # about the ``.sender`` or the ``.chat``, so if you *really* want it # you should use ``get_chat()`` and ``get_sender()`` while working # with events. Since they are methods, you know they may make an API # call, which can be expensive. chat = await event.get_chat() if event.is_group: if event.out: sprint('>> sent "{}" to chat {}'.format( event.text, get_display_name(chat) )) else: sprint('<< {} @ {} sent "{}"'.format( get_display_name(await event.get_sender()), get_display_name(chat), event.text )) else: if event.out: sprint('>> "{}" to user {}'.format( event.text, get_display_name(chat) )) else: sprint('<< {} sent "{}"'.format( get_display_name(chat), event.text ))
Example #4
Source File: gui.py From Telethon with MIT License | 5 votes |
def on_message(self, event): """ Event handler that will add new messages to the message log. """ # We want to show only messages sent to this chat if event.chat_id != self.chat_id: return # Save the message ID so we know which to reply to self.message_ids.append(event.id) # Decide a prefix (">> " for our messages, "<user>" otherwise) if event.out: text = '>> ' else: sender = await event.get_sender() text = '<{}> '.format(sanitize_str( utils.get_display_name(sender))) # If the message has media show "(MediaType) " if event.media: text += '({}) '.format(event.media.__class__.__name__) text += sanitize_str(event.text) text += '\n' # Append the text to the end with a newline, and scroll to the end self.log.insert(tkinter.END, text) self.log.yview(tkinter.END) # noinspection PyUnusedLocal
Example #5
Source File: downloader.py From telegram-export with Mozilla Public License 2.0 | 5 votes |
def enqueue_entities(self, entities): """ Enqueues the given iterable of entities to be dumped later by a different coroutine. These in turn might enqueue profile photos. """ for entity in entities: eid = utils.get_peer_id(entity) self._displays[eid] = utils.get_display_name(entity) if isinstance(entity, types.User): if entity.deleted or entity.min: continue # Empty name would cause IntegrityError elif isinstance(entity, types.Channel): if entity.left: continue # Getting full info triggers ChannelPrivateError elif not isinstance(entity, (types.Chat, types.InputPeerUser, types.InputPeerChat, types.InputPeerChannel)): # Drop UserEmpty, ChatEmpty, ChatForbidden and ChannelForbidden continue if eid in self._checked_entity_ids: continue else: self._checked_entity_ids.add(eid) if isinstance(entity, (types.User, types.InputPeerUser)): self._user_queue.put_nowait(entity) else: self._chat_queue.put_nowait(entity)
Example #6
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 #7
Source File: helpers.py From TG-UserBot with GNU General Public License v3.0 | 5 votes |
def printUser(entity: types.User) -> None: """Print the user's first name + last name upon start""" user = get_display_name(entity) print() LOGGER.warning("Successfully logged in as {0}".format(user))
Example #8
Source File: helpers.py From TG-UserBot with GNU General Public License v3.0 | 5 votes |
def get_chat_link( arg: Union[types.User, types.Chat, types.Channel, NewMessage.Event], reply=None ) -> str: if isinstance(arg, (types.User, types.Chat, types.Channel)): entity = arg else: entity = await arg.get_chat() if isinstance(entity, types.User): if entity.is_self: name = "yourself" else: name = get_display_name(entity) or "Deleted Account?" extra = f"[{name}](tg://user?id={entity.id})" else: if hasattr(entity, 'username') and entity.username is not None: username = '@' + entity.username else: username = entity.id if reply is not None: if isinstance(username, str) and username.startswith('@'): username = username[1:] else: username = f"c/{username}" extra = f"[{entity.title}](https://t.me/{username}/{reply})" else: if isinstance(username, int): username = f"`{username}`" extra = f"{entity.title} ( {username} )" else: extra = f"[{entity.title}](tg://resolve?domain={username})" return extra
Example #9
Source File: informer.py From informer with MIT License | 5 votes |
def get_channel_all_users(self, channel_id): # TODO: this function is not complete channel = self.client.get_entity(PeerChat(channel_id)) users = self.client.get_participants(channel) print('total users: {}'.format(users.total)) for user in users: if user.username is not None and not user.is_self: print(utils.get_display_name(user), user.username, user.id, user.bot, user.verified, user.restricted, user.first_name, user.last_name, user.phone, user.is_self) # ===================== # Get # of participants # =====================
Example #10
Source File: who.py From BotHub with Apache License 2.0 | 5 votes |
def get_who_string(who): who_string = html.escape(utils.get_display_name(who)) if isinstance(who, (types.User, types.Channel)) and who.username: who_string += f" is Party & Party's username <i>(@{who.username})</i>" who_string += f"& Party's ID <a href='tg://user?id={who.id}'> {who.id}</a>" return who_string
Example #11
Source File: helpers.py From BotHub with Apache License 2.0 | 5 votes |
def printUser(entity: types.User) -> None: """Print the user's first name + last name upon start""" user = get_display_name(entity) print() LOGGER.warning("Successfully logged in as {0}{2}{1}".format( CUSR, CEND, user))
Example #12
Source File: helpers.py From BotHub with Apache License 2.0 | 5 votes |
def get_chat_link(arg: Union[types.User, types.Chat, types.Channel, NewMessage.Event], reply=None) -> str: if isinstance(arg, (types.User, types.Chat, types.Channel)): entity = arg else: entity = await arg.get_chat() if isinstance(entity, types.User): if entity.is_self: name = "your 'Saved Messages'" else: name = get_display_name(entity) or "Deleted Account?" extra = f"[{name}](tg://user?id={entity.id})" else: if hasattr(entity, 'username') and entity.username is not None: username = '@' + entity.username else: username = entity.id if reply is not None: if isinstance(username, str) and username.startswith('@'): username = username[1:] else: username = f"c/{username}" extra = f"[{entity.title}](https://t.me/{username}/{reply})" else: if isinstance(username, int): username = f"`{username}`" extra = f"{entity.title} ( {username} )" else: extra = f"[{entity.title}](tg://resolve?domain={username})" return extra
Example #13
Source File: assistant.py From Telethon with MIT License | 4 votes |
def handler(event): """ #haste: Replaces the message you reply to with a dogbin link. """ await event.delete() if not event.reply_to_msg_id: return msg = await event.get_reply_message() if len(msg.raw_text or '') < 200: return sent = await event.respond( 'Uploading paste…', reply_to=msg.reply_to_msg_id) name = html.escape( utils.get_display_name(await msg.get_sender()) or 'A user') text = msg.raw_text code = '' for _, string in msg.get_entities_text(( types.MessageEntityCode, types.MessageEntityPre)): code += f'{string}\n' text = text.replace(string, '') code = code.rstrip() if code: text = re.sub(r'\s+', ' ', text) else: code = msg.raw_text text = '' async with aiohttp.ClientSession() as session: async with session.post('https://del.dog/documents', data=code.encode('utf-8')) as resp: if resp.status >= 300: await sent.edit("Dogbin seems to be down… ( ^^')") return haste = (await resp.json())['key'] await asyncio.wait([ msg.delete(), sent.edit(f'<a href="tg://user?id={msg.sender_id}">{name}</a> ' f'said: {text} del.dog/{haste}.py' .replace(' ', ' '), parse_mode='html') ]) # ============================== Commands ============================== # ============================== Inline ==============================
Example #14
Source File: userdata.py From TG-UserBot with GNU General Public License v3.0 | 4 votes |
def name(event: NewMessage.Event) -> None: """ Get your current name or update it. `{prefix}name` or **{prefix}name (first) [(last)]** The name will be split from the first space unless args are used. **Arguments:** `first` and `last` """ match = event.matches[0].group(1) or '' me = await client.get_me() if not match: text = f"**First name:** `{me.first_name}`" if me.last_name: text += f"\n**Last name:** `{me.last_name}`" await event.answer(text) return _, kwargs = await client.parse_arguments(match) if kwargs: first = kwargs.get('first', me.first_name) last = kwargs.get('last', me.last_name) else: split = match.strip().split(maxsplit=1) if len(split) > 1: first, last = split else: first = split[0] last = me.last_name n1 = get_display_name(me) try: await client(functions.account.UpdateProfileRequest( first_name=first, last_name=last )) n2 = get_display_name(await client.get_me()) await event.answer( f"`Name was successfully changed to {n2}.`", log=("name", f"Name changed from {n1} to {n2}") ) except errors.FirstNameInvalidError: await event.answer("`The first name is invalid.`") except Exception as e: await event.answer(f'```{await client.get_traceback(e)}```')