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


Python utils.get_peer_id方法代碼示例

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


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

示例1: get_entity_rows_by_id

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_peer_id [as 別名]
def get_entity_rows_by_id(self, key: int, exact: bool = True) -> Optional[Tuple[int, int]]:
        t = self.Entity.__table__
        if exact:
            rows = self.engine.execute(select([t.c.id, t.c.hash]).where(
                and_(t.c.session_id == self.session_id, t.c.id == key)))
        else:
            ids = (
                utils.get_peer_id(PeerUser(key)),
                utils.get_peer_id(PeerChat(key)),
                utils.get_peer_id(PeerChannel(key))
            )
            rows = self.engine.execute(select([t.c.id, t.c.hash])
                .where(
                and_(t.c.session_id == self.session_id, t.c.id.in_(ids))))

        try:
            return next(rows)
        except StopIteration:
            return None 
開發者ID:tulir,項目名稱:telethon-session-sqlalchemy,代碼行數:21,代碼來源:core.py

示例2: dump_channel

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_peer_id [as 別名]
def dump_channel(self, channel_full, channel, photo_id, timestamp=None):
        """Dump a Channel into the Channel table.
        Params: ChannelFull, Channel to dump, MediaID
                of the profile photo in the DB
        Returns -"""
        # Need to get the full object too for 'about' info
        values = (get_peer_id(channel),
                  timestamp or round(time.time()),
                  channel_full.about,
                  channel.title,
                  channel.username,
                  photo_id,
                  channel_full.pinned_msg_id)

        for callback in self._dump_callbacks['channel']:
            callback(values)

        return self._insert_if_valid_date('Channel', values, date_column=1,
                                          where=('ID', get_peer_id(channel))) 
開發者ID:expectocode,項目名稱:telegram-export,代碼行數:21,代碼來源:dumper.py

示例3: dump_supergroup

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_peer_id [as 別名]
def dump_supergroup(self, supergroup_full, supergroup, photo_id,
                        timestamp=None):
        """Dump a Supergroup into the Supergroup table
        Params: ChannelFull, Channel to dump, MediaID
                of the profile photo in the DB.
        Returns -"""
        # Need to get the full object too for 'about' info
        values = (get_peer_id(supergroup),
                  timestamp or round(time.time()),
                  getattr(supergroup_full, 'about', None) or '',
                  supergroup.title,
                  supergroup.username,
                  photo_id,
                  supergroup_full.pinned_msg_id)

        for callback in self._dump_callbacks['supergroup']:
            callback(values)

        return self._insert_if_valid_date('Supergroup', values, date_column=1,
                                          where=('ID', get_peer_id(supergroup))) 
開發者ID:expectocode,項目名稱:telegram-export,代碼行數:22,代碼來源:dumper.py

示例4: _dump_admin_log

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_peer_id [as 別名]
def _dump_admin_log(self, events, target):
        """
        Helper method to iterate the events from a GetAdminLogRequest
        and dump them into the Dumper, mostly to avoid excessive nesting.

        Also enqueues any media to be downloaded later by a different coroutine.
        """
        for event in events:
            assert isinstance(event, types.ChannelAdminLogEvent)
            if isinstance(event.action,
                          types.ChannelAdminLogEventActionChangePhoto):
                media_id1 = self.dumper.dump_media(event.action.new_photo)
                media_id2 = self.dumper.dump_media(event.action.prev_photo)
                self.enqueue_photo(event.action.new_photo, media_id1, target,
                                   peer_id=event.user_id, date=event.date)
                self.enqueue_photo(event.action.prev_photo, media_id2, target,
                                   peer_id=event.user_id, date=event.date)
            else:
                media_id1 = None
                media_id2 = None
            self.dumper.dump_admin_log_event(
                event, utils.get_peer_id(target), media_id1, media_id2
            )
        return min(e.id for e in events) 
開發者ID:expectocode,項目名稱:telegram-export,代碼行數:26,代碼來源:downloader.py

示例5: on_regex

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_peer_id [as 別名]
def on_regex(event):
    if event.fwd_from:
        return
    if not event.is_private and\
            await group_has_sedbot(await event.get_input_chat()):
        # await event.edit("This group has a sed bot. Ignoring this message!")
        return

    chat_id = utils.get_peer_id(await event.get_input_chat())

    m, s = doit(chat_id, event.pattern_match, await event.get_reply_message())

    if m is not None:
        s = f"{HEADER}{s}"
        out = await borg.send_message(
            await event.get_input_chat(), s, reply_to=m.id
        )
        last_msgs[chat_id].appendleft(out)
    elif s is not None:
        await event.edit(s)

    raise events.StopPropagation 
開發者ID:mkaraniya,項目名稱:BotHub,代碼行數:24,代碼來源:sed.py

示例6: on_regex

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_peer_id [as 別名]
def on_regex(event):
    if event.fwd_from:
        return
    if not event.is_private and\
            await group_has_sedbot(await event.get_input_chat()):
        # await event.edit("This group has a sed bot. Ignoring this message!")
        return

    chat_id = utils.get_peer_id(await event.get_input_chat())

    m, s = doit(chat_id, event.pattern_match, await event.get_reply_message())

    if m is not None:
        s = f"{HEADER}{s}"
        out = await bot.send_message(
            await event.get_input_chat(), s, reply_to=m.id
        )
        last_msgs[chat_id].appendleft(out)
    elif s is not None:
        await event.edit(s)

    raise events.StopPropagation 
開發者ID:Dark-Princ3,項目名稱:X-tra-Telegram,代碼行數:24,代碼來源:sed.py

示例7: get_entity_rows_by_id

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_peer_id [as 別名]
def get_entity_rows_by_id(self, key: int, exact: bool = True) -> Optional[Tuple[int, int]]:
        if exact:
            query = self._db_query(self.Entity, self.Entity.id == key)
        else:
            ids = (
                utils.get_peer_id(PeerUser(key)),
                utils.get_peer_id(PeerChat(key)),
                utils.get_peer_id(PeerChannel(key))
            )
            query = self._db_query(self.Entity, self.Entity.id.in_(ids))

        row = query.one_or_none()
        return (row.id, row.hash) if row else None 
開發者ID:tulir,項目名稱:telethon-session-sqlalchemy,代碼行數:15,代碼來源:orm.py

示例8: get_peer_id

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_peer_id [as 別名]
def get_peer_id(
            self: 'TelegramClient',
            peer: 'hints.EntityLike',
            add_mark: bool = True) -> int:
        """
        Gets the ID for the given entity.

        This method needs to be ``async`` because `peer` supports usernames,
        invite-links, phone numbers (from people in your contact list), etc.

        If ``add_mark is False``, then a positive ID will be returned
        instead. By default, bot-API style IDs (signed) are returned.

        Example
            .. code-block:: python

                print(await client.get_peer_id('me'))
        """
        if isinstance(peer, int):
            return utils.get_peer_id(peer, add_mark=add_mark)

        try:
            if peer.SUBCLASS_OF_ID not in (0x2d45687, 0xc91c90b6):
                # 0x2d45687, 0xc91c90b6 == crc32(b'Peer') and b'InputPeer'
                peer = await self.get_input_entity(peer)
        except AttributeError:
            peer = await self.get_input_entity(peer)

        if isinstance(peer, types.InputPeerSelf):
            peer = await self.get_me(input_peer=True)

        return utils.get_peer_id(peer, add_mark=add_mark)

    # endregion

    # region Private methods 
開發者ID:LonamiWebs,項目名稱:Telethon,代碼行數:38,代碼來源:users.py

示例9: test_formatter_get_chat

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_peer_id [as 別名]
def test_formatter_get_chat(self):
        """
        Ensures that the BaseFormatter is able to fetch the expected
        entities when using a date parameter.
        """
        chat = types.Chat(
            id=123,
            title='Some title',
            photo=types.ChatPhotoEmpty(),
            participants_count=7,
            date=datetime.now(),
            version=1
        )
        dumper = Dumper(self.dumper_config)

        fmt = BaseFormatter(dumper.conn)
        for month in range(1, 13):
            dumper.dump_chat(chat, None, timestamp=int(datetime(
                year=2010, month=month, day=1
            ).timestamp()))
        dumper.commit()
        cid = tl_utils.get_peer_id(chat)
        # Default should get the most recent version
        date = fmt.get_chat(cid).date_updated
        assert date == datetime(year=2010, month=12, day=1)

        # Expected behaviour is to get the previous available date
        target = datetime(year=2010, month=6, day=29)
        date = fmt.get_chat(cid, target).date_updated
        assert date == datetime(year=2010, month=6, day=1)

        # Expected behaviour is to get the next date if previous unavailable
        target = datetime(year=2009, month=12, day=1)
        date = fmt.get_chat(cid, target).date_updated
        assert date == datetime(year=2010, month=1, day=1) 
開發者ID:expectocode,項目名稱:telegram-export,代碼行數:37,代碼來源:tests.py

示例10: fmt_dialog

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_peer_id [as 別名]
def fmt_dialog(dialog, id_pad=0, username_pad=0):
    """
    Space-fill a row with given padding values
    to ensure alignment when printing dialogs.
    """
    username = getattr(dialog.entity, 'username', None)
    username = '@' + username if username else NO_USERNAME
    return '{:<{id_pad}} | {:<{username_pad}} | {}'.format(
        utils.get_peer_id(dialog.entity), username, dialog.name,
        id_pad=id_pad, username_pad=username_pad
    ) 
開發者ID:expectocode,項目名稱:telegram-export,代碼行數:13,代碼來源:__main__.py

示例11: find_fmt_dialog_padding

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_peer_id [as 別名]
def find_fmt_dialog_padding(dialogs):
    """
    Find the correct amount of space padding
    to give dialogs when printing them.
    """
    no_username = NO_USERNAME[:-1]  # Account for the added '@' if username
    return (
        max(len(str(utils.get_peer_id(dialog.entity))) for dialog in dialogs),
        max(len(getattr(dialog.entity, 'username', no_username) or no_username)
            for dialog in dialogs) + 1
    ) 
開發者ID:expectocode,項目名稱:telegram-export,代碼行數:13,代碼來源:__main__.py

示例12: _dump_messages

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

示例13: enqueue_entities

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_peer_id [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

示例14: enqueue_photo

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_peer_id [as 別名]
def enqueue_photo(self, photo, photo_id, context,
                      peer_id=None, date=None):
        if not photo_id:
            return
        if not isinstance(context, int):
            context = utils.get_peer_id(context)
        if peer_id is None:
            peer_id = context
        if date is None:
            date = getattr(photo, 'date', None) or datetime.datetime.now()
        self.enqueue_media(photo_id, context, peer_id, date) 
開發者ID:expectocode,項目名稱:telegram-export,代碼行數:13,代碼來源:downloader.py

示例15: download_past_media

# 需要導入模塊: from telethon import utils [as 別名]
# 或者: from telethon.utils import get_peer_id [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


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