我如何恢复 telethon telegram 中旧的会话并再次连接(无需再次发送代码))

net*_*vil 2 python api telegram telethon

我使用这个脚本在电视马拉松中连接和创建会话

from telethon import TelegramClient
from telethon.tl.functions.messages import GetHistoryRequest
from telethon.utils import get_input_peer
api_id = 7****
api_hash = 'ef584d*****************'
client = TelegramClient('+15159947451', api_id, api_hash)
client.connect()
if not client.is_user_authorized():
    client.send_code_request('+15159947451')
client.sign_in('+15159947451', cod)
Run Code Online (Sandbox Code Playgroud)

有了这个代码,我可以在这个号码电报中登录并创建文件:+15159947451.session。

现在我关闭并断开连接,我如何使用此文件+15159947451.session再次登录此号码。

我使用这段代码,但这段代码有错误:

from telethon import TelegramClient
from telethon.tl.functions.messages import GetHistoryRequest
from telethon.utils import get_input_peer
api_id = 7****
api_hash = 'ef584d180eee*******************'
number='+15152934803'
client = TelegramClient('00', api_id, api_hash)
client.session.try_load_or_create_new(session_user_id='+15159947451')
client.connect()
Run Code Online (Sandbox Code Playgroud)

但我有这个错误

raise error
telethon.errors.RPCError: (RPCError(...), 'AUTH_KEY_UNREGISTERED (401):       The key is not registered in the system.')
Run Code Online (Sandbox Code Playgroud)

Lon*_*ami 5

问题是这一行:

client = TelegramClient('+15xxxxxxxxx', api_id, api_hash)
Run Code Online (Sandbox Code Playgroud)

您不必将电话号码作为第一个参数传递。您必须传递会话的名称,例如“myname”。

你得到这个:

telethon.errors.RPCError: (RPCError(...), 'AUTH_KEY_UNREGISTERED (401):       The key is not registered in the system.')
Run Code Online (Sandbox Code Playgroud)

因为您已经更改了会话的名称(现在将其称为“00”),并且尚未在该会话上登录。因此,为了简单地解决您的问题:

client = TelegramClient('some_name', api_id, api_hash)
client.connect()
if not client.is_user_authorized():
    client.send_code_request('+15xxxxxxxxx')
    client.sign_in('+15xxxxxxxxx', cod)
Run Code Online (Sandbox Code Playgroud)

然后删除该.send_code_request(...)行:

client = TelegramClient('some_name', api_id, api_hash)
client.connect()
Run Code Online (Sandbox Code Playgroud)

请注意,如果您将“some_name”更改为.session尚不存在的名称,则必须重新创建它。此外,您可以将.session文件重命名为您想要的任何名称,并使用其名称作为参数(因为它已经存在)。