问题
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 PeerUser
s, 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?
回答1:
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
来源:https://stackoverflow.com/questions/48684915/telethon-library-how-to-add-user-by-phone-number