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
postpilot/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """
2
+ PostPilot package root.
3
+ """
4
+
5
+ __version__ = "0.1.0"
6
+ __app_name__ = "postpilot"
@@ -0,0 +1 @@
1
+ """AI layer package."""
postpilot/ai/base.py ADDED
@@ -0,0 +1,23 @@
1
+ """
2
+ Abstract base class for AI Providers.
3
+ """
4
+
5
+ from abc import ABC, abstractmethod
6
+ from typing import List
7
+
8
+
9
+ class BaseAIProvider(ABC):
10
+ @abstractmethod
11
+ async def generate(self, prompt: str, system_prompt: str, count: int = 1) -> List[str]:
12
+ """Generate a list of candidate social posts."""
13
+ pass
14
+
15
+ @abstractmethod
16
+ async def test_connection(self) -> bool:
17
+ """Verify API key and provider availability."""
18
+ pass
19
+
20
+ @abstractmethod
21
+ def get_provider_name(self) -> str:
22
+ """Return provider identifier name."""
23
+ pass
postpilot/ai/gemini.py ADDED
@@ -0,0 +1,46 @@
1
+ """
2
+ Google Gemini Provider implementation (Generous Free Quota).
3
+ """
4
+
5
+ from typing import List
6
+ import httpx
7
+ from postpilot.ai.base import BaseAIProvider
8
+ from postpilot.utils.config import settings
9
+
10
+
11
+ class GeminiProvider(BaseAIProvider):
12
+ def __init__(self, api_key: str | None = None, model: str = "gemini-1.5-flash"):
13
+ self.api_key = api_key or settings.GEMINI_API_KEY
14
+ self.model = model
15
+
16
+ def get_provider_name(self) -> str:
17
+ return "gemini"
18
+
19
+ async def test_connection(self) -> bool:
20
+ if not self.api_key:
21
+ return False
22
+ url = f"https://generativelanguage.googleapis.com/v1beta/models/{self.model}?key={self.api_key}"
23
+ try:
24
+ async with httpx.AsyncClient(timeout=10.0) as client:
25
+ res = await client.get(url)
26
+ return res.status_code == 200
27
+ except Exception:
28
+ return False
29
+
30
+ async def generate(self, prompt: str, system_prompt: str, count: int = 1) -> List[str]:
31
+ if not self.api_key:
32
+ raise ValueError("GEMINI_API_KEY is not configured in .env")
33
+
34
+ url = f"https://generativelanguage.googleapis.com/v1beta/models/{self.model}:generateContent?key={self.api_key}"
35
+ full_prompt = f"{system_prompt}\n\nTask:\n{prompt}\n\nPlease output exactly {count} distinct post options separated by '---'."
36
+ payload = {
37
+ "contents": [{"parts": [{"text": full_prompt}]}]
38
+ }
39
+
40
+ async with httpx.AsyncClient(timeout=30.0) as client:
41
+ res = await client.post(url, json=payload)
42
+ res.raise_for_status()
43
+ data = res.json()
44
+ text = data["candidates"][0]["content"]["parts"][0]["text"]
45
+ posts = [p.strip() for p in text.split("---") if p.strip()]
46
+ return posts[:count]
postpilot/ai/groq.py ADDED
@@ -0,0 +1,59 @@
1
+ """
2
+ Groq AI Provider implementation (High-speed LLaMA-3 / GPT-OSS).
3
+ """
4
+
5
+ from typing import List
6
+ import httpx
7
+ from postpilot.ai.base import BaseAIProvider
8
+ from postpilot.utils.config import settings
9
+
10
+
11
+ class GroqProvider(BaseAIProvider):
12
+ def __init__(self, api_key: str | None = None, model: str | None = None):
13
+ self.api_key = api_key or settings.GROQ_API_KEY
14
+ self.model = model or settings.GROQ_MODEL
15
+ self.endpoint = "https://api.groq.com/openai/v1/chat/completions"
16
+
17
+ def get_provider_name(self) -> str:
18
+ return "groq"
19
+
20
+ async def test_connection(self) -> bool:
21
+ if not self.api_key:
22
+ return False
23
+ headers = {"Authorization": f"Bearer {self.api_key}"}
24
+ try:
25
+ async with httpx.AsyncClient(timeout=10.0) as client:
26
+ res = await client.get("https://api.groq.com/openai/v1/models", headers=headers)
27
+ return res.status_code == 200
28
+ except Exception:
29
+ return False
30
+
31
+ async def generate(self, prompt: str, system_prompt: str, count: int = 1) -> List[str]:
32
+ if not self.api_key:
33
+ raise ValueError("GROQ_API_KEY is not configured in .env")
34
+
35
+ headers = {
36
+ "Authorization": f"Bearer {self.api_key}",
37
+ "Content-Type": "application/json",
38
+ }
39
+ user_message = (
40
+ f"{prompt}\n\n"
41
+ f"Please generate exactly {count} distinct post variants. "
42
+ f"Separate each variant with '---' on its own line."
43
+ )
44
+ payload = {
45
+ "model": self.model,
46
+ "messages": [
47
+ {"role": "system", "content": system_prompt},
48
+ {"role": "user", "content": user_message},
49
+ ],
50
+ "temperature": 0.7,
51
+ }
52
+
53
+ async with httpx.AsyncClient(timeout=30.0) as client:
54
+ res = await client.post(self.endpoint, json=payload, headers=headers)
55
+ res.raise_for_status()
56
+ data = res.json()
57
+ content = data["choices"][0]["message"]["content"]
58
+ posts = [p.strip() for p in content.split("---") if p.strip()]
59
+ return posts[:count]
postpilot/ai/ollama.py ADDED
@@ -0,0 +1,42 @@
1
+ """
2
+ Ollama Local Provider implementation ($0 Offline execution).
3
+ """
4
+
5
+ from typing import List
6
+ import httpx
7
+ from postpilot.ai.base import BaseAIProvider
8
+ from postpilot.utils.config import settings
9
+
10
+
11
+ class OllamaProvider(BaseAIProvider):
12
+ def __init__(self, base_url: str | None = None, model: str | None = None):
13
+ self.base_url = base_url or settings.OLLAMA_BASE_URL
14
+ self.model = model or settings.OLLAMA_MODEL
15
+
16
+ def get_provider_name(self) -> str:
17
+ return "ollama"
18
+
19
+ async def test_connection(self) -> bool:
20
+ try:
21
+ async with httpx.AsyncClient(timeout=5.0) as client:
22
+ res = await client.get(f"{self.base_url}/api/tags")
23
+ return res.status_code == 200
24
+ except Exception:
25
+ return False
26
+
27
+ async def generate(self, prompt: str, system_prompt: str, count: int = 1) -> List[str]:
28
+ endpoint = f"{self.base_url}/api/generate"
29
+ full_prompt = f"{system_prompt}\n\nUser topic: {prompt}\n\nReturn {count} post variants separated by '---'."
30
+ payload = {
31
+ "model": self.model,
32
+ "prompt": full_prompt,
33
+ "stream": False,
34
+ }
35
+
36
+ async with httpx.AsyncClient(timeout=60.0) as client:
37
+ res = await client.post(endpoint, json=payload)
38
+ res.raise_for_status()
39
+ data = res.json()
40
+ response_text = data.get("response", "")
41
+ posts = [p.strip() for p in response_text.split("---") if p.strip()]
42
+ return posts[:count]
postpilot/ai/router.py ADDED
@@ -0,0 +1,45 @@
1
+ """
2
+ AIRouter: Intelligent routing and fallback among Groq, Gemini, and Ollama.
3
+ """
4
+
5
+ from typing import List, Optional
6
+ from postpilot.ai.base import BaseAIProvider
7
+ from postpilot.ai.groq import GroqProvider
8
+ from postpilot.ai.gemini import GeminiProvider
9
+ from postpilot.ai.ollama import OllamaProvider
10
+ from postpilot.utils.config import settings
11
+
12
+
13
+ class AIRouter:
14
+ def __init__(self):
15
+ self.providers: dict[str, BaseAIProvider] = {
16
+ "groq": GroqProvider(),
17
+ "gemini": GeminiProvider(),
18
+ "ollama": OllamaProvider(),
19
+ }
20
+
21
+ def get_provider(self, name: Optional[str] = None) -> BaseAIProvider:
22
+ target = name.lower() if name else settings.DEFAULT_AI_PROVIDER.lower()
23
+ if target not in self.providers:
24
+ target = "groq"
25
+ return self.providers[target]
26
+
27
+ async def generate_with_fallback(
28
+ self, prompt: str, system_prompt: str, preferred: Optional[str] = None, count: int = 1
29
+ ) -> tuple[List[str], str]:
30
+ """Try preferred provider; fall back automatically if requested and needed."""
31
+ provider_name = preferred or settings.DEFAULT_AI_PROVIDER
32
+ candidates = [provider_name] + [p for p in ["groq", "gemini", "ollama"] if p != provider_name]
33
+
34
+ last_error = None
35
+ for prov_id in candidates:
36
+ provider = self.providers[prov_id]
37
+ try:
38
+ results = await provider.generate(prompt, system_prompt, count=count)
39
+ if results:
40
+ return results, prov_id
41
+ except Exception as e:
42
+ last_error = e
43
+ continue
44
+
45
+ raise RuntimeError(f"All AI providers failed. Last error: {last_error}")
postpilot/cli.py ADDED
@@ -0,0 +1,93 @@
1
+ """
2
+ Command-Line Interface for PostPilot using Typer and Rich.
3
+ """
4
+
5
+ import typer
6
+ from rich.console import Console
7
+
8
+ from postpilot import __app_name__, __version__
9
+ from postpilot.commands import (
10
+ autopilot_cmd,
11
+ config_cmd,
12
+ dna_cmd,
13
+ doctor_cmd,
14
+ drafts_cmd,
15
+ generate_cmd,
16
+ init_cmd,
17
+ publish_cmd,
18
+ queue_cmd,
19
+ schedule_cmd,
20
+ )
21
+
22
+ app = typer.Typer(
23
+ name=__app_name__,
24
+ help="PostPilot: AI-powered content management & publishing assistant for X (Twitter).",
25
+ add_completion=False,
26
+ )
27
+ console = Console()
28
+
29
+
30
+ def version_callback(value: bool):
31
+ if value:
32
+ console.print(f"[bold cyan]{__app_name__}[/] version [bold green]{__version__}[/]")
33
+ raise typer.Exit()
34
+
35
+
36
+ @app.callback()
37
+ def main(
38
+ version: bool = typer.Option(
39
+ None,
40
+ "--version",
41
+ "-v",
42
+ help="Show version and exit.",
43
+ callback=version_callback,
44
+ is_eager=True,
45
+ ),
46
+ ):
47
+ """Personal AI-powered content management and publishing assistant."""
48
+ pass
49
+
50
+
51
+ # Register CLI Subcommands
52
+ app.add_typer(init_cmd.app, name="init", help="Initialize PostPilot configuration and database.")
53
+ app.add_typer(generate_cmd.app, name="generate", help="Generate draft posts using AI.")
54
+ app.add_typer(dna_cmd.app, name="dna", help="TweetDNA creator intelligence and style cloning.")
55
+ app.add_typer(drafts_cmd.app, name="drafts", help="Manage and inspect draft posts.")
56
+ app.add_typer(queue_cmd.app, name="queue", help="Manage post publishing queue.")
57
+ app.add_typer(schedule_cmd.app, name="schedule", help="Schedule posts for publication.")
58
+ app.add_typer(publish_cmd.app, name="publish", help="Publish approved posts immediately.")
59
+ app.add_typer(autopilot_cmd.app, name="autopilot", help="Configure and manage autopilot mode.")
60
+ app.add_typer(config_cmd.app, name="config", help="Manage settings and creator profile.")
61
+ app.add_typer(doctor_cmd.app, name="doctor", help="Run system diagnostics and connectivity checks.")
62
+
63
+
64
+ @app.command("status")
65
+ def status():
66
+ """Display system health, active AI provider, and queue summary."""
67
+ from postpilot.commands.status_cmd import run_status
68
+ run_status()
69
+
70
+
71
+ @app.command("run")
72
+ def run_worker():
73
+ """Run the scheduler and background worker process."""
74
+ from postpilot.scheduler.worker import start_worker
75
+ start_worker()
76
+
77
+
78
+ @app.command("telegram")
79
+ def run_telegram():
80
+ """Start the Telegram Bot long-polling service."""
81
+ from postpilot.telegram.bot import run_telegram_bot
82
+ run_telegram_bot()
83
+
84
+
85
+ @app.command("start")
86
+ def start():
87
+ """Run the unified daemon (Scheduler + Telegram Bot + Health Check)."""
88
+ from postpilot.daemon import start_daemon
89
+ start_daemon()
90
+
91
+
92
+ if __name__ == "__main__":
93
+ app()
@@ -0,0 +1,31 @@
1
+ """
2
+ CLI command exports.
3
+ """
4
+
5
+ from postpilot.commands import (
6
+ autopilot_cmd,
7
+ config_cmd,
8
+ dna_cmd,
9
+ doctor_cmd,
10
+ drafts_cmd,
11
+ generate_cmd,
12
+ init_cmd,
13
+ publish_cmd,
14
+ queue_cmd,
15
+ schedule_cmd,
16
+ status_cmd,
17
+ )
18
+
19
+ __all__ = [
20
+ "autopilot_cmd",
21
+ "config_cmd",
22
+ "dna_cmd",
23
+ "doctor_cmd",
24
+ "drafts_cmd",
25
+ "generate_cmd",
26
+ "init_cmd",
27
+ "publish_cmd",
28
+ "queue_cmd",
29
+ "schedule_cmd",
30
+ "status_cmd",
31
+ ]
@@ -0,0 +1,102 @@
1
+ """
2
+ CLI command: autopilot
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.autopilot import AutopilotService
11
+
12
+ app = typer.Typer(help="Configure and manage autopilot mode.")
13
+ console = Console()
14
+
15
+
16
+ @app.command("status")
17
+ def status():
18
+ """Check autopilot status and settings."""
19
+ db = get_db()
20
+ try:
21
+ service = AutopilotService(db)
22
+ enabled = service.is_enabled()
23
+ paused = service.is_paused()
24
+ mode = service.get_mode()
25
+
26
+ status_str = "[bold red]PAUSED[/]" if paused else ("[bold green]ENABLED[/]" if enabled else "[yellow]DISABLED[/]")
27
+ console.print(f"Autopilot State: {status_str}")
28
+ console.print(f"Mode: [cyan]{mode}[/] (approval = prepares drafts for review | autopilot = auto-publishes)")
29
+ finally:
30
+ db.close()
31
+
32
+
33
+ @app.command("enable")
34
+ def enable():
35
+ """Enable autopilot."""
36
+ db = get_db()
37
+ try:
38
+ service = AutopilotService(db)
39
+ service.enable()
40
+ console.print("[bold green]✔ Autopilot enabled.[/]")
41
+ finally:
42
+ db.close()
43
+
44
+
45
+ @app.command("disable")
46
+ def disable():
47
+ """Disable autopilot."""
48
+ db = get_db()
49
+ try:
50
+ service = AutopilotService(db)
51
+ service.disable()
52
+ console.print("[yellow]Autopilot disabled.[/]")
53
+ finally:
54
+ db.close()
55
+
56
+
57
+ @app.command("pause")
58
+ def pause():
59
+ """Emergency pause autopilot immediately."""
60
+ db = get_db()
61
+ try:
62
+ service = AutopilotService(db)
63
+ service.pause()
64
+ console.print("[bold red]⏸ Emergency Pause activated. Autopilot halted.[/]")
65
+ finally:
66
+ db.close()
67
+
68
+
69
+ @app.command("resume")
70
+ def resume():
71
+ """Resume autopilot operations."""
72
+ db = get_db()
73
+ try:
74
+ service = AutopilotService(db)
75
+ service.resume()
76
+ console.print("[bold green]▶ Autopilot resumed.[/]")
77
+ finally:
78
+ db.close()
79
+
80
+
81
+ @app.command("run-cycle")
82
+ def run_cycle(topic: str = typer.Option(None, "--topic", "-t", help="Optional topic override")):
83
+ """Trigger a single autopilot generation and rotation cycle immediately."""
84
+ console.print("[bold cyan]🔄 Running Autopilot cycle...[/]")
85
+ db = get_db()
86
+ try:
87
+ service = AutopilotService(db)
88
+ loop = asyncio.new_event_loop()
89
+ asyncio.set_event_loop(loop)
90
+ drafts = loop.run_until_complete(service.execute_cycle(topic=topic))
91
+ for d in drafts:
92
+ console.print(
93
+ Panel(
94
+ d.content,
95
+ title=f"[bold green]Autopilot Draft #{d.id}[/] ([cyan]{d.category}[/]) - Status: [magenta]{d.status}[/]",
96
+ border_style="cyan",
97
+ )
98
+ )
99
+ except Exception as e:
100
+ console.print(f"[bold red]✘ Autopilot cycle failed: {e}[/]")
101
+ finally:
102
+ db.close()
@@ -0,0 +1,65 @@
1
+ """
2
+ CLI command: config
3
+ """
4
+
5
+ import typer
6
+ from rich.console import Console
7
+ from postpilot.database.db import get_db
8
+ from postpilot.database.repositories import SettingsRepository
9
+ from postpilot.utils.config import settings
10
+
11
+ app = typer.Typer(help="Manage settings and creator profile.")
12
+ console = Console()
13
+
14
+
15
+ @app.command("show")
16
+ def show_config():
17
+ """Display active settings."""
18
+ db = get_db()
19
+ try:
20
+ repo = SettingsRepository(db)
21
+ pub_method = repo.get("DEFAULT_PUBLISH_METHOD", settings.DEFAULT_PUBLISH_METHOD)
22
+ ai_provider = repo.get("DEFAULT_AI_PROVIDER", settings.DEFAULT_AI_PROVIDER)
23
+
24
+ console.print("[bold cyan]PostPilot Active Configuration:[/]")
25
+ console.print(f"Timezone: [green]{settings.TIMEZONE}[/]")
26
+ console.print(f"AI Provider: [green]{ai_provider}[/]")
27
+ console.print(f"Publish Method: [green]{pub_method}[/] (manual: $0 free | x_api: paid official)")
28
+ console.print(f"Publish Mode: [green]{settings.DEFAULT_PUBLISH_MODE}[/]")
29
+ console.print(f"Max Posts/Day: [green]{settings.MAX_POSTS_PER_DAY}[/]")
30
+ finally:
31
+ db.close()
32
+
33
+
34
+ @app.command("set-publisher")
35
+ def set_publisher(method: str = typer.Argument(..., help="Publishing method: manual or x_api")):
36
+ """Switch default publishing method between 'manual' ($0 fallback) and 'x_api'."""
37
+ val = method.lower()
38
+ if val not in ("manual", "x_api"):
39
+ console.print("[bold red]✘ Invalid method. Choose 'manual' or 'x_api'.[/]")
40
+ return
41
+
42
+ db = get_db()
43
+ try:
44
+ repo = SettingsRepository(db)
45
+ repo.set("DEFAULT_PUBLISH_METHOD", val)
46
+ console.print(f"[bold green]✔ Default publish method set to: [cyan]{val}[/][/]")
47
+ finally:
48
+ db.close()
49
+
50
+
51
+ @app.command("set-provider")
52
+ def set_provider(provider: str = typer.Argument(..., help="AI provider: groq, gemini, or ollama")):
53
+ """Switch default AI provider."""
54
+ val = provider.lower()
55
+ if val not in ("groq", "gemini", "ollama"):
56
+ console.print("[bold red]✘ Invalid provider. Choose 'groq', 'gemini', or 'ollama'.[/]")
57
+ return
58
+
59
+ db = get_db()
60
+ try:
61
+ repo = SettingsRepository(db)
62
+ repo.set("DEFAULT_AI_PROVIDER", val)
63
+ console.print(f"[bold green]✔ Default AI provider set to: [cyan]{val}[/][/]")
64
+ finally:
65
+ db.close()
@@ -0,0 +1,126 @@
1
+ """
2
+ CLI command: dna (TweetDNA Creator Intelligence & Hourly Drop Controls)
3
+ """
4
+
5
+ import asyncio
6
+ import typer
7
+ from rich.console import Console
8
+ from rich.table import Table
9
+ from rich.panel import Panel
10
+
11
+ from postpilot.database.db import get_db, init_db
12
+ from postpilot.services.dna import DNAService
13
+ from postpilot.scheduler.hourly_delivery import deliver_hourly_posts
14
+
15
+ app = typer.Typer(help="TweetDNA creator intelligence and style cloning commands.")
16
+ console = Console()
17
+
18
+
19
+ @app.command("track")
20
+ def track(username: str = typer.Argument(..., help="X handle of the creator to track (e.g. @levelsio)")):
21
+ """Scrape and extract Content DNA for a creator."""
22
+ init_db()
23
+ clean_user = username.lstrip("@").strip()
24
+ console.print(f"[bold cyan]🧬 Analyzing and extracting Content DNA for @{clean_user}...[/]")
25
+
26
+ db = get_db()
27
+ try:
28
+ service = DNAService(db)
29
+ loop = asyncio.new_event_loop()
30
+ asyncio.set_event_loop(loop)
31
+ result = loop.run_until_complete(service.track_creator(clean_user))
32
+
33
+ dna = result["dna"]
34
+ console.print(f"[bold green]✔ Successfully analyzed @{clean_user} ({result['tweets_count']} tweets analyzed)![/]")
35
+ console.print(f"• Tone: [cyan]{dna.tone}[/]")
36
+ console.print(f"• Content Pillars: [yellow]{dna.content_pillars}[/]")
37
+ console.print(f"• Hook Styles: [magenta]{dna.hook_patterns}[/]")
38
+ console.print(f"[green]Added to your hourly generation pool! Posts will now reflect this creator's style.[/]")
39
+ finally:
40
+ db.close()
41
+
42
+
43
+ @app.command("list")
44
+ def list_creators():
45
+ """List all tracked creators in your intelligence pool."""
46
+ init_db()
47
+ db = get_db()
48
+ try:
49
+ service = DNAService(db)
50
+ creators = service.list_creators()
51
+ if not creators:
52
+ console.print("[yellow]No creators tracked yet. Track one with: postpilot dna track @username[/]")
53
+ return
54
+
55
+ table = Table(title="TweetDNA Tracked Creator Pool")
56
+ table.add_column("Username", style="cyan")
57
+ table.add_column("Tweets Cached", justify="right", style="green")
58
+ table.add_column("Tone", style="white")
59
+ table.add_column("Last Synced", style="dim")
60
+
61
+ for c in creators:
62
+ tone = c.dna.tone if c.dna else "Analyzing"
63
+ last_synced = c.last_synced_at.strftime("%Y-%m-%d %H:%M") if c.last_synced_at else "Recent"
64
+ table.add_row(f"@{c.username}", str(len(c.tweets)), tone, last_synced)
65
+
66
+ console.print(table)
67
+ finally:
68
+ db.close()
69
+
70
+
71
+ @app.command("untrack")
72
+ def untrack(username: str = typer.Argument(..., help="X handle to remove")):
73
+ """Remove a creator from the tracking pool."""
74
+ init_db()
75
+ clean_user = username.lstrip("@").strip()
76
+ db = get_db()
77
+ try:
78
+ service = DNAService(db)
79
+ if service.untrack_creator(clean_user):
80
+ console.print(f"[bold yellow]✔ Removed @{clean_user} from tracked creators.[/]")
81
+ else:
82
+ console.print(f"[bold red]✘ Creator @{clean_user} not found.[/]")
83
+ finally:
84
+ db.close()
85
+
86
+
87
+ @app.command("ideas")
88
+ def ideas(
89
+ count: int = typer.Option(4, "--count", "-c", help="Number of posts to generate"),
90
+ topic: str = typer.Option(None, "--topic", "-t", help="Optional specific topic"),
91
+ ):
92
+ """Generate fresh posts synthesized from your creator pool."""
93
+ init_db()
94
+ console.print(f"[bold cyan]⚡ Generating {count} posts from your creator intelligence pool...[/]")
95
+ db = get_db()
96
+ try:
97
+ service = DNAService(db)
98
+ loop = asyncio.new_event_loop()
99
+ asyncio.set_event_loop(loop)
100
+ posts = loop.run_until_complete(service.generate_posts_from_pool(count=count, topic=topic))
101
+
102
+ for idx, item in enumerate(posts, start=1):
103
+ creator_tag = f"Style: @{item['creator']}" if item.get('creator') != 'general' else "General Style"
104
+ console.print(
105
+ Panel(
106
+ item["content"],
107
+ title=f"[bold green]Post #{idx}[/] ([cyan]{creator_tag}[/]) - [dim]{len(item['content'])} chars[/]",
108
+ border_style="green",
109
+ )
110
+ )
111
+ finally:
112
+ db.close()
113
+
114
+
115
+ @app.command("drop-now")
116
+ def drop_now(count: int = typer.Option(4, "--count", "-c", help="Number of posts to deliver")):
117
+ """Trigger an immediate test run of the hourly content delivery."""
118
+ init_db()
119
+ console.print(f"[bold cyan]🚀 Triggering immediate hourly delivery test ({count} posts)...[/]")
120
+ loop = asyncio.new_event_loop()
121
+ asyncio.set_event_loop(loop)
122
+ try:
123
+ loop.run_until_complete(deliver_hourly_posts(count=count))
124
+ console.print("[bold green]✔ Delivery test complete![/]")
125
+ finally:
126
+ loop.close()