当前位置: 首页>>代码示例>>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;未经允许,请勿转载。