Use Python 3 to import a contact list from a CSV file to Telegram… here is a solution to the problem.
Use Python 3 to import a contact list from a CSV file to Telegram
I’m trying to import contacts from a CSV file using Python3.
The code works fine and doesn’t show any errors, but no contacts are added in Telegram. Any ideas?
Take a look at 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]))
Solution
For unknown reasons, Telegram now does not support ImportContacts correctly. It only loads 4-5 contacts for the newly created account, the following ones will be ignored. 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))
That is, only one ImportContactsRequest is used to ≈ 1000 contacts (an account is less than 5000).