Beispiel #1
0
def contact_list():
    errormsg = ''
    if 'error' in session:
        errormsg = session['error']
        session.pop('error')

    users = []

    contacts = client(GetContactsRequest(0))
    log.debug('{}'.format(contacts))
    for user in contacts.users:
        user_profile = dict()
        user_profile['id'] = user.id
        user_profile['access_hash'] = user.access_hash
        user_profile['first_name'] = user.first_name
        user_profile['last_name'] = user.last_name
        user_profile['phone'] = user.phone
        if user.photo:
            filename = 'app/contacts/static/tmp/{}.jpg'.format(
                user.photo.photo_id)
            if not Path(filename).is_file():
                log.info('Downloading profile photo {}_{} to {}'.format(
                    user.first_name, user.last_name, filename))
                client.download_profile_photo(user, file=filename)
            user_profile['photo'] = '{}.jpg'.format(user.photo.photo_id)
        users.append(user_profile)

    output = render_template('contact_list.html',
                             contacts=sorted(users,
                                             key=lambda k: k['first_name']),
                             errormsg=errormsg)
    return output
Beispiel #2
0
    def sync_contacts(self):
        contact_hash = ""
        # request all contacts
        logging.info('Sync contact hash :  {}...'.format(contact_hash))
        result = self.invoke(GetContactsRequest(contact_hash))
        # logging.info(result)
        if type(result) is Contacts and len(result.users) > 0:
            logging.info('Contact results : {}'.format(str(len(result.users))))
            for user in result.users:
                if type(user) is User:
                    isExists = TLContact.objects.filter(
                        owner=self.user_phone,
                        phone=phone_norm(user.phone)).exists()
                    if isExists:
                        continue
                    contact = TLContact(owner=self.user_phone,
                                        phone=phone_norm(user.phone),
                                        username=user.username,
                                        first_name=user.first_name,
                                        last_name=user.last_name,
                                        access_hash=user.access_hash,
                                        user_id=user.id)
                    contact.save()

        sleep(0.1)
        # get dialogs
        dialog_count = settings.TELETHON_CONTACT_SYNC_DIALOG_COUNT
        dialogs, entities = self.get_dialogs(dialog_count)
        for entity in entities:
            if type(entity) is User:
                contactModel = self.get_or_create_new_contact(
                    phone_norm(entity.phone),
                    entity.first_name,
                    last_name=entity.last_name)
async def get_contacts_info(client):
    print("获取contacts列表信息...")
    contacts = await client(GetContactsRequest(0))
    users = contacts.users

    me = await client.get_me()
    for user in users:
        user_info = save_user_info(user)
        print(user_info)
Beispiel #4
0
 async def sync_contacts(self):
     response = await self.client(GetContactsRequest(hash=self._hash_contacts()))
     if isinstance(response, ContactsNotModified):
         return
     self.log.debug("Updating contacts...")
     self.contacts = []
     self.saved_contacts = response.saved_count
     for user in response.users:
         puppet = pu.Puppet.get(user.id)
         await puppet.update_info(self, user)
         self.contacts.append(puppet)
     self.save()
Beispiel #5
0
async def _(event):
    if not (await util.isAdmin(event) and event.message.forward == None):
        return

    result = await borg(GetContactsRequest(hash=0))
    await event.reply(
        f"saved_count: {result.saved_count}\ncontacts: {len(result.contacts)}\nusers: {len(result.users)}"
    )

    async def give_contacts(cwd, **kwargs):
        c = z("jq > {cwd}/contacts.json", cmd_stdin=result.to_json())

    #
    # embed2()
    await util.run_and_upload(event=event, to_await=give_contacts)
Beispiel #6
0
    async def get_dialogs_(self):
        self.friends = []
        self.channels = []
        self.contacts = []

        contacts = await self.client(GetContactsRequest(0))
        users = contacts.users
        self.contacts = [user for user in users]

        dialogs = await self.client.get_dialogs()

        for dialog in dialogs:
            entity = dialog.entity
            # 是User
            if isinstance(entity, User):
                self.friends.append(entity)

            # 是Channel
            elif isinstance(entity, Channel):
                self.channels.append(entity)
Beispiel #7
0
 async def sync_contacts(self, get_info: bool = False) -> dict[TelegramID, dict]:
     existing_contacts = await self.get_contacts()
     contact_hash = self._hash_contacts(self.saved_contacts, existing_contacts)
     response = await self.client(GetContactsRequest(hash=contact_hash))
     if isinstance(response, ContactsNotModified):
         if get_info:
             return {
                 tgid: (await pu.Puppet.get_by_tgid(tgid)).contact_info
                 for tgid in existing_contacts
             }
         return {}
     self.log.debug(f"Updating contacts of {self.name}...")
     if self.saved_contacts != response.saved_count:
         self.saved_contacts = response.saved_count
         await self.save()
     contacts = {}
     for user in response.users:
         puppet: pu.Puppet = await pu.Puppet.get_by_tgid(user.id)
         await puppet.update_info(self, user)
         contacts[user.id] = puppet.contact_info
     await self.set_contacts(contacts.keys())
     return contacts
Beispiel #8
0
            result += word[index]
            index += 1

    return result


#okt = Okt()

api_id = 975193
api_hash = '90be99d7814d42c99e5cea19d43701bf'
client = TelegramClient('an', api_id, api_hash)
client.start()

contact_list = {}

contacts = client(GetContactsRequest(0))
print(contacts)

for u in contacts.users:
    contact_list[u.id] = u.access_hash
    print(contact_list[u.id], u.first_name, u.last_name, u.username)
""""
channel ='ASDFZCXV'
channels = {d.entity.username: d.entity
            for d in client.get_dialogs()
            if d.is_channel}

channel = channels[channel]
print(channel)
for u in client.iter_participants(channel, aggressive=True):
  print(u.id, u.first_name, u.last_name, u.username)
Beispiel #9
0
def get_contacts(args):
    client = get_client()
    if not client.is_user_authorized():
        print(str(errors.ERROR_NOT_CONNECTED))
        return

    renew = False
    if os.path.exists("contacts") and time.time() - 30 > float(
            os.path.getmtime("contacts")):
        contacts = pickle.load(open("contacts", "rb"))
    else:
        contacts = []

        users = client.invoke(GetContactsRequest(0)).users
        for u in users:
            c = PicklableContact()
            c.id = u.id
            c.mode = "user"
            d = ""
            if u.first_name is not None:
                d += str(u.first_name) + " "
            if u.last_name is not None:
                d += str(u.last_name)
            c.name = d
            contacts.append(c)

        chats = client.invoke(GetAllChatsRequest([])).chats
        for c in chats:
            cc = PicklableContact()
            cc.id = c.id
            cc.mode = "group"
            cc.name = c.title
            contacts.append(cc)
        renew = True
    """if os.path.exists("chats") and time.time() - 30 > float(os.path.getmtime("chats")):
        
    else:
        
        renew = True"""

    if ALFRED_MODE:
        contact_name = args.name
        s = "<?xml version=\"1.0\"?>"
        s += "<items>"
        for u in contacts:

            if not (contact_name.lower() in u.name.lower()
                    or contact_name.lower().startswith(u.name.lower())):
                continue

            msg = ""
            if contact_name.lower() not in u.name.lower() and u.name.lower(
            ) in contact_name.lower():
                msg = contact_name[len(u.name):]

            s += "<item uid=\"" + str(u.id) + "\" arg=\"" + u.mode + " " + str(
                u.id) + " " + msg + "\" autocomplete=\"" + u.name + " \">"
            s += "<title>"
            s += u.name
            s += "</title>"
            s += "<subtitle>"
            s += msg
            s += "</subtitle>"
            s += "</item>"
        s += "</items>"
        #s = s.encode("utf-8")
        #s = s.encode("ascii", "backslashreplace")

        #print(s.decode("ascii", "ignore"))
        if renew:
            pickle.dump(contacts, open("contacts", "wb"))
        print(s)
    else:
        cc = [(x.first_name, x.last_name, x.id) for x in users]
        contacts = []
        for f, l, i in cc:
            if i is not None:
                s = "U" + str(i) + ":"
            else:
                continue
            if f is not None:
                s += f + " "
            if l is not None:
                s += l

            contacts.append(s.strip())

        contacts.extend(["C" + str(x.id) + ":" + x.title for x in chats])
        print(0)
        for c in contacts:
            print(c)
Beispiel #10
0
async def main():
    client = TelegramClient(None, api_id, api_hash)
    await client.connect()
    if not await client.is_user_authorized():
        try:
            phone_number = input("Phone number: {}".format(" " * 7))
            try:
                await client.send_code_request(phone=phone_number)
            except PhoneNumberInvalidError:
                print("-3, Phone number invalid")
                sleep(5)
                exit("-3")
            try:
                await client.sign_in(phone=phone_number,
                                     code=input('Enter telegram code: '))
            except PhoneCodeInvalidError:
                print("-2, Code invalid")
                sleep(5)
                exit("-2")
            except SessionPasswordNeededError:
                try:
                    await client.sign_in(
                        password=getpass("2FA password: {}".format(" " * 7)))
                except (PasswordHashInvalidError, PasswordEmptyError):
                    print("-1, Password invalid")
                    sleep(5)
                    exit("-1")
        except FloodWaitError:
            print(
                "Account login limited for 24 hours due login attempts flood.\nExiting..."
            )
            sleep(5)
            exit("-5")
        cls()
    self_user = await client.get_me()
    print("""
first_name= [{0}]
last_name=  [{1}]
username=   [{2}]
id=         [{3}]
phone=      [{4}]
        """.format(self_user.first_name, self_user.last_name,
                   self_user.username, self_user.id, self_user.phone))
    answer = input("Leave channels?\n(Y)es | (n)o\n")

    if match(r'(y|yes)', answer, flags=IGNORECASE):
        leavechat = True
    else:
        leavechat = False
    answer = input("Clear account? \n(Y)es | (n)o\n")
    cls()
    if match(r'(y|yes)', answer, flags=IGNORECASE):
        dialogs = await client.get_dialogs()
        contacts_list = await client(GetContactsRequest(0))
        animation = Animate(dialogs, "1 of 3 - chats wiping: ")
        for _ in dialogs:
            animation.callback()
            try:
                sleep(0.5)
                try:
                    await client(DeleteHistoryRequest(_, 0))
                except PeerIdInvalidError:
                    if leavechat:
                        await client(LeaveChannelRequest(_))
            except FloodWaitError as e:
                print(
                    "Telegram limits number of requests, please wait for {} seconds"
                    .format(e.seconds))
                print(
                    "When the limit passes, we will do everything ourselves\n")
                flood_waiter(e.seconds)
                try:
                    await client(DeleteHistoryRequest(_, 0))
                except PeerIdInvalidError:
                    await client(LeaveChannelRequest(_))

        del animation
        cls()
        animation = Animate(
            range(2),
            "1 of 3 - chats wiping: Done!\n2 of 3 - contacts wiping: ")
        for _ in range(2):
            animation.callback()
            try:
                sleep(0.5)
                await client(DeleteContactsRequest(contacts_list.users))
            except FloodWaitError as e:
                print(
                    "Telegram limits number of requests, please wait for {} seconds"
                    .format(e.seconds))
                print(
                    "When the limit passes, we will do everything ourselves\n")
                flood_waiter(e.seconds)
                await client(DeleteContactsRequest(contacts_list.users))

        del animation
        cls()
        print(
            """1 of 3 - chats wiping: Done!\n2 of 3 - contacts wiping: Done!\nName set to default\n\
Username cleared\nBio cleared\nProfile pics: Done!\n""")
        await client(
            UpdateProfileRequest(about="", first_name="default", last_name=""))
        try:
            await client(UpdateUsernameRequest(""))
        except UsernameNotModifiedError:
            pass
        me = await client.get_me()
        photos_list = await client(GetUserPhotosRequest(me, 0, 0, 0))
        await client(DeletePhotosRequest(photos_list.photos))
        input("Enjoy your brand-new account! (Press enter)")
        await client.log_out()
        exit("1")
    else:
        await client.log_out()
        exit("0")