【问题标题】:How to send message to unsaved number using Telegram API(Telethon)如何使用 Telegram API(Telethon) 向未保存的号码发送消息
【发布时间】:2021-03-11 22:01:17
【问题描述】:

我正在使用 Telethon 的 send_message 函数向各种号码发送消息。 我面临的问题是我可以向我的联系人列表中的号码发送消息,但是当我向未保存的号码发送消息时,我收到一个错误 "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())

【问题讨论】:

  • 如果用户在您的通讯录中,您只能通过电话号码发送消息。

标签: python telegram telethon


【解决方案1】:

首先,您需要让 Telethon 至少了解所有实体一次: 用于此用途:

dialogs = await client.get_dialogs()

之后使用命令获取手机号码所代表的实体:

entity = await client.get_entity(<mobile_num>)

现在你可以使用实体发送消息了

await client.send_message(entity, 'Hello, friend!')

欲了解更多信息,请查看:Telethon Entities

【讨论】:

  • 现在我在 entity = await client.get_entity() 中遇到同样的错误
  • 您是否发起过任何转化?有那个号码了吗?
【解决方案2】:

这是关于获取帐户数量的新电报限制

如果是Nobody,如果您之前的联系人中没有此号码,则无法通过号码找到它

【讨论】:

  • 已将其更改为收件人和发件人电报帐户中的每个人,但仍然无法正常工作。
  • 所以你必须把它保存在你的联系人中然后再试一次
【解决方案3】:

以上答案都不适合我,所以经过大量努力,我得到了问题的解决方案。 如果不保存他们的号码,就无法向电报用户发送消息。 为了克服这个问题,我们必须先通过这些代码行来保存数字:

注意:您必须将 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!')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 2018-02-13
    • 2021-04-23
    相关资源
    最近更新 更多