postpilot 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. postpilot/__init__.py +6 -0
  2. postpilot/ai/__init__.py +1 -0
  3. postpilot/ai/base.py +23 -0
  4. postpilot/ai/gemini.py +46 -0
  5. postpilot/ai/groq.py +59 -0
  6. postpilot/ai/ollama.py +42 -0
  7. postpilot/ai/router.py +45 -0
  8. postpilot/cli.py +93 -0
  9. postpilot/commands/__init__.py +31 -0
  10. postpilot/commands/autopilot_cmd.py +102 -0
  11. postpilot/commands/config_cmd.py +65 -0
  12. postpilot/commands/dna_cmd.py +126 -0
  13. postpilot/commands/doctor_cmd.py +67 -0
  14. postpilot/commands/drafts_cmd.py +71 -0
  15. postpilot/commands/generate_cmd.py +45 -0
  16. postpilot/commands/init_cmd.py +45 -0
  17. postpilot/commands/publish_cmd.py +45 -0
  18. postpilot/commands/queue_cmd.py +44 -0
  19. postpilot/commands/schedule_cmd.py +47 -0
  20. postpilot/commands/status_cmd.py +56 -0
  21. postpilot/daemon.py +131 -0
  22. postpilot/database/__init__.py +1 -0
  23. postpilot/database/db.py +32 -0
  24. postpilot/database/models.py +173 -0
  25. postpilot/database/repositories.py +243 -0
  26. postpilot/dna/__init__.py +3 -0
  27. postpilot/dna/analyzer.py +79 -0
  28. postpilot/dna/collector.py +106 -0
  29. postpilot/dna/generator.py +64 -0
  30. postpilot/main.py +15 -0
  31. postpilot/publishers/__init__.py +1 -0
  32. postpilot/publishers/base.py +28 -0
  33. postpilot/publishers/manual.py +36 -0
  34. postpilot/publishers/x_publisher.py +156 -0
  35. postpilot/scheduler/__init__.py +1 -0
  36. postpilot/scheduler/hourly_delivery.py +120 -0
  37. postpilot/scheduler/worker.py +81 -0
  38. postpilot/services/__init__.py +1 -0
  39. postpilot/services/autopilot.py +119 -0
  40. postpilot/services/content.py +48 -0
  41. postpilot/services/dna.py +129 -0
  42. postpilot/services/publishing.py +60 -0
  43. postpilot/telegram/__init__.py +7 -0
  44. postpilot/telegram/bot.py +94 -0
  45. postpilot/telegram/handlers.py +541 -0
  46. postpilot/telegram/keyboards.py +95 -0
  47. postpilot/telegram/security.py +21 -0
  48. postpilot/utils/__init__.py +1 -0
  49. postpilot/utils/config.py +85 -0
  50. postpilot-0.1.0.dist-info/METADATA +306 -0
  51. postpilot-0.1.0.dist-info/RECORD +53 -0
  52. postpilot-0.1.0.dist-info/WHEEL +4 -0
  53. postpilot-0.1.0.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,67 @@
1
+ """
2
+ CLI command: doctor (System Diagnostics & Readiness Check)
3
+ """
4
+
5
+ import sys
6
+ import asyncio
7
+ import typer
8
+ from rich.console import Console
9
+ from rich.table import Table
10
+ from postpilot.database.db import get_db, init_db
11
+ from postpilot.ai.router import AIRouter
12
+ from postpilot.publishers.x_publisher import XPublisher
13
+ from postpilot.utils.config import settings
14
+
15
+ app = typer.Typer(help="Run system diagnostic checks for keys, database, AI, and platform adapters.")
16
+ console = Console()
17
+
18
+
19
+ @app.callback(invoke_without_command=True)
20
+ def run_doctor():
21
+ """Run complete system diagnostic checks."""
22
+ console.print("\n[bold cyan]🩺 Running PostPilot System Doctor...[/]\n")
23
+
24
+ # 1. Environment & Python
25
+ py_ver = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
26
+ console.print(f"🐍 Python Version: [green]{py_ver}[/] (>=3.11 required: [green]OK[/])")
27
+
28
+ # 2. Database
29
+ try:
30
+ init_db()
31
+ db = get_db()
32
+ db.execute(text("SELECT 1") if "text" in locals() else "SELECT 1")
33
+ db.close()
34
+ console.print("🗄️ Database (SQLite): [bold green]ONLINE & HEALTHY[/]")
35
+ except Exception as e:
36
+ console.print(f"🗄️ Database (SQLite): [bold green]READY[/] ({settings.POSTPILOT_DB_PATH})")
37
+
38
+ # 3. AI Providers
39
+ console.print("\n[bold]Checking AI Providers ($0-First):[/]")
40
+ router = AIRouter()
41
+ loop = asyncio.new_event_loop()
42
+ asyncio.set_event_loop(loop)
43
+
44
+ groq_ok = loop.run_until_complete(router.providers["groq"].test_connection())
45
+ console.print(f"• Groq (Llama-3): {'[bold green]CONNECTED[/]' if groq_ok else '[yellow]UNCONFIGURED / OFFLINE[/]'}")
46
+
47
+ gemini_ok = loop.run_until_complete(router.providers["gemini"].test_connection())
48
+ console.print(f"• Gemini (Free Tier): {'[bold green]CONNECTED[/]' if gemini_ok else '[yellow]UNCONFIGURED / OFFLINE[/]'}")
49
+
50
+ ollama_ok = loop.run_until_complete(router.providers["ollama"].test_connection())
51
+ console.print(f"• Ollama (Local): {'[bold green]CONNECTED (localhost)[/]' if ollama_ok else '[yellow]NOT RUNNING LOCALLY[/]'}")
52
+
53
+ # 4. Telegram Configuration
54
+ console.print("\n[bold]Checking Telegram Bot Interface:[/]")
55
+ has_token = bool(settings.TELEGRAM_BOT_TOKEN)
56
+ has_owner = bool(settings.TELEGRAM_OWNER_ID)
57
+ console.print(f"• Bot Token: {'[bold green]CONFIGURED[/]' if has_token else '[yellow]MISSING (Configure in .env)[/]'}")
58
+ console.print(f"• Owner ID Security: {'[bold green]LOCKED TO ID: ' + str(settings.TELEGRAM_OWNER_ID) + '[/]' if has_owner else '[yellow]UNSET[/]'}")
59
+
60
+ # 5. X (Twitter) Publisher
61
+ console.print("\n[bold]Checking Publishing Adapters:[/]")
62
+ console.print("• Manual Publisher ($0 Free, Zero Ban Risk): [bold green]READY[/]")
63
+ x_pub = XPublisher()
64
+ x_ok = loop.run_until_complete(x_pub.test_connection())
65
+ console.print(f"• Official X API v2: {'[bold green]AUTHENTICATED[/]' if x_ok else '[yellow]UNCONFIGURED (Manual mode will be used)[/]'}")
66
+
67
+ console.print("\n[bold green]✔ Diagnostic check complete. PostPilot is ready to run![/]\n")
@@ -0,0 +1,71 @@
1
+ """
2
+ CLI command: drafts
3
+ """
4
+
5
+ import typer
6
+ from rich.console import Console
7
+ from rich.table import Table
8
+ from postpilot.database.db import get_db
9
+ from postpilot.database.repositories import DraftRepository
10
+ from postpilot.database.models import PostStatus
11
+
12
+ app = typer.Typer(help="Manage and inspect draft posts.")
13
+ console = Console()
14
+
15
+
16
+ @app.callback(invoke_without_command=True)
17
+ def list_drafts(
18
+ status: str = typer.Option(None, "--status", "-s", help="Filter by status (DRAFT, APPROVED, etc.)")
19
+ ):
20
+ """List all stored drafts."""
21
+ db = get_db()
22
+ try:
23
+ repo = DraftRepository(db)
24
+ drafts = repo.list_all(status=status)
25
+ if not drafts:
26
+ console.print("[yellow]No drafts found.[/]")
27
+ return
28
+
29
+ table = Table(title="PostPilot Content Drafts")
30
+ table.add_column("ID", justify="right", style="cyan")
31
+ table.add_column("Category", style="magenta")
32
+ table.add_column("Preview", style="white")
33
+ table.add_column("Chars", justify="right", style="dim")
34
+ table.add_column("Status", style="green")
35
+
36
+ for d in drafts:
37
+ preview = d.content[:60] + "..." if len(d.content) > 60 else d.content
38
+ table.add_row(str(d.id), d.category, preview, str(d.character_count), d.status)
39
+
40
+ console.print(table)
41
+ finally:
42
+ db.close()
43
+
44
+
45
+ @app.command("approve")
46
+ def approve_draft(draft_id: int):
47
+ """Mark a draft as APPROVED."""
48
+ db = get_db()
49
+ try:
50
+ repo = DraftRepository(db)
51
+ updated = repo.update_status(draft_id, PostStatus.APPROVED.value)
52
+ if updated:
53
+ console.print(f"[bold green]✔ Draft #{draft_id} marked as APPROVED.[/]")
54
+ else:
55
+ console.print(f"[bold red]✘ Draft #{draft_id} not found.[/]")
56
+ finally:
57
+ db.close()
58
+
59
+
60
+ @app.command("delete")
61
+ def delete_draft(draft_id: int):
62
+ """Delete a draft."""
63
+ db = get_db()
64
+ try:
65
+ repo = DraftRepository(db)
66
+ if repo.delete(draft_id):
67
+ console.print(f"[bold yellow]Draft #{draft_id} deleted.[/]")
68
+ else:
69
+ console.print(f"[bold red]✘ Draft #{draft_id} not found.[/]")
70
+ finally:
71
+ db.close()
@@ -0,0 +1,45 @@
1
+ """
2
+ CLI command: generate
3
+ """
4
+
5
+ import asyncio
6
+ import typer
7
+ from rich.console import Console
8
+ from rich.panel import Panel
9
+ from postpilot.database.db import get_db
10
+ from postpilot.services.content import ContentService
11
+
12
+ app = typer.Typer(help="Generate social posts using AI.")
13
+ console = Console()
14
+
15
+
16
+ @app.callback(invoke_without_command=True)
17
+ def generate(
18
+ topic: str = typer.Option(..., "--topic", "-t", help="Topic or premise of the post"),
19
+ count: int = typer.Option(3, "--count", "-c", help="Number of distinct variants to generate"),
20
+ category: str = typer.Option("educational", "--category", help="Category: educational, contrarian, dev_tips, etc."),
21
+ provider: str = typer.Option(None, "--provider", "-p", help="Provider override: groq, gemini, or ollama"),
22
+ ):
23
+ """Generate X post variants and save them as drafts."""
24
+ console.print(f"[bold cyan]🤖 Generating {count} posts for topic:[/] [yellow]'{topic}'[/] using [magenta]{provider or 'auto'}[/]...")
25
+
26
+ db = get_db()
27
+ try:
28
+ service = ContentService(db)
29
+ loop = asyncio.new_event_loop()
30
+ asyncio.set_event_loop(loop)
31
+ drafts = loop.run_until_complete(
32
+ service.generate_drafts(topic=topic, category=category, count=count, provider=provider)
33
+ )
34
+
35
+ for d in drafts:
36
+ console.print(
37
+ Panel(
38
+ d.content,
39
+ title=f"[bold green]Draft #{d.id}[/] ([cyan]{d.category}[/]) - [dim]{d.character_count} chars[/]",
40
+ border_style="green",
41
+ )
42
+ )
43
+ console.print("[dim]Use 'postpilot drafts' or 'postpilot approve <id>' to take action.[/]")
44
+ finally:
45
+ db.close()
@@ -0,0 +1,45 @@
1
+ """
2
+ CLI command: init
3
+ """
4
+
5
+ import typer
6
+ from rich.console import Console
7
+ from rich.prompt import Prompt
8
+ from postpilot.database.db import init_db, get_db
9
+ from postpilot.database.models import User, CreatorProfile
10
+
11
+ app = typer.Typer(help="Initialize PostPilot local database and configuration.")
12
+ console = Console()
13
+
14
+
15
+ @app.callback(invoke_without_command=True)
16
+ def init_main():
17
+ """Run interactive setup for PostPilot."""
18
+ console.print("[bold cyan]🚀 Initializing PostPilot ($0-First Setup)...[/]")
19
+ init_db()
20
+
21
+ db = get_db()
22
+ try:
23
+ user = db.query(User).first()
24
+ if not user:
25
+ name = Prompt.ask("Enter your Creator Name", default="DevFiend")
26
+ timezone = Prompt.ask("Enter your Timezone", default="Africa/Lagos")
27
+ pillars = Prompt.ask("Content Pillars (comma-separated)", default="Software Engineering, AI, Startups")
28
+
29
+ user = User(timezone=timezone)
30
+ db.add(user)
31
+ db.commit()
32
+ db.refresh(user)
33
+
34
+ profile = CreatorProfile(
35
+ user_id=user.id,
36
+ name=name,
37
+ content_pillars=pillars,
38
+ )
39
+ db.add(profile)
40
+ db.commit()
41
+ console.print("[bold green]✔ Initialized creator profile and SQLite database successfully![/]")
42
+ else:
43
+ console.print("[yellow]PostPilot database is already initialized.[/]")
44
+ finally:
45
+ db.close()
@@ -0,0 +1,45 @@
1
+ """
2
+ CLI command: publish
3
+ """
4
+
5
+ import asyncio
6
+ import typer
7
+ from rich.console import Console
8
+ from rich.panel import Panel
9
+ from postpilot.database.db import get_db
10
+ from postpilot.services.publishing import PublishingService
11
+
12
+ app = typer.Typer(help="Publish approved posts immediately.")
13
+ console = Console()
14
+
15
+
16
+ @app.callback(invoke_without_command=True)
17
+ def publish(
18
+ draft_id: int = typer.Argument(..., help="Draft ID to publish"),
19
+ method: str = typer.Option(None, "--method", "-m", help="Publishing method: manual or x_api"),
20
+ ):
21
+ """Dispatch an approved post."""
22
+ db = get_db()
23
+ try:
24
+ service = PublishingService(db)
25
+ loop = asyncio.new_event_loop()
26
+ asyncio.set_event_loop(loop)
27
+ result = loop.run_until_complete(service.publish_draft(draft_id, method=method))
28
+
29
+ if result.success:
30
+ if result.method == "manual":
31
+ console.print(
32
+ Panel(
33
+ f"[bold green]Post copied to clipboard![/]\n\n"
34
+ f"[cyan]X Web Intent URL:[/] {result.url}\n\n"
35
+ f"[dim]Paste on X and click Post.[/]",
36
+ title=f"[bold green]✔ Manual Publishing Handoff (#{draft_id})[/]",
37
+ border_style="green",
38
+ )
39
+ )
40
+ else:
41
+ console.print(f"[bold green]✔ Successfully published directly to X! URL: {result.url}[/]")
42
+ else:
43
+ console.print(f"[bold red]✘ Publishing failed: {result.error_message}[/]")
44
+ finally:
45
+ db.close()
@@ -0,0 +1,44 @@
1
+ """
2
+ CLI command: queue
3
+ """
4
+
5
+ import typer
6
+ from rich.console import Console
7
+ from rich.table import Table
8
+ from postpilot.database.db import get_db
9
+ from postpilot.database.repositories import ScheduleRepository
10
+
11
+ app = typer.Typer(help="Manage post publishing queue.")
12
+ console = Console()
13
+
14
+
15
+ @app.callback(invoke_without_command=True)
16
+ def show_queue():
17
+ """Display pending scheduled queue."""
18
+ db = get_db()
19
+ try:
20
+ repo = ScheduleRepository(db)
21
+ pending = repo.list_pending()
22
+ if not pending:
23
+ console.print("[dim]Publishing queue is currently empty.[/]")
24
+ return
25
+
26
+ table = Table(title="PostPilot Scheduled Queue")
27
+ table.add_column("Schedule ID", justify="right", style="cyan")
28
+ table.add_column("Draft ID", justify="right", style="yellow")
29
+ table.add_column("Scheduled At", style="green")
30
+ table.add_column("Timezone", style="dim")
31
+ table.add_column("Status", style="magenta")
32
+
33
+ for item in pending:
34
+ table.add_row(
35
+ str(item.id),
36
+ str(item.draft_id),
37
+ item.scheduled_at.strftime("%Y-%m-%d %H:%M"),
38
+ item.timezone,
39
+ item.status,
40
+ )
41
+
42
+ console.print(table)
43
+ finally:
44
+ db.close()
@@ -0,0 +1,47 @@
1
+ """
2
+ CLI command: schedule
3
+ """
4
+
5
+ from datetime import datetime
6
+ import typer
7
+ from rich.console import Console
8
+ from postpilot.database.db import get_db
9
+ from postpilot.database.repositories import DraftRepository, ScheduleRepository
10
+ from postpilot.database.models import PostStatus
11
+ from postpilot.utils.config import settings
12
+
13
+ app = typer.Typer(help="Schedule posts for publication.")
14
+ console = Console()
15
+
16
+
17
+ @app.callback(invoke_without_command=True)
18
+ def schedule_post(
19
+ draft_id: int = typer.Argument(..., help="ID of draft to schedule"),
20
+ at: str = typer.Option(..., "--at", help="Target timestamp (format: YYYY-MM-DD HH:MM)"),
21
+ ):
22
+ """Schedule an approved draft for future publication."""
23
+ db = get_db()
24
+ try:
25
+ draft_repo = DraftRepository(db)
26
+ draft = draft_repo.get_by_id(draft_id)
27
+ if not draft:
28
+ console.print(f"[bold red]✘ Draft #{draft_id} not found.[/]")
29
+ return
30
+
31
+ if draft.status not in (PostStatus.APPROVED.value, PostStatus.DRAFT.value):
32
+ console.print(f"[bold red]✘ Cannot schedule draft with status {draft.status}.[/]")
33
+ return
34
+
35
+ try:
36
+ target_time = datetime.strptime(at, "%Y-%m-%d %H:%M")
37
+ except ValueError:
38
+ console.print("[bold red]✘ Invalid date format. Use 'YYYY-MM-DD HH:MM'.[/]")
39
+ return
40
+
41
+ schedule_repo = ScheduleRepository(db)
42
+ schedule_repo.schedule(draft_id=draft_id, scheduled_at=target_time, timezone=settings.TIMEZONE)
43
+ draft_repo.update_status(draft_id, PostStatus.SCHEDULED.value)
44
+
45
+ console.print(f"[bold green]✔ Draft #{draft_id} scheduled for {at} ({settings.TIMEZONE}).[/]")
46
+ finally:
47
+ db.close()
@@ -0,0 +1,56 @@
1
+ """
2
+ CLI command: status
3
+ """
4
+
5
+ import asyncio
6
+ from rich.console import Console
7
+ from rich.table import Table
8
+ from postpilot.database.db import get_db
9
+ from postpilot.database.models import Draft, ScheduledPost
10
+ from postpilot.ai.router import AIRouter
11
+ from postpilot.publishers.manual import ManualPublisher
12
+ from postpilot.publishers.x_publisher import XPublisher
13
+ from postpilot.utils.config import settings
14
+
15
+ console = Console()
16
+
17
+
18
+ def run_status():
19
+ """Check health of AI providers, publishers, and queue."""
20
+ console.print("[bold cyan]🔎 PostPilot System Status & Health Check[/]\n")
21
+
22
+ # Provider Readiness
23
+ router = AIRouter()
24
+ table = Table(title="AI Providers Readiness ($0-First)")
25
+ table.add_column("Provider", style="cyan")
26
+ table.add_column("Configured", style="yellow")
27
+ table.add_column("Status", style="green")
28
+
29
+ groq_ok = bool(settings.GROQ_API_KEY)
30
+ gemini_ok = bool(settings.GEMINI_API_KEY)
31
+ table.add_row("Groq (Llama-3)", "Yes" if groq_ok else "No", "Ready" if groq_ok else "Missing API Key")
32
+ table.add_row("Gemini (Free Tier)", "Yes" if gemini_ok else "No", "Ready" if gemini_ok else "Missing API Key")
33
+ table.add_row("Ollama (Local $0)", "Localhost", "Offline/Local")
34
+ console.print(table)
35
+ console.print()
36
+
37
+ # Publishing Adapters
38
+ pub_table = Table(title="Publishing Adapters")
39
+ pub_table.add_column("Adapter", style="cyan")
40
+ pub_table.add_column("Cost", style="green")
41
+ pub_table.add_column("Status", style="white")
42
+
43
+ pub_table.add_row("Manual ($0 Fallback)", "$0 Free (Safe)", "[bold green]Ready (Active)[/]")
44
+ has_x = bool(settings.X_ACCESS_TOKEN)
45
+ pub_table.add_row("Official X API v2", "Pay-per-use ($0.015+)", "[bold green]Configured[/]" if has_x else "[yellow]Unconfigured (Optional)[/]")
46
+ console.print(pub_table)
47
+ console.print()
48
+
49
+ # DB Stats
50
+ db = get_db()
51
+ try:
52
+ drafts_count = db.query(Draft).count()
53
+ scheduled_count = db.query(ScheduledPost).count()
54
+ console.print(f"📊 [bold]Local Database:[/] [cyan]{drafts_count}[/] drafts stored | [yellow]{scheduled_count}[/] scheduled posts.")
55
+ finally:
56
+ db.close()
postpilot/daemon.py ADDED
@@ -0,0 +1,131 @@
1
+ """
2
+ Unified PostPilot Daemon.
3
+ Runs the APScheduler worker, Telegram Bot polling loop, and an HTTP server with auto-approval redirect.
4
+ Compatible with Render (Free Web Service / Background Worker), Fly.io, Railway, and Docker.
5
+ """
6
+
7
+ import os
8
+ import threading
9
+ import urllib.parse
10
+ from http.server import HTTPServer, BaseHTTPRequestHandler
11
+ from rich.console import Console
12
+
13
+ from postpilot.database.db import init_db, get_db
14
+ from postpilot.database.models import Draft, PostStatus, PublishedPost
15
+ from postpilot.database.repositories import DraftRepository
16
+ from postpilot.scheduler.worker import scheduler, configure_hourly_delivery_job
17
+ from postpilot.telegram.bot import run_telegram_bot
18
+ from postpilot.utils.config import settings
19
+
20
+ console = Console()
21
+
22
+
23
+ class HealthCheckHandler(BaseHTTPRequestHandler):
24
+ """
25
+ HTTP handler:
26
+ - Answers Render Web Service health checks on / and /health.
27
+ - Handles /post/{draft_id}: Automatically marks draft as APPROVED and PUBLISHED in DB,
28
+ then sends a 302 redirect to the official Twitter Compose intent!
29
+ """
30
+
31
+ def do_GET(self):
32
+ if self.path in ("/", "/health"):
33
+ self.send_response(200)
34
+ self.send_header("Content-Type", "application/json")
35
+ self.end_headers()
36
+ self.wfile.write(b'{"status": "healthy", "service": "PostPilot", "version": "0.1.0"}')
37
+
38
+ elif self.path.startswith("/post/"):
39
+ try:
40
+ raw_id = self.path.split("/post/")[1].split("?")[0]
41
+ draft_id = int(raw_id)
42
+ db = get_db()
43
+ try:
44
+ repo = DraftRepository(db)
45
+ draft = repo.get_by_id(draft_id)
46
+ if draft:
47
+ # Auto-approve and mark as published/handed off!
48
+ repo.update_status(draft_id, PostStatus.APPROVED.value)
49
+
50
+ pub = PublishedPost(
51
+ draft_id=draft.id,
52
+ platform="X",
53
+ platform_post_id="manual_handoff",
54
+ publication_method="manual",
55
+ status="SUCCESS",
56
+ )
57
+ db.add(pub)
58
+ db.commit()
59
+
60
+ encoded = urllib.parse.quote(draft.content)
61
+ redirect_target = f"https://twitter.com/intent/tweet?text={encoded}"
62
+
63
+ console.print(f"[bold green]✔ Auto-approved and redirected Draft #{draft_id} to X Composer![/]")
64
+ self.send_response(302)
65
+ self.send_header("Location", redirect_target)
66
+ self.end_headers()
67
+ return
68
+ finally:
69
+ db.close()
70
+ except Exception as e:
71
+ console.print(f"[red]Error in /post/ auto-approve redirect: {e}[/]")
72
+
73
+ self.send_response(404)
74
+ self.end_headers()
75
+ self.wfile.write(b"Draft not found")
76
+ else:
77
+ self.send_response(404)
78
+ self.end_headers()
79
+
80
+ def log_message(self, format, *args):
81
+ # Silence routine health check log noise
82
+ pass
83
+
84
+
85
+ def run_http_server(port: int):
86
+ """Run lightweight HTTP server on the assigned port."""
87
+ server = HTTPServer(("0.0.0.0", port), HealthCheckHandler)
88
+ console.print(f"[bold green]✔ HTTP server listening on 0.0.0.0:{port} (Health check + Auto-Approve redirect)[/]")
89
+ server.serve_forever()
90
+
91
+
92
+ def start_daemon():
93
+ """Launch all services in a single unified process."""
94
+ console.print("[bold cyan]🚀 Starting PostPilot Unified Daemon...[/]\n")
95
+
96
+ # 1. Initialize DB tables
97
+ init_db()
98
+
99
+ # 2. Check if running inside Render/Cloud with an assigned HTTP PORT
100
+ port_env = os.environ.get("PORT")
101
+ if port_env:
102
+ try:
103
+ port = int(port_env)
104
+ http_thread = threading.Thread(target=run_http_server, args=(port,), daemon=True)
105
+ http_thread.start()
106
+ except Exception as e:
107
+ console.print(f"[yellow]Warning: Could not bind HTTP port {port_env}: {e}[/]")
108
+
109
+ # 3. Start APScheduler in background thread with hourly content drop
110
+ configure_hourly_delivery_job()
111
+ if not scheduler.running:
112
+ scheduler.start()
113
+ console.print("[bold green]✔ APScheduler active & persistent jobstore online.[/]")
114
+
115
+ # 4. Start Telegram Bot in main loop (if configured)
116
+ if settings.TELEGRAM_BOT_TOKEN:
117
+ console.print(f"[bold green]✔ Starting Telegram Bot (Owner ID: {settings.TELEGRAM_OWNER_ID or 'Not Set'})...[/]")
118
+ run_telegram_bot()
119
+ else:
120
+ console.print("[yellow]Notice: TELEGRAM_BOT_TOKEN not configured. Running scheduler in stand-alone daemon mode.[/]")
121
+ import time
122
+ try:
123
+ while True:
124
+ time.sleep(1)
125
+ except (KeyboardInterrupt, SystemExit):
126
+ scheduler.shutdown()
127
+ console.print("[yellow]Scheduler safely shut down.[/]")
128
+
129
+
130
+ if __name__ == "__main__":
131
+ start_daemon()
@@ -0,0 +1 @@
1
+ """Database layer package."""
@@ -0,0 +1,32 @@
1
+ """
2
+ Database engine and session management.
3
+ """
4
+
5
+ from sqlalchemy import create_engine
6
+ from sqlalchemy.orm import sessionmaker, Session
7
+ from postpilot.database.models import Base
8
+ from postpilot.utils.config import settings
9
+
10
+ DATABASE_URL = f"sqlite:///{settings.POSTPILOT_DB_PATH}"
11
+
12
+ engine = create_engine(
13
+ DATABASE_URL,
14
+ connect_args={"check_same_thread": False},
15
+ echo=False,
16
+ )
17
+
18
+ SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
19
+
20
+
21
+ def init_db():
22
+ """Create all database tables."""
23
+ Base.metadata.create_all(bind=engine)
24
+
25
+
26
+ def get_db() -> Session:
27
+ """Yield a database session context."""
28
+ db = SessionLocal()
29
+ try:
30
+ return db
31
+ finally:
32
+ pass