Example #1
0
    def fetch_peers(self, entities: list):
        for entity in entities:
            if isinstance(entity, types.User):
                user_id = entity.id

                access_hash = entity.access_hash

                if access_hash is None:
                    continue

                username = entity.username
                phone = entity.phone

                input_peer = types.InputPeerUser(
                    user_id=user_id,
                    access_hash=access_hash
                )

                self.peers_by_id[user_id] = input_peer

                if username is not None:
                    self.peers_by_username[username.lower()] = input_peer

                if phone is not None:
                    self.peers_by_phone[phone] = input_peer

            if isinstance(entity, (types.Chat, types.ChatForbidden)):
                chat_id = entity.id
                peer_id = -chat_id

                input_peer = types.InputPeerChat(
                    chat_id=chat_id
                )

                self.peers_by_id[peer_id] = input_peer

            if isinstance(entity, (types.Channel, types.ChannelForbidden)):
                channel_id = entity.id
                peer_id = int("-100" + str(channel_id))

                access_hash = entity.access_hash

                if access_hash is None:
                    continue

                username = getattr(entity, "username", None)

                input_peer = types.InputPeerChannel(
                    channel_id=channel_id,
                    access_hash=access_hash
                )

                self.peers_by_id[peer_id] = input_peer

                if username is not None:
                    self.peers_by_username[username.lower()] = input_peer
Example #2
0
def get_input_peer(peer_id: int, access_hash: int, peer_type: str):
    if peer_type in ["user", "bot"]:
        return types.InputPeerUser(user_id=peer_id, access_hash=access_hash)

    if peer_type == "group":
        return types.InputPeerChat(chat_id=-peer_id)

    if peer_type in ["channel", "supergroup"]:
        return types.InputPeerChannel(channel_id=utils.get_channel_id(peer_id),
                                      access_hash=access_hash)

    raise ValueError("Invalid peer type: {}".format(peer_type))
Example #3
0
def main():
    client = Client('session', api_key=(API_ID, API_HASH))
    client.start()

    def _get_dialog_name(type_, id_, client):
        try:
            ip = client.resolve_peer(id_)
        except Exception as e:
            print(type_, id_, e)

        if type_ == PT_CHANNEL:
            chats = client.send(functions.channels.GetChannels([
                ip,
            ]))
            channel = chats.chats[0]
            name = channel.title
        elif type_ == PT_CHAT:
            chats = client.send(functions.messages.GetChats([id_]))
            chat = chats.chats[0]
            name = chat.title
        elif type_ == PT_USER:
            fu = client.send(functions.users.GetFullUser(ip))
            name = fu.user.first_name
        else:
            TypeError(f'undefined type {type_}')

        return name

    def _extract_dialogs_data(dialogs):
        data = []
        for d in dialogs:
            type_, id_ = get_dialog_type_id(d)
            name = _get_dialog_name(type_, id_, client)
            data.append((type_, id_, name, d.write()))
        return data

    # def _get_offset_date(dslice):
    #     for m in reversed(dslice.messages):
    #         if isinstance(m, types.MessageEmpty):
    #             continue
    #
    #         return m.date
    #
    #     return 0

    # offset_date, limit = 0, 20
    # saved = 0
    # while True:
    # dslice = client.send(functions.messages.GetDialogs(0, 0, types.InputPeerEmpty(), 100))
    # if not dslice.dialogs:
    #     break
    # dialogs = _extract_dialogs_data(dslice.dialogs)
    # Dialog.insert_many(dialogs, fields=(Dialog.type, Dialog.dialog_id, Dialog.name, Dialog.bin_data))\
    #       .execute()

    # saved += len(dslice.dialogs)
    # offset_date = _get_offset_date(dslice)
    # logger.info(f'saved {saved} messages')

    show_dialogs()
    id_ = input('id: ')
    offset, limit = 0, 100
    saved = 0
    try:
        peer = client.resolve_peer(int(id_))
    except PeerIdInvalid:
        peer = types.InputPeerChat(int(id_))

    while True:
        hist = client.send(
            functions.messages.GetHistory(
                peer,
                0,
                0,
                offset,
                limit,
                0,
                0,
                0,
            ))
        if not hist.messages:
            break
        save_history(hist.messages, id_)
        saved += len(hist.messages)
        offset += limit
    logger.info(f'saved {saved} messages')
    client.stop()
Example #4
0
def get_input_peer(peer_id: int, access_hash: int):
    return (types.InputPeerUser(peer_id, access_hash) if peer_id > 0 else
            types.InputPeerChannel(int(str(peer_id)[4:]), access_hash) if
            (str(peer_id).startswith("-100")
             and access_hash) else types.InputPeerChat(-peer_id))