A
A
Adam2021-01-31 16:39:20
Python
Adam, 2021-01-31 16:39:20

Telethon Telegram api How to add to contacts without phone number?

I am writing a bot that should add users to the contacts of the account, but at the same time I have only id and username. What to do? Is there a way to add a person without knowing their number?

from telethon import TelegramClient
from telethon.tl.functions.contacts import GetContactsRequest
from telethon.tl.types import InputPeerUser
client = TelegramClient('session_name', api_id, api_hash)
client.connect()
#id=23515451
#username='User123'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
ya_ne_znau, 2021-01-31
@lollol9

you can’t find a user through id, it’s written in telegram, but through username please

from time import sleep
from telethon.tl.functions.contacts import ImportContactRequest
from telethon.tl.types import InputPhoneContact, User
from telethon.errors.rpcerrorlist import FloodWaitError
from telethon import TelegramClient
client = TelegramClient("имя сессии", "апи ид", "апи хеш")  # можешь сюда ещё старт вписать
async def run():
    while True:
        try:
            result = await client(ImportContactsRequest([InputPhoneContact(
                client_id=1,  # любой ид
                phone=<сюда точно подойдет телефон, возможно что и username тоже>,
                first_name="имя", last_name="фамилия",
            )]))
            except FloodWaitError as e:
                sleep(e.seconds)
client.loop.run_until_complete(run())

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question