[英]How to send message to unsaved number using Telegram API(Telethon)
我正在使用 Telethon 的 send_message function 向各种号码发送消息。 我面临的问题是我可以向联系人列表中的号码发送消息,但是当我向未保存的号码发送消息时出现错误“ValueError:找不到与“+XXXXXXXXXXXX”相对应的任何实体
from telethon import TelegramClient
api_id = xxxxx
api_hash = 'xxxxx'
client = TelegramClient('anon', api_id, api_hash)
async def main():
await client.send_message('+XYZXYZXYZXYZ', 'Hello, friend!')
with client:
client.loop.run_until_complete(main())
首先,您需要让 Telethon 至少知道所有实体一次:对于此用途:
dialogs = await client.get_dialogs()
在此之后,使用以下命令获取手机号码所代表的实体:
entity = await client.get_entity(<mobile_num>)
现在您可以使用实体发送消息
await client.send_message(entity, 'Hello, friend!')
有关更多信息,请查看: Telethon Entities
以上答案都不适合我,所以经过大量努力,我得到了问题的解决方案。 如果不保存他们的号码,就无法向电报用户发送消息。 为了克服这个问题,我们首先必须通过这些代码行来保存数字:
注意:您必须将 Telethon 降级到 0.19,只需运行pip install telethon==0.19
contact = InputPhoneContact(client_id=0, phone=guest_phone_number,\
first_name="first_name", last_name="last_name")
result = client.invoke(ImportContactsRequest([contact]))
这是完整的工作代码:
from telethon import TelegramClient
from telethon.tl.functions.messages import AddChatUserRequest
from telethon.tl.types import InputPhoneContact
from telethon.tl.functions.contacts import ImportContactsRequest
api_id = XXXXX
api_hash = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
phone_number = '+XXXXXXXXXXXX' #sender's phone number
guest_phone_number='+XXXXXXXXXXXX' #recievers phone number
client = TelegramClient('session_name',
api_id,
api_hash)
assert client.connect()
if not client.is_user_authorized():
client.send_code_request(phone_number)
me = client.sign_in(phone_number, input('Enter code: '))
# ---------------------------------------
# add user to contact
contact = InputPhoneContact(client_id=0, phone=guest_phone_number,\
first_name="user", last_name=" ")
result = client.invoke(ImportContactsRequest([contact]))
# ---------------------------------------
# send message to reciever
client.send_message(result.users[0], 'Hello, friend!')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.