-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiloagent.py
More file actions
2378 lines (1978 loc) · 85.6 KB
/
miloagent.py
File metadata and controls
2378 lines (1978 loc) · 85.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Milo — AI Growth Agent for social media automation."""
import os
import sys
import time
import logging
from pathlib import Path
import click
import yaml
# Ensure project root is on path
PROJECT_ROOT = Path(__file__).parent
sys.path.insert(0, str(PROJECT_ROOT))
def load_yaml(path: str) -> dict:
"""Load a YAML config file."""
with open(path) as f:
return yaml.safe_load(f) or {}
def load_projects(projects_dir: str = "projects/") -> list:
"""Auto-discover all YAML project files."""
projects = []
pdir = Path(projects_dir)
if not pdir.exists():
return projects
for f in pdir.glob("*.yaml"):
data = load_yaml(str(f))
if data and data.get("project", {}).get("enabled", True):
projects.append(data)
projects.sort(
key=lambda p: p.get("project", {}).get("weight", 1.0), reverse=True
)
return projects
def find_project(projects: list, name: str) -> dict:
"""Find a project by name (case-insensitive)."""
for p in projects:
if p.get("project", {}).get("name", "").lower() == name.lower():
return p
return {}
def setup_logging(level: str = "INFO"):
"""Configure logging with console + rotating file output."""
from logging.handlers import RotatingFileHandler
log_level = getattr(logging, level.upper(), logging.INFO)
fmt = "%(asctime)s [%(levelname)s] %(name)s: %(message)s"
datefmt = "%Y-%m-%d %H:%M:%S"
# Root logger
root = logging.getLogger()
root.setLevel(log_level)
# Console handler (for TUI dashboard)
if not root.handlers:
console = logging.StreamHandler()
console.setLevel(log_level)
console.setFormatter(logging.Formatter(fmt, datefmt=datefmt))
root.addHandler(console)
# Persistent file handler (5MB, keep 3 rotated files)
log_dir = PROJECT_ROOT / "logs"
log_dir.mkdir(exist_ok=True)
file_handler = RotatingFileHandler(
log_dir / "miloagent.log",
maxBytes=5 * 1024 * 1024,
backupCount=3,
encoding="utf-8",
)
file_handler.setLevel(log_level)
file_handler.setFormatter(logging.Formatter(fmt, datefmt=datefmt))
root.addHandler(file_handler)
# Suppress noisy third-party loggers that flood the log
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
logging.getLogger("hpack").setLevel(logging.WARNING)
logging.getLogger("telethon.client.updates").setLevel(logging.WARNING)
logging.getLogger("telethon.extensions.messagepacker").setLevel(logging.WARNING)
def check_config_placeholders(config: dict, name: str) -> list:
"""Check for placeholder values in config. Returns list of warnings."""
warnings = []
def _check(d, path=""):
if isinstance(d, dict):
for k, v in d.items():
_check(v, f"{path}.{k}" if path else k)
elif isinstance(d, list):
for i, v in enumerate(d):
_check(v, f"{path}[{i}]")
elif isinstance(d, str) and d.startswith("YOUR_"):
warnings.append(f" {name}: {path} = {d}")
_check(config)
return warnings
# ─── CLI ─────────────────────────────────────────────────────────────
@click.group()
@click.option("--verbose", "-v", is_flag=True, help="Enable debug logging")
@click.pass_context
def cli(ctx, verbose):
"""Milo — AI Growth Agent."""
ctx.ensure_object(dict)
os.chdir(PROJECT_ROOT)
setup_logging("DEBUG" if verbose else "INFO")
ctx.obj["settings"] = load_yaml("config/settings.yaml")
ctx.obj["projects"] = load_projects()
# Lazy-init business manager (only created if needed)
ctx.obj["_business_mgr"] = None
def _get_business_mgr():
"""Get or create the BusinessManager singleton."""
from core.business_manager import BusinessManager
return BusinessManager()
# ─── BUSINESS MANAGEMENT ─────────────────────────────────────────────
@cli.group()
def business():
"""Manage businesses/projects (add, remove, list, show)."""
pass
@business.command(name="list")
@click.pass_context
def business_list(ctx):
"""List all configured businesses."""
mgr = _get_business_mgr()
projects = mgr.projects
if not projects:
click.echo("No projects configured. Add one with: business add")
return
click.echo(f"\n=== {len(projects)} Business(es) ===\n")
for p in projects:
proj = p["project"]
enabled = click.style("enabled", fg="green") if proj.get("enabled", True) else click.style("disabled", fg="red")
url = proj.get("url", "")
weight = proj.get("weight", 1.0)
has_profile = "+" if proj.get("business_profile") else "-"
click.echo(f" {proj['name']} ({url}) [{enabled}] weight={weight} profile={has_profile}")
click.echo("")
@business.command(name="add")
@click.option("--name", required=True, prompt="Business name")
@click.option("--url", required=True, prompt="Website URL")
@click.option("--description", required=True, prompt="Short description")
@click.option("--type", "project_type", default="SaaS", help="Business type")
def business_add(name, url, description, project_type):
"""Add a new business/project."""
mgr = _get_business_mgr()
try:
filepath = mgr.add_project(name, url, description, project_type)
click.echo(click.style(f"\nCreated: {filepath}", fg="green"))
click.echo("Next steps:")
click.echo(f" 1. Edit {filepath} to add keywords, subreddits, and business profile")
click.echo(f" 2. Run: python miloagent.py business show {name}")
click.echo(f" 3. Run: python miloagent.py scan reddit -p {name.lower()}")
except ValueError as e:
click.echo(click.style(str(e), fg="red"))
@business.command(name="remove")
@click.argument("name")
@click.confirmation_option(prompt="Are you sure you want to delete this project?")
def business_remove(name):
"""Remove a business/project by name."""
mgr = _get_business_mgr()
if mgr.delete_project(name):
click.echo(click.style(f"Removed project: {name}", fg="green"))
else:
click.echo(click.style(f"Project '{name}' not found.", fg="red"))
available = mgr.list_projects()
if available:
click.echo(f"Available: {', '.join(available)}")
@business.command(name="show")
@click.argument("name")
def business_show(name):
"""Show detailed info for a business."""
mgr = _get_business_mgr()
proj = mgr.get_project(name)
if not proj:
click.echo(click.style(f"Project '{name}' not found.", fg="red"))
available = mgr.list_projects()
if available:
click.echo(f"Available: {', '.join(available)}")
return
click.echo(f"\n=== {proj['project']['name']} ===\n")
click.echo(yaml.dump(proj, default_flow_style=False, sort_keys=False))
filepath = mgr.get_project_filepath(name)
if filepath:
click.echo(f"File: {filepath}")
@business.command(name="edit")
@click.argument("name")
def business_edit(name):
"""Open a business YAML file for editing (shows file path)."""
mgr = _get_business_mgr()
filepath = mgr.get_project_filepath(name)
if not filepath:
click.echo(click.style(f"Project '{name}' not found.", fg="red"))
return
click.echo(f"Edit this file: {filepath}")
click.echo("Changes are auto-detected when the bot is running (hot-reload).")
# ─── SCAN ────────────────────────────────────────────────────────────
@cli.command()
@click.argument("platform", type=click.Choice(["reddit", "twitter", "telegram", "all"]))
@click.option("--project", "-p", default=None, help="Specific project name (or 'all')")
@click.pass_context
def scan(ctx, platform, project):
"""Scan a platform for opportunities."""
from core.database import Database
from core.llm_provider import LLMProvider
from core.content_gen import ContentGenerator
settings = ctx.obj["settings"]
projects = ctx.obj["projects"]
db = Database(settings["database"]["path"])
llm = LLMProvider("config/llm.yaml")
content_gen = ContentGenerator(llm)
# Filter projects
if project and project.lower() != "all":
matched = find_project(projects, project)
if not matched:
click.echo(click.style(f"Project '{project}' not found.", fg="red"))
click.echo(f"Available: {', '.join(pr['project']['name'] for pr in projects)}")
db.close()
return
projects = [matched]
if platform in ("reddit", "all"):
_scan_reddit(db, content_gen, projects)
if platform in ("twitter", "all"):
_scan_twitter(db, content_gen, projects)
if platform in ("telegram", "all"):
_scan_telegram(db, content_gen, projects)
db.close()
def _get_reddit_bot(db, content_gen):
"""Create the right Reddit bot based on auth_mode config."""
reddit_cfg = load_yaml("config/reddit_accounts.yaml")
auth_mode = reddit_cfg.get("auth_mode", "web")
accounts = reddit_cfg.get("accounts", [])
if not accounts:
click.echo(click.style("No Reddit accounts configured.", fg="red"))
return None
account = next((a for a in accounts if a.get("enabled", True)), None)
if not account:
click.echo(click.style("No enabled Reddit accounts.", fg="red"))
return None
if auth_mode == "api" and account.get("client_id"):
from platforms.reddit_bot import RedditBot
click.echo(" (using PRAW/API mode)")
return RedditBot(db, content_gen, account)
else:
from platforms.reddit_web import RedditWebBot
click.echo(" (using web/cookie mode — no API app needed)")
return RedditWebBot(db, content_gen, account)
def _scan_reddit(db, content_gen, projects):
"""Run Reddit scan for given projects."""
bot = _get_reddit_bot(db, content_gen)
if not bot:
return
for proj in projects:
proj_name = proj.get("project", {}).get("name", "unknown")
click.echo(f"\nScanning Reddit for {proj_name}...")
opportunities = bot.scan(proj)
click.echo(f" Found {len(opportunities)} opportunities:")
for opp in opportunities[:10]:
score_color = "green" if opp["relevance_score"] >= 7 else (
"yellow" if opp["relevance_score"] >= 5 else "red"
)
score_str = f"{opp['relevance_score']:.1f}"
click.echo(
f" [{click.style(score_str, fg=score_color)}] "
f"r/{opp['subreddit']}: {opp['title'][:60]}"
)
def _scan_twitter(db, content_gen, projects):
"""Run Twitter scan for given projects."""
from platforms.twitter_bot import TwitterBot
accounts = load_yaml("config/twitter_accounts.yaml").get("accounts", [])
if not accounts:
click.echo(click.style("No Twitter accounts configured.", fg="red"))
return
account = next((a for a in accounts if a.get("enabled", True)), None)
if not account:
click.echo(click.style("No enabled Twitter accounts.", fg="red"))
return
bot = TwitterBot(db, content_gen, account)
for proj in projects:
proj_name = proj.get("project", {}).get("name", "unknown")
click.echo(f"\nScanning Twitter for {proj_name}...")
opportunities = bot.scan(proj)
click.echo(f" Found {len(opportunities)} opportunities:")
for opp in opportunities[:10]:
click.echo(
f" @{opp.get('user', '?')}: {opp['text'][:80]}"
)
def _scan_telegram(db, content_gen, projects):
"""Run Telegram group scan for given projects."""
from platforms.telegram_group_bot import TelegramGroupBot
accounts = load_yaml("config/telegram_user_accounts.yaml").get("accounts", [])
if not accounts:
click.echo(click.style("No Telegram user accounts configured.", fg="red"))
return
account = next(
(a for a in accounts
if a.get("enabled", True)
and a.get("api_id")
and not a.get("phone", "").startswith("+00XXX")),
None,
)
if not account:
click.echo(click.style("No enabled Telegram accounts with credentials.", fg="red"))
return
bot = TelegramGroupBot(db, content_gen, account)
for proj in projects:
tg_cfg = proj.get("telegram", {})
if not tg_cfg.get("enabled", False):
continue
proj_name = proj.get("project", {}).get("name", "unknown")
click.echo(f"\nScanning Telegram groups for {proj_name}...")
opportunities = bot.scan(proj)
click.echo(f" Found {len(opportunities)} opportunities:")
for opp in opportunities[:10]:
click.echo(
f" [{opp.get('group_name', '?')}] @{opp.get('author_name', '?')}: "
f"{opp.get('text', '')[:80]}"
)
# ─── POST ────────────────────────────────────────────────────────────
@cli.command()
@click.argument("platform", type=click.Choice(["reddit", "twitter"]))
@click.option("--project", "-p", required=True, help="Project name")
@click.option("--dry-run", is_flag=True, help="Generate content but don't post")
@click.option("--target", "-t", default=None, help="Specific target ID to act on")
@click.pass_context
def post(ctx, platform, project, dry_run, target):
"""Post content to a platform for a project."""
from core.database import Database
from core.llm_provider import LLMProvider
from core.content_gen import ContentGenerator
settings = ctx.obj["settings"]
projects = ctx.obj["projects"]
db = Database(settings["database"]["path"])
llm = LLMProvider("config/llm.yaml")
content_gen = ContentGenerator(llm)
proj = find_project(projects, project)
if not proj:
click.echo(click.style(f"Project '{project}' not found.", fg="red"))
db.close()
return
if platform == "reddit":
_post_reddit(db, content_gen, proj, dry_run, target)
elif platform == "twitter":
_post_twitter(db, content_gen, proj, dry_run, target)
db.close()
def _post_reddit(db, content_gen, project, dry_run, target_id):
"""Post a Reddit comment."""
bot = _get_reddit_bot(db, content_gen)
if not bot:
return
proj_name = project.get("project", {}).get("name", "unknown")
# Get target opportunity
if target_id:
opp = {"target_id": target_id, "title": "(manual target)", "body": "", "subreddit": "unknown"}
else:
# Pick the best pending opportunity
pending = db.get_pending_opportunities(platform="reddit", project=proj_name)
if not pending:
click.echo("No pending Reddit opportunities. Run 'scan reddit' first.")
return
opp = pending[0]
# Map DB field to what the bot expects
if "subreddit_or_query" in opp and "subreddit" not in opp:
opp["subreddit"] = opp["subreddit_or_query"]
if "body" not in opp:
opp["body"] = ""
click.echo(
f"Best opportunity [{opp['score']:.1f}]: "
f"r/{opp.get('subreddit', '?')}: {opp['title'][:60]}"
)
if dry_run:
click.echo("\n--- DRY RUN (not posting) ---")
comment = bot.act_dry_run(opp, project)
click.echo(f"\nGenerated comment:\n{comment}")
else:
click.echo("\nPosting comment...")
success = bot.act(opp, project)
if success:
click.echo(click.style("Comment posted successfully!", fg="green"))
else:
click.echo(click.style("Failed to post comment.", fg="red"))
def _post_twitter(db, content_gen, project, dry_run, target_id):
"""Post a tweet or reply."""
from platforms.twitter_bot import TwitterBot
accounts = load_yaml("config/twitter_accounts.yaml").get("accounts", [])
account = next((a for a in accounts if a.get("enabled", True)), None)
if not account:
click.echo(click.style("No enabled Twitter accounts.", fg="red"))
return
bot = TwitterBot(db, content_gen, account)
proj_name = project.get("project", {}).get("name", "unknown")
if target_id:
opp = {"target_id": target_id, "text": "(manual target)", "user": "unknown"}
else:
pending = db.get_pending_opportunities(platform="twitter", project=proj_name)
if not pending:
click.echo("No pending Twitter opportunities. Run 'scan twitter' first.")
return
opp = pending[0]
click.echo(f"Best opportunity: {opp['title'][:60]}")
if dry_run:
click.echo("\n--- DRY RUN (not posting) ---")
reply = content_gen.generate_twitter_reply(
tweet_text=opp.get("text", opp.get("title", "")),
tweet_author=opp.get("user", "unknown"),
project=project,
)
click.echo(f"\nGenerated reply:\n{reply}")
else:
click.echo("\nPosting to Twitter...")
success = bot.act(opp, project)
if success:
click.echo(click.style("Posted successfully!", fg="green"))
else:
click.echo(click.style("Failed to post.", fg="red"))
# ─── ENGAGE (Warm-up & organic engagement) ────────────────────────────
@cli.command()
@click.argument("platform", type=click.Choice(["reddit", "twitter", "all"]))
@click.option("--project", "-p", default=None, help="Specific project name (or all)")
@click.pass_context
def engage(ctx, platform, project):
"""Run organic engagement: upvote, subscribe, like, follow.
Makes accounts look natural. Run before posting for the first time.
\b
Examples:
python miloagent.py engage reddit # Engage on Reddit (all projects)
python miloagent.py engage twitter -p my_project # Engage on Twitter for a project
python miloagent.py engage all # Engage on all platforms
"""
from core.database import Database
from core.llm_provider import LLMProvider
from core.content_gen import ContentGenerator
settings = ctx.obj["settings"]
projects = ctx.obj["projects"]
db = Database(settings["database"]["path"])
llm = LLMProvider("config/llm.yaml")
content_gen = ContentGenerator(llm)
# Filter projects
if project and project.lower() != "all":
matched = find_project(projects, project)
if not matched:
click.echo(click.style(f"Project '{project}' not found.", fg="red"))
db.close()
return
projects = [matched]
if platform in ("reddit", "all"):
_engage_reddit(db, content_gen, projects)
if platform in ("twitter", "all"):
_engage_twitter(db, content_gen, projects)
db.close()
def _engage_reddit(db, content_gen, projects):
"""Run Reddit engagement (subscribe, upvote, save)."""
bot = _get_reddit_bot(db, content_gen)
if not bot:
return
if not hasattr(bot, "warm_up"):
click.echo(click.style("Reddit bot doesn't support warm-up (API mode).", fg="yellow"))
return
for proj in projects:
proj_name = proj.get("project", {}).get("name", "unknown")
click.echo(f"\nEngaging on Reddit for {proj_name}...")
# Show account info first
info = bot.get_user_info() if hasattr(bot, "get_user_info") else None
if info:
click.echo(
f" Account: u/{info['username']} | "
f"Comment karma: {info['comment_karma']} | "
f"Link karma: {info['link_karma']} | "
f"Verified: {info['verified']}"
)
stats = bot.warm_up(proj)
click.echo(click.style(
f" Subscribed: {stats['subscribed']} | "
f"Upvoted: {stats['upvoted']} | "
f"Saved: {stats['saved']}",
fg="green",
))
def _engage_twitter(db, content_gen, projects):
"""Run Twitter engagement (like, follow, retweet)."""
from platforms.twitter_bot import TwitterBot
accounts = load_yaml("config/twitter_accounts.yaml").get("accounts", [])
account = next((a for a in accounts if a.get("enabled", True)), None)
if not account:
click.echo(click.style("No enabled Twitter accounts.", fg="red"))
return
bot = TwitterBot(db, content_gen, account)
for proj in projects:
proj_name = proj.get("project", {}).get("name", "unknown")
click.echo(f"\nEngaging on Twitter for {proj_name}...")
stats = bot.warm_up(proj)
click.echo(click.style(
f" Liked: {stats['liked']} | "
f"Followed: {stats['followed']} | "
f"Bookmarked: {stats['bookmarked']} | "
f"Retweeted: {stats['retweeted']}",
fg="green",
))
@cli.command(name="account-info")
@click.argument("platform", type=click.Choice(["reddit", "twitter"]))
def account_info(platform):
"""Show detailed info for an account (karma, followers, etc.)."""
from core.database import Database
from core.llm_provider import LLMProvider
from core.content_gen import ContentGenerator
db = Database("data/miloagent.db")
llm = LLMProvider("config/llm.yaml")
content_gen = ContentGenerator(llm)
if platform == "reddit":
bot = _get_reddit_bot(db, content_gen)
if not bot:
db.close()
return
if not hasattr(bot, "get_user_info"):
click.echo("Account info not available in API mode.")
db.close()
return
info = bot.get_user_info()
if info:
click.echo(f"\n=== Reddit Account: u/{info['username']} ===\n")
click.echo(f" Comment Karma: {info['comment_karma']}")
click.echo(f" Link Karma: {info['link_karma']}")
click.echo(f" Email Verified: {info['verified']}")
click.echo(f" Reddit Gold: {info['is_gold']}")
click.echo(f" Inbox: {info['inbox_count']} messages")
# Account age
if info['created_utc']:
from datetime import datetime, timezone
created = datetime.fromtimestamp(info['created_utc'], tz=timezone.utc)
age_days = (datetime.now(tz=timezone.utc) - created).days
click.echo(f" Account Age: {age_days} days ({created.strftime('%Y-%m-%d')})")
else:
click.echo(click.style("Failed to get account info. Check authentication.", fg="red"))
elif platform == "twitter":
click.echo("Twitter account info: use 'python miloagent.py test twitter'")
db.close()
# ─── STATUS ──────────────────────────────────────────────────────────
@cli.command()
@click.pass_context
def status(ctx):
"""Show bot status and recent activity."""
from core.database import Database
settings = ctx.obj["settings"]
projects = ctx.obj["projects"]
db = Database(settings["database"]["path"])
click.echo("\n=== Milo Status ===\n")
# Mode info
mode = settings.get("bot", {}).get("mode", "unknown")
cost = settings.get("bot", {}).get("cost_mode", "unknown")
click.echo(f"Mode: {mode} | Cost: {cost}")
click.echo(f"Projects: {', '.join(p['project']['name'] for p in projects)}\n")
# Stats
stats = db.get_stats_summary(hours=24)
click.echo("--- Last 24h Actions ---")
actions = stats.get("actions", {})
if not actions:
click.echo(" No actions yet.")
else:
for platform, types in actions.items():
for action_type, count in types.items():
click.echo(f" {platform}/{action_type}: {count}")
click.echo(f"\n--- Opportunities ---")
opps = stats.get("opportunities", {})
if not opps:
click.echo(" No opportunities scanned yet.")
else:
for status_name, count in opps.items():
click.echo(f" {status_name}: {count}")
click.echo(f" Avg score: {stats.get('avg_opportunity_score', 0)}")
# Recent actions
click.echo("\n--- Recent Actions ---")
recent = db.get_recent_actions(hours=24, limit=5)
if not recent:
click.echo(" None")
else:
for action in recent:
ts = action["timestamp"][:16]
click.echo(
f" [{ts}] {action['platform']}/{action['action_type']} "
f"by {action['account']} ({action['project']})"
)
db.close()
# ─── STATS ───────────────────────────────────────────────────────────
@cli.command()
@click.option("--hours", "-h", default=24, help="Time window in hours")
@click.pass_context
def stats(ctx, hours):
"""Show detailed statistics."""
from core.database import Database
settings = ctx.obj["settings"]
db = Database(settings["database"]["path"])
summary = db.get_stats_summary(hours=hours)
click.echo(f"\n=== Milo Stats (last {hours}h) ===\n")
actions = summary.get("actions", {})
total = sum(sum(t.values()) for t in actions.values())
click.echo(f"Total actions: {total}")
for platform, types in actions.items():
click.echo(f"\n {platform.upper()}:")
for action_type, count in types.items():
click.echo(f" {action_type}: {count}")
opps = summary.get("opportunities", {})
click.echo(f"\nOpportunities: {sum(opps.values())}")
for s, c in opps.items():
click.echo(f" {s}: {c}")
click.echo(f"Avg opportunity score: {summary.get('avg_opportunity_score', 0)}")
db.close()
# ─── TEST ────────────────────────────────────────────────────────────
@cli.command()
@click.argument("service", type=click.Choice(["llm", "reddit", "twitter", "telegram", "telegram-groups", "all"]))
def test(service):
"""Test connectivity to services."""
results = {}
if service in ("llm", "all"):
click.echo("\nTesting LLM providers...")
from core.llm_provider import LLMProvider
try:
llm = LLMProvider("config/llm.yaml")
llm_results = llm.test_connection()
for name, ok in llm_results.items():
label = f"llm/{name}"
results[label] = ok
except Exception as e:
results["llm"] = False
click.echo(f" Error: {e}")
if service in ("reddit", "all"):
click.echo("\nTesting Reddit...")
try:
from core.database import Database
from core.content_gen import ContentGenerator
from core.llm_provider import LLMProvider
db = Database("data/miloagent.db")
llm = LLMProvider("config/llm.yaml")
cg = ContentGenerator(llm)
bot = _get_reddit_bot(db, cg)
if bot:
results["reddit"] = bot.test_connection()
else:
results["reddit"] = False
db.close()
except Exception as e:
results["reddit"] = False
click.echo(f" Error: {e}")
if service in ("twitter", "all"):
click.echo("\nTesting Twitter...")
try:
accounts = load_yaml("config/twitter_accounts.yaml").get("accounts", [])
account = next((a for a in accounts if a.get("enabled", True)), None)
if account and not account.get("username", "").startswith("YOUR_"):
from core.database import Database
from core.content_gen import ContentGenerator
from core.llm_provider import LLMProvider
from platforms.twitter_bot import TwitterBot
db = Database("data/miloagent.db")
llm = LLMProvider("config/llm.yaml")
cg = ContentGenerator(llm)
bot = TwitterBot(db, cg, account)
results["twitter"] = bot.test_connection()
db.close()
else:
results["twitter"] = False
click.echo(" Twitter account not configured (placeholder values)")
except Exception as e:
results["twitter"] = False
click.echo(f" Error: {e}")
if service in ("telegram", "all"):
click.echo("\nTesting Telegram...")
try:
tg_config = load_yaml("config/telegram.yaml")
token = tg_config.get("bot_token", "")
if token and not token.startswith("YOUR_"):
import requests
resp = requests.get(
f"https://api.telegram.org/bot{token}/getMe",
timeout=10,
)
results["telegram"] = resp.status_code == 200
else:
results["telegram"] = False
click.echo(" Telegram bot not configured (placeholder values)")
except Exception as e:
results["telegram"] = False
click.echo(f" Error: {e}")
if service in ("telegram-groups", "telegram", "all"):
click.echo("\nTesting Telegram Groups (Telethon)...")
try:
tg_user_cfg = load_yaml("config/telegram_user_accounts.yaml")
accounts = tg_user_cfg.get("accounts", [])
account = next(
(a for a in accounts
if a.get("enabled", True)
and a.get("api_id")
and not a.get("phone", "").startswith("+00XXX")),
None,
)
if account:
from core.database import Database
from core.content_gen import ContentGenerator
from core.llm_provider import LLMProvider
from platforms.telegram_group_bot import TelegramGroupBot
db = Database("data/miloagent.db")
llm = LLMProvider("config/llm.yaml")
cg = ContentGenerator(llm)
bot = TelegramGroupBot(db, cg, account)
results["telegram-groups"] = bot.test_connection()
db.close()
else:
results["telegram-groups"] = False
click.echo(" Telegram user account not configured")
except Exception as e:
results["telegram-groups"] = False
click.echo(f" Error: {e}")
# Print results
click.echo("\n=== Test Results ===")
for name, ok in results.items():
icon = click.style("PASS", fg="green") if ok else click.style("FAIL", fg="red")
click.echo(f" {name}: {icon}")
if not results:
click.echo(" No services tested.")
# ─── SETUP ───────────────────────────────────────────────────────────
@cli.command()
def setup():
"""Check configuration and guide setup."""
click.echo("\n=== Milo Setup Check ===\n")
all_warnings = []
configs = {
"settings": "config/settings.yaml",
"llm": "config/llm.yaml",
"reddit": "config/reddit_accounts.yaml",
"twitter": "config/twitter_accounts.yaml",
"telegram": "config/telegram.yaml",
}
for name, path in configs.items():
if os.path.exists(path):
data = load_yaml(path)
warnings = check_config_placeholders(data, name)
if warnings:
click.echo(click.style(f" {name}: needs configuration", fg="yellow"))
all_warnings.extend(warnings)
else:
click.echo(click.style(f" {name}: OK", fg="green"))
else:
click.echo(click.style(f" {name}: MISSING ({path})", fg="red"))
# Check projects
projects = load_projects()
click.echo(f"\n Projects found: {len(projects)}")
for p in projects:
click.echo(f" - {p['project']['name']}")
if all_warnings:
click.echo(click.style("\nPlaceholder values found:", fg="yellow"))
for w in all_warnings:
click.echo(w)
click.echo(
"\nEdit the config files to replace YOUR_* values with real credentials."
)
click.echo("\nQuick links:")
click.echo(" Groq API Key: https://console.groq.com")
click.echo(" Gemini API Key: https://aistudio.google.com")
click.echo(" Reddit App: https://www.reddit.com/prefs/apps")
click.echo(" Telegram Bot: Message @BotFather on Telegram")
else:
click.echo(click.style("\nAll configs look good!", fg="green"))
click.echo("Run 'python miloagent.py test all' to verify connections.")
# ─── ACCOUNTS ────────────────────────────────────────────────────────
@cli.command()
@click.pass_context
def accounts(ctx):
"""Show account status."""
from core.database import Database
settings = ctx.obj["settings"]
db = Database(settings["database"]["path"])
click.echo("\n=== Account Status ===\n")
# Reddit accounts
reddit_cfg = load_yaml("config/reddit_accounts.yaml")
click.echo("Reddit:")
for acc in reddit_cfg.get("accounts", []):
enabled = "enabled" if acc.get("enabled", True) else "disabled"
username = acc.get("username", "?")
if username.startswith("YOUR_"):
click.echo(f" {username}: not configured")
else:
action_count = db.get_action_count(hours=24, account=username, platform="reddit")
click.echo(f" u/{username}: {enabled}, {action_count} actions (24h)")
# Twitter accounts
twitter_cfg = load_yaml("config/twitter_accounts.yaml")
click.echo("\nTwitter:")
for acc in twitter_cfg.get("accounts", []):
enabled = "enabled" if acc.get("enabled", True) else "disabled"
username = acc.get("username", "?")
if username.startswith("YOUR_"):
click.echo(f" {username}: not configured")
else:
action_count = db.get_action_count(hours=24, account=username, platform="twitter")
click.echo(f" @{username}: {enabled}, {action_count} actions (24h)")
db.close()
# ─── RUN (Background Mode) ──────────────────────────────────────────
@cli.command()
@click.pass_context
def dashboard(ctx):
"""Launch the Rich TUI dashboard (full-screen terminal).
Starts the bot and displays a live-updating dashboard with:
- System resources & bot status
- LLM provider stats (dual routing)
- Actions, opportunities, recent activity
- Relationship pipeline
- Scheduler jobs
\b
Keyboard shortcuts:
s = trigger scan a = trigger action l = trigger learn
p = pause/resume r = refresh q = quit
"""
# Check environment — warn if headless server
from core.environment import detect_environment, get_env_summary
env = detect_environment()
click.echo(f"Environment: {get_env_summary()}")
if env["is_headless"] and not env["has_tty"]:
click.echo(click.style(
"Headless server detected — TUI requires a terminal.",
fg="yellow",
))
click.echo(" Use 'python3 miloagent.py run --daemon' + Telegram dashboard instead.")
return
click.echo("Starting Milo with TUI dashboard...")
# Check we're running inside a venv
if "VIRTUAL_ENV" not in os.environ and not hasattr(sys, "real_prefix"):
venv_path = os.path.join(PROJECT_ROOT.parent, "venv", "bin", "python3")
if os.path.exists(venv_path):
click.echo(click.style("Not running inside the venv. Use:", fg="yellow"))