
Pyrogram 登录时频繁提示“OTP 已过期”,即使秒级输入也失败——根本原因常在于客户端非预期断连、phone_code_hash 时效错配或异步生命周期管理不当,本文提供可落地的四步诊断与修复方案。
pyrogram 登录时频繁提示“otp 已过期”,即使秒级输入也失败——根本原因常在于客户端非预期断连、phone_code_hash 时效错配或异步生命周期管理不当,本文提供可落地的四步诊断与修复方案。
在使用 Pyrogram 实现 Telegram 双因素认证(尤其是短信/Telegram App OTP)时,开发者常遇到一个看似矛盾的现象:用户在收到验证码后立即输入(甚至 ,却仍收到 errors.PhoneCodeExpired 错误。这并非 Telegram API 的随机失效,而是由客户端状态管理缺陷引发的典型问题。下面我们将从原理到实践,系统性地定位并解决该问题。
? 根本原因分析
Pyrogram 的 sign_in() 要求 同一 Client 实例 必须保持连接状态,且 phone_code_hash 必须与调用 send_code() 时返回的完全一致、未过期。常见失效链如下:
- ✅
send_code()成功返回sent_code_info.phone_code_hash - ❌
auth_with_otp启动新Client实例(未复用),导致会话上下文丢失 - ❌
await self.client.disconnect()在send_code后被意外调用(当前代码虽未显式写,但QThread中多次创建 Client 易引发隐式状态污染) - ⚠️
phone_code_hash有效期仅 10 分钟,且单次有效:重复使用或跨 Client 实例即触发PhoneCodeExpired
? 关键认知:
phone_code_hash不是“令牌”,而是与本次send_code请求强绑定的一次性会话密钥,不可缓存、不可跨实例复用。
✅ 四步修复方案(含完整代码优化)
1. 禁止 Client 频繁重建 —— 复用连接实例
当前 TelegramWorker 每次都新建 Client,导致 phone_code_hash 与新 Client 不匹配。应改为:
✅ 在 send_code 阶段初始化 Client 并持久持有引用,后续 OTP 验证复用同一实例。
# 修改 TelegramWorker.run() 和 perform_action()
def run(self):
# 使用 asyncio.get_event_loop() 替代 asyncio.run(),避免事件循环销毁
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(self.perform_action())
finally:
loop.close()
async def perform_action(self):
try:
# ✅ 仅在 send_code 时创建 client;其他动作复用传入的 client(需重构传参)
if self.action == "send_code":
self.client = Client(TELEGRAM_SESSION, api_id=API_ID, api_hash=API_HASH)
await self.client.connect()
sent_code_info = await self.client.send_code(self.phone_number)
# ? 关键:将 client 实例与 phone_code_hash 一并传出,供后续复用
self.otp_sent.emit({
"client": self.client,
"phone_code_hash": sent_code_info.phone_code_hash
})
elif self.action == "auth_with_otp":
# ✅ 复用 send_code 时创建的 client 实例(通过 signal 传递)
if not hasattr(self, 'client') or self.client is None:
raise ValueError("Client not initialized. Call send_code first.")
await self.client.sign_in(
self.phone_number,
self.phone_code_hash,
self.otp
)
self.auth_complete.emit(True, "Authentication successful!")
# ... 其他分支保持不变,但注意:disconnect 仅在最终成功/失败后统一调用
except errors.PhoneCodeExpired:
self.auth_complete.emit(False, "The confirmation code has expired. Request a new one.")
# ✅ 立即触发重发逻辑(见第2步)
self.trigger_resend()
except Exception as e:
self.auth_complete.emit(False, str(e))
finally:
# ✅ 仅在 auth 流程结束时断开(避免中断 OTP 验证)
if self.client and self.action in ["auth_with_otp", "auth_with_password"]:
await self.client.disconnect()
2. UI 层强制启用重发倒计时(无论成功/失败)
在 handle_auth_result 中,只要 OTP 验证结束(无论成功与否),都应重置并启动倒计时,防止用户误操作:
def handle_auth_result(self, success, message):
if success:
QMessageBox.information(self, "Success", message)
self.accept()
else:
QMessageBox.warning(self, "Error", message)
# ✅ 无论 expired 还是 invalid,都允许重发
self.start_resend_timer() # ← 此行必须存在!
if "password" in message.lower():
# ... password flow
elif "expired" in message.lower() or "invalid" in message.lower():
self.otp_input.clear()
self.action_button.setText("Resend OTP")
self.action_button.clicked.disconnect()
self.action_button.clicked.connect(self.resend_otp)
3. 校准重发间隔:180 秒 ≠ 安全值
Telegram 官方文档明确要求 resendCode 最小间隔为 60 秒,但实际建议设为 120 秒以规避限流。将 start_resend_timer() 中的初始值修正为:
def start_resend_timer(self):
self.resend_countdown = 120 # ✅ 推荐值:120 秒(2分钟)
self.resend_label.setText(f"Didn't receive OTP? Resend in {self.resend_countdown} seconds")
self.resend_timer.start(1000)
4. 添加关键日志,定位时序问题
在 perform_action 中加入调试日志,确认 phone_code_hash 一致性及耗时:
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# 在 sign_in 前添加:
logger.info(f"[OTP Auth] Using phone_code_hash: {self.phone_code_hash[:8]}... (len={len(self.phone_code_hash)})")
start_time = asyncio.get_event_loop().time()
await self.client.sign_in(...)
end_time = asyncio.get_event_loop().time()
logger.info(f"[OTP Auth] sign_in completed in {end_time - start_time:.2f}s")
⚠️ 注意事项与最佳实践
-
绝不跨线程共享 Client 实例:Pyrogram Client 非线程安全。若需多线程,应使用
asyncio.Queue或进程间通信传递结果,而非直接传递 Client 对象。 -
Session 文件命名唯一性:确保
TELEGRAM_SESSION对不同手机号唯一(如f"session_{phone_number}"),避免会话冲突。 -
异常兜底处理:始终捕获
errors.PhoneCodeInvalid和errors.PhoneCodeExpired单独处理,避免被通用Exception掩盖。 -
超时控制:为
sign_in()添加超时(Pyrogram v2.0.107+ 支持):await asyncio.wait_for( self.client.sign_in(...), timeout=30.0 )
✅ 总结
OTP “秒输仍过期”的本质,是 Pyrogram 的会话状态(Client + phone_code_hash)未被正确维持。修复核心在于:一次连接、一次 hash、一次验证、一次断连。通过复用 Client 实例、精准控制 disconnect 时机、强化 UI 重发机制与日志可观测性,99% 的此类问题可彻底解决。切记:这不是 Pyrogram 的 Bug,而是对 Telegram 认证协议理解偏差导致的工程实践失误。











