首页 > 解决方案 > 使用 Telethon 自动登录 Telegram 客户端(python)

问题描述

我正在尝试使用 Telethon 库对访问 Telegram 客户端的电报机器人进行编程。下面的代码中一切正常,但是在运行代码时,Telegram Auth 程序是通过终端运行的。有没有办法自动化该过程,以便我可以使用 Python 登录客户端(无需在终端中输入)。

Auth 程序要求:

我想要实现的是,当用户调用某个命令时,机器人会启动客户端登录过程并要求用户输入密码和安全码,然后它用于登录客户端。该机器人将使用 python-telegram-bot 库来管理与用户的对话,同时它会使用 Telethon 库连接到客户端。这甚至可能吗?谢谢

这是主文件:(一个工作测试示例,尝试在使用 python-telegram-bot 时登录 Telethon Telegram 客户端)

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')

使用上面的代码,我在终端中收到以下过程:

标签: pythontelegramtelegram-botpython-telegram-bottelethon

解决方案


你可以用最简单的方法以多种方式做到这一点.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)

它们都必须是返回字符串或字符串的可调用对象。


推荐阅读