【问题标题】:how i can restore sessions old in telethon telegram and connect this again(without send again code))我如何在 Telethon 电报中恢复旧会话并再次连接(无需再次发送代码))
【发布时间】:2017-09-10 17:39:10
【问题描述】:

我使用这个脚本在 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)

有了这个密码,我可以很好地登录这个号码电报并创建文件:+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()

但我有这个错误

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

【问题讨论】:

  • 你是如何断开连接的?你最后是否从 Telethon 调用任何 disconnet 函数?

标签: python api telegram telethon


【解决方案1】:

问题出在这一行:

client = TelegramClient('+15xxxxxxxxx', api_id, api_hash)

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

你明白了:

telethon.errors.RPCError: (RPCError(...), 'AUTH_KEY_UNREGISTERED (401):       The key is not registered in the system.')

因为您更改了会话的名称(现在将其称为“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)

然后删除.send_code_request(...)这一行:

client = TelegramClient('some_name', api_id, api_hash)
client.connect()

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

【讨论】:

  • @netdevil 这是正确答案,感谢 Lonami 的回答。我将很快删除我的。参加电视马拉松!
  • @Lonami 在 Telethon 上的出色工作。但是我在 Flask 中实现登录/授权时遇到了问题。
【解决方案2】:
from telethon import TelegramClient

# These example values won't work. You must get your own api_id and
# api_hash from https://my.telegram.org, under API Development.
api_id = ****** # Your api_id
api_hash = '********************************' # Your api_hash
phone_number = '+989122594574' # Your phone number

client = TelegramClient(phone_number, api_id, api_hash)
client.connect()

if not client.is_user_authorized():
    client.send_code_request(phone_number)
    client.sign_in(phone_number, input('Enter the code: '))


client.send_message('amir2b', 'Hello! Amir Bashiri')

【讨论】:

  • 欢迎来到 SO。仅代码的答案不被视为好的答案,请发布说明问题所在以及您的代码如何解决问题的文字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-29
  • 2018-07-12
相关资源
最近更新 更多