使用 Telethon 发送消息(Telegram API Python 的客户端)

Sending message with Telethon(Telegram API Client for Python)

我想使用 phone 号码通过 telethon 发送消息,但它给我一个错误,phone 格式是 incorrect.this 是我的代码:

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")

注意:Python 3.6 版和最新版本的 Telethon。

get_entity 仅适用于保存的 phone 号码。您必须先在联系人中保存 phone 号码,然后获取用户实体。要保存联系人,您可以执行以下操作:

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")