Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 236
Foad Avatar asked Oct 19 '25 09:10

Foad


1 Answers

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")
like image 82
Emad Helmi Avatar answered Oct 21 '25 22:10

Emad Helmi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!