当前位置: 首页>>代码示例>>Python>>正文


Python types.User方法代码示例

本文整理汇总了Python中telethon.tl.types.User方法的典型用法代码示例。如果您正苦于以下问题:Python types.User方法的具体用法?Python types.User怎么用?Python types.User使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在telethon.tl.types的用法示例。


在下文中一共展示了types.User方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_target

# 需要导入模块: from telethon.tl import types [as 别名]
# 或者: from telethon.tl.types import User [as 别名]
def get_target(message, arg_no=0):
    if any(isinstance(ent, MessageEntityMentionName) for ent in (message.entities or [])):
        e = sorted(filter(lambda x: isinstance(x, MessageEntityMentionName),
                          message.entities), key=lambda x: x.offset)[0]
        return e.user_id
    elif len(get_args(message)) > arg_no:
        user = get_args(message)[arg_no]
    elif message.is_reply:
        return (await message.get_reply_message()).from_id
    elif hasattr(message.to_id, "user_id"):
        user = message.to_id.user_id
    else:
        return None
    try:
        ent = await message.client.get_entity(user)
    except ValueError:
        return None
    else:
        if isinstance(ent, User):
            return ent.id 
开发者ID:friendly-telegram,项目名称:friendly-telegram,代码行数:22,代码来源:utils.py

示例2: get_user_info

# 需要导入模块: from telethon.tl import types [as 别名]
# 或者: from telethon.tl.types import User [as 别名]
def get_user_info(event) -> dict:
    """Returns a dictionary of user information"""
    chat_type = "user" if event.is_private else "group" if event.is_group else "channel"
    chat = await event.get_chat()
    if isinstance(chat, User):
        sender = await event.get_sender()
        name = ''
        if sender.first_name:
            name += sender.first_name.strip()
        if sender.last_name:
            name += ' ' + sender.last_name.strip()
        username = sender.username if sender.username else None
        chat_id = sender.id
    else:
        name = chat.title
        try:
            username = chat.username if chat.username else None
        except AttributeError:
            username = None
        chat_id = chat.id
    return {'id': chat_id, 'username': username, 'name': name, 'type': chat_type} 
开发者ID:XiaomiFirmwareUpdater,项目名称:xiaomi_uranus_chatbot,代码行数:23,代码来源:chat.py

示例3: get_users

# 需要导入模块: from telethon.tl import types [as 别名]
# 或者: from telethon.tl.types import User [as 别名]
def get_users(event: NewMessage.Event) -> types.User or None:
    match = event.matches[0].group(1)
    users = []
    if match:
        matches, _ = await client.parse_arguments(match)
        for match in matches:
            try:
                entity = await client.get_entity(match)
                if isinstance(entity, types.User):
                    users.append(entity)
            except (TypeError, ValueError):
                pass
    elif event.is_private and event.out:
        users = [await event.get_chat()]
    elif event.reply_to_msg_id:
        reply = await event.get_reply_message()
        users = [await reply.get_sender()]
    return users 
开发者ID:TG-UserBot,项目名称:TG-UserBot,代码行数:20,代码来源:pmpermit.py

示例4: _sign_in

# 需要导入模块: from telethon.tl import types [as 别名]
# 或者: from telethon.tl.types import User [as 别名]
def _sign_in(evt: CommandEvent, login_as: 'u.User' = None, **sign_in_info) -> EventID:
    login_as = login_as or evt.sender
    try:
        await login_as.ensure_started(even_if_no_session=True)
        user = await login_as.client.sign_in(**sign_in_info)
        await _finish_sign_in(evt, user)
    except PhoneCodeExpiredError:
        return await evt.reply("Phone code expired. Try again with `$cmdprefix+sp login`.")
    except PhoneCodeInvalidError:
        return await evt.reply("Invalid phone code.")
    except PasswordHashInvalidError:
        return await evt.reply("Incorrect password.")
    except SessionPasswordNeededError:
        evt.sender.command_status = {
            "next": enter_password,
            "action": "Login (password entry)",
        }
        return await evt.reply("Your account has two-factor authentication. "
                               "Please send your password here.") 
开发者ID:tulir,项目名称:mautrix-telegram,代码行数:21,代码来源:auth.py

示例5: _finish_sign_in

# 需要导入模块: from telethon.tl import types [as 别名]
# 或者: from telethon.tl.types import User [as 别名]
def _finish_sign_in(evt: CommandEvent, user: User, login_as: 'u.User' = None) -> EventID:
    login_as = login_as or evt.sender
    existing_user = u.User.get_by_tgid(TelegramID(user.id))
    if existing_user and existing_user != login_as:
        await existing_user.log_out()
        await evt.reply(f"[{existing_user.displayname}]"
                        f"(https://matrix.to/#/{existing_user.mxid})"
                        " was logged out from the account.")
    asyncio.ensure_future(login_as.post_login(user, first_login=True), loop=evt.loop)
    evt.sender.command_status = None
    name = f"@{user.username}" if user.username else f"+{user.phone}"
    if login_as != evt.sender:
        msg = (f"Successfully logged in [{login_as.mxid}](https://matrix.to/#/{login_as.mxid})"
               f" as {name}")
    else:
        msg = f"Successfully logged in as {name}"
    return await evt.reply(msg) 
开发者ID:tulir,项目名称:mautrix-telegram,代码行数:19,代码来源:auth.py

示例6: login_client

# 需要导入模块: from telethon.tl import types [as 别名]
# 或者: from telethon.tl.types import User [as 别名]
def login_client(client, username):
    """
    Logs-in the given client and sets the desired username.

    This method will sign up, sign in, or delete existing 2FA-protected
    accounts as required.
    """
    client.session.set_dc(0, '149.154.167.40', 80)
    assert client.connect()
    phone = '+999662' + str(random.randint(0, 9999)).zfill(4)
    client.send_code_request(phone)
    while True:
        try:
            print('Signing up as', phone)
            client.sign_up('22222', username, 'User')
            break
        except PhoneNumberOccupiedError:
            try:
                print('Signing in as', phone)
                client.sign_in(phone, '22222')
                break
            except SessionPasswordNeededError:
                print('Occupied', phone, 'had password! Deleting!')
                client(functions.account.DeleteAccountRequest(''))

    print('Changing', phone, 'username to', username)
    client(functions.account.UpdateUsernameRequest(username)) 
开发者ID:expectocode,项目名称:telegram-export,代码行数:29,代码来源:tests.py

示例7: _get_name

# 需要导入模块: from telethon.tl import types [as 别名]
# 或者: from telethon.tl.types import User [as 别名]
def _get_name(self, peer_id):
        if peer_id is None:
            return ''

        name = self._displays.get(peer_id)
        if name:
            return name

        c = self.dumper.conn.cursor()
        _, kind = utils.resolve_id(peer_id)
        if kind == types.PeerUser:
            row = c.execute('SELECT FirstName, LastName FROM User '
                            'WHERE ID = ?', (peer_id,)).fetchone()
            if row:
                return '{} {}'.format(row[0] or '',
                                      row[1] or '').strip()
        elif kind == types.PeerChat:
            row = c.execute('SELECT Title FROM Chat '
                            'WHERE ID = ?', (peer_id,)).fetchone()
            if row:
                return row[0]
        elif kind == types.PeerChannel:
            row = c.execute('SELECT Title FROM Channel '
                            'WHERE ID = ?', (peer_id,)).fetchone()
            if row:
                return row[0]
            row = c.execute('SELECT Title FROM Supergroup '
                            'WHERE ID = ?', (peer_id,)).fetchone()
            if row:
                return row[0]
        return '' 
开发者ID:expectocode,项目名称:telegram-export,代码行数:33,代码来源:downloader.py

示例8: enqueue_entities

# 需要导入模块: from telethon.tl import types [as 别名]
# 或者: from telethon.tl.types import User [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

示例9: verifyLoggerGroup

# 需要导入模块: from telethon.tl import types [as 别名]
# 或者: from telethon.tl.types import User [as 别名]
def verifyLoggerGroup(client: UserBotClient) -> None:
    client.logger = True

    def disable_logger(error: str):
        if LOGGER_CHAT_ID != 0:
            LOGGER.error(error)
        client.logger = False

    try:
        entity = client.loop.run_until_complete(
            client.get_entity(LOGGER_CHAT_ID)
        )
        if not isinstance(entity, types.User):
            if not entity.creator:
                if entity.default_banned_rights.send_messages:
                    disable_logger(
                        "Permissions missing to send messages "
                        "for the specified Logger group."
                    )
        client.logger = entity
    except ValueError:
        disable_logger(
            "Logger group ID cannot be found. "
            "Make sure it's correct."
        )
    except TypeError:
        disable_logger(
            "Logger group ID is unsupported. "
            "Make sure it's correct."
        )
    except Exception as e:
        disable_logger(
            "An Exception occured upon trying to verify "
            "the logger group.\n" + str(e)
        ) 
开发者ID:TG-UserBot,项目名称:TG-UserBot,代码行数:37,代码来源:__init__.py

示例10: printUser

# 需要导入模块: from telethon.tl import types [as 别名]
# 或者: from telethon.tl.types import User [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

示例11: get_chat_link

# 需要导入模块: from telethon.tl import types [as 别名]
# 或者: from telethon.tl.types import User [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

示例12: get_entity_from_msg

# 需要导入模块: from telethon.tl import types [as 别名]
# 或者: from telethon.tl.types import User [as 别名]
def get_entity_from_msg(event: NewMessage.Event) -> Tuple[
    Union[None, types.User], Union[None, bool, str], Union[None, bool, str]
]:
    """Get a User entity and/or a reason from the event's regex pattern"""
    exception = False
    entity = None
    match = event.matches[0].group(1)

    # TODO: Find better logic to differentiate user and reason
    pattern = re.compile(r"(@?\w+|\d+)(?: |$)(.*)")
    user = pattern.match(match).group(1) if match else None
    extra = pattern.match(match).group(2) if match else None
    reply = await event.get_reply_message()

    if reply and not (user and extra):
        user = reply.from_id
        extra = match.strip()

    user = int(user) if isinstance(user, str) and user.isdigit() else user
    if not user:
        return None, None, "Couldn't fetch an entity from your message!"

    try:
        entity = await event.client.get_entity(user)
    except Exception as e:
        exception = True
        LOGGER.exception(e)

    return entity, extra, exception 
开发者ID:TG-UserBot,项目名称:TG-UserBot,代码行数:31,代码来源:ids.py

示例13: get_who_string

# 需要导入模块: from telethon.tl import types [as 别名]
# 或者: from telethon.tl.types import User [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

示例14: printUser

# 需要导入模块: from telethon.tl import types [as 别名]
# 或者: from telethon.tl.types import User [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

示例15: get_chat_link

# 需要导入模块: from telethon.tl import types [as 别名]
# 或者: from telethon.tl.types import User [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


注:本文中的telethon.tl.types.User方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。