當前位置: 首頁>>代碼示例>>Python>>正文


Python utils.get_display_name方法代碼示例

本文整理匯總了Python中telethon.utils.get_display_name方法的典型用法代碼示例。如果您正苦於以下問題:Python utils.get_display_name方法的具體用法?Python utils.get_display_name怎麽用?Python utils.get_display_name使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在telethon.utils的用法示例。


在下文中一共展示了utils.get_display_name方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: format_message

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_display_name [as 別名]
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 
開發者ID:LonamiWebs,項目名稱:Telethon,代碼行數:20,代碼來源:quart_login.py

示例2: handler

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_display_name [as 別名]
def handler(event):
    sender = await event.get_sender()
    name = utils.get_display_name(sender)
    print(name, 'said', event.text, '!') 
開發者ID:LonamiWebs,項目名稱:Telethon,代碼行數:6,代碼來源:print_messages.py

示例3: message_handler

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_display_name [as 別名]
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
                )) 
開發者ID:LonamiWebs,項目名稱:Telethon,代碼行數:32,代碼來源:interactive_telegram_client.py

示例4: on_message

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_display_name [as 別名]
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 
開發者ID:LonamiWebs,項目名稱:Telethon,代碼行數:33,代碼來源:gui.py

示例5: enqueue_entities

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_display_name [as 別名]
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) 
開發者ID:expectocode,項目名稱:telegram-export,代碼行數:31,代碼來源:downloader.py

示例6: download_past_media

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_display_name [as 別名]
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() 
開發者ID:expectocode,項目名稱:telegram-export,代碼行數:33,代碼來源:downloader.py

示例7: printUser

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_display_name [as 別名]
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)) 
開發者ID:TG-UserBot,項目名稱:TG-UserBot,代碼行數:7,代碼來源:helpers.py

示例8: get_chat_link

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_display_name [as 別名]
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 
開發者ID:TG-UserBot,項目名稱:TG-UserBot,代碼行數:35,代碼來源:helpers.py

示例9: get_channel_all_users

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_display_name [as 別名]
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
    # ===================== 
開發者ID:paulpierre,項目名稱:informer,代碼行數:14,代碼來源:informer.py

示例10: get_who_string

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_display_name [as 別名]
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 
開發者ID:mkaraniya,項目名稱:BotHub,代碼行數:8,代碼來源:who.py

示例11: printUser

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_display_name [as 別名]
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)) 
開發者ID:mkaraniya,項目名稱:BotHub,代碼行數:8,代碼來源:helpers.py

示例12: get_chat_link

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_display_name [as 別名]
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 
開發者ID:mkaraniya,項目名稱:BotHub,代碼行數:34,代碼來源:helpers.py

示例13: handler

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_display_name [as 別名]
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  ============================== 
開發者ID:LonamiWebs,項目名稱:Telethon,代碼行數:53,代碼來源:assistant.py

示例14: name

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_display_name [as 別名]
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)}```') 
開發者ID:TG-UserBot,項目名稱:TG-UserBot,代碼行數:47,代碼來源:userdata.py


注:本文中的telethon.utils.get_display_name方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。