31 lines
1.1 KiB
Python
31 lines
1.1 KiB
Python
import phonenumbers
|
|
from phonenumbers import NumberParseException
|
|
from typing import Optional
|
|
|
|
def normalize_phone(phone: str, default_region: str = "US") -> Optional[str]:
|
|
"""
|
|
Normalize a phone number to E.164 format.
|
|
For Telegram provider, accepts plain user IDs (just digits).
|
|
Returns None if the phone number is invalid.
|
|
"""
|
|
try:
|
|
# Clean the phone number
|
|
phone = str(phone).strip()
|
|
|
|
# If it's a short number (< 11 digits), treat as Telegram ID
|
|
# Telegram user IDs are typically 9-10 digits
|
|
if phone.isdigit() and len(phone) <= 10:
|
|
return phone # Return as-is for Telegram
|
|
|
|
# For longer numbers, try phone number validation
|
|
# If phone doesn't start with '+', try adding it
|
|
if phone and not phone.startswith('+'):
|
|
phone = '+' + phone
|
|
|
|
parsed = phonenumbers.parse(phone, default_region)
|
|
if phonenumbers.is_valid_number(parsed):
|
|
return phonenumbers.format_number(parsed, phonenumbers.PhoneNumberFormat.E164)
|
|
return None
|
|
except NumberParseException:
|
|
return None
|