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

时间:2018-08-27 08:52:55

标签: python client telegram telethon

我想使用电话号码通过Telethon发送消息,但这给我一个错误,提示电话格式不正确。这是我的代码:

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的最新版本。

1 个答案:

答案 0 :(得分:1)

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

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