Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import a list of contacts from CSV file to Telegram using Python3

I am trying to import contacts from a CSV file using Python3.

The code is running well and not showing any errors, but the contacts did not get added in Telegram. Any ideas why?

See the code below:

import csv
from telethon import TelegramClient
from telethon.tl.functions.contacts import GetContactsRequest
from telethon.tl.types import InputPeerUser
from telethon.tl.types import InputPhoneContact
api_id = *******
api_hash = '*********'

client = TelegramClient('myname', api_id, api_hash)
client.connect()
with open('list.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for line in csv_reader:
 contact = InputPhoneContact(client_id = 0, phone = (line[0]), first_name=(line[1]), last_name=(line[2]))
    contacts = client(GetContactsRequest(0))
    result = client.invoke(ImportContactsRequest([contact]))
like image 481
Ameer Drebee Avatar asked Oct 16 '25 02:10

Ameer Drebee


1 Answers

Nowadays Telegram does not support ImportContacts properly for unknown reason. It loads only 4-5 contacts for newly created account, the following ones are ignored. And you should use telethon's ImportContactsRequest method like this:

contacts_book = []
with open('list.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    for line in csv_reader:
        contacts_book.append(InputPhoneContact(client_id=0, phone='+' + line[0], first_name=line[1], last_name=line[2]))
result = client(ImportContactsRequest(contacts_book))

i.e. only one ImportContactsRequest for ≈1000 contacts (and below 5000 for one account)

like image 114
hioma Avatar answered Oct 18 '25 21:10

hioma