导入:
from telethon import TelegramClient, events, sync
from telethon.tl.types import InputPhoneContact
from telethon import functions, types
代码:
phone_number = "some_friend_phone_no"
contact = InputPhoneContact(client_id=0, phone=phone_number, first_name="first", last_name="last") #enter phone number with settings
contacts = client(functions.contacts.ImportContactsRequest([contact])) #import that number to contacts
if len(contacts.users) > 0: #if user exists on telegram
username = contacts.users[0].username #then insert user value into username variable
if username is not None: #if username is not empty
client(functions.contacts.DeleteContactsRequest(id=[username])) #then DELETE that contact
该代码首先将phone_number
添加到我们的联系人列表中,然后我们可以轻松地获得他们的用户名。
在我们删除该联系人后,因为我们只需要他们的用户名。
但有些用户没有设置用户名,所以我们将用户名设置为None
。
现在如何删除该联系人?目前我使用client(functions.contacts.DeleteContactsRequest(id=[username]))
,如果用户名是None
,它将失败。
根据文档,您可以制作一个InputUser
,然后将其交给DeleteContactRequest
。
由于你已经有了用户,你可以:
client(functions.contacts.DeleteContactsRequest(id=[contacts.users[0]]))