kurtgn
kurtgn

Reputation: 8710

telethon library: how to add user by phone number

I am studying Telethon library for Telegram that can act as a Telegram client using Telegram API (Important: this is Telegram client API, not Bot API).

The functionality I need is creating a group chat and inviting users there. This works fine when I add somebody who is in my contact list:

import telethon
from telethon.tl.functions.messages import CreateChatRequest
client = telethon.TelegramClient('some_session', 'key', '6284f5acf91b03somehash441ac9eef319')
client.start()
client(CreateChatRequest(['+79297226653'], 'Test Group')) # number from my contact list

However, this breaks if the number I pass is not in my contact list (an I am certain this phone number is registered with Telegram)

  File "/Users/1111/.virtualenvs/inviter-WB5rPISo/lib/python3.6/site-packages/telethon/telegram_client.py", line 1680, in _get_entity_from_string
    'Cannot turn "{}" into any entity (user or chat)'.format(string)
TypeError: Cannot turn "+79291101517" into any entity (user or chat)

My suspicion is that CreateChatRequest only works for my PeerUsers, i.e. using non-peer phones is prohibited in this method.

So the question is, how do I add somebody to a group chat if he is not one of my contacts?

Upvotes: 4

Views: 15148

Answers (3)

unsafePtr
unsafePtr

Reputation: 1763

The below will be valid for v1.24.0. If you plan to add user to channel you will need to use InviteToChannelRequest.

# add user to channel     
# https://docs.telethon.dev/en/stable/examples/chats-and-channels.html#adding-someone-else-to-such-chat-or-channel
inviteRequest = await client(InviteToChannelRequest(
    my_private_channel,
    [user] # you can get user from InputPhoneContact when adding it to the peers
))

Please beware of telegram limitations. According to the docs you can add up to 200 users via API. After that users can be invited by invitation link. Instead you can send message to user with the invitation link

# get private channel
async for dialog in client.iter_dialogs():
    if dialog.name == channelName:
        my_private_channel = dialog
        my_private_channel_id = dialog.id
        break

# get invitation link
chatInvite = ExportChatInviteRequest(my_private_channel_id)
invitations = await client(chatInvite)

# send invitation link to user
receiver = InputPeerUser(user.id, user.access_hash)
await client.send_message(receiver, invitations.link)

Upvotes: 0

Marcos Antonio
Marcos Antonio

Reputation: 31

Completing the answer, to remove the contact you may use the DeleteContactsRequest function:

from telethon import TelegramClient
from telethon.tl.functions.messages import AddChatUserRequest
from telethon.tl.types import InputPhoneContact
from telethon.tl.functions.contacts import ImportContactsRequest

from telethon.tl.functions.contacts import DeleteContactsRequest

api_id = XXXXXX
api_hash = 'XXXXXXXXXXXXXXXXXXXXXXXX'
phone_number = '+98XXXXXXXXXX'
################################################
group_id = 263549607 
guest_phone_number=XXXXXXXXXXXX
################################################

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="custom_first_name", last_name="custom_last_name")
result = client.invoke(ImportContactsRequest([contact]))
# ---------------------------------------
# add contact to your group
client(AddChatUserRequest(user_id=result.users[0], fwd_limit=0, chat_id=group_id))
# ---------------------------------------
# remove contact
client(DeleteContactsRequest(id=result.users[0]))

Upvotes: 3

Alihossein shahabi
Alihossein shahabi

Reputation: 4352

According to the telegram document:

You can add your contacts, or use search by username.

So you can follow the steps in Telethon :

  • Add user to contact
  • Add a contact to the group
  • delete Contact(optional)

for example, you can use this code :

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 = XXXXXX
api_hash = 'XXXXXXXXXXXXXXXXXXXXXXXX'
phone_number = '+98XXXXXXXXXX'
################################################
group_id = 263549607 
guest_phone_number=XXXXXXXXXXXX
################################################

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="custom_first_name", last_name="custom_last_name")
result = client.invoke(ImportContactsRequest([contact]))
# ---------------------------------------
# add contact to your group
client(AddChatUserRequest(user_id=result.users[0], fwd_limit=0, chat_id=group_id))
# ---------------------------------------
# remote contact

I used ‍Telethon V0.19, but the previous versions are pretty much the same

Upvotes: 7

Related Questions