需要pyrogram根据对 API 的请求创建和授权会话。
get-code有效,但sign-in由于代码过期而失败。我很确定这是因为我Client发布了不同代码并执行操作sign_in,但我不知道如何使用代码。
关于可以做什么的任何想法?
代码:
from fastapi import APIRouter, Body
from pyrogram import Client
from pyrogram.errors import SessionPasswordNeeded, BadRequest
from pyrogram.types import SentCode
from core import settings
from .redis_db import save_to_redis, get_from_redis, delete_from_redis
router = APIRouter(tags=['Telegram'])
@router.post('/telegram/get-code')
async def get_code(
data=Body()
):
phone = str(data['phone'])
phone = phone.replace('+', '')
client = Client(name=f"{phone}",
api_id=settings.API_ID,
api_hash=settings.API_HASH,
workdir=settings.WORKDIR
)
await client.connect()
try:
code_data: SentCode = await client.send_code(
phone_number=phone,
)
await save_to_redis(key=f"tg_client_{phone}", value={
'phone': phone,
'phone_code_hash': code_data.phone_code_hash
})
return {'success': True}
except Exception as err:
await client.disconnect()
raise err
@router.post('/telegram/sign-in')
async def sign_in(
data=Body()
):
phone = str(data['phone'])
phone = phone.replace('+', '')
phone_code = data['phone_code']
session_data = await get_from_redis(key=f"tg_client_{phone}")
if not session_data:
return {'success': False, 'message': 'Session not found'}
client = Client(
name=f"{phone}",
api_id=settings.API_ID,
api_hash=settings.API_HASH,
workdir=settings.WORKDIR
)
await client.connect()
phone_code_hash = session_data['phone_code_hash']
try:
await client.sign_in(phone_number=phone,
phone_code_hash=phone_code_hash,
phone_code=phone_code)
await client.disconnect()
await delete_from_redis(key=f"tg_client_{phone}")
return {'success': True}
except SessionPasswordNeeded:
password = data.get('password', None)
try:
await client.check_password(password=password)
except BadRequest:
await client.disconnect()
return {'success': False, 'message': 'Incorrect password'}
else:
await client.disconnect()
return {'success': True}
错误:
INFO: 127.0.0.1:41094 - "POST /api/v1/telegram/sign-in HTTP/1.1" 500 Internal Server Error
pyrogram.errors.exceptions.bad_request_400.PhoneCodeExpired: Telegram says: [400 PHONE_CODE_EXPIRED] - The confirmation code has expired (caused by "auth.SignIn")
我是通过websockets做到的: