Foad
Foad

Reputation: 109

Sending message with Telethon(Telegram API Client for Python)

I want to send a message with telethon using phone number but it give me an error that phone format is incorrect.this is my code:

from telethon import TelegramClient
from telethon.tl.types import PeerUser

api_id = 123456
api_hash = 'Something'

client = TelegramClient('Telethon', api_id, api_hash)
client.start()

contact = client.get_entity("+98XXXXXXXXXX")

Note: Python version 3.6 and latest version of Telethon.

Upvotes: 4

Views: 3205

Answers (1)

Emad Helmi
Emad Helmi

Reputation: 695

get_entity just works with saved phone numbers. You must first save the phone number in your contacts and then get the user entity. for saving the contact you can do as follow:

from telethon.tl.types import InputPhoneContact
from telethon.tl.functions.contacts import ImportContactsRequest

# Here you must connect to your client.
contact = InputPhoneContact(
        client_id=0,
        phone=phone_number,
        first_name="FN",
        last_name="LN"
    ) # For new contacts you should use client_id = 0
    result = client(ImportContactsRequest([contact]))
    try:
        client.get_entity(phone_number)
        print("There is an entity with the phone number")
    except:
        print("There is no such entity")

Upvotes: 4

Related Questions