DEV Community

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

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

luvejo profile image Luis Velásquez ・2 min read

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 where not 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',

Enter fullscreen mode Exit fullscreen mode

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

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'},


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.')
    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!

Alt Text

Discussion (1)

Editor guide
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