问题描述
我正在尝试编写一个使用Telethon库访问Telegram Client的电报机器人。 一切在下面的代码中均能正常工作,但是在运行代码时,Telegram Auth过程是通过终端运行的。 有没有一种方法可以使该过程自动化,以便我可以使用Python登录客户端(而无需在终端中键入内容)。
Auth过程要求:
- 电话号码
- 密码
- 安全码
我要实现的目标是,当用户调用某个命令时,该bot会启动客户端登录过程,并要求用户输入密码和安全码,然后将其用于登录客户端。该机器人将使用python-telegram-bot库管理与用户的对话,而它会使用Telethon库连接到客户端。 那有可能吗? 谢谢
这是主文件:(一个有效的测试示例,尝试在使用python-telegram-bot时登录Telethon Telegram Client)
from telethon import TelegramClient
from karim.secrets import secrets
import asyncio
# this def gets called when the /telethon command is sent by the user to the bot
def telethonMessage(update,context):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
api_id = secrets.get_var('API_ID')
api_hash = secrets.get_var('API_HASH')
client = TelegramClient('anon',api_id,api_hash,loop=loop)
with client:
loop.run_until_complete(send_telethon_message(client,update.effective_user.id))
async def send_telethon_message(client,user_id):
me = await client.get_me()
print('TELETHON: {}',me.username)
await client.send_message(user_id,'Testing Telethon')
使用上面的代码,我在终端中收到以下过程:
- 请输入您的电话(或漫游器令牌):
- 请输入您收到的验证码:
- 请输入您的密码:
解决方法
您可以通过多种方式来做到这一点,最简单的方法是.start
。
当您进行with client:
时,telethon在后台使用默认值进行.start
文档参考:https://docs.telethon.dev/en/latest/modules/client.html?telethon.client.auth.AuthMethods.start
因此,回答问题的方法不是打电话给with client:
await client.start(phone=your_phone_callback,password=your_password_callback,code_callback=your_code_callback)
所有这些都必须是可返回字符串或字符串的可调用项。
,验证用户身份的另一种方法是将send_code_request
和sign_in
方法用作documented in this section
作为完整示例:
async def main(): client = TelegramClient('anon',api_id,api_hash) assert await client.connect() if not client.is_user_authorized(): await client.send_code_request(phone_number) me = await client.sign_in(phone_number,input('Enter code: '))
所有这些都可以通过调用.start()来完成:
async def main(): client = TelegramClient('anon',api_hash) await client.start()
显示的代码就是
.start()
在幕后所做的事情 (带有一些额外的支票), ,这样您就可以知道如何签名 想避免出于任何原因使用input()
(默认设置) 。
通读本节以了解如何处理诸如需要2FA密码之类的极端情况。
,您可能希望将 bot_token 用于身份验证过程,这是对 phone_number 的补充。
bot = await TelegramClient(username,api_hash).start(bot_token=token,max_attempts=10)