fix(services): ensure session directory exists and handle container paths

This commit is contained in:
mamad
2026-08-27 20:42:23 +03:30
parent 4e807bbb7e
commit 76a19131a6
3 changed files with 24 additions and 23 deletions
+12 -11
View File
@@ -10,7 +10,8 @@ from core.metrics import COLLECTED_POSTS_TOTAL
logger = logging.getLogger(__name__)
MEDIA_DIR = os.getenv("MEDIA_DIR", "/projects/telegram-bots/copykar/data/media")
SESSION_DIR = os.getenv("SESSION_DIR", "/app/sessions" if os.path.exists("/app") else "/projects/telegram-bots/copykar/sessions")
MEDIA_DIR = os.getenv("MEDIA_DIR", "/app/data/media" if os.path.exists("/app") else "/projects/telegram-bots/copykar/data/media")
class CollectorService:
def __init__(
@@ -19,21 +20,25 @@ class CollectorService:
ai_processor: AIProcessor,
api_id: Optional[int] = None,
api_hash: Optional[str] = None,
session_name: str = "/projects/telegram-bots/copykar/sessions/collector.session",
phone: Optional[str] = None,
session_name: Optional[str] = None,
):
self.repo = repo
self.ai_processor = ai_processor
self.api_id = api_id or int(os.getenv("API_ID", "0"))
self.api_hash = api_hash or os.getenv("API_HASH", "")
self.session_name = session_name
self.phone = phone or os.getenv("PHONE")
self.session_name = session_name or os.path.join(SESSION_DIR, "collector.session")
os.makedirs(os.path.dirname(self.session_name), exist_ok=True)
os.makedirs(MEDIA_DIR, exist_ok=True)
self.client = TelegramClient(self.session_name, self.api_id, self.api_hash)
async def start(self):
os.makedirs(os.path.dirname(self.session_name), exist_ok=True)
os.makedirs(MEDIA_DIR, exist_ok=True)
logger.info("Starting Collector Userbot...")
await self.client.start()
if self.phone:
await self.client.start(phone=self.phone)
else:
await self.client.start()
logger.info("Collector Userbot connected successfully.")
@self.client.on(events.NewMessage)
@@ -42,7 +47,6 @@ class CollectorService:
async def _handle_message(self, event: events.NewMessage.Event):
try:
# Check if source channel is in our monitored sources
chat_id = event.chat_id
source = await self.repo.get_source_by_channel_id(chat_id)
if not source or not source.is_active:
@@ -53,7 +57,6 @@ class CollectorService:
media_type = None
media_hash = None
# Download media if present
if event.message.media:
if isinstance(event.message.media, MessageMediaPhoto):
media_type = "photo"
@@ -71,7 +74,6 @@ class CollectorService:
content_hash = compute_content_hash(raw_text, media_hash)
# Store raw post in DB
post_id = await self.repo.create_raw_post(
source_channel_id=chat_id,
source_message_id=event.message.id,
@@ -84,7 +86,6 @@ class CollectorService:
if post_id:
COLLECTED_POSTS_TOTAL.labels(source_channel_id=str(chat_id)).inc()
logger.info(f"Collected new post ID {post_id} from channel {chat_id}")
# Trigger AI Processor pipeline
await self.ai_processor.process_post(post_id)
except Exception as e:
logger.error(f"Error handling message from {event.chat_id}: {e}", exc_info=True)