问题描述
我正在研究电报的Telethon库,该库可以使用电报API充当电报客户端(重要:这是电报客户端API ,而不是Bot API).
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
但是,如果我通过的电话号码不在我的联系人列表中(我确定此电话号码已在Telegram中注册),这会中断
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)
我怀疑CreateChatRequest
仅适用于我的PeerUser
,即此方法禁止使用非对等电话.
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?
推荐答案
根据电报文档:
因此您可以按照Telethon
中的步骤进行操作:
So you can follow the steps in Telethon
:
- 将用户添加到联系人
- 将联系人添加到群组
- 删除联系人(可选)
例如,您可以使用以下代码:
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
我使用了Telethon V0.19
,但以前的版本几乎相同
I used Telethon V0.19
, but the previous versions are pretty much the same
这篇关于telethon库:如何通过电话号码添加用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!