skip to Main Content

I have a python script which allows me to check if a number is used on telegram or not.

I try to change the variable "phone_number" to a .txt list which basically contain phone number (There is one phone number per line)
I want the script to take a phone number from the file.txt check if it exists or not then move on to the next one and so on until all the numbers are checked.

This is what i try so far…

import random
from telethon import TelegramClient
from telethon import functions, types
import ast


api_id = XXXXX
api_hash = 'XXXXXXXXXXXXXXXXXX'
client = TelegramClient('session', api_id, api_hash)

async def main():
    phone_in = []
    with open('file.txt', 'r') as f:
        phone_str = f.readline()
        phone_in.append(ast.literal_eval(phone_str))

    result = await client(functions.contacts.ImportContactsRequest(
        contacts=[types.InputPhoneContact(
            client_id=random.randrange(-2**63, 2**63),
            phone=phone_in,
            first_name='Some Name',
            last_name=''
        )]
    ))

    if len(result.users):
        print(f"{phone_in} has a telegram account")
        await client(functions.contacts.DeleteContactsRequest(result.users))
    else:
        print(f"couldn't find an account for {phone_in}")

client.start()
client.loop.run_until_complete(main())

I tried this but I had an error which is the following :

Traceback (most recent call last):
  File "/Users/me/phone.py", line 33, in <module>
    client.loop.run_until_complete(main())
  File "/usr/local/Cellar/[email protected]/3.9.1_7/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
    return future.result()
  File "/Users/me/phone.py", line 17, in main
    result = await client(functions.contacts.ImportContactsRequest(
  File "/usr/local/lib/python3.9/site-packages/telethon/client/users.py", line 30, in __call__
    return await self._call(self._sender, request, ordered=ordered)
  File "/usr/local/lib/python3.9/site-packages/telethon/client/users.py", line 58, in _call
    future = sender.send(request, ordered=ordered)
  File "/usr/local/lib/python3.9/site-packages/telethon/network/mtprotosender.py", line 174, in send
    state = RequestState(request)
  File "/usr/local/lib/python3.9/site-packages/telethon/network/requeststate.py", line 17, in __init__
    self.data = bytes(request)
  File "/usr/local/lib/python3.9/site-packages/telethon/tl/tlobject.py", line 194, in __bytes__
    return self._bytes()
  File "/usr/local/lib/python3.9/site-packages/telethon/tl/functions/contacts.py", line 498, in _bytes
    b'x15xc4xb5x1c',struct.pack('<i', len(self.contacts)),b''.join(x._bytes() for x in self.contacts),
  File "/usr/local/lib/python3.9/site-packages/telethon/tl/functions/contacts.py", line 498, in <genexpr>
    b'x15xc4xb5x1c',struct.pack('<i', len(self.contacts)),b''.join(x._bytes() for x in self.contacts),
  File "/usr/local/lib/python3.9/site-packages/telethon/tl/types/__init__.py", line 9789, in _bytes
    self.serialize_bytes(self.phone),
  File "/usr/local/lib/python3.9/site-packages/telethon/tl/tlobject.py", line 112, in serialize_bytes
    raise TypeError(
TypeError: bytes or str expected, not <class 'list'>

Here is the same code but the phone number to check is "hardcoded"

import random
from telethon import TelegramClient
from telethon import functions, types

api_id = XXXXXXX
api_hash = 'XXXXXXXXXXXXXXXXX'
client = TelegramClient('session', api_id, api_hash)

async def main():
    phone_number = '+XXXXXXXXX'
    result = await client(functions.contacts.ImportContactsRequest(
        contacts=[types.InputPhoneContact(
            client_id=random.randrange(-2**63, 2**63),
            phone=phone_number,
            first_name='Some Name',
            last_name=''
        )]
    ))

    if len(result.users):
        print(f"{phone_number} has a telegram account")
        await client(functions.contacts.DeleteContactsRequest(result.users))
    else:
        print(f"couldn't find an account for {phone_number}")

client.start()
client.loop.run_until_complete(main())

Does anyone know how I can assign the file.txt to the phone_in variable?

2

Answers


  1. If ImportContactsRequests expects one phone number at a time, then you have to call it for each phone number. That will create multiple records for a single name, but if the API doesn’t allow multiple phone numbers per person, you’ll have to decide how to handle it.

        with open('file.txt', 'r') as f:
            phone_str = f.readline()
    
            result = await client(functions.contacts.ImportContactsRequest(
                contacts=[types.InputPhoneContact(
                    client_id=random.randrange(-2**63, 2**63),
                    phone=phone_str,
                    first_name='Some Name',
                    last_name=''
                )]
            ))
    
            if len(result.users):
                print(f"{phone_number} has a telegram account")
                await client(functions.contacts.DeleteContactsRequest(result.users))
            else:
                print(f"couldn't find an account for {phone_number}")
    
    Login or Signup to reply.
  2. According to the doc of InputPhoneContact, the phone argument takes string type not list. So you could read all phones in the file.txt first, then loop through the list.

    async def main():
        phone_in = []
        with open('file.txt', 'r') as f:
            phone_str = f.readline()
            phone_in.append(ast.literal_eval(phone_str))
    
        for phone in phone_in:
            result = await client(functions.contacts.ImportContactsRequest(
                contacts=[types.InputPhoneContact(
                    client_id=random.randrange(-2**63, 2**63),
                    phone=phone,
                    first_name='Some Name',
                    last_name=''
                )]
            ))
        
            if len(result.users):
                print(f"{phone} has a telegram account")
                await client(functions.contacts.DeleteContactsRequest(result.users))
            else:
                print(f"couldn't find an account for {phone}")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search