python - 使用 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')
使用上面的代码,我在终端中收到以下过程:
- 请输入您的手机(或机器人令牌):
- 请输入您收到的代码:
- 请输入您的密码:
解决方案
你可以用最简单的方法以多种方式做到这一点.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)
它们都必须是返回字符串或字符串的可调用对象。
推荐阅读
- python - 来自xarray dataarray的三角波的主频率
- pandas - 在 Pandas 中解析字符串
- microsoft-graph-api - 无法从图形 api 检索团队 - 未找到 GetThreadS2SRequest
- flutter - 每当我点击 Textfield 时,它都会显示一个白色容器。如何在颤振中消除该问题?
- swift - 仅当父级存在于 Vapor 中时才使用 Fluent 创建记录
- javascript - 如何在 JSX 中添加超链接
- python - Python 没有将值替换为 \\ 被映射为 \
- java - 如何以编程方式更改 Eclipse 运行配置的工作目录?
- linear-programming - 以乘数形式编写 DEA LPP
- github - 您的网站在构建时遇到问题:无法构建页面。请稍后再试