From ebc9cfc5ab8c829909a4758b13bc84762d52e07e Mon Sep 17 00:00:00 2001 From: Jelmer de Wit <1598297+jdwit@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:34:32 +0100 Subject: [PATCH 1/6] feat: per-profile moderation policy and moderation log storage Add 'profile policy show|edit|set' for profiles//moderation.md, built on the same show/edit/set code as 'profile brand'. Add an owner-only append-only JSONL log in the profile directory. --- src/ytstudio/commands/profile.py | 143 ++++++++++++++++++++----------- src/ytstudio/config.py | 46 ++++++++++ tests/conftest.py | 20 +++++ tests/test_profile.py | 82 ++++++++++++++---- 4 files changed, 223 insertions(+), 68 deletions(-) diff --git a/src/ytstudio/commands/profile.py b/src/ytstudio/commands/profile.py index d1eba8a..fe98c8e 100644 --- a/src/ytstudio/commands/profile.py +++ b/src/ytstudio/commands/profile.py @@ -100,9 +100,6 @@ def remove( success_message(f"Profile '{name}' removed.") -brand_app = typer.Typer(help="Manage per-channel brand voice (brand.md)") -app.add_typer(brand_app, name="brand") - _BRAND_TEMPLATE = """# Brand voice +## Reject -@brand_app.command("show") -def brand_show( - profile: str = typer.Option(None, "--profile", "-p", help="Profile (default: active)"), -): - """Print the brand voice for a profile""" - target = _resolve_brand_target(profile) - text = config.load_brand(target) - if not text: - console.print( - f"[yellow]No brand voice for '{target}'. Set one with " - f"'ytstudio profile brand edit' or '... brand set --file '.[/yellow]" - ) - raise typer.Exit(1) - # Raw stdout so an agent can capture the markdown verbatim for a system prompt. - print(text) +## Leave held +## Never touch -@brand_app.command("set") -def brand_set( - file: str = typer.Option(..., "--file", "-f", help="Path to a markdown file to import"), - profile: str = typer.Option(None, "--profile", "-p", help="Profile (default: active)"), -): - """Set brand voice non-interactively from a file""" - target = _resolve_brand_target(profile) - src = Path(file) - if not src.is_file(): - console.print(f"[red]File not found: {file}[/red]") +## Always send to me +""" + + +def _resolve_profile(profile: str | None) -> str: + target = profile or config.get_active_profile() + if not config.profile_exists(target): + console.print(f"[red]No profile named '{target}'. See 'ytstudio profile list'.[/red]") raise typer.Exit(1) - config.save_brand(target, src.read_text()) - success_message(f"Brand voice set for '{target}'.") + return target -@brand_app.command("edit") -def brand_edit( - profile: str = typer.Option(None, "--profile", "-p", help="Profile (default: active)"), -): - """Open the brand voice in $EDITOR""" - target = _resolve_brand_target(profile) - if config.load_brand(target) is None: - config.save_brand(target, _BRAND_TEMPLATE) - path = config.brand_path(target) - editor = os.environ.get("EDITOR", "vi") - subprocess.run([editor, str(path)], check=False) - # An editor may rewrite the file with looser permissions; re-assert owner-only. - if os.name == "posix": - path.chmod(0o600) - success_message(f"Brand voice saved for '{target}'.") +def _markdown_file_app(*, cmd: str, label: str, template: str, load, save, path) -> typer.Typer: + """show/set/edit commands for one per-profile markdown file (brand.md, moderation.md).""" + sub = typer.Typer(help=f"Manage per-channel {label.lower()} ({path('x').name})") + + @sub.command("show") + def show( + profile: str = typer.Option(None, "--profile", "-p", help="Profile (default: active)"), + ): + target = _resolve_profile(profile) + text = load(target) + if not text: + console.print( + f"[yellow]No {label.lower()} for '{target}'. Set one with " + f"'ytstudio profile {cmd} edit' or '... {cmd} set --file '.[/yellow]" + ) + raise typer.Exit(1) + # Raw stdout so an agent can capture the markdown verbatim for a system prompt. + print(text) + + show.__doc__ = f"Print the {label.lower()} for a profile" + + @sub.command("set") + def set_( + file: str = typer.Option(..., "--file", "-f", help="Path to a markdown file to import"), + profile: str = typer.Option(None, "--profile", "-p", help="Profile (default: active)"), + ): + target = _resolve_profile(profile) + src = Path(file) + if not src.is_file(): + console.print(f"[red]File not found: {file}[/red]") + raise typer.Exit(1) + save(target, src.read_text()) + success_message(f"{label} set for '{target}'.") + + set_.__doc__ = f"Set {label.lower()} non-interactively from a file" + + @sub.command("edit") + def edit( + profile: str = typer.Option(None, "--profile", "-p", help="Profile (default: active)"), + ): + target = _resolve_profile(profile) + if load(target) is None: + save(target, template) + file_path = path(target) + editor = os.environ.get("EDITOR", "vi") + subprocess.run([editor, str(file_path)], check=False) + # An editor may rewrite the file with looser permissions; re-assert owner-only. + if os.name == "posix": + file_path.chmod(0o600) + success_message(f"{label} saved for '{target}'.") + + edit.__doc__ = f"Open the {label.lower()} in $EDITOR" + return sub + + +app.add_typer( + _markdown_file_app( + cmd="brand", + label="Brand voice", + template=_BRAND_TEMPLATE, + load=config.load_brand, + save=config.save_brand, + path=config.brand_path, + ), + name="brand", +) +app.add_typer( + _markdown_file_app( + cmd="policy", + label="Moderation policy", + template=_POLICY_TEMPLATE, + load=config.load_policy, + save=config.save_policy, + path=config.policy_path, + ), + name="policy", +) diff --git a/src/ytstudio/config.py b/src/ytstudio/config.py index 7daec39..a38ca82 100644 --- a/src/ytstudio/config.py +++ b/src/ytstudio/config.py @@ -211,6 +211,14 @@ def brand_path(name: str | None = None) -> Path: return profile_dir(name or get_active_profile()) / "brand.md" +def policy_path(name: str | None = None) -> Path: + return profile_dir(name or get_active_profile()) / "moderation.md" + + +def moderation_log_path(name: str | None = None) -> Path: + return profile_dir(name or get_active_profile()) / "moderation-log.jsonl" + + def list_profiles() -> list[str]: if not PROFILES_DIR.exists(): return [] @@ -284,6 +292,44 @@ def save_brand(name: str, text: str) -> None: _write_private(brand_path(name), text) +def load_policy(name: str | None = None) -> str | None: + path = policy_path(name) + if not path.exists(): + return None + return path.read_text() + + +def save_policy(name: str, text: str) -> None: + _ensure_profile_dir(name) + _write_private(policy_path(name), text) + + +def append_moderation_log(records: list[dict], name: str | None = None) -> None: + """Append JSONL records and fsync, so they survive a crash during the API call.""" + target = _ensure_profile_dir(name or get_active_profile()) + path = target / moderation_log_path(name).name + data = "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in records) + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) + try: + os.write(fd, data.encode()) + os.fsync(fd) + finally: + os.close(fd) + + +def read_moderation_log(name: str | None = None) -> list[dict]: + path = moderation_log_path(name) + if not path.exists(): + return [] + records = [] + for line in path.read_text().splitlines(): + try: + records.append(json.loads(line)) + except json.JSONDecodeError: + continue # a torn last line must not block recovery + return records + + def migrate_legacy_credentials() -> bool: """Move a pre-profiles credentials.json into the default profile. One-shot. diff --git a/tests/conftest.py b/tests/conftest.py index 6991a5b..45b1416 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,6 +2,7 @@ import pytest +from ytstudio import config from ytstudio.commands import playlists as _playlists_module MOCK_CHANNEL = { @@ -101,6 +102,7 @@ "topLevelComment": { "snippet": { "authorDisplayName": "Test User", + "authorChannelId": {"value": "UC_test_user"}, "textOriginal": "Great video! Love it!", "textDisplay": "Great video! Love it!", "likeCount": 5, @@ -117,6 +119,7 @@ "topLevelComment": { "snippet": { "authorDisplayName": "Angry User", + "authorChannelId": {"value": "UC_angry_user"}, "textOriginal": "This is terrible and boring", "textDisplay": "This is terrible and boring", "likeCount": 0, @@ -271,3 +274,20 @@ def mock_credentials(): } with patch("ytstudio.config.load_credentials", return_value=mock_creds): yield mock_creds + + +@pytest.fixture +def temp_config(tmp_path, monkeypatch): + config_dir = tmp_path / ".config" / "ytstudio-cli" + config_dir.mkdir(parents=True) + + monkeypatch.delenv(config.PROFILE_ENV_VAR, raising=False) + + with ( + patch.object(config, "CONFIG_DIR", config_dir), + patch.object(config, "CLIENT_SECRETS_FILE", config_dir / "client_secrets.json"), + patch.object(config, "PROFILES_DIR", config_dir / "profiles"), + patch.object(config, "STATE_FILE", config_dir / "state.json"), + patch.object(config, "LEGACY_CREDENTIALS_FILE", config_dir / "credentials.json"), + ): + yield config_dir diff --git a/tests/test_profile.py b/tests/test_profile.py index 1b181f5..48811fe 100644 --- a/tests/test_profile.py +++ b/tests/test_profile.py @@ -11,23 +11,6 @@ runner = CliRunner() -@pytest.fixture -def temp_config(tmp_path, monkeypatch): - config_dir = tmp_path / ".config" / "ytstudio-cli" - config_dir.mkdir(parents=True) - - monkeypatch.delenv(config.PROFILE_ENV_VAR, raising=False) - - with ( - patch.object(config, "CONFIG_DIR", config_dir), - patch.object(config, "CLIENT_SECRETS_FILE", config_dir / "client_secrets.json"), - patch.object(config, "PROFILES_DIR", config_dir / "profiles"), - patch.object(config, "STATE_FILE", config_dir / "state.json"), - patch.object(config, "LEGACY_CREDENTIALS_FILE", config_dir / "credentials.json"), - ): - yield config_dir - - def _make_profile(name, title=None): config.save_credentials({"token": "x"}, name=name) config.save_profile_meta(name, {"title": title or f"{name} channel"}) @@ -219,3 +202,68 @@ def loosen(*args, **kwargs): assert result.exit_code == 0 assert stat.S_IMODE(path.stat().st_mode) == 0o600 assert path.read_text() == "edited by editor" + + +class TestProfilePolicy: + def test_policy_path_helper(self, temp_config): + path = config.policy_path("work") + assert path.name == "moderation.md" + assert path.parent == config.profile_dir("work") + + def test_set_and_show_verbatim(self, temp_config, tmp_path): + _make_profile("work") + config.set_active_profile("work") + src = tmp_path / "policy.md" + src.write_text("# Policy\n- Reject crypto bait.\n") + + assert runner.invoke(app, ["profile", "policy", "set", "--file", str(src)]).exit_code == 0 + result = runner.invoke(app, ["profile", "policy", "show"]) + assert result.exit_code == 0 + assert result.stdout == "# Policy\n- Reject crypto bait.\n\n" + + def test_separate_from_brand(self, temp_config, tmp_path): + _make_profile("work") + config.set_active_profile("work") + src = tmp_path / "policy.md" + src.write_text("policy text") + runner.invoke(app, ["profile", "policy", "set", "--file", str(src)]) + assert config.load_policy("work") == "policy text" + assert config.load_brand("work") is None + + def test_show_missing(self, temp_config): + _make_profile("work") + config.set_active_profile("work") + result = runner.invoke(app, ["profile", "policy", "show"]) + assert result.exit_code == 1 + assert "No moderation policy" in result.stdout + assert "profile policy edit" in result.stdout + + def test_edit_seeds_template_owner_only(self, temp_config): + _make_profile("work") + config.set_active_profile("work") + with patch("ytstudio.commands.profile.subprocess.run") as run: + result = runner.invoke(app, ["profile", "policy", "edit"]) + assert result.exit_code == 0 + run.assert_called_once() + path = config.policy_path("work") + assert "Moderation policy" in path.read_text() + if os.name == "posix": + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + + +class TestModerationLog: + def test_append_and_read(self, temp_config): + _make_profile("work") + config.append_moderation_log([{"id": "a"}, {"id": "b"}], name="work") + config.append_moderation_log([{"id": "c"}], name="work") + assert [r["id"] for r in config.read_moderation_log("work")] == ["a", "b", "c"] + if os.name == "posix": + mode = stat.S_IMODE(config.moderation_log_path("work").stat().st_mode) + assert mode == 0o600 + + def test_torn_line_is_skipped(self, temp_config): + _make_profile("work") + config.append_moderation_log([{"id": "a"}], name="work") + with config.moderation_log_path("work").open("a") as fh: + fh.write('{"id": "b"') + assert [r["id"] for r in config.read_moderation_log("work")] == ["a"] From b47102e54a5906959ed4fc3abda495a1d512e912 Mon Sep 17 00:00:00 2001 From: Jelmer de Wit <1598297+jdwit@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:34:32 +0100 Subject: [PATCH 2/6] feat: preview-first comment moderation with write-ahead log - comments list follows nextPageToken up to --limit - --status now applies together with --video - reject, publish and reply preview by default; --execute applies - the preview resolves ids from the API (thread, comment, held and spam queues), then from the local log; unknown ids stop the command - each batch is logged before the API call; on failure the command stops and reports applied and unapplied ids - -o json adds deterministic signals (links, duplicates, author channel id, impersonation suspect) - comments list --unanswered --- src/ytstudio/commands/comments.py | 403 +++++++++++++++++++++++++----- src/ytstudio/comment_signals.py | 83 ++++++ tests/test_comment_signals.py | 83 ++++++ tests/test_comments.py | 311 +++++++++++++++++++++-- 4 files changed, 802 insertions(+), 78 deletions(-) create mode 100644 src/ytstudio/comment_signals.py create mode 100644 tests/test_comment_signals.py diff --git a/src/ytstudio/commands/comments.py b/src/ytstudio/commands/comments.py index 8db0d63..3538cd1 100644 --- a/src/ytstudio/commands/comments.py +++ b/src/ytstudio/commands/comments.py @@ -1,16 +1,25 @@ import json -from dataclasses import asdict, dataclass +from collections.abc import Iterator +from dataclasses import asdict, dataclass, field +from datetime import UTC, datetime from enum import StrEnum import typer +from google.auth.exceptions import RefreshError from googleapiclient.errors import HttpError +from ytstudio import comment_signals, config from ytstudio.api import api, handle_api_error from ytstudio.services import get_data_service from ytstudio.ui import console, create_table, time_ago, truncate app = typer.Typer(help="Comment commands") +# comments.setModerationStatus accepts up to 50 ids per call (50 quota units each call). +MODERATION_BATCH_SIZE = 50 +# commentThreads.list / comments.list with id= accept a comma-separated list; keep it bounded. +LOOKUP_BATCH_SIZE = 50 + class SortOrder(StrEnum): relevance = "relevance" @@ -35,14 +44,90 @@ class Comment: likes: int published_at: str video_id: str = "" + author_channel_id: str = "" + reply_count: int = 0 + has_link: bool = False + off_channel_link: bool = False + link_hosts: list[str] = field(default_factory=list) + duplicate_of: str | None = None + impersonation_suspect: bool = False + + +@dataclass +class Owner: + id: str + names: list[str] -def get_channel_id(service) -> str: - response = api(service.channels().list(part="id", mine=True)) +def get_owner(service) -> Owner: + response = api(service.channels().list(part="id,snippet", mine=True)) if not response.get("items"): console.print("[red]No channel found[/red]") raise typer.Exit(1) - return response["items"][0]["id"] + item = response["items"][0] + snippet = item.get("snippet", {}) + names = [n for n in (snippet.get("title"), snippet.get("customUrl")) if n] + return Owner(id=item["id"], names=names) + + +def _parse_comment(comment_id: str, snippet: dict, reply_count: int = 0) -> Comment: + return Comment( + id=comment_id, + author=snippet.get("authorDisplayName", ""), + # textOriginal is only guaranteed for some callers; textDisplay is the fallback. + text=snippet.get("textOriginal", snippet.get("textDisplay", "")), + likes=snippet.get("likeCount", 0), + published_at=snippet.get("publishedAt", ""), + video_id=snippet.get("videoId", ""), + author_channel_id=snippet.get("authorChannelId", {}).get("value", ""), + reply_count=reply_count, + ) + + +def _parse_thread(item: dict) -> Comment: + snippet = item["snippet"] + return _parse_comment( + item["id"], snippet["topLevelComment"]["snippet"], snippet.get("totalReplyCount", 0) + ) + + +def add_signals(comments: list[Comment], owner: Owner | None) -> None: + duplicates = comment_signals.duplicate_map(comments) + for c in comments: + c.link_hosts = comment_signals.link_hosts(c.text) + c.has_link = bool(c.link_hosts) + c.off_channel_link = any(not comment_signals.is_youtube_host(h) for h in c.link_hosts) + c.duplicate_of = duplicates.get(c.id) + if owner: + c.impersonation_suspect = comment_signals.impersonation_suspect( + c.author, c.author_channel_id, owner.id, owner.names + ) + + +def _iter_pages(request_fn, params: dict) -> Iterator[dict]: + """Yield items across all pages of a list call.""" + token = None + while True: + page_params = {**params, "pageToken": token} if token else params + response = api(request_fn(**page_params)) + yield from response.get("items", []) + token = response.get("nextPageToken") + if not token: + return + + +def _owner_replied(service, item: dict, owner_id: str) -> bool: + replies = item.get("replies", {}).get("comments", []) + if any(r["snippet"].get("authorChannelId", {}).get("value") == owner_id for r in replies): + return True + if item["snippet"].get("totalReplyCount", 0) <= len(replies): + return False + # The replies part holds only a few replies; page through the rest. + params = {"part": "snippet", "parentId": item["id"], "maxResults": 100} + for reply in _iter_pages(service.comments().list, params): + if reply["snippet"].get("authorChannelId", {}).get("value") == owner_id: + return True + return False def fetch_comments( @@ -51,43 +136,38 @@ def fetch_comments( limit: int = 100, order: SortOrder = SortOrder.relevance, moderation_status: ModerationStatus = ModerationStatus.published, + owner: Owner | None = None, + unanswered: bool = False, ) -> list[Comment]: - try: - # Build query parameters based on filters - params = { - "part": "snippet", - "maxResults": min(limit, 100), - "order": order.value, - } - - if video_id: - params["videoId"] = video_id - else: - channel_id = get_channel_id(data_service) - params["allThreadsRelatedToChannelId"] = channel_id - if moderation_status != ModerationStatus.published: - params["moderationStatus"] = moderation_status.to_api_value() + """List comment threads, following nextPageToken until `limit` comments are collected.""" + params = { + "part": "snippet,replies" if unanswered else "snippet", + "maxResults": 100 if unanswered else min(limit, 100), + "order": order.value, + } + if video_id: + params["videoId"] = video_id + else: + params["allThreadsRelatedToChannelId"] = (owner or get_owner(data_service)).id + if moderation_status != ModerationStatus.published: + params["moderationStatus"] = moderation_status.to_api_value() - response = api(data_service.commentThreads().list(**params)) + comments = [] + try: + for item in _iter_pages(data_service.commentThreads().list, params): + c = _parse_thread(item) + if unanswered and ( + c.author_channel_id == owner.id or _owner_replied(data_service, item, owner.id) + ): + continue + comments.append(c) + if len(comments) >= limit: + break except HttpError as e: handle_api_error(e) except Exception as e: console.print(f"[yellow]Could not fetch comments (may be disabled): {e}[/yellow]") raise typer.Exit(1) from None - - comments = [] - for item in response.get("items", []): - snippet = item["snippet"]["topLevelComment"]["snippet"] - comments.append( - Comment( - id=item["id"], - author=snippet["authorDisplayName"], - text=snippet["textOriginal"], - likes=snippet["likeCount"], - published_at=snippet["publishedAt"], - video_id=snippet.get("videoId", ""), - ) - ) return comments @@ -99,15 +179,23 @@ def list_comments( ), limit: int = typer.Option(20, "--limit", "-n", help="Number of comments"), sort: SortOrder = typer.Option(SortOrder.time, "--sort", "-s", help="Sort order"), + unanswered: bool = typer.Option( + False, "--unanswered", help="Only threads with no reply from the channel owner" + ), output: str = typer.Option("table", "--output", "-o", help="Output format: table, json"), ): """List comments across channel or for a specific video""" if sort == SortOrder.relevance and not video_id: console.print("[red]--sort relevance requires --video (YouTube API limitation)[/red]") raise typer.Exit(1) + if unanswered and status != ModerationStatus.published: + console.print("[red]--unanswered only applies to published comments[/red]") + raise typer.Exit(1) service = get_data_service() - comments = fetch_comments(service, video_id, limit, sort, status) + owner = get_owner(service) + comments = fetch_comments(service, video_id, limit, sort, status, owner, unanswered) + add_signals(comments, owner) if output == "json": print(json.dumps([asdict(c) for c in comments], indent=2)) @@ -115,6 +203,8 @@ def list_comments( status_label = {"published": "Published", "held": "Held for Review", "spam": "Likely Spam"} label = status_label.get(status.value, status.value) + if unanswered: + label = f"Unanswered {label}" scope = f"video {video_id}" if video_id else "channel" console.print(f"\n[bold]{label} Comments ({len(comments)})[/bold] — {scope}\n") @@ -137,43 +227,228 @@ def list_comments( console.print(table) -def _set_moderation_status(comment_ids: list[str], status: str, ban_author: bool = False) -> int: - service = get_data_service() - success = 0 - batch_size = 50 - for i in range(0, len(comment_ids), batch_size): - batch = comment_ids[i : i + batch_size] - try: +# --- moderation: preview, write-ahead log, batched apply --- + + +def _chunks(items: list, size: int) -> Iterator[list]: + for i in range(0, len(items), size): + yield items[i : i + size] + + +def _log_lookup(ids: set[str]) -> dict[str, Comment]: + """Latest logged copy of each id, so a rejected comment can still be previewed for undo.""" + found = {} + for r in config.read_moderation_log(): + if r.get("phase") == "intent" and r.get("id") in ids: + found[r["id"]] = Comment( + id=r["id"], + author=r.get("author", ""), + text=r.get("text", ""), + likes=0, + published_at=r.get("published_at", ""), + video_id=r.get("video_id", ""), + author_channel_id=r.get("author_channel_id", ""), + ) + return found + + +def resolve_comments(service, ids: list[str]) -> tuple[dict[str, Comment], set[str]]: + """Look up comment ids so the preview and the log show API truth, not caller input. + + Order: threads by id, comments by id (replies), the held and spam queues, then the + local moderation log. Returns (found, from_log) where from_log marks log-only hits. + """ + found: dict[str, Comment] = {} + + def missing() -> list[str]: + return [i for i in ids if i not in found] + + for chunk in _chunks(missing(), LOOKUP_BATCH_SIZE): + resp = api(service.commentThreads().list(part="snippet", id=",".join(chunk))) + for item in resp.get("items", []): + found[item["id"]] = _parse_thread(item) + + for chunk in _chunks(missing(), LOOKUP_BATCH_SIZE): + resp = api(service.comments().list(part="snippet", id=",".join(chunk))) + for item in resp.get("items", []): + found[item["id"]] = _parse_comment(item["id"], item["snippet"]) + + if missing(): + # Not documented whether id lookups return held comments; the queues do. + owner_id = get_owner(service).id + for status in (ModerationStatus.held, ModerationStatus.spam): params = { - "id": ",".join(batch), - "moderationStatus": status, + "part": "snippet", + "allThreadsRelatedToChannelId": owner_id, + "moderationStatus": status.to_api_value(), + "maxResults": 100, } - if ban_author and status == "rejected": - params["banAuthor"] = True - api(service.comments().setModerationStatus(**params)) - success += len(batch) - except HttpError as e: - handle_api_error(e) - return success + wanted = set(missing()) + for item in _iter_pages(service.commentThreads().list, params): + if item["id"] in wanted: + found[item["id"]] = _parse_thread(item) + wanted.discard(item["id"]) + if not wanted: + break + if not missing(): + break + + from_log = set() + if missing(): + logged = _log_lookup(set(missing())) + found.update(logged) + from_log = set(logged) + return found, from_log + + +def _flags(c: Comment, from_log: bool) -> str: + flags = [] + if c.off_channel_link: + flags.append("link:" + ",".join(c.link_hosts)) + elif c.has_link: + flags.append("link:youtube") + if c.duplicate_of: + flags.append(f"dup:{c.duplicate_of}") + if c.impersonation_suspect: + flags.append("impersonation?") + if from_log: + flags.append("from log") + return " ".join(flags) + + +def _print_preview(comments: list[Comment], from_log: set[str], action: str) -> None: + console.print(f"\n[bold]{action} {len(comments)} comment(s)[/bold]\n") + table = create_table() + table.add_column("ID", style="yellow") + table.add_column("Video", style="cyan") + table.add_column("Author") + table.add_column("Flags") + table.add_column("Comment") + for c in comments: + table.add_row( + c.id, c.video_id, c.author, _flags(c, c.id in from_log), truncate(c.text, 100) + ) + console.print(table) + + +def _now() -> str: + return datetime.now(UTC).isoformat(timespec="seconds") + + +def _api_error_text(error: Exception) -> str: + if isinstance(error, RefreshError): + return "session expired or revoked" + details = error.error_details[0] if getattr(error, "error_details", None) else {} + reason = details.get("reason") if isinstance(details, dict) else None + return f"HTTP {error.resp.status}" + (f" {reason}" if reason else "") + + +def _set_moderation_status( + service, comments: list[Comment], action: str, status: str, ban_author: bool +) -> tuple[list[str], list[str], str | None]: + """Apply in batches. Log each batch before its call; stop at the first failed batch. + + Returns (applied ids, unapplied ids, error text). + """ + applied: list[str] = [] + batches = list(_chunks(comments, MODERATION_BATCH_SIZE)) + for n, batch in enumerate(batches): + ids = [c.id for c in batch] + config.append_moderation_log( + [ + { + "ts": _now(), + "phase": "intent", + "action": action, + "ban": ban_author, + "id": c.id, + "author": c.author, + "author_channel_id": c.author_channel_id, + "video_id": c.video_id, + "published_at": c.published_at, + "text": c.text, + } + for c in batch + ] + ) + params = {"id": ",".join(ids), "moderationStatus": status} + if ban_author and status == "rejected": + params["banAuthor"] = True + try: + service.comments().setModerationStatus(**params).execute() + except (HttpError, RefreshError) as e: + err = _api_error_text(e) + config.append_moderation_log( + [ + {"ts": _now(), "phase": "failed", "action": action, "id": i, "error": err} + for i in ids + ] + ) + unapplied = [c.id for b in batches[n:] for c in b] + return applied, unapplied, err + config.append_moderation_log( + [{"ts": _now(), "phase": "applied", "action": action, "id": i} for i in ids] + ) + applied.extend(ids) + return applied, [], None + + +def _moderate(comment_ids: list[str], action: str, status: str, ban: bool, execute: bool) -> None: + ids = list(dict.fromkeys(comment_ids)) + service = get_data_service() + found, from_log = resolve_comments(service, ids) + comments = [found[i] for i in ids if i in found] + unresolved = [i for i in ids if i not in found] + add_signals(comments, None) + + label = f"{'Would ' if not execute else ''}{action}" + (" and ban the author of" if ban else "") + _print_preview(comments, from_log, label[0].upper() + label[1:]) + + if unresolved: + console.print( + f"\n[red]{len(unresolved)} id(s) not found by the API or in the moderation log. " + "Nothing was changed.[/red]\n" + " ".join(unresolved) + ) + raise typer.Exit(1) + + if not execute: + console.print( + f"\n[dim]Dry run. Run with --execute to apply " + f"({len(list(_chunks(comments, MODERATION_BATCH_SIZE)))} call(s), " + f"50 quota units each).[/dim]" + ) + return + + applied, unapplied, err = _set_moderation_status(service, comments, action, status, ban) + past = {"reject": "rejected", "publish": "published"}[action] + console.print(f"\n{len(applied)} comment(s) {past}") + if unapplied: + console.print( + f"[red]Stopped: {err}. {len(unapplied)} comment(s) not {past}:[/red]\n" + + " ".join(unapplied) + ) + console.print(f"[dim]Log: {config.moderation_log_path()}[/dim]") + if unapplied: + raise typer.Exit(1) @app.command() def publish( comment_ids: list[str] = typer.Argument(help="Comment IDs to publish"), + execute: bool = typer.Option(False, "--execute", help="Apply changes (default is dry-run)"), ): - """Publish held comments (approve for public display)""" - count = _set_moderation_status(comment_ids, "published") - console.print(f"{count} comment(s) published") + """Publish held comments (approve for public display). Dry-run by default.""" + _moderate(comment_ids, "publish", "published", ban=False, execute=execute) @app.command() def reject( comment_ids: list[str] = typer.Argument(help="Comment IDs to reject"), ban: bool = typer.Option(False, "--ban", help="Also ban the comment author"), + execute: bool = typer.Option(False, "--execute", help="Apply changes (default is dry-run)"), ): - """Reject comments (hide from public display)""" - count = _set_moderation_status(comment_ids, "rejected", ban_author=ban) - console.print(f"{count} comment(s) rejected") + """Reject comments (hide from public display). Dry-run by default.""" + _moderate(comment_ids, "reject", "rejected", ban=ban, execute=execute) @app.command() @@ -182,13 +457,25 @@ def reply( help="Top-level comment ID to reply to (from 'comments list')" ), text: str = typer.Option(..., "--text", "-t", help="Reply text"), + execute: bool = typer.Option(False, "--execute", help="Post the reply (default is dry-run)"), ): - """Reply to a top-level comment. + """Reply to a top-level comment. Dry-run by default. Replies are flat on YouTube: COMMENT_ID must be a top-level comment id (the id shown by 'comments list'), not the id of another reply. """ service = get_data_service() + if not execute: + resp = api(service.commentThreads().list(part="snippet", id=comment_id)) + items = resp.get("items", []) + if items: + parent = _parse_thread(items[0]) + console.print(f"\n[bold]Comment[/bold] {parent.id} by {parent.author}:\n{parent.text}") + else: + console.print(f"\n[yellow]Comment {comment_id} not found by id.[/yellow]") + console.print(f"\n[bold]Would reply:[/bold]\n{text}") + console.print("\n[dim]Dry run. Run with --execute to post (50 quota units).[/dim]") + return try: response = api( service.comments().insert( diff --git a/src/ytstudio/comment_signals.py b/src/ytstudio/comment_signals.py new file mode 100644 index 0000000..a3f4952 --- /dev/null +++ b/src/ytstudio/comment_signals.py @@ -0,0 +1,83 @@ +"""Deterministic triage signals for comments. No model; evidence for the agent and the human.""" + +import re +import unicodedata +from difflib import SequenceMatcher + +# Scheme, "www." or a bare host followed by a path ("t.me/x", "wa.me/123"). +_LINK = re.compile( + r"(?:https?://|www\.)([a-z0-9.-]+\.[a-z]{2,})|\b([a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-z]{2,})/", + re.IGNORECASE, +) +_YOUTUBE_HOSTS = ("youtube.com", "youtu.be") +_NON_WORD = re.compile(r"[\W_]+") + +# Shorter normalized texts ("nice video") repeat by chance, so they never count as duplicates. +DUPLICATE_MIN_LENGTH = 15 +IMPERSONATION_RATIO = 0.85 + + +def link_hosts(text: str) -> list[str]: + hosts = [] + for m in _LINK.finditer(text): + host = (m.group(1) or m.group(2)).lower().rstrip(".") + host = host.removeprefix("www.") + if host not in hosts: + hosts.append(host) + return hosts + + +def is_youtube_host(host: str) -> bool: + return any(host == h or host.endswith("." + h) for h in _YOUTUBE_HOSTS) + + +def normalize(text: str) -> str: + """Casefold and drop punctuation, emoji and spacing, so near-identical copies compare equal.""" + text = unicodedata.normalize("NFKC", text).casefold() + return _NON_WORD.sub(" ", text).strip() + + +def _name_key(name: str) -> str: + # authorDisplayName now carries the @handle; strip it so "@chan" matches "Chan". + return _NON_WORD.sub("", normalize(name.removeprefix("@"))) + + +def impersonation_suspect( + author: str, author_channel_id: str, owner_id: str, owner_names: list[str] +) -> bool: + """Display name close to the channel's title or handle, posted from another channel.""" + if not owner_id or not author_channel_id or author_channel_id == owner_id: + return False + key = _name_key(author) + if not key: + return False + for name in owner_names: + target = _name_key(name) + if target and SequenceMatcher(None, key, target).ratio() >= IMPERSONATION_RATIO: + return True + return False + + +def duplicate_map(comments: list) -> dict[str, str]: + """Map comment id -> id of the earliest copy of the same text. + + A copy counts when it is on another video or from the same author. Different + authors with the same text on one video are left alone. + """ + groups: dict[str, list] = {} + for c in comments: + key = normalize(c.text) + if len(key) >= DUPLICATE_MIN_LENGTH: + groups.setdefault(key, []).append(c) + + result = {} + for group in groups.values(): + if len(group) < 2: + continue + group.sort(key=lambda c: c.published_at) + first = group[0] + for c in group[1:]: + same_author = c.author_channel_id and c.author_channel_id == first.author_channel_id + if c.video_id != first.video_id or same_author: + result[c.id] = first.id + return result diff --git a/tests/test_comment_signals.py b/tests/test_comment_signals.py new file mode 100644 index 0000000..94fe1a3 --- /dev/null +++ b/tests/test_comment_signals.py @@ -0,0 +1,83 @@ +from ytstudio.commands.comments import Comment +from ytstudio.comment_signals import ( + duplicate_map, + impersonation_suspect, + is_youtube_host, + link_hosts, + normalize, +) + + +def _c(cid, text, video="v1", channel="UC_a", ts="2026-01-01T00:00:00Z"): + return Comment(cid, "x", text, 0, ts, video_id=video, author_channel_id=channel) + + +class TestLinks: + def test_hosts(self): + assert link_hosts("go to https://Scam.example.com/a and www.foo.io") == [ + "scam.example.com", + "foo.io", + ] + + def test_bare_host_with_path(self): + assert link_hosts("chat on wa.me/31612345678 or t.me/bob") == ["wa.me", "t.me"] + + def test_plain_text_has_no_links(self): + assert link_hosts("v2.0 is great, see file.py") == [] + + def test_youtube_hosts(self): + assert is_youtube_host("youtube.com") + assert is_youtube_host("m.youtube.com") + assert is_youtube_host("youtu.be") + assert not is_youtube_host("notyoutube.com") + + +class TestDuplicates: + def test_normalize_ignores_case_punctuation_and_spacing(self): + assert normalize("Free GIFT!!! Click now") == normalize("free gift click now") + + def test_same_text_across_videos(self): + dups = duplicate_map( + [ + _c("b", "free gift card click my profile", "v2", "UC_b", "2026-01-02T00:00:00Z"), + _c("a", "Free gift card, click my profile!", "v1", "UC_a"), + ] + ) + assert dups == {"b": "a"} + + def test_same_author_same_video(self): + dups = duplicate_map( + [_c("a", "subscribe to my channel please"), _c("b", "subscribe to my channel please")] + ) + assert dups == {"b": "a"} + + def test_different_authors_same_video_not_flagged(self): + dups = duplicate_map( + [ + _c("a", "this helped me a lot, thanks", channel="UC_a"), + _c("b", "this helped me a lot, thanks", channel="UC_b"), + ] + ) + assert dups == {} + + def test_short_text_not_flagged(self): + assert duplicate_map([_c("a", "nice video", "v1"), _c("b", "nice video", "v2")]) == {} + + +class TestImpersonation: + names = ("Test Channel", "@testchannel") + + def test_exact_copy_from_other_channel(self): + assert impersonation_suspect("Test Channel", "UC_fake", "UC_owner", self.names) + + def test_handle_form(self): + assert impersonation_suspect("@TestChannel", "UC_fake", "UC_owner", self.names) + + def test_near_miss(self): + assert impersonation_suspect("Test Channe1", "UC_fake", "UC_owner", self.names) + + def test_owner_is_never_suspect(self): + assert not impersonation_suspect("Test Channel", "UC_owner", "UC_owner", self.names) + + def test_unrelated_name(self): + assert not impersonation_suspect("@janedoe", "UC_fake", "UC_owner", self.names) diff --git a/tests/test_comments.py b/tests/test_comments.py index 0adb3e3..d8540c9 100644 --- a/tests/test_comments.py +++ b/tests/test_comments.py @@ -1,14 +1,72 @@ +import json from datetime import UTC, datetime, timedelta from unittest.mock import MagicMock +import pytest from googleapiclient.errors import HttpError from typer.testing import CliRunner +from tests.conftest import MOCK_CHANNEL, MOCK_COMMENT +from ytstudio import config from ytstudio.main import app from ytstudio.ui import time_ago runner = CliRunner() +OWNER_ID = MOCK_CHANNEL["id"] + + +def _thread(cid, text="hello there", author="Someone", channel="UC_x", video="vid1", **extra): + snippet = { + "authorDisplayName": author, + "authorChannelId": {"value": channel}, + "textOriginal": text, + "likeCount": 0, + "publishedAt": extra.pop("published_at", "2026-01-20T15:00:00Z"), + "videoId": video, + } + item = { + "id": cid, + "snippet": { + "topLevelComment": {"id": cid, "snippet": snippet}, + "totalReplyCount": extra.pop("total_replies", 0), + }, + } + if "replies" in extra: + item["replies"] = {"comments": extra.pop("replies")} + return item + + +def _reply(channel): + return {"snippet": {"authorChannelId": {"value": channel}}} + + +def _request(response): + req = MagicMock() + if isinstance(response, Exception): + req.execute.side_effect = response + else: + req.execute.return_value = response + return req + + +def _route(mock_method, fn): + """Answer each list(**kwargs) call with fn(kwargs).""" + mock_method.side_effect = lambda **kw: _request(fn(kw)) + + +def _http_error(status=500, reason="backendError"): + resp = MagicMock() + resp.status = status + body = json.dumps({"error": {"errors": [{"reason": reason}], "message": reason}}) + return HttpError(resp, body.encode()) + + +@pytest.fixture +def profile(temp_config): + config.save_credentials({"token": "x"}, name="default") + return temp_config + class TestTimeAgo: def test_formats_correctly(self): @@ -19,7 +77,7 @@ def test_formats_correctly(self): assert "5h ago" in time_ago(hours_ago) -class TestCommentsCommands: +class TestCommentsList: def test_list_channel_wide(self, mock_auth): result = runner.invoke(app, ["comments", "list"]) assert result.exit_code == 0 @@ -49,8 +107,167 @@ def test_list_json_output(self, mock_auth): assert '"id": "UgwComment123"' in result.stdout assert '"author": "Test User"' in result.stdout - def test_publish_comments(self, mock_auth): - result = runner.invoke(app, ["comments", "publish", "UgwComment123", "UgwComment456"]) + def test_status_applies_with_video_filter(self, mock_auth): + result = runner.invoke(app, ["comments", "list", "-v", "vid1", "--status", "held"]) + assert result.exit_code == 0 + kwargs = mock_auth.commentThreads.return_value.list.call_args.kwargs + assert kwargs["videoId"] == "vid1" + assert kwargs["moderationStatus"] == "heldForReview" + + def test_paginates_past_100(self, mock_auth): + pages = { + None: {"items": [_thread(f"a{i}") for i in range(100)], "nextPageToken": "p2"}, + "p2": {"items": [_thread(f"b{i}") for i in range(100)], "nextPageToken": "p3"}, + "p3": {"items": [_thread(f"c{i}") for i in range(100)]}, + } + method = mock_auth.commentThreads.return_value.list + _route(method, lambda kw: pages[kw.get("pageToken")]) + + result = runner.invoke(app, ["comments", "list", "-n", "150", "-o", "json"]) + + assert result.exit_code == 0 + assert len(json.loads(result.stdout)) == 150 + assert method.call_count == 2 # stops once the limit is reached + + def test_paginates_until_last_page(self, mock_auth): + pages = { + None: {"items": [_thread(f"a{i}") for i in range(100)], "nextPageToken": "p2"}, + "p2": {"items": [_thread(f"b{i}") for i in range(30)]}, + } + _route(mock_auth.commentThreads.return_value.list, lambda kw: pages[kw.get("pageToken")]) + result = runner.invoke(app, ["comments", "list", "-n", "500", "-o", "json"]) + assert len(json.loads(result.stdout)) == 130 + + def test_json_signals(self, mock_auth): + items = [ + _thread("s1", "Win a prize at https://scam.example.com/x now", channel="UC_a"), + _thread("s2", "WIN a prize at https://scam.example.com/x now!!", "B", "UC_b", "vid2"), + _thread("imp", "message me on telegram", "@TestChannel", "UC_fake"), + _thread("own", "pinned note", "@testchannel", OWNER_ID), + _thread("yt", "see https://youtu.be/abc", channel="UC_c"), + ] + items[1]["snippet"]["topLevelComment"]["snippet"]["publishedAt"] = "2026-01-21T00:00:00Z" + _route(mock_auth.commentThreads.return_value.list, lambda kw: {"items": items}) + + result = runner.invoke(app, ["comments", "list", "-o", "json"]) + + rows = {r["id"]: r for r in json.loads(result.stdout)} + assert rows["s1"]["has_link"] and rows["s1"]["off_channel_link"] + assert rows["s1"]["link_hosts"] == ["scam.example.com"] + assert rows["s1"]["duplicate_of"] is None + assert rows["s2"]["duplicate_of"] == "s1" + assert rows["s1"]["author_channel_id"] == "UC_a" + assert rows["imp"]["impersonation_suspect"] is True + assert rows["own"]["impersonation_suspect"] is False + assert rows["yt"]["has_link"] and not rows["yt"]["off_channel_link"] + + def test_comments_disabled(self, mock_auth): + mock_auth.commentThreads.return_value.list.return_value.execute.side_effect = Exception( + "Comments disabled" + ) + result = runner.invoke(app, ["comments", "list", "--video", "test_video_123"]) + assert result.exit_code == 1 + + +class TestUnanswered: + def test_filters_threads_the_owner_answered(self, mock_auth): + items = [ + _thread("open", "how do I do this?"), + _thread("answered", "q", total_replies=1, replies=[_reply(OWNER_ID)]), + _thread("others", "q", total_replies=1, replies=[_reply("UC_other")]), + _thread("mine", "my own comment", channel=OWNER_ID), + _thread("deep", "q", total_replies=7, replies=[_reply("UC_other")] * 5), + ] + _route(mock_auth.commentThreads.return_value.list, lambda kw: {"items": items}) + # Full reply list for "deep" holds the owner's reply beyond the inline five. + _route( + mock_auth.comments.return_value.list, + lambda kw: {"items": [_reply("UC_other"), _reply(OWNER_ID)]}, + ) + + result = runner.invoke(app, ["comments", "list", "--unanswered", "-o", "json"]) + + assert result.exit_code == 0 + assert [r["id"] for r in json.loads(result.stdout)] == ["open", "others"] + thread_kwargs = mock_auth.commentThreads.return_value.list.call_args.kwargs + assert thread_kwargs["part"] == "snippet,replies" + reply_kwargs = mock_auth.comments.return_value.list.call_args.kwargs + assert reply_kwargs["parentId"] == "deep" + + def test_requires_published(self, mock_auth): + result = runner.invoke(app, ["comments", "list", "--unanswered", "--status", "held"]) + assert result.exit_code == 1 + assert "published" in result.stdout + + +class TestModerationPreview: + def test_reject_is_dry_run_by_default(self, mock_auth, profile): + result = runner.invoke(app, ["comments", "reject", "UgwComment123"]) + assert result.exit_code == 0 + assert "Would reject 1 comment(s)" in result.stdout + assert "Test User" in result.stdout + assert "Great video" in result.stdout + assert "--execute" in result.stdout + mock_auth.comments.return_value.setModerationStatus.assert_not_called() + assert not config.moderation_log_path().exists() + + def test_publish_is_dry_run_by_default(self, mock_auth, profile): + result = runner.invoke(app, ["comments", "publish", "UgwComment123"]) + assert result.exit_code == 0 + assert "Would publish" in result.stdout + mock_auth.comments.return_value.setModerationStatus.assert_not_called() + + def test_ban_still_needs_execute(self, mock_auth, profile): + result = runner.invoke(app, ["comments", "reject", "UgwComment123", "--ban"]) + assert result.exit_code == 0 + assert "ban" in result.stdout + mock_auth.comments.return_value.setModerationStatus.assert_not_called() + + def test_unresolved_id_blocks_execute(self, mock_auth, profile): + _route(mock_auth.commentThreads.return_value.list, lambda kw: {"items": []}) + _route(mock_auth.comments.return_value.list, lambda kw: {"items": []}) + result = runner.invoke(app, ["comments", "reject", "ghost", "--execute"]) + assert result.exit_code == 1 + assert "ghost" in result.stdout + assert "Nothing was changed" in result.stdout + mock_auth.comments.return_value.setModerationStatus.assert_not_called() + + def test_resolves_from_held_queue(self, mock_auth, profile): + held = _thread("held1", "buy followers cheap", "Spammer") + + def threads(kw): + if kw.get("moderationStatus") == "heldForReview": + return {"items": [held]} + return {"items": []} + + _route(mock_auth.commentThreads.return_value.list, threads) + _route(mock_auth.comments.return_value.list, lambda kw: {"items": []}) + + result = runner.invoke(app, ["comments", "reject", "held1"]) + + assert result.exit_code == 0 + assert "Spammer" in result.stdout + assert "buy followers" in result.stdout + + def test_resolves_from_log_for_undo(self, mock_auth, profile): + config.append_moderation_log( + [{"phase": "intent", "id": "gone1", "author": "Was Rejected", "text": "oops"}] + ) + _route(mock_auth.commentThreads.return_value.list, lambda kw: {"items": []}) + _route(mock_auth.comments.return_value.list, lambda kw: {"items": []}) + + result = runner.invoke(app, ["comments", "publish", "gone1", "--execute"]) + + assert result.exit_code == 0 + assert "from log" in result.stdout + assert "1 comment(s) published" in result.stdout + + +class TestModerationExecute: + def test_publish(self, mock_auth, profile): + result = runner.invoke( + app, ["comments", "publish", "UgwComment123", "UgwComment456", "--execute"] + ) assert result.exit_code == 0 assert "2 comment(s) published" in result.stdout mock_auth.comments.return_value.setModerationStatus.assert_called_once_with( @@ -58,8 +275,8 @@ def test_publish_comments(self, mock_auth): moderationStatus="published", ) - def test_reject_comments_with_ban(self, mock_auth): - result = runner.invoke(app, ["comments", "reject", "UgwComment123", "--ban"]) + def test_reject_with_ban(self, mock_auth, profile): + result = runner.invoke(app, ["comments", "reject", "UgwComment123", "--ban", "--execute"]) assert result.exit_code == 0 assert "1 comment(s) rejected" in result.stdout mock_auth.comments.return_value.setModerationStatus.assert_called_once_with( @@ -68,34 +285,88 @@ def test_reject_comments_with_ban(self, mock_auth): banAuthor=True, ) - def test_list_comments_disabled(self, mock_auth): - mock_auth.commentThreads.return_value.list.return_value.execute.side_effect = Exception( - "Comments disabled" + def test_log_is_written_before_the_call(self, mock_auth, profile): + seen = [] + + def capture(**kwargs): + seen.extend(config.read_moderation_log()) + return _request({}) + + mock_auth.comments.return_value.setModerationStatus.side_effect = capture + result = runner.invoke(app, ["comments", "reject", "UgwComment123", "--execute"]) + + assert result.exit_code == 0 + assert len(seen) == 1 + entry = seen[0] + assert entry["phase"] == "intent" + assert entry["action"] == "reject" + assert entry["id"] == MOCK_COMMENT["id"] + assert entry["author"] == "Test User" + assert entry["text"] == "Great video! Love it!" + assert entry["video_id"] == "test_video_123" + assert entry["ts"] + phases = [r["phase"] for r in config.read_moderation_log()] + assert phases == ["intent", "applied"] + + def test_partial_failure_reports_applied_and_unapplied(self, mock_auth, profile): + ids = [f"c{i}" for i in range(120)] + _route( + mock_auth.commentThreads.return_value.list, + lambda kw: {"items": [_thread(i) for i in kw["id"].split(",")]}, ) - result = runner.invoke(app, ["comments", "list", "--video", "test_video_123"]) + calls = [] + + def set_status(**kwargs): + calls.append(kwargs["id"].split(",")) + return _request(_http_error() if len(calls) == 2 else {}) + + mock_auth.comments.return_value.setModerationStatus.side_effect = set_status + + result = runner.invoke(app, ["comments", "reject", *ids, "--execute"]) + assert result.exit_code == 1 + assert [len(c) for c in calls] == [50, 50] # third batch never sent + assert "50 comment(s) rejected" in result.stdout + assert "70 comment(s) not rejected" in result.stdout + assert "HTTP 500 backendError" in result.stdout + assert "c50" in result.stdout and "c119" in result.stdout + log = config.read_moderation_log() + assert sum(r["phase"] == "applied" for r in log) == 50 + assert sum(r["phase"] == "failed" for r in log) == 50 - def test_reply(self, mock_auth): + def test_duplicate_ids_sent_once(self, mock_auth, profile): + runner.invoke(app, ["comments", "publish", "UgwComment123", "UgwComment123", "--execute"]) + kwargs = mock_auth.comments.return_value.setModerationStatus.call_args.kwargs + assert kwargs["id"] == "UgwComment123" + + +class TestReply: + def test_dry_run_by_default(self, mock_auth): + result = runner.invoke(app, ["comments", "reply", "UgwComment123", "-t", "Thanks!"]) + assert result.exit_code == 0 + assert "Would reply" in result.stdout + assert "Great video" in result.stdout + mock_auth.comments.return_value.insert.assert_not_called() + + def test_execute(self, mock_auth): result = runner.invoke( - app, ["comments", "reply", "UgwComment123", "--text", "Thanks for watching!"] + app, + ["comments", "reply", "UgwComment123", "--text", "Thanks for watching!", "--execute"], ) assert result.exit_code == 0 assert "UgwReply789" in result.stdout - insert = mock_auth.comments.return_value.insert - body = insert.call_args.kwargs["body"] + body = mock_auth.comments.return_value.insert.call_args.kwargs["body"] assert body["snippet"]["parentId"] == "UgwComment123" assert body["snippet"]["textOriginal"] == "Thanks for watching!" - def test_reply_requires_text(self, mock_auth): + def test_requires_text(self, mock_auth): result = runner.invoke(app, ["comments", "reply", "UgwComment123"]) assert result.exit_code != 0 - def test_reply_invalid_parent(self, mock_auth): - resp = MagicMock() - resp.status = 400 - mock_auth.comments.return_value.insert.return_value.execute.side_effect = HttpError( - resp, b'{"error": {"message": "invalid"}}' + def test_invalid_parent(self, mock_auth): + mock_auth.comments.return_value.insert.return_value.execute.side_effect = _http_error(400) + result = runner.invoke( + app, ["comments", "reply", "not_a_top_level_id", "--text", "hi", "--execute"] ) - result = runner.invoke(app, ["comments", "reply", "not_a_top_level_id", "--text", "hi"]) assert result.exit_code == 1 assert "top-level comment id" in result.stdout From 60800f1d9035a24aae706a74bb7b0e23d73fac08 Mon Sep 17 00:00:00 2001 From: Jelmer de Wit <1598297+jdwit@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:34:33 +0100 Subject: [PATCH 3/6] docs: comment triage loop, policy file and moderation quota --- docs/api-quota.md | 11 +++ docs/comments.md | 107 +++++++++++++++++++----- docs/profiles.md | 21 ++++- skills/ytstudio/SKILL.md | 104 +++++++++++++++++++---- skills/ytstudio/references/reference.md | 79 ++++++++++++++++- 5 files changed, 278 insertions(+), 44 deletions(-) diff --git a/docs/api-quota.md b/docs/api-quota.md index b6b0de3..ed032ba 100644 --- a/docs/api-quota.md +++ b/docs/api-quota.md @@ -49,6 +49,17 @@ Captions are the other pricey read: `videos transcript` first lists the tracks Author metadata per video rather than pulling transcripts across a whole channel. +Comment moderation is the other cost to plan for. `comments.setModerationStatus` +costs 50 units per call, and `commentThreads.list` costs 1 unit per page of up to +100 comments. One call can change up to 50 comment ids, and `comments reject` and +`comments publish` send them in batches of 50. A run of 200 ids is 4 calls (200 +units). One call per id is 200 calls (10 000 units), which is the full daily +budget. Always pass all ids to one command. + +`comments list --unanswered` reads the `replies` part with the thread. That part +holds only a few replies, so a thread with more replies costs one more +`comments.list` call (1 unit per page) to check for a reply from the owner. + ## Increasing the quota In the Google Cloud Console, go to **IAM & Admin** :material-arrow-right: diff --git a/docs/comments.md b/docs/comments.md index c4444ca..02b87f6 100644 --- a/docs/comments.md +++ b/docs/comments.md @@ -11,49 +11,112 @@ downstream tooling. ytstudio comments list --video ytstudio comments list --video -o json | jq -# Held queue, ordered chronologically +# Held queue for one video, newest first ytstudio comments list --video --status held --sort time + +# Whole held queue of the channel +ytstudio comments list --status held -n 500 -o json ``` `--status` accepts `published`, `held`, or `spam` (mapped internally to -YouTube's `published`, `heldForReview`, and `likelySpam` values). `--sort` -accepts `time` or `relevance`; the YouTube API only honours `relevance` for -a single video, so `--sort relevance` requires `--video `. Omit -`--video` to list across the channel (time-sorted only). +YouTube's `published`, `heldForReview`, and `likelySpam` values). It works +with and without `--video`. `--sort` accepts `time` or `relevance`; the +YouTube API only honours `relevance` for a single video, so +`--sort relevance` requires `--video `. Omit `--video` to list across +the channel (time-sorted only). + +`--limit/-n` is the number of comments to return. The CLI reads as many +pages of 100 as it needs (1 quota unit per page). -## Approve held comments +### Unanswered comments ```bash -ytstudio comments publish [ ...] +ytstudio comments list --unanswered -n 50 -o json ``` -`publish` takes one or more comment IDs and transitions each to -`published`. +`--unanswered` returns only threads where the channel owner has not replied. +Threads that the owner started are left out. It works only with published +comments. + +### Signals in JSON output + +`-o json` adds fields that the CLI calculates without a model. They are +evidence for the reader, not a decision: -## Reject +| Field | Meaning | +|---|---| +| `author_channel_id` | Channel id of the author. Use it to find repeat authors. | +| `reply_count` | Number of replies in the thread. | +| `has_link` | The text contains a link (`https://`, `www.`, or `host/path` such as `t.me/x`). | +| `link_hosts` | The hosts of those links. | +| `off_channel_link` | At least one link goes to a host that is not YouTube. | +| `duplicate_of` | Id of an earlier comment with the same text (case, punctuation and spacing ignored) on another video or from the same author. Texts shorter than 15 characters are not compared. | +| `impersonation_suspect` | The display name is close to the channel title or handle, and the author is not the channel owner. | + +Duplicates are found only in the comments of one command run, so raise `-n` +to compare across more of the backlog. + +## Approve and reject ```bash -ytstudio comments reject [ ...] -ytstudio comments reject --ban # also ban the author +ytstudio comments publish [ ...] # preview +ytstudio comments publish [ ...] --execute # apply + +ytstudio comments reject [ ...] # preview +ytstudio comments reject [ ...] --execute # apply +ytstudio comments reject --ban --execute # also ban the author ``` -`reject` hides the comment from public view. Pass `--ban` to also ban the -author from the channel. +Both commands are **dry-run by default**. The preview shows the author, the +text, the video and the signals of each comment, and changes nothing. Add +`--execute` to apply. `--ban` also needs `--execute`. + +The preview reads the comments from the API, not from your input. It looks up +each id by thread id, then by comment id, then in the held and spam queues, +and last in the local moderation log. If an id is not found, the command lists +it, changes nothing and exits with code 1. + +### Moderation log + +`--execute` appends to `profiles//moderation-log.jsonl` **before** each +API call. Each line has the comment id, author, author channel id, text, video +id, a timestamp and the action. After the call the CLI appends an `applied` or +`failed` line for each id. + +This log is the only record of a rejected comment. The API cannot list +rejected comments, and a reject also hides all replies of the comment. To undo +a reject, run `comments publish ` with the ids from the log. The preview +then shows the text from the log. It is not documented if YouTube accepts a +publish on a rejected comment. + +### Batches and partial failure + +The CLI sends up to 50 ids per API call. If a call fails, the CLI stops, +prints the ids that were applied and the ids that were not, and exits with +code 1. Run the command again with the ids that were not applied. ## Reply ```bash -ytstudio comments reply --text "Thanks for watching!" +ytstudio comments reply --text "Thanks for watching!" # preview +ytstudio comments reply --text "Thanks for watching!" --execute # post ``` -`reply` posts a public reply to a comment and prints the new reply id. -Replies are flat on YouTube: `` must be a **top-level** comment -id (the `id` shown by `comments list`), not the id of another reply. Passing -a reply id (or an otherwise invalid id) returns a clear error. Like -`publish` and `reject`, `reply` executes immediately. +`reply` is dry-run by default: it shows the comment and the reply text. With +`--execute` it posts the reply and prints the new reply id. Replies are flat +on YouTube: `` must be a **top-level** comment id (the `id` shown +by `comments list`), not the id of another reply. Passing a reply id (or an +otherwise invalid id) returns a clear error. + +## Triage with an agent + +The agent does the judgement; the CLI supplies the context and a safe write +path. Store the channel's rules once with `ytstudio profile policy edit` (see +[Profiles](profiles.md#moderation-policy)). The loop and the label set are in +the bundled agent skill (`skills/ytstudio/SKILL.md`). !!! note "Quota" `comments.setModerationStatus` and `comments.insert` (reply) each cost - about 50 quota units per call. For larger moderation runs, see - [API quota](api-quota.md). + about 50 quota units per call. A preview costs about 1 unit per 50 ids. + For larger moderation runs, see [API quota](api-quota.md). diff --git a/docs/profiles.md b/docs/profiles.md index 8e983c9..68ad6ec 100644 --- a/docs/profiles.md +++ b/docs/profiles.md @@ -48,6 +48,23 @@ The file lives at `profiles//brand.md` and is written owner-only (`0600`), the same as credentials, because a brand voice can encode private channel strategy. +## Moderation policy + +Each profile can also carry a **moderation policy**: a markdown file that says +how an agent must triage comments on the channel. Write down what to reject, +what to leave held, what never to touch, and which topics always go to you. +The agent reads it before [comment triage](comments.md#triage-with-an-agent). + +```bash +ytstudio profile policy show # print the active profile's policy +ytstudio profile policy edit # create/open moderation.md in $EDITOR +ytstudio profile policy set --file policy.md # import a policy file +``` + +The commands work the same as the `brand` commands. The file lives at +`profiles//moderation.md` (`0600`). `moderation.md` controls what happens +to a comment; `brand.md` controls how a reply sounds. Keep them separate. + ## Storage ``` @@ -61,7 +78,9 @@ channel strategy. └── work/ ├── credentials.json ├── meta.json - └── brand.md # optional; per-channel brand voice (0600) + ├── brand.md # optional; per-channel brand voice (0600) + ├── moderation.md # optional; comment moderation policy (0600) + └── moderation-log.jsonl # written by comments reject/publish --execute (0600) ``` Profile directories are `0700`; credential files are `0600`. State writes go diff --git a/skills/ytstudio/SKILL.md b/skills/ytstudio/SKILL.md index 1a028b1..62c7d02 100644 --- a/skills/ytstudio/SKILL.md +++ b/skills/ytstudio/SKILL.md @@ -32,15 +32,17 @@ mistakes: also support `-o csv`. The auth/setup commands (`init`, `login`, `status`) have no JSON mode. 2. **Most mutations are dry-run by default.** Commands with `--execute` - (`videos update/search-replace/upload`, `livestreams schedule/update`, and - playlist writes) preview what they *would* do and change nothing until you + (`videos update/search-replace/upload`, `livestreams schedule/update`, + `comments publish/reject/reply`, and playlist writes) preview what they *would* do and change nothing until you re-run the exact command with `--execute`. Always preview first, show the user the preview when consequential, then re-run with `--execute`. -Some writes execute immediately because they have no `--execute`: comment -moderation/replies (`comments publish`, `comments reject`, `comments reply`) and -livestream transitions (`livestreams start`, `livestreams stop`). Treat these as -high-risk: confirm intent before running them. +Some writes execute immediately because they have no `--execute`: livestream +transitions (`livestreams start`, `livestreams stop`). Treat these as high-risk: +confirm intent before running them. + +`comments publish`, `comments reject` and `comments reply` were immediate up to +0.4.x. They now preview by default and need `--execute`. Treat write operations as costly and irreversible-ish: they consume API quota (see [Quota](#quota-awareness)) and act on a real, public channel. @@ -302,19 +304,86 @@ ytstudio comments list -o json # recent comments across t ytstudio comments list --status held -o json # the moderation queue ytstudio comments list --status spam -o json # likely spam comments ytstudio comments list --sort time -o json # channel-wide newest first +ytstudio comments list -v --status held -o json # held queue of one video ytstudio comments list -v --sort relevance -n 50 -o json -ytstudio comments publish [ ...] # approve held; executes immediately -ytstudio comments reject --ban # reject (+ optional ban); executes immediately -ytstudio comments reply -t "Thanks!" # executes immediately +ytstudio comments list --unanswered -n 50 -o json # no reply from the owner yet +ytstudio comments publish [ ...] # preview +ytstudio comments publish [ ...] --execute # approve held +ytstudio comments reject [ ...] --execute # reject +ytstudio comments reply -t "Thanks!" # preview +ytstudio comments reply -t "Thanks!" --execute # post ``` -`comments list` without `-v/--video` is channel-wide. Use `--status spam` for -spam review. Channel-wide listing supports `--sort time`; `--sort relevance` -requires `-v/--video` because of a YouTube API limitation. `publish`/`reject` -take one or more comment ids and execute immediately (no `--execute` dry-run). -`reply` also posts immediately. Confirm the exact comment ids/text first. -`--ban` on `reject` also bans the author - only use it when the user explicitly -asks to ban. +`comments list` without `-v/--video` is channel-wide. `--status` works with and +without `-v`. Channel-wide listing supports `--sort time`; `--sort relevance` +requires `-v/--video` because of a YouTube API limitation. `-n` follows pages, so +`-n 500` returns up to 500 comments. + +`-o json` adds signals for each comment: `author_channel_id`, `reply_count`, +`has_link`, `link_hosts`, `off_channel_link` (a link to a host that is not +YouTube), `duplicate_of` (id of an earlier copy of the same text on another video +or from the same author) and `impersonation_suspect` (name close to the channel +title or handle, from another channel). They are evidence, not decisions. + +`publish`/`reject` take one or more ids. The preview shows author, text, video +and signals from the API. An id that the CLI cannot find stops the command and +changes nothing. `--execute` writes each comment to +`profiles//moderation-log.jsonl` before the API call. If a batch fails, the +command prints the applied and unapplied ids and exits 1. `--ban` on `reject` +also bans the author. Never pass `--ban` unless the user explicitly asks to ban. + +#### Comment triage - policy-grounded, preview first + +You do the judgement. The CLI gives you the policy, the comments, the signals +and a safe write path. Run this loop: + +1. `ytstudio profile policy show` - the channel's moderation rules. If there is + no policy, tell the user and ask them to write one with + `ytstudio profile policy edit`. Do not moderate without it. +2. `ytstudio comments list --status held -n 500 -o json` (add `-v ` for one + video, or use `--status spam` for the likely-spam queue). +3. Label each comment against the policy with the labels below. +4. `ytstudio comments reject ` without `--execute`. **Show the preview to + the user**, grouped by label, with the reason for each comment. +5. After the user confirms, run the same command with `--execute`. Do the same + for `comments publish `. +6. Report what you left held and why: questions, leads, and anything you were + not sure about. + +| Label | Meaning | Default action | +|---|---|---| +| `junk` | link farms, fake giveaways, phishing, crypto/WhatsApp/Telegram bait | propose reject | +| `impersonation` | author name copies the channel, "message me on Telegram" | propose reject, flag to the user | +| `toxic` | harassment, slurs, threats | propose reject | +| `question` | a question to the creator | leave held, show to the user, candidate for a reply | +| `lead` | buying intent, price or availability questions, collaboration requests | leave held, show to the user, never act on it | +| `criticism` | negative but genuine | publish, never reject | +| `praise` / `neutral` | positive or plain | publish | + +Use `junk`, not `spam`: `--status spam` is YouTube's own classification; the +label is your judgement. If you cannot place a comment with confidence, leave it +held and put it in the "needs you" list. + +Hard rules: + +- Never ban. +- When in doubt, leave the comment held. +- Never reject genuine criticism or negative feedback. +- Never reject a comment only because it is negative about the channel. +- Every proposed reject must point to a line in the policy or a signal. + +**Pass all ids to one command.** `comments.setModerationStatus` costs 50 units +per call and the CLI sends 50 ids per call. A per-id loop costs 50 units per +comment and uses the full 10,000-unit daily budget after 200 comments. + +Undo: the API cannot list rejected comments. To restore one, read its id from +`moderation-log.jsonl` and run `comments publish ` (preview, then +`--execute`). It is not documented if YouTube accepts this; report the result. + +Reply triage is a separate pass on published comments: +`ytstudio comments list --unanswered -o json`. Draft replies with the brand +voice (`profile brand show`), preview each with `comments reply -t "..."`, +show the user, then post with `--execute`. ### livestreams - broadcast lifecycle @@ -360,7 +429,8 @@ resetting at midnight Pacific. Rough costs: | Read (list/show videos, comments, playlists; analytics) | ~1 unit | | Caption list (`videos captions`) | ~50 units | | Caption download (`videos transcript`) | ~200 units | -| Write (update video, moderate comment, playlist insert/reorder, schedule broadcast) | ~50 units | +| Write (update video, playlist insert/reorder, schedule broadcast, reply) | ~50 units | +| Comment moderation (`comments publish/reject`) | ~50 units per call of up to 50 ids | | Search (`playlists add --from-search`) | ~100 units/call | | Upload (`videos upload`) | ~1600 units | diff --git a/skills/ytstudio/references/reference.md b/skills/ytstudio/references/reference.md index 591ece1..739cafc 100644 --- a/skills/ytstudio/references/reference.md +++ b/skills/ytstudio/references/reference.md @@ -428,7 +428,7 @@ $ ytstudio comments [OPTIONS] COMMAND [ARGS]... * `list`: List comments across channel or for a... * `publish`: Publish held comments (approve for public... -* `reject`: Reject comments (hide from public display) +* `reject`: Reject comments (hide from public display). * `reply`: Reply to a top-level comment. ### `ytstudio comments list` @@ -447,12 +447,13 @@ $ ytstudio comments list [OPTIONS] * `--status `: Moderation status: published, held, spam [default: published] * `-n, --limit `: Number of comments [default: 20] * `-s, --sort `: Sort order [default: time] +* `--unanswered`: Only threads with no reply from the channel owner * `-o, --output `: Output format: table, json [default: table] * `--help`: Show this message and exit. ### `ytstudio comments publish` -Publish held comments (approve for public display) +Publish held comments (approve for public display). Dry-run by default. **Usage**: @@ -466,11 +467,12 @@ $ ytstudio comments publish [OPTIONS] {comment_ids}... **Options**: +* `--execute`: Apply changes (default is dry-run) * `--help`: Show this message and exit. ### `ytstudio comments reject` -Reject comments (hide from public display) +Reject comments (hide from public display). Dry-run by default. **Usage**: @@ -485,11 +487,12 @@ $ ytstudio comments reject [OPTIONS] {comment_ids}... **Options**: * `--ban`: Also ban the comment author +* `--execute`: Apply changes (default is dry-run) * `--help`: Show this message and exit. ### `ytstudio comments reply` -Reply to a top-level comment. +Reply to a top-level comment. Dry-run by default. Replies are flat on YouTube: COMMENT_ID must be a top-level comment id (the id shown by 'comments list'), not the id of another reply. @@ -507,6 +510,7 @@ $ ytstudio comments reply [OPTIONS] {comment_id} **Options**: * `-t, --text `: Reply text [required] +* `--execute`: Post the reply (default is dry-run) * `--help`: Show this message and exit. ## `ytstudio livestreams` @@ -904,6 +908,7 @@ $ ytstudio profile [OPTIONS] COMMAND [ARGS]... * `status`: Show authentication status for a profile * `remove`: Remove a profile and its stored credentials * `brand`: Manage per-channel brand voice (brand.md) +* `policy`: Manage per-channel moderation policy... ### `ytstudio profile add` @@ -1058,3 +1063,69 @@ $ ytstudio profile brand edit [OPTIONS] * `-p, --profile `: Profile (default: active) * `--help`: Show this message and exit. + +### `ytstudio profile policy` + +Manage per-channel moderation policy (moderation.md) + +**Usage**: + +```console +$ ytstudio profile policy [OPTIONS] COMMAND [ARGS]... +``` + +**Options**: + +* `--help`: Show this message and exit. + +**Commands**: + +* `show`: Print the moderation policy for a profile +* `set`: Set moderation policy non-interactively... +* `edit`: Open the moderation policy in $EDITOR + +#### `ytstudio profile policy show` + +Print the moderation policy for a profile + +**Usage**: + +```console +$ ytstudio profile policy show [OPTIONS] +``` + +**Options**: + +* `-p, --profile `: Profile (default: active) +* `--help`: Show this message and exit. + +#### `ytstudio profile policy set` + +Set moderation policy non-interactively from a file + +**Usage**: + +```console +$ ytstudio profile policy set [OPTIONS] +``` + +**Options**: + +* `-f, --file `: Path to a markdown file to import [required] +* `-p, --profile `: Profile (default: active) +* `--help`: Show this message and exit. + +#### `ytstudio profile policy edit` + +Open the moderation policy in $EDITOR + +**Usage**: + +```console +$ ytstudio profile policy edit [OPTIONS] +``` + +**Options**: + +* `-p, --profile `: Profile (default: active) +* `--help`: Show this message and exit. From 5529368a8efd39ed617c9d19369b6ed5e16fbe81 Mon Sep 17 00:00:00 2001 From: Jelmer de Wit <1598297+jdwit@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:11:50 +0100 Subject: [PATCH 4/6] docs: strict STE100 pass on triage docs and messages --- docs/api-quota.md | 4 +- docs/comments.md | 51 ++++++----- docs/profiles.md | 6 +- skills/ytstudio/SKILL.md | 113 ++++++++++++++---------- skills/ytstudio/references/reference.md | 10 +-- src/ytstudio/commands/comments.py | 20 +++-- src/ytstudio/commands/profile.py | 2 +- tests/test_comments.py | 4 +- 8 files changed, 119 insertions(+), 91 deletions(-) diff --git a/docs/api-quota.md b/docs/api-quota.md index ed032ba..77f8168 100644 --- a/docs/api-quota.md +++ b/docs/api-quota.md @@ -57,8 +57,8 @@ units). One call per id is 200 calls (10 000 units), which is the full daily budget. Always pass all ids to one command. `comments list --unanswered` reads the `replies` part with the thread. That part -holds only a few replies, so a thread with more replies costs one more -`comments.list` call (1 unit per page) to check for a reply from the owner. +holds only a few replies. For a thread with more replies, the CLI makes one +more `comments.list` call (1 unit per page) to check for a reply from the owner. ## Increasing the quota diff --git a/docs/comments.md b/docs/comments.md index 02b87f6..d5530ad 100644 --- a/docs/comments.md +++ b/docs/comments.md @@ -20,8 +20,8 @@ ytstudio comments list --status held -n 500 -o json `--status` accepts `published`, `held`, or `spam` (mapped internally to YouTube's `published`, `heldForReview`, and `likelySpam` values). It works -with and without `--video`. `--sort` accepts `time` or `relevance`; the -YouTube API only honours `relevance` for a single video, so +with and without `--video`. `--sort` accepts `time` or `relevance`. The +YouTube API honours `relevance` only for a single video, so `--sort relevance` requires `--video `. Omit `--video` to list across the channel (time-sorted only). @@ -34,8 +34,8 @@ pages of 100 as it needs (1 quota unit per page). ytstudio comments list --unanswered -n 50 -o json ``` -`--unanswered` returns only threads where the channel owner has not replied. -Threads that the owner started are left out. It works only with published +`--unanswered` returns only threads that have no reply from the channel +owner. It skips threads that the owner started. It works only with published comments. ### Signals in JSON output @@ -50,11 +50,11 @@ evidence for the reader, not a decision: | `has_link` | The text contains a link (`https://`, `www.`, or `host/path` such as `t.me/x`). | | `link_hosts` | The hosts of those links. | | `off_channel_link` | At least one link goes to a host that is not YouTube. | -| `duplicate_of` | Id of an earlier comment with the same text (case, punctuation and spacing ignored) on another video or from the same author. Texts shorter than 15 characters are not compared. | +| `duplicate_of` | Id of an earlier comment with the same text on another video or from the same author. The CLI ignores case, punctuation and spacing. It does not compare texts shorter than 15 characters. | | `impersonation_suspect` | The display name is close to the channel title or handle, and the author is not the channel owner. | -Duplicates are found only in the comments of one command run, so raise `-n` -to compare across more of the backlog. +The CLI looks for duplicates only in the comments of one command run. Raise +`-n` to compare more of the backlog. ## Approve and reject @@ -67,14 +67,20 @@ ytstudio comments reject [ ...] --execute # apply ytstudio comments reject --ban --execute # also ban the author ``` -Both commands are **dry-run by default**. The preview shows the author, the -text, the video and the signals of each comment, and changes nothing. Add +Both commands do a **dry run by default**. The preview shows the author, the +text, the video and the signals of each comment. It changes nothing. Add `--execute` to apply. `--ban` also needs `--execute`. -The preview reads the comments from the API, not from your input. It looks up -each id by thread id, then by comment id, then in the held and spam queues, -and last in the local moderation log. If an id is not found, the command lists -it, changes nothing and exits with code 1. +The preview reads the comments from the API, not from your input. It searches +for each id in this order: + +1. By thread id. +2. By comment id. +3. In the held and spam queues. +4. In the local moderation log. + +If the CLI cannot find an id, the command lists it, changes nothing and exits +with code 1. ### Moderation log @@ -86,14 +92,15 @@ id, a timestamp and the action. After the call the CLI appends an `applied` or This log is the only record of a rejected comment. The API cannot list rejected comments, and a reject also hides all replies of the comment. To undo a reject, run `comments publish ` with the ids from the log. The preview -then shows the text from the log. It is not documented if YouTube accepts a -publish on a rejected comment. +then shows the text from the log. The YouTube documentation does not say if +YouTube accepts a publish on a rejected comment. ### Batches and partial failure -The CLI sends up to 50 ids per API call. If a call fails, the CLI stops, -prints the ids that were applied and the ids that were not, and exits with -code 1. Run the command again with the ids that were not applied. +The CLI sends up to 50 ids per API call. If a call fails, the CLI stops. It +prints the ids that it applied and the ids that it did not apply. Then it +exits with code 1. Run the command again with the ids that the CLI did not +apply. ## Reply @@ -102,16 +109,16 @@ ytstudio comments reply --text "Thanks for watching!" # ytstudio comments reply --text "Thanks for watching!" --execute # post ``` -`reply` is dry-run by default: it shows the comment and the reply text. With -`--execute` it posts the reply and prints the new reply id. Replies are flat +`reply` does a dry run by default. The preview shows the comment and the +reply text. With `--execute`, it posts the reply and prints the new reply id. Replies are flat on YouTube: `` must be a **top-level** comment id (the `id` shown by `comments list`), not the id of another reply. Passing a reply id (or an otherwise invalid id) returns a clear error. ## Triage with an agent -The agent does the judgement; the CLI supplies the context and a safe write -path. Store the channel's rules once with `ytstudio profile policy edit` (see +The agent makes the decisions. The CLI supplies the context, a preview and a +log for each write. Store the channel's rules once with `ytstudio profile policy edit` (see [Profiles](profiles.md#moderation-policy)). The loop and the label set are in the bundled agent skill (`skills/ytstudio/SKILL.md`). diff --git a/docs/profiles.md b/docs/profiles.md index 68ad6ec..4aab2a3 100644 --- a/docs/profiles.md +++ b/docs/profiles.md @@ -63,7 +63,7 @@ ytstudio profile policy set --file policy.md # import a policy file The commands work the same as the `brand` commands. The file lives at `profiles//moderation.md` (`0600`). `moderation.md` controls what happens -to a comment; `brand.md` controls how a reply sounds. Keep them separate. +to a comment. `brand.md` controls how a reply sounds. Keep them separate. ## Storage @@ -78,8 +78,8 @@ to a comment; `brand.md` controls how a reply sounds. Keep them separate. └── work/ ├── credentials.json ├── meta.json - ├── brand.md # optional; per-channel brand voice (0600) - ├── moderation.md # optional; comment moderation policy (0600) + ├── brand.md # optional, per-channel brand voice (0600) + ├── moderation.md # optional, comment moderation policy (0600) └── moderation-log.jsonl # written by comments reject/publish --execute (0600) ``` diff --git a/skills/ytstudio/SKILL.md b/skills/ytstudio/SKILL.md index 62c7d02..d18ab7b 100644 --- a/skills/ytstudio/SKILL.md +++ b/skills/ytstudio/SKILL.md @@ -33,16 +33,17 @@ mistakes: have no JSON mode. 2. **Most mutations are dry-run by default.** Commands with `--execute` (`videos update/search-replace/upload`, `livestreams schedule/update`, - `comments publish/reject/reply`, and playlist writes) preview what they *would* do and change nothing until you - re-run the exact command with `--execute`. Always preview first, show the + `comments publish/reject/reply`, and playlist writes) preview what they + *would* do. They change nothing until you re-run the exact command with + `--execute`. Always preview first, show the user the preview when consequential, then re-run with `--execute`. -Some writes execute immediately because they have no `--execute`: livestream -transitions (`livestreams start`, `livestreams stop`). Treat these as high-risk: -confirm intent before running them. +Livestream transitions (`livestreams start`, `livestreams stop`) have no +`--execute`, so they execute immediately. Treat them as high-risk. Confirm the +intent of the user before you run them. -`comments publish`, `comments reject` and `comments reply` were immediate up to -0.4.x. They now preview by default and need `--execute`. +Up to 0.4.x, `comments publish`, `comments reject` and `comments reply` +executed immediately. Now they show a preview by default and need `--execute`. Treat write operations as costly and irreversible-ish: they consume API quota (see [Quota](#quota-awareness)) and act on a real, public channel. @@ -315,54 +316,63 @@ ytstudio comments reply -t "Thanks!" --execute # post ``` `comments list` without `-v/--video` is channel-wide. `--status` works with and -without `-v`. Channel-wide listing supports `--sort time`; `--sort relevance` +without `-v`. Channel-wide listing supports `--sort time`. `--sort relevance` requires `-v/--video` because of a YouTube API limitation. `-n` follows pages, so `-n 500` returns up to 500 comments. -`-o json` adds signals for each comment: `author_channel_id`, `reply_count`, -`has_link`, `link_hosts`, `off_channel_link` (a link to a host that is not -YouTube), `duplicate_of` (id of an earlier copy of the same text on another video -or from the same author) and `impersonation_suspect` (name close to the channel -title or handle, from another channel). They are evidence, not decisions. - -`publish`/`reject` take one or more ids. The preview shows author, text, video -and signals from the API. An id that the CLI cannot find stops the command and -changes nothing. `--execute` writes each comment to +`-o json` adds these signals for each comment. They are evidence, not decisions. + +- `author_channel_id` +- `reply_count` +- `has_link` +- `link_hosts` +- `off_channel_link`: a link to a host that is not YouTube. +- `duplicate_of`: the id of an earlier copy of the same text, on another video + or from the same author. +- `impersonation_suspect`: the name is close to the channel title or handle, + and the comment comes from another channel. + +`publish`/`reject` take one or more ids. The preview shows the author, text, +video and signals from the API. If the CLI cannot find an id, the command stops +and changes nothing. `--execute` writes each comment to `profiles//moderation-log.jsonl` before the API call. If a batch fails, the -command prints the applied and unapplied ids and exits 1. `--ban` on `reject` -also bans the author. Never pass `--ban` unless the user explicitly asks to ban. +command prints the applied ids and the unapplied ids. Then it exits with code 1. +`--ban` on `reject` also bans the author. Never pass `--ban` unless the user +explicitly asks to ban. #### Comment triage - policy-grounded, preview first -You do the judgement. The CLI gives you the policy, the comments, the signals -and a safe write path. Run this loop: - -1. `ytstudio profile policy show` - the channel's moderation rules. If there is - no policy, tell the user and ask them to write one with - `ytstudio profile policy edit`. Do not moderate without it. -2. `ytstudio comments list --status held -n 500 -o json` (add `-v ` for one - video, or use `--status spam` for the likely-spam queue). -3. Label each comment against the policy with the labels below. -4. `ytstudio comments reject ` without `--execute`. **Show the preview to - the user**, grouped by label, with the reason for each comment. -5. After the user confirms, run the same command with `--execute`. Do the same - for `comments publish `. -6. Report what you left held and why: questions, leads, and anything you were - not sure about. +You make the decisions. The CLI gives you the policy, the comments, the +signals, and a preview and a log for each write. Do these steps: + +1. Run `ytstudio profile policy show` to get the moderation rules of the + channel. If there is no policy, tell the user. Ask the user to write one + with `ytstudio profile policy edit`. Do not moderate without a policy. +2. Run `ytstudio comments list --status held -n 500 -o json`. For one video, + add `-v `. For the likely-spam queue, use `--status spam`. +3. Give each comment one label from the table below. Use the policy to select + the label. +4. Run `ytstudio comments reject ` without `--execute`. **Show the preview + to the user.** Group the comments by label and give the reason for each + comment. +5. After the user confirms, run the same command with `--execute`. Use the same + steps for `comments publish `. +6. Tell the user which comments you left held, and why. Include questions, + leads, and all comments that you were not sure about. | Label | Meaning | Default action | |---|---|---| | `junk` | link farms, fake giveaways, phishing, crypto/WhatsApp/Telegram bait | propose reject | -| `impersonation` | author name copies the channel, "message me on Telegram" | propose reject, flag to the user | +| `impersonation` | author name copies the channel, "message me on Telegram" | propose reject, tell the user | | `toxic` | harassment, slurs, threats | propose reject | | `question` | a question to the creator | leave held, show to the user, candidate for a reply | | `lead` | buying intent, price or availability questions, collaboration requests | leave held, show to the user, never act on it | | `criticism` | negative but genuine | publish, never reject | | `praise` / `neutral` | positive or plain | publish | -Use `junk`, not `spam`: `--status spam` is YouTube's own classification; the -label is your judgement. If you cannot place a comment with confidence, leave it -held and put it in the "needs you" list. +Use the label `junk`, not `spam`. `--status spam` is the classification of +YouTube. The label is your decision. If you are not sure about the label of a +comment, leave the comment held. Put it in the "needs you" list. Hard rules: @@ -370,20 +380,29 @@ Hard rules: - When in doubt, leave the comment held. - Never reject genuine criticism or negative feedback. - Never reject a comment only because it is negative about the channel. -- Every proposed reject must point to a line in the policy or a signal. +- For each reject that you propose, give the line in the policy or the signal + that is the reason. **Pass all ids to one command.** `comments.setModerationStatus` costs 50 units -per call and the CLI sends 50 ids per call. A per-id loop costs 50 units per -comment and uses the full 10,000-unit daily budget after 200 comments. +per call. The CLI sends 50 ids per call. A loop with one command per id costs +50 units per comment. After 200 comments, that loop uses the full 10,000-unit +daily budget. + +Undo: the API cannot list rejected comments. To restore a rejected comment: -Undo: the API cannot list rejected comments. To restore one, read its id from -`moderation-log.jsonl` and run `comments publish ` (preview, then -`--execute`). It is not documented if YouTube accepts this; report the result. +1. Read its id from `moderation-log.jsonl`. +2. Run `comments publish ` (preview, then `--execute`). + +The YouTube documentation does not say if YouTube accepts this. Report the +result to the user. Reply triage is a separate pass on published comments: -`ytstudio comments list --unanswered -o json`. Draft replies with the brand -voice (`profile brand show`), preview each with `comments reply -t "..."`, -show the user, then post with `--execute`. + +1. Run `ytstudio comments list --unanswered -o json`. +2. Write draft replies in the brand voice (`profile brand show`). +3. Preview each reply with `comments reply -t "..."`. +4. Show the previews to the user. +5. Post each reply with `--execute`. ### livestreams - broadcast lifecycle diff --git a/skills/ytstudio/references/reference.md b/skills/ytstudio/references/reference.md index 739cafc..fe80f67 100644 --- a/skills/ytstudio/references/reference.md +++ b/skills/ytstudio/references/reference.md @@ -428,7 +428,7 @@ $ ytstudio comments [OPTIONS] COMMAND [ARGS]... * `list`: List comments across channel or for a... * `publish`: Publish held comments (approve for public... -* `reject`: Reject comments (hide from public display). +* `reject`: Reject comments (hide from public view). * `reply`: Reply to a top-level comment. ### `ytstudio comments list` @@ -447,13 +447,13 @@ $ ytstudio comments list [OPTIONS] * `--status `: Moderation status: published, held, spam [default: published] * `-n, --limit `: Number of comments [default: 20] * `-s, --sort `: Sort order [default: time] -* `--unanswered`: Only threads with no reply from the channel owner +* `--unanswered`: Show only threads that have no reply from the channel owner * `-o, --output `: Output format: table, json [default: table] * `--help`: Show this message and exit. ### `ytstudio comments publish` -Publish held comments (approve for public display). Dry-run by default. +Publish held comments (approve for public view). The default is a dry run. **Usage**: @@ -472,7 +472,7 @@ $ ytstudio comments publish [OPTIONS] {comment_ids}... ### `ytstudio comments reject` -Reject comments (hide from public display). Dry-run by default. +Reject comments (hide from public view). The default is a dry run. **Usage**: @@ -492,7 +492,7 @@ $ ytstudio comments reject [OPTIONS] {comment_ids}... ### `ytstudio comments reply` -Reply to a top-level comment. Dry-run by default. +Reply to a top-level comment. The default is a dry run. Replies are flat on YouTube: COMMENT_ID must be a top-level comment id (the id shown by 'comments list'), not the id of another reply. diff --git a/src/ytstudio/commands/comments.py b/src/ytstudio/commands/comments.py index 3538cd1..ccc8e98 100644 --- a/src/ytstudio/commands/comments.py +++ b/src/ytstudio/commands/comments.py @@ -180,7 +180,7 @@ def list_comments( limit: int = typer.Option(20, "--limit", "-n", help="Number of comments"), sort: SortOrder = typer.Option(SortOrder.time, "--sort", "-s", help="Sort order"), unanswered: bool = typer.Option( - False, "--unanswered", help="Only threads with no reply from the channel owner" + False, "--unanswered", help="Show only threads that have no reply from the channel owner" ), output: str = typer.Option("table", "--output", "-o", help="Output format: table, json"), ): @@ -189,7 +189,7 @@ def list_comments( console.print("[red]--sort relevance requires --video (YouTube API limitation)[/red]") raise typer.Exit(1) if unanswered and status != ModerationStatus.published: - console.print("[red]--unanswered only applies to published comments[/red]") + console.print("[red]--unanswered works only with published comments[/red]") raise typer.Exit(1) service = get_data_service() @@ -406,8 +406,8 @@ def _moderate(comment_ids: list[str], action: str, status: str, ban: bool, execu if unresolved: console.print( - f"\n[red]{len(unresolved)} id(s) not found by the API or in the moderation log. " - "Nothing was changed.[/red]\n" + " ".join(unresolved) + f"\n[red]The CLI did not find {len(unresolved)} id(s) in the API or in the " + "moderation log. The CLI changed nothing.[/red]\n" + " ".join(unresolved) ) raise typer.Exit(1) @@ -424,7 +424,7 @@ def _moderate(comment_ids: list[str], action: str, status: str, ban: bool, execu console.print(f"\n{len(applied)} comment(s) {past}") if unapplied: console.print( - f"[red]Stopped: {err}. {len(unapplied)} comment(s) not {past}:[/red]\n" + f"[red]Stopped: {err}. {len(unapplied)} comment(s) are not {past}:[/red]\n" + " ".join(unapplied) ) console.print(f"[dim]Log: {config.moderation_log_path()}[/dim]") @@ -437,7 +437,7 @@ def publish( comment_ids: list[str] = typer.Argument(help="Comment IDs to publish"), execute: bool = typer.Option(False, "--execute", help="Apply changes (default is dry-run)"), ): - """Publish held comments (approve for public display). Dry-run by default.""" + """Publish held comments (approve for public view). The default is a dry run.""" _moderate(comment_ids, "publish", "published", ban=False, execute=execute) @@ -447,7 +447,7 @@ def reject( ban: bool = typer.Option(False, "--ban", help="Also ban the comment author"), execute: bool = typer.Option(False, "--execute", help="Apply changes (default is dry-run)"), ): - """Reject comments (hide from public display). Dry-run by default.""" + """Reject comments (hide from public view). The default is a dry run.""" _moderate(comment_ids, "reject", "rejected", ban=ban, execute=execute) @@ -459,7 +459,7 @@ def reply( text: str = typer.Option(..., "--text", "-t", help="Reply text"), execute: bool = typer.Option(False, "--execute", help="Post the reply (default is dry-run)"), ): - """Reply to a top-level comment. Dry-run by default. + """Reply to a top-level comment. The default is a dry run. Replies are flat on YouTube: COMMENT_ID must be a top-level comment id (the id shown by 'comments list'), not the id of another reply. @@ -472,7 +472,9 @@ def reply( parent = _parse_thread(items[0]) console.print(f"\n[bold]Comment[/bold] {parent.id} by {parent.author}:\n{parent.text}") else: - console.print(f"\n[yellow]Comment {comment_id} not found by id.[/yellow]") + console.print( + f"\n[yellow]The API did not return comment {comment_id} for this id.[/yellow]" + ) console.print(f"\n[bold]Would reply:[/bold]\n{text}") console.print("\n[dim]Dry run. Run with --execute to post (50 quota units).[/dim]") return diff --git a/src/ytstudio/commands/profile.py b/src/ytstudio/commands/profile.py index fe98c8e..558b03a 100644 --- a/src/ytstudio/commands/profile.py +++ b/src/ytstudio/commands/profile.py @@ -121,7 +121,7 @@ def remove( _POLICY_TEMPLATE = """# Moderation policy + The agent reads this file verbatim into its context. Delete these hints. --> ## Reject diff --git a/tests/test_comments.py b/tests/test_comments.py index d8540c9..a1745d2 100644 --- a/tests/test_comments.py +++ b/tests/test_comments.py @@ -229,7 +229,7 @@ def test_unresolved_id_blocks_execute(self, mock_auth, profile): result = runner.invoke(app, ["comments", "reject", "ghost", "--execute"]) assert result.exit_code == 1 assert "ghost" in result.stdout - assert "Nothing was changed" in result.stdout + assert "changed nothing" in result.stdout mock_auth.comments.return_value.setModerationStatus.assert_not_called() def test_resolves_from_held_queue(self, mock_auth, profile): @@ -327,7 +327,7 @@ def set_status(**kwargs): assert result.exit_code == 1 assert [len(c) for c in calls] == [50, 50] # third batch never sent assert "50 comment(s) rejected" in result.stdout - assert "70 comment(s) not rejected" in result.stdout + assert "70 comment(s) are not rejected" in result.stdout assert "HTTP 500 backendError" in result.stdout assert "c50" in result.stdout and "c119" in result.stdout log = config.read_moderation_log() From eff728def37e807a39df565c12ace399225f5259 Mon Sep 17 00:00:00 2001 From: Jelmer de Wit <1598297+jdwit@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:17:47 +0100 Subject: [PATCH 5/6] fix: review findings on comment moderation - catch network, timeout and httplib2 errors in the batch loop - report 5xx and network failures as status unknown, not as unapplied - duplicate_of points to the earliest qualifying earlier copy - preview passes the owner, so impersonation_suspect shows - rename off_channel_link to off_youtube_link - request textFormat=plainText on lookups and lists - write the moderation log through os.fdopen - docs: fallback cost, three result groups --- docs/comments.md | 22 +++++-- skills/ytstudio/SKILL.md | 6 +- src/ytstudio/commands/comments.py | 102 ++++++++++++++++++++---------- src/ytstudio/comment_signals.py | 21 +++--- src/ytstudio/config.py | 14 ++-- 5 files changed, 105 insertions(+), 60 deletions(-) diff --git a/docs/comments.md b/docs/comments.md index d5530ad..a9019b8 100644 --- a/docs/comments.md +++ b/docs/comments.md @@ -21,7 +21,7 @@ ytstudio comments list --status held -n 500 -o json `--status` accepts `published`, `held`, or `spam` (mapped internally to YouTube's `published`, `heldForReview`, and `likelySpam` values). It works with and without `--video`. `--sort` accepts `time` or `relevance`. The -YouTube API honours `relevance` only for a single video, so +YouTube API uses `relevance` only for a single video, so `--sort relevance` requires `--video `. Omit `--video` to list across the channel (time-sorted only). @@ -49,7 +49,7 @@ evidence for the reader, not a decision: | `reply_count` | Number of replies in the thread. | | `has_link` | The text contains a link (`https://`, `www.`, or `host/path` such as `t.me/x`). | | `link_hosts` | The hosts of those links. | -| `off_channel_link` | At least one link goes to a host that is not YouTube. | +| `off_youtube_link` | At least one link goes to a host that is not YouTube. | | `duplicate_of` | Id of an earlier comment with the same text on another video or from the same author. The CLI ignores case, punctuation and spacing. It does not compare texts shorter than 15 characters. | | `impersonation_suspect` | The display name is close to the channel title or handle, and the author is not the channel owner. | @@ -97,10 +97,17 @@ YouTube accepts a publish on a rejected comment. ### Batches and partial failure -The CLI sends up to 50 ids per API call. If a call fails, the CLI stops. It -prints the ids that it applied and the ids that it did not apply. Then it -exits with code 1. Run the command again with the ids that the CLI did not -apply. +The CLI sends up to 50 ids per API call. If a call fails, the CLI stops and +exits with code 1. It prints the ids in three groups: + +- Applied: the API accepted the call. +- Status unknown: the call failed with a 5xx error, a timeout or a network + error. The change can be applied or not. Check these comments in YouTube + Studio before you run the command again. +- Not applied: the CLI did not send these ids, or the API refused the call + with a 4xx error. Run the command again with these ids. + +The log marks each id as `applied`, `unknown` or `failed`. ## Reply @@ -126,4 +133,7 @@ the bundled agent skill (`skills/ytstudio/SKILL.md`). `comments.setModerationStatus` and `comments.insert` (reply) each cost about 50 quota units per call. A preview costs about 1 unit per 50 ids. + If an id lookup does not find a comment, the preview also reads the + held and spam queues. That fallback costs 1 unit per page of 100 + comments. For larger moderation runs, see [API quota](api-quota.md). diff --git a/skills/ytstudio/SKILL.md b/skills/ytstudio/SKILL.md index d18ab7b..562b54a 100644 --- a/skills/ytstudio/SKILL.md +++ b/skills/ytstudio/SKILL.md @@ -326,7 +326,7 @@ requires `-v/--video` because of a YouTube API limitation. `-n` follows pages, s - `reply_count` - `has_link` - `link_hosts` -- `off_channel_link`: a link to a host that is not YouTube. +- `off_youtube_link`: a link to a host that is not YouTube. - `duplicate_of`: the id of an earlier copy of the same text, on another video or from the same author. - `impersonation_suspect`: the name is close to the channel title or handle, @@ -336,7 +336,9 @@ requires `-v/--video` because of a YouTube API limitation. `-n` follows pages, s video and signals from the API. If the CLI cannot find an id, the command stops and changes nothing. `--execute` writes each comment to `profiles//moderation-log.jsonl` before the API call. If a batch fails, the -command prints the applied ids and the unapplied ids. Then it exits with code 1. +command stops and exits with code 1. It prints three groups: applied, status +unknown (5xx, timeout or network error), and not applied. Tell the user to check +the "status unknown" ids in YouTube Studio. Do not send them again without a check. `--ban` on `reject` also bans the author. Never pass `--ban` unless the user explicitly asks to ban. diff --git a/src/ytstudio/commands/comments.py b/src/ytstudio/commands/comments.py index ccc8e98..b9dc4de 100644 --- a/src/ytstudio/commands/comments.py +++ b/src/ytstudio/commands/comments.py @@ -4,6 +4,7 @@ from datetime import UTC, datetime from enum import StrEnum +import httplib2 import typer from google.auth.exceptions import RefreshError from googleapiclient.errors import HttpError @@ -17,7 +18,7 @@ # comments.setModerationStatus accepts up to 50 ids per call (50 quota units each call). MODERATION_BATCH_SIZE = 50 -# commentThreads.list / comments.list with id= accept a comma-separated list; keep it bounded. +# commentThreads.list / comments.list with id= accept a comma-separated list. Keep it bounded. LOOKUP_BATCH_SIZE = 50 @@ -47,7 +48,7 @@ class Comment: author_channel_id: str = "" reply_count: int = 0 has_link: bool = False - off_channel_link: bool = False + off_youtube_link: bool = False link_hosts: list[str] = field(default_factory=list) duplicate_of: str | None = None impersonation_suspect: bool = False @@ -74,7 +75,7 @@ def _parse_comment(comment_id: str, snippet: dict, reply_count: int = 0) -> Comm return Comment( id=comment_id, author=snippet.get("authorDisplayName", ""), - # textOriginal is only guaranteed for some callers; textDisplay is the fallback. + # The API does not always return textOriginal. textDisplay is the fallback. text=snippet.get("textOriginal", snippet.get("textDisplay", "")), likes=snippet.get("likeCount", 0), published_at=snippet.get("publishedAt", ""), @@ -96,7 +97,7 @@ def add_signals(comments: list[Comment], owner: Owner | None) -> None: for c in comments: c.link_hosts = comment_signals.link_hosts(c.text) c.has_link = bool(c.link_hosts) - c.off_channel_link = any(not comment_signals.is_youtube_host(h) for h in c.link_hosts) + c.off_youtube_link = any(not comment_signals.is_youtube_host(h) for h in c.link_hosts) c.duplicate_of = duplicates.get(c.id) if owner: c.impersonation_suspect = comment_signals.impersonation_suspect( @@ -122,7 +123,7 @@ def _owner_replied(service, item: dict, owner_id: str) -> bool: return True if item["snippet"].get("totalReplyCount", 0) <= len(replies): return False - # The replies part holds only a few replies; page through the rest. + # The replies part holds only a few replies. Page through the rest. params = {"part": "snippet", "parentId": item["id"], "maxResults": 100} for reply in _iter_pages(service.comments().list, params): if reply["snippet"].get("authorChannelId", {}).get("value") == owner_id: @@ -142,6 +143,7 @@ def fetch_comments( """List comment threads, following nextPageToken until `limit` comments are collected.""" params = { "part": "snippet,replies" if unanswered else "snippet", + "textFormat": "plainText", "maxResults": 100 if unanswered else min(limit, 100), "order": order.value, } @@ -252,7 +254,7 @@ def _log_lookup(ids: set[str]) -> dict[str, Comment]: return found -def resolve_comments(service, ids: list[str]) -> tuple[dict[str, Comment], set[str]]: +def resolve_comments(service, ids: list[str], owner: Owner) -> tuple[dict[str, Comment], set[str]]: """Look up comment ids so the preview and the log show API truth, not caller input. Order: threads by id, comments by id (replies), the held and spam queues, then the @@ -264,21 +266,28 @@ def missing() -> list[str]: return [i for i in ids if i not in found] for chunk in _chunks(missing(), LOOKUP_BATCH_SIZE): - resp = api(service.commentThreads().list(part="snippet", id=",".join(chunk))) + resp = api( + service.commentThreads().list( + part="snippet", id=",".join(chunk), textFormat="plainText" + ) + ) for item in resp.get("items", []): found[item["id"]] = _parse_thread(item) for chunk in _chunks(missing(), LOOKUP_BATCH_SIZE): - resp = api(service.comments().list(part="snippet", id=",".join(chunk))) + resp = api( + service.comments().list(part="snippet", id=",".join(chunk), textFormat="plainText") + ) for item in resp.get("items", []): found[item["id"]] = _parse_comment(item["id"], item["snippet"]) if missing(): - # Not documented whether id lookups return held comments; the queues do. - owner_id = get_owner(service).id + # The docs do not say if id lookups return held comments. The queues do. + owner_id = owner.id for status in (ModerationStatus.held, ModerationStatus.spam): params = { "part": "snippet", + "textFormat": "plainText", "allThreadsRelatedToChannelId": owner_id, "moderationStatus": status.to_api_value(), "maxResults": 100, @@ -303,7 +312,7 @@ def missing() -> list[str]: def _flags(c: Comment, from_log: bool) -> str: flags = [] - if c.off_channel_link: + if c.off_youtube_link: flags.append("link:" + ",".join(c.link_hosts)) elif c.has_link: flags.append("link:youtube") @@ -338,19 +347,34 @@ def _now() -> str: def _api_error_text(error: Exception) -> str: if isinstance(error, RefreshError): return "session expired or revoked" + if not isinstance(error, HttpError): + return f"{type(error).__name__}: {error}" if str(error) else type(error).__name__ details = error.error_details[0] if getattr(error, "error_details", None) else {} reason = details.get("reason") if isinstance(details, dict) else None return f"HTTP {error.resp.status}" + (f" {reason}" if reason else "") +@dataclass +class ModerationResult: + applied: list[str] = field(default_factory=list) + # Sent, but the call failed with a 5xx or a network error: the change may have landed. + unknown: list[str] = field(default_factory=list) + # Never sent, or refused by the API (4xx, auth). + unapplied: list[str] = field(default_factory=list) + error: str | None = None + + +def _outcome_unknown(error: Exception) -> bool: + if isinstance(error, HttpError): + return error.resp.status >= 500 + return not isinstance(error, RefreshError) + + def _set_moderation_status( service, comments: list[Comment], action: str, status: str, ban_author: bool -) -> tuple[list[str], list[str], str | None]: - """Apply in batches. Log each batch before its call; stop at the first failed batch. - - Returns (applied ids, unapplied ids, error text). - """ - applied: list[str] = [] +) -> ModerationResult: + """Apply in batches. Log each batch before its call. Stop at the first failed batch.""" + result = ModerationResult() batches = list(_chunks(comments, MODERATION_BATCH_SIZE)) for n, batch in enumerate(batches): ids = [c.id for c in batch] @@ -376,30 +400,33 @@ def _set_moderation_status( params["banAuthor"] = True try: service.comments().setModerationStatus(**params).execute() - except (HttpError, RefreshError) as e: - err = _api_error_text(e) + except (HttpError, RefreshError, OSError, httplib2.HttpLib2Error) as e: + result.error = _api_error_text(e) + phase = "unknown" if _outcome_unknown(e) else "failed" config.append_moderation_log( [ - {"ts": _now(), "phase": "failed", "action": action, "id": i, "error": err} + {"ts": _now(), "phase": phase, "action": action, "id": i, "error": result.error} for i in ids ] ) - unapplied = [c.id for b in batches[n:] for c in b] - return applied, unapplied, err + (result.unknown if phase == "unknown" else result.unapplied).extend(ids) + result.unapplied.extend(c.id for b in batches[n + 1 :] for c in b) + return result config.append_moderation_log( [{"ts": _now(), "phase": "applied", "action": action, "id": i} for i in ids] ) - applied.extend(ids) - return applied, [], None + result.applied.extend(ids) + return result def _moderate(comment_ids: list[str], action: str, status: str, ban: bool, execute: bool) -> None: ids = list(dict.fromkeys(comment_ids)) service = get_data_service() - found, from_log = resolve_comments(service, ids) + owner = get_owner(service) + found, from_log = resolve_comments(service, ids, owner) comments = [found[i] for i in ids if i in found] unresolved = [i for i in ids if i not in found] - add_signals(comments, None) + add_signals(comments, owner) label = f"{'Would ' if not execute else ''}{action}" + (" and ban the author of" if ban else "") _print_preview(comments, from_log, label[0].upper() + label[1:]) @@ -419,16 +446,23 @@ def _moderate(comment_ids: list[str], action: str, status: str, ban: bool, execu ) return - applied, unapplied, err = _set_moderation_status(service, comments, action, status, ban) + result = _set_moderation_status(service, comments, action, status, ban) past = {"reject": "rejected", "publish": "published"}[action] - console.print(f"\n{len(applied)} comment(s) {past}") - if unapplied: + console.print(f"\n{len(result.applied)} comment(s) {past}") + if result.error: + console.print(f"[red]Stopped: {result.error}.[/red]") + if result.unknown: console.print( - f"[red]Stopped: {err}. {len(unapplied)} comment(s) are not {past}:[/red]\n" - + " ".join(unapplied) + f"[yellow]{len(result.unknown)} comment(s) have status unknown, check:[/yellow]\n" + + " ".join(result.unknown) + ) + if result.unapplied: + console.print( + f"[red]{len(result.unapplied)} comment(s) are not {past}:[/red]\n" + + " ".join(result.unapplied) ) console.print(f"[dim]Log: {config.moderation_log_path()}[/dim]") - if unapplied: + if result.error: raise typer.Exit(1) @@ -466,7 +500,9 @@ def reply( """ service = get_data_service() if not execute: - resp = api(service.commentThreads().list(part="snippet", id=comment_id)) + resp = api( + service.commentThreads().list(part="snippet", id=comment_id, textFormat="plainText") + ) items = resp.get("items", []) if items: parent = _parse_thread(items[0]) diff --git a/src/ytstudio/comment_signals.py b/src/ytstudio/comment_signals.py index a3f4952..e428feb 100644 --- a/src/ytstudio/comment_signals.py +++ b/src/ytstudio/comment_signals.py @@ -38,7 +38,7 @@ def normalize(text: str) -> str: def _name_key(name: str) -> str: - # authorDisplayName now carries the @handle; strip it so "@chan" matches "Chan". + # authorDisplayName now carries the @handle. Strip it so "@chan" matches "Chan". return _NON_WORD.sub("", normalize(name.removeprefix("@"))) @@ -59,10 +59,10 @@ def impersonation_suspect( def duplicate_map(comments: list) -> dict[str, str]: - """Map comment id -> id of the earliest copy of the same text. + """Map comment id -> id of the earliest earlier copy of the same text. - A copy counts when it is on another video or from the same author. Different - authors with the same text on one video are left alone. + An earlier copy counts when it is on another video or from the same author. + Different authors with the same text on one video do not count. """ groups: dict[str, list] = {} for c in comments: @@ -72,12 +72,11 @@ def duplicate_map(comments: list) -> dict[str, str]: result = {} for group in groups.values(): - if len(group) < 2: - continue group.sort(key=lambda c: c.published_at) - first = group[0] - for c in group[1:]: - same_author = c.author_channel_id and c.author_channel_id == first.author_channel_id - if c.video_id != first.video_id or same_author: - result[c.id] = first.id + for j, c in enumerate(group): + for prev in group[:j]: + same_author = c.author_channel_id and c.author_channel_id == prev.author_channel_id + if c.video_id != prev.video_id or same_author: + result[c.id] = prev.id + break return result diff --git a/src/ytstudio/config.py b/src/ytstudio/config.py index a38ca82..5a7ed88 100644 --- a/src/ytstudio/config.py +++ b/src/ytstudio/config.py @@ -306,15 +306,13 @@ def save_policy(name: str, text: str) -> None: def append_moderation_log(records: list[dict], name: str | None = None) -> None: """Append JSONL records and fsync, so they survive a crash during the API call.""" - target = _ensure_profile_dir(name or get_active_profile()) - path = target / moderation_log_path(name).name + _ensure_profile_dir(name or get_active_profile()) data = "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in records) - fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) - try: - os.write(fd, data.encode()) - os.fsync(fd) - finally: - os.close(fd) + fd = os.open(moderation_log_path(name), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write(data) + fh.flush() + os.fsync(fh.fileno()) def read_moderation_log(name: str | None = None) -> list[dict]: From b912e71cd9125c26f173f33cfc06d9ae249a3f0c Mon Sep 17 00:00:00 2001 From: Jelmer de Wit <1598297+jdwit@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:17:47 +0100 Subject: [PATCH 6/6] test: failure modes, reply-id lookup, held-queue pagination, duplicates --- tests/test_comment_signals.py | 11 +++ tests/test_comments.py | 130 +++++++++++++++++++++++++++++++--- 2 files changed, 132 insertions(+), 9 deletions(-) diff --git a/tests/test_comment_signals.py b/tests/test_comment_signals.py index 94fe1a3..01b4e17 100644 --- a/tests/test_comment_signals.py +++ b/tests/test_comment_signals.py @@ -51,6 +51,17 @@ def test_same_author_same_video(self): ) assert dups == {"b": "a"} + def test_earlier_copy_from_same_author_after_other_author(self): + # Order [B v1, A v1, A v1]: the second A copy points to the first A copy, not to B. + dups = duplicate_map( + [ + _c("b1", "join my telegram for signals", "v1", "UC_b", "2026-01-01T00:00:00Z"), + _c("a1", "join my telegram for signals", "v1", "UC_a", "2026-01-02T00:00:00Z"), + _c("a2", "join my telegram for signals", "v1", "UC_a", "2026-01-03T00:00:00Z"), + ] + ) + assert dups == {"a2": "a1"} + def test_different_authors_same_video_not_flagged(self): dups = duplicate_map( [ diff --git a/tests/test_comments.py b/tests/test_comments.py index a1745d2..590e78f 100644 --- a/tests/test_comments.py +++ b/tests/test_comments.py @@ -2,6 +2,7 @@ from datetime import UTC, datetime, timedelta from unittest.mock import MagicMock +import httplib2 import pytest from googleapiclient.errors import HttpError from typer.testing import CliRunner @@ -152,14 +153,14 @@ def test_json_signals(self, mock_auth): result = runner.invoke(app, ["comments", "list", "-o", "json"]) rows = {r["id"]: r for r in json.loads(result.stdout)} - assert rows["s1"]["has_link"] and rows["s1"]["off_channel_link"] + assert rows["s1"]["has_link"] and rows["s1"]["off_youtube_link"] assert rows["s1"]["link_hosts"] == ["scam.example.com"] assert rows["s1"]["duplicate_of"] is None assert rows["s2"]["duplicate_of"] == "s1" assert rows["s1"]["author_channel_id"] == "UC_a" assert rows["imp"]["impersonation_suspect"] is True assert rows["own"]["impersonation_suspect"] is False - assert rows["yt"]["has_link"] and not rows["yt"]["off_channel_link"] + assert rows["yt"]["has_link"] and not rows["yt"]["off_youtube_link"] def test_comments_disabled(self, mock_auth): mock_auth.commentThreads.return_value.list.return_value.execute.side_effect = Exception( @@ -249,6 +250,74 @@ def threads(kw): assert "Spammer" in result.stdout assert "buy followers" in result.stdout + def test_resolves_reply_ids_by_comment_id(self, mock_auth, profile): + reply = { + "id": "reply1", + "snippet": { + "authorDisplayName": "Replier", + "authorChannelId": {"value": "UC_r"}, + "textOriginal": "a reply text", + "videoId": "vid1", + }, + } + _route(mock_auth.commentThreads.return_value.list, lambda kw: {"items": []}) + _route( + mock_auth.comments.return_value.list, + lambda kw: {"items": [reply] if "reply1" in kw["id"].split(",") else []}, + ) + + result = runner.invoke(app, ["comments", "reject", "reply1"]) + + assert result.exit_code == 0 + assert "Replier" in result.stdout + kwargs = mock_auth.comments.return_value.list.call_args.kwargs + assert kwargs["id"] == "reply1" + # The held and spam queues are not read when id lookups find everything. + statuses = [ + c.kwargs.get("moderationStatus") + for c in mock_auth.commentThreads.return_value.list.call_args_list + ] + assert statuses == [None] + + def test_held_queue_fallback_paginates(self, mock_auth, profile): + pages = { + None: {"items": [_thread(f"h{i}") for i in range(100)], "nextPageToken": "p2"}, + "p2": {"items": [_thread("target", "found on page two", "Late")]}, + } + + def threads(kw): + if kw.get("moderationStatus") == "heldForReview": + return pages[kw.get("pageToken")] + return {"items": []} + + _route(mock_auth.commentThreads.return_value.list, threads) + _route(mock_auth.comments.return_value.list, lambda kw: {"items": []}) + + result = runner.invoke(app, ["comments", "reject", "target"]) + + assert result.exit_code == 0 + assert "found on page two" in result.stdout + tokens = [ + c.kwargs.get("pageToken") + for c in mock_auth.commentThreads.return_value.list.call_args_list + if c.kwargs.get("moderationStatus") == "heldForReview" + ] + assert tokens == [None, "p2"] + + def test_preview_flags_impersonation(self, mock_auth, profile): + fake = _thread("fake1", "dm me on telegram", "@TestChannel", "UC_fake") + _route(mock_auth.commentThreads.return_value.list, lambda kw: {"items": [fake]}) + + result = runner.invoke(app, ["comments", "reject", "fake1"]) + + assert result.exit_code == 0 + assert "impersonation?" in result.stdout + + def test_lookups_ask_for_plain_text(self, mock_auth, profile): + runner.invoke(app, ["comments", "reject", "UgwComment123"]) + kwargs = mock_auth.commentThreads.return_value.list.call_args.kwargs + assert kwargs["textFormat"] == "plainText" + def test_resolves_from_log_for_undo(self, mock_auth, profile): config.append_moderation_log( [{"phase": "intent", "id": "gone1", "author": "Was Rejected", "text": "oops"}] @@ -308,8 +377,8 @@ def capture(**kwargs): phases = [r["phase"] for r in config.read_moderation_log()] assert phases == ["intent", "applied"] - def test_partial_failure_reports_applied_and_unapplied(self, mock_auth, profile): - ids = [f"c{i}" for i in range(120)] + def _run_with_failure(self, mock_auth, error, n_ids=120): + ids = [f"c{i}" for i in range(n_ids)] _route( mock_auth.commentThreads.return_value.list, lambda kw: {"items": [_thread(i) for i in kw["id"].split(",")]}, @@ -318,21 +387,64 @@ def test_partial_failure_reports_applied_and_unapplied(self, mock_auth, profile) def set_status(**kwargs): calls.append(kwargs["id"].split(",")) - return _request(_http_error() if len(calls) == 2 else {}) + return _request(error if len(calls) == 2 else {}) mock_auth.comments.return_value.setModerationStatus.side_effect = set_status - result = runner.invoke(app, ["comments", "reject", *ids, "--execute"]) + return result, calls + + @staticmethod + def _section(stdout, header): + # The ids after a report header. Rich can wrap them over several lines. + lines = stdout.splitlines() + i = next(n for n, line in enumerate(lines) if header in line) + ids = [] + for line in lines[i + 1 :]: + if "comment(s)" in line or line.startswith("Log:"): + break + ids += line.split() + return ids + + def test_5xx_batch_is_status_unknown(self, mock_auth, profile): + result, calls = self._run_with_failure(mock_auth, _http_error(500)) assert result.exit_code == 1 assert [len(c) for c in calls] == [50, 50] # third batch never sent assert "50 comment(s) rejected" in result.stdout - assert "70 comment(s) are not rejected" in result.stdout assert "HTTP 500 backendError" in result.stdout - assert "c50" in result.stdout and "c119" in result.stdout + unknown = self._section(result.stdout, "50 comment(s) have status unknown, check") + assert unknown == [f"c{i}" for i in range(50, 100)] + unapplied = self._section(result.stdout, "20 comment(s) are not rejected") + assert unapplied == [f"c{i}" for i in range(100, 120)] log = config.read_moderation_log() assert sum(r["phase"] == "applied" for r in log) == 50 - assert sum(r["phase"] == "failed" for r in log) == 50 + assert sum(r["phase"] == "unknown" for r in log) == 50 + + def test_4xx_batch_is_not_applied(self, mock_auth, profile): + result, _ = self._run_with_failure(mock_auth, _http_error(400, "invalidParameter")) + + assert result.exit_code == 1 + assert "status unknown" not in result.stdout + unapplied = self._section(result.stdout, "70 comment(s) are not rejected") + assert unapplied == [f"c{i}" for i in range(50, 120)] + assert sum(r["phase"] == "failed" for r in config.read_moderation_log()) == 50 + + @pytest.mark.parametrize( + "error", [TimeoutError("timed out"), ConnectionResetError("reset"), OSError("down")] + ) + def test_network_error_mid_batch_still_reports(self, mock_auth, profile, error): + result, calls = self._run_with_failure(mock_auth, error) + + assert result.exit_code == 1 + assert len(calls) == 2 + assert "50 comment(s) rejected" in result.stdout + assert "50 comment(s) have status unknown, check" in result.stdout + assert "20 comment(s) are not rejected" in result.stdout + + def test_httplib2_error_mid_batch_still_reports(self, mock_auth, profile): + result, _ = self._run_with_failure(mock_auth, httplib2.ServerNotFoundError("no host")) + assert result.exit_code == 1 + assert "50 comment(s) have status unknown, check" in result.stdout def test_duplicate_ids_sent_once(self, mock_auth, profile): runner.invoke(app, ["comments", "publish", "UgwComment123", "UgwComment123", "--execute"])