DEV Community

Cover image for Checking if a phone number is on Telegram, using TDLib and Python
Luis Velásquez
Luis Velásquez

Posted on • Updated on

Checking if a phone number is on Telegram, using TDLib and Python

This may come in handy if you plan to migrate, for example, an existing WhatsApp group. A good number of users that have already migrated may be a convincing argument to promote such change, specially in communities where Telegram wasn't that well known so far.

In this tutorial we'll be using the Telegram Database Library (or TDLib), which lets you build your own Telegram clients. Happily, there is a nice python wrapper for it.

1. Setting up

The first thing is registering a new Telegram Application.

Once that we have both api_id and api_hash, we need to get python-telegram. Make sure you use Python 3.6+.

python3 -m pip install python-telegram
Enter fullscreen mode Exit fullscreen mode

2. Calling the API

We are ready to instantiate the client.

from telegram.client import Telegram

tg = Telegram(
    api_id='YOUR API ID',
    api_hash='YOUR API HASH',
    phone='+575555555555',
    database_encryption_key='changeme1234',
)

tg.login()
Enter fullscreen mode Exit fullscreen mode

A prompt will wait for us to enter a verification code, which will be sent to our telegram account.

Note: database_encryption_key is just a string TDLib needs in order to encrypt and decrypt the local database. If you're going to build a real Telegram client, make sure this key is a strong one (just like a password). For this exercise it may not be worth coming up with a super secure key, but this is up to you.

The Telegram class has some TDLib methods available, like login(), send_message(), and a few more. For any other we need to use call_method().

In order to check whether a phone number is using Telegram or not, we need to add it as a contact. importContacts() is what we are looking for. It let us add new contacts just by their phone numbers, though you can also specify things like first_name, last_name, and others.

response = tg.call_method('importContacts', {
    'contacts': [
        {'phone_number': '+57 555 123 4567'},
    ]
})

response.wait()

user_ids = response.update['user_ids']
Enter fullscreen mode Exit fullscreen mode

If a number is not currently on the platform, it will return 0 as its user id.

if user_ids[0] == 0:
    print('This contact is NOT using Telegram.')
else:
    print(f'¡This contact({user_ids[0]}) uses Telegram!')
Enter fullscreen mode Exit fullscreen mode

3. Cleaning

Time to remove those testing contacts.

tg.call_method('removeContacts', {'user_ids': user_ids})
Enter fullscreen mode Exit fullscreen mode

And that's it. Hope you enjoyed my first tutorial 🧪

Happy hacking!

Link to my Buy me a coffee account

Top comments (12)

Collapse
 
hafizusman924 profile image
Usman Ali

TypeError Traceback (most recent call last)
in ()
12 response.wait()
13 counter += 1
---> 14 user_ids = response.update['user_ids']
15 if user_ids[0] == 0:
16 print('This contact is NOT using Telegram.'+value)

TypeError: 'NoneType' object is not subscriptable

After Running this code i check only 1000 number and after this this code stop working. Because number error. when i change phone number this code again start working perfectly. Can you please guide me who i can avoid this error?

!python3 -m pip install python-telegram
from google.colab import drive
drive.mount('/content/drive')

import pandas as pd
from telegram.client import Telegram

tg = Telegram(
api_id='Write Your Api',
api_hash='Write Your Hash',
phone='Write you Number',
database_encryption_key='hisunny1',
)

tg.login()
from time import sleep

counter = 0
tel_num = []
for x, value in df.Number.iteritems():

response = tg.call_method('importContacts', {
'contacts': [
{'phone_number': '+'+value},
]
})
response.wait()
counter += 1
user_ids = response.update['user_ids']
if user_ids[0] == 0:
print('This contact is NOT using Telegram.'+value)
sleep(15)
else:
print(f'¡This contact({user_ids[0]}) uses Telegram!'+value)
tel_num.append('+'+value)
sleep(15)

Collapse
 
luvejo profile image
Luis Velásquez • Edited

Sorry, I cannot help you these days. It would require me to setup the environment and to dig into a documentation I haven't went through in months.

But it seems like an API restriction. I would suggest you to debug/inspect the response object 🐞

By the way: it might be a good idea to use Markdown to format your code snippets 🎨 That makes it easier for other people to help you.

Cheers!

Collapse
 
hafizusman924 profile image
Usman Ali

Thanks for your reply. Could you please take a look whenever you free.

Thread Thread
 
alexkolzov profile image
alexkolzov

Are you solve this problem?

Collapse
 
trn21 profile image
trn21

hi luis...
every time i am getting "this contact is not using telegram" even if the contact is on telegram. please help me..

Collapse
 
luvejo profile image
Luis Velásquez

🤔 Interesting. Did you checked if it was because of that user's privacy settings?

Collapse
 
trn21 profile image
trn21

but how it depends on privacy, the script is getting only response from api.

Collapse
 
amirmohamad profile image
Amir-Mohamad

how can i get access to the username of that user instead of id

Collapse
 
komiljonov profile image
KOMILJONOV

Hello how can i get

database_encryption_key

Collapse
 
luvejo profile image
Luis Velásquez

Hey. It can be whatever you want. Just like a password, make sure it's a strong one!

Collapse
 
spidermanir profile image
Siavash • Edited

Hi Luis,
i'm run this code but it gives Error:
user_ids = response.update['user_ids']
TypeError: 'NoneType' object is not subscriptable

response.wait() returns None

Collapse
 
luvejo profile image
Luis Velásquez

Hey! I ran the snippets once again and they still work as expected. Maybe check that you are actually authenticating the client.