Add source
This commit is contained in:
82
bot/utils/telegram_user.py
Normal file
82
bot/utils/telegram_user.py
Normal file
@@ -0,0 +1,82 @@
|
||||
"""
|
||||
Utilities for working with Telegram user information
|
||||
"""
|
||||
from typing import Optional, Dict
|
||||
from pyrogram import Client
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def get_app_client() -> Optional[Client]:
|
||||
"""
|
||||
Get Pyrogram client from executor.py.
|
||||
|
||||
Uses a single source of client to avoid conflicts.
|
||||
|
||||
Returns:
|
||||
Pyrogram client instance, or None if import fails
|
||||
"""
|
||||
try:
|
||||
from bot.modules.task_scheduler.executor import get_app_client as get_executor_client
|
||||
return get_executor_client()
|
||||
except ImportError:
|
||||
logger.warning("Failed to import get_app_client from executor")
|
||||
return None
|
||||
|
||||
|
||||
async def get_user_info(user_id: int) -> Optional[Dict[str, Optional[str]]]:
|
||||
"""
|
||||
Get user information from Telegram API.
|
||||
|
||||
Args:
|
||||
user_id: Telegram user ID
|
||||
|
||||
Returns:
|
||||
Dictionary with user information:
|
||||
{
|
||||
"username": str or None,
|
||||
"first_name": str or None,
|
||||
"last_name": str or None
|
||||
}
|
||||
or None in case of error
|
||||
"""
|
||||
app_client = get_app_client()
|
||||
|
||||
if not app_client:
|
||||
logger.warning(f"Pyrogram client not set, cannot get user information for {user_id}")
|
||||
return None
|
||||
|
||||
try:
|
||||
# Get user information through Pyrogram
|
||||
user = await app_client.get_users(user_id)
|
||||
|
||||
if user:
|
||||
return {
|
||||
"username": user.username,
|
||||
"first_name": user.first_name,
|
||||
"last_name": user.last_name
|
||||
}
|
||||
else:
|
||||
logger.warning(f"User {user_id} not found in Telegram")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting user information for {user_id}: {e}", exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
async def get_username_by_id(user_id: int) -> Optional[str]:
|
||||
"""
|
||||
Get username by user ID.
|
||||
|
||||
Args:
|
||||
user_id: Telegram user ID
|
||||
|
||||
Returns:
|
||||
Username or None if not found
|
||||
"""
|
||||
user_info = await get_user_info(user_id)
|
||||
if user_info:
|
||||
return user_info.get("username")
|
||||
return None
|
||||
|
||||
Reference in New Issue
Block a user