使用Pyrogram登录Telegram时验证码过期问题求助
问题分析与解决方案
你遇到的验证码过期问题,核心原因是**phone_code_hash与Telegram客户端会话状态绑定,两次运行时的Client实例未共享会话上下文**。
问题根源
Telegram的send_code返回的phone_code_hash并非独立有效,它和发起请求的Client实例的会话状态(临时请求上下文、会话文件数据)绑定。你的代码分两次运行程序时,每次都会重新初始化一个全新的Client实例,第二次的Client没有第一次send_code时的会话上下文,导致服务器认为该hash对应的验证码已过期。
修正方案
需要确保两次操作共享同一个Client会话状态,具体实现如下:
步骤1:第一次运行(发送验证码并保存会话+hash)
import asyncio from telethon import Client app_id = 你的API_ID app_hash = "你的API_HASH" async def send_code(phone_number): client = Client('sessin', api_id=app_id, api_hash=app_hash) await client.connect() try: result = await client.send_code(phone_number) # 持久化保存phone_code_hash with open('phone_hash.txt', 'w') as f: f.write(result.phone_code_hash) print("验证码已发送,hash已保存") finally: # 断开连接时Client会自动保存会话状态到sessin.session文件 await client.disconnect() asyncio.run(send_code("你的手机号"))
步骤2:第二次运行(加载会话+hash,完成登录)
import asyncio from telethon import Client app_id = 你的API_ID app_hash = "你的API_HASH" async def main(phone_number, phone_code): # 使用同一个会话文件名,加载之前的会话状态 client = Client('sessin', api_id=app_id, api_hash=app_hash) await client.connect() try: # 读取保存的hash with open('phone_hash.txt', 'r') as f: phone_code_hash = f.read().strip() result = await client.sign_in(phone_number=phone_number, phone_code=phone_code, phone_code_hash=phone_code_hash) print("登录成功") except Exception as e: print(f"登录失败: {str(e)}") finally: await client.disconnect() asyncio.run(main("你的手机号", "收到的验证码"))
关键注意点
- 必须使用同一个会话文件名(示例中为
sessin),确保Client加载第一次运行时保存的会话状态。 send_code后必须调用await client.disconnect(),让Client将会话状态写入本地文件。- 验证码本身有5分钟左右的有效期,需在有效期内完成
sign_in操作。
内容的提问来源于stack exchange,提问作者valeX
相关产品推荐
相关产品推荐

