AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(reddit): add moderation blocks (#12945)
Nicholas Tindlebd439de0119c
diff --git a/autogpt_platform/backend/backend/blocks/reddit.py b/autogpt_platform/backend/backend/blocks/reddit.pyindex e835c40842..c4d745ae1e 100644--- a/autogpt_platform/backend/backend/blocks/reddit.py+++ b/autogpt_platform/backend/backend/blocks/reddit.py@@ -19,6 +19,7 @@ from backend.data.model import (OAuth2Credentials,SchemaField,)+from backend.integrations.oauth.reddit import RedditOAuthHandlerfrom backend.integrations.providers import ProviderNamefrom backend.util.mock import MockObjectfrom backend.util.settings import Settings@@ -36,29 +37,58 @@ RedditCredentialsInput = CredentialsMetaInput[Literal["oauth2"],]+# Single source of truth for the baseline scopes: the OAuth handler owns them, so+# the two lists can't drift apart.+REDDIT_BASE_SCOPES = frozenset(RedditOAuthHandler.DEFAULT_SCOPES)++# Elevated moderator scopes. These are never in `DEFAULT_SCOPES`; only blocks that+# actually need them ask for them via `RedditCredentialsField(required_scopes=...)`.+MOD_POSTS_SCOPE = "modposts" # Remove/approve/lock posts and comments+MOD_CONTRIBUTORS_SCOPE = "modcontributors" # Ban and unban subreddit users+MODMAIL_SCOPE = "modmail" # Send modmail conversations+REDDIT_MODERATION_SCOPES = frozenset(+ {MOD_POSTS_SCOPE, MOD_CONTRIBUTORS_SCOPE, MODMAIL_SCOPE}+)+-def RedditCredentialsField() -> RedditCredentialsInput:- """Creates a Reddit credentials input on a block."""+def RedditCredentialsField(+ required_scopes: set[str] | None = None,+) -> RedditCredentialsInput:+ """+ Creates a Reddit credentials input on a block.++ `required_scopes=None` preserves the legacy implicit-scope path, where the OAuth+ handler supplies `DEFAULT_SCOPES`. Passing a set opts into explicit scope metadata;+ the baseline is then merged because `BaseOAuthHandler.handle_default_scopes`+ *replaces* `DEFAULT_SCOPES` with a non-empty requested list rather than unioning+ them — without the merge, a moderation block would mint a token that can't even+ call `client.user.me()`.+ """+ if required_scopes is None:+ merged_scopes: set[str] = set()+ else:+ merged_scopes = set(REDDIT_BASE_SCOPES) | required_scopesreturn CredentialsField(+ required_scopes=merged_scopes,description="Connect your Reddit account to access Reddit features.",)+def reddit_disabled() -> bool:+ """Whether Reddit blocks should be disabled for want of app credentials."""+ return (+ not settings.secrets.reddit_client_id+ or not settings.secrets.reddit_client_secret+ )++TEST_CREDENTIALS = OAuth2Credentials(id="01234567-89ab-cdef-0123-456789abcdef",provider="reddit",access_token=SecretStr("mock-reddit-access-token"),refresh_token=SecretStr("mock-reddit-refresh-token"),access_token_expires_at=9999999999,- scopes=[- "identity",- "read",- "submit",- "edit",- "history",- "privatemessages",- "flair",- ],+ scopes=sorted(REDDIT_BASE_SCOPES | REDDIT_MODERATION_SCOPES),title="Mock Reddit credentials",username="mock-reddit-username",)diff --git a/autogpt_platform/backend/backend/blocks/reddit_moderation.py b/autogpt_platform/backend/backend/blocks/reddit_moderation.pynew file mode 100644index 0000000000..7866746bbc--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/reddit_moderation.py@@ -0,0 +1,649 @@+from typing import Any, Literal++from praw.models import Comment, Submission++from backend.blocks._base import (+ Block,+ BlockCategory,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+)+from backend.blocks.reddit import (+ MOD_CONTRIBUTORS_SCOPE,+ MOD_POSTS_SCOPE,+ MODMAIL_SCOPE,+ TEST_CREDENTIALS,+ TEST_CREDENTIALS_INPUT,+ RedditCredentials,+ RedditCredentialsField,+ RedditCredentialsInput,+ get_praw,+ reddit_disabled,+ strip_reddit_prefix,+)+from backend.data.model import SchemaField++REMOVE_MOD_NOTE_MAX_LENGTH = 250+BAN_REASON_MAX_LENGTH = 100+BAN_MOD_NOTE_MAX_LENGTH = 300+BAN_MESSAGE_MAX_LENGTH = 1000+MODMAIL_SUBJECT_MAX_LENGTH = 100+MODMAIL_BODY_MAX_LENGTH = 10000+MOD_QUEUE_MAX_LIMIT = 100+BAN_MAX_DURATION_DAYS = 999 # Reddit's cap for temporary bans++COMMENT_PREFIX = "t1_"+SUBMISSION_PREFIX = "t3_"++THING_ID_DESCRIPTION = (+ "Full Reddit thing ID, prefixed with 't3_' for a post (e.g. 't3_abc123') or "+ "'t1_' for a comment (e.g. 't1_xyz789'). Bare IDs are rejected: posts and "+ "comments share an ID namespace, so an unprefixed ID cannot be resolved safely."+)+++def _get_thing_type(thing_id: str) -> Literal["comment", "submission"]:+ """+ Classify a Reddit thing ID by its prefix.++ The prefix is mandatory. Reddit comment and submission IDs are drawn from the+ same base-36 namespace, so a bare ID like ``abc123`` is a valid submission ID+ *and* a valid comment ID — guessing would let a moderation action land on an+ unrelated object.+ """+ if thing_id.startswith(COMMENT_PREFIX):+ return "comment"+ if thing_id.startswith(SUBMISSION_PREFIX):+ return "submission"+ raise ValueError(+ f"Ambiguous Reddit thing ID {thing_id!r}. Prefix it with "+ f"'{SUBMISSION_PREFIX}' for a post or '{COMMENT_PREFIX}' for a comment — "+ "bare IDs are ambiguous because posts and comments share an ID namespace. "+ "The Mod Queue block emits prefixed IDs on its 'post_id' output."+ )+++def _get_moderated_thing(+ creds: RedditCredentials, thing_id: str+) -> Comment | Submission:+ """Resolve a Reddit thing ID to the comment or submission it names."""+ client = get_praw(creds)+ bare_id = strip_reddit_prefix(thing_id)+ if _get_thing_type(thing_id) == "comment":+ return client.comment(id=bare_id)+ return client.submission(id=bare_id)+++class ModQueueBlock(Block):+ class Input(BlockSchemaInput):+ credentials: RedditCredentialsInput = RedditCredentialsField(+ required_scopes={MOD_POSTS_SCOPE}+ )+ subreddit: str = SchemaField(+ description="Subreddit name, excluding the /r/ prefix",+ )+ limit: int = SchemaField(+ description=(+ "Maximum number of items to fetch from the mod queue "+ f"(1-{MOD_QUEUE_MAX_LIMIT})"+ ),+ default=25,+ ge=1,+ le=MOD_QUEUE_MAX_LIMIT,+ )+ only: Literal["submissions", "comments"] | None = SchemaField(+ description="Filter to only submissions or only comments. Leave blank for both.",+ default=None,+ )++ class Output(BlockSchemaOutput):+ post_id: str = SchemaField(+ description="Full Reddit thing ID of a queued item, such as 't3_abc123' or 't1_xyz789'"+ )+ item_type: Literal["comment", "submission"] = SchemaField(+ description="Whether the queued item is a comment or submission"+ )+ post_title: str = SchemaField(description="Title of the queued item")+ author: str = SchemaField(description="Username of the author")+ permalink: str = SchemaField(description="Full Reddit permalink")+ reason: str = SchemaField(description="Mod queue reason (if any)")+ items: list[dict[str, Any]] = SchemaField(+ description=(+ "All queued items as a list. Emitted exactly once; an empty list "+ "signals that the queue was checked and had no items."+ )+ )++ def __init__(self):+ super().__init__(+ id="166f3083-51da-4cfc-9f7a-57f47b1ba590",+ description=(+ "Fetches the mod queue for a subreddit. Scalar outputs fan out once "+ "per queued post or comment; items emits the full batch once. "+ "Requires moderator access."+ ),+ categories={BlockCategory.SOCIAL},+ disabled=reddit_disabled(),+ input_schema=ModQueueBlock.Input,+ output_schema=ModQueueBlock.Output,+ test_credentials=TEST_CREDENTIALS,+ test_input={+ "credentials": TEST_CREDENTIALS_INPUT,+ "subreddit": "testsubreddit",+ "limit": 5,+ },+ test_output=[+ ("post_id", "t3_abc123"),+ ("item_type", "submission"),+ ("post_title", "Test queued post"),+ ("author", "testuser"),+ ("permalink", "/r/testsubreddit/comments/abc123/test_queued_post/"),+ ("reason", ""),+ (+ "items",+ [+ {+ "id": "t3_abc123",+ "type": "submission",+ "title": "Test queued post",+ "author": "testuser",+ "permalink": "/r/testsubreddit/comments/abc123/test_queued_post/",+ "reason": "",+ }+ ],+ ),+ ],+ test_mock={+ "get_mod_queue": lambda creds, subreddit, limit, only: [+ {+ "id": "t3_abc123",+ "type": "submission",+ "title": "Test queued post",+ "author": "testuser",+ "permalink": "/r/testsubreddit/comments/abc123/test_queued_post/",+ "reason": "",+ }+ ]+ },+ )++ @staticmethod+ def get_mod_queue(+ creds: RedditCredentials,+ subreddit: str,+ limit: int,+ only: Literal["submissions", "comments"] | None,+ ) -> list[dict[str, Any]]:+ client = get_praw(creds)+ sub = client.subreddit(subreddit)+ kwargs: dict[str, Any] = {"limit": limit}+ if only:+ kwargs["only"] = only++ def to_item(item: Comment | Submission) -> dict[str, Any]:+ thing_id = item.fullname+ return {+ "id": thing_id,+ "type": _get_thing_type(thing_id),+ "title": getattr(item, "title", "[comment]"),+ "author": str(item.author) if item.author else "[deleted]",+ "permalink": item.permalink,+ "reason": getattr(item, "mod_reason_title", "") or "",+ }++ return [to_item(item) for item in sub.mod.modqueue(**kwargs)]++ async def run(+ self, input_data: Input, *, credentials: RedditCredentials, **kwargs+ ) -> BlockOutput:+ items = self.get_mod_queue(+ credentials,+ subreddit=input_data.subreddit,+ limit=input_data.limit,+ only=input_data.only,+ )+ for item in items:+ # Scalar pins intentionally fan out; the aggregate pin below emits once.+ yield "post_id", item["id"]+ yield "item_type", item["type"]+ yield "post_title", item["title"]+ yield "author", item["author"]+ yield "permalink", item["permalink"]+ yield "reason", item["reason"]+ yield "items", items+++class RemoveRedditPostBlock(Block):+ class Input(BlockSchemaInput):+ credentials: RedditCredentialsInput = RedditCredentialsField(+ required_scopes={MOD_POSTS_SCOPE}+ )+ post_id: str = SchemaField(+ description=f"Post or comment to remove. {THING_ID_DESCRIPTION}",+ )+ spam: bool = SchemaField(+ description="Mark as spam (True) or just remove (False). Spam trains the filter.",+ default=False,+ )+ mod_note: str | None = SchemaField(+ description="Optional internal moderator note visible only to mods",+ default=None,+ max_length=REMOVE_MOD_NOTE_MAX_LENGTH,+ )++ class Output(BlockSchemaOutput):+ post_id: str = SchemaField(description="ID of the removed post (pass-through)")+ success: bool = SchemaField(description="Whether the removal succeeded")++ def __init__(self):+ super().__init__(+ id="f75643df-0a1a-4240-aa5b-9b2a1b20dcdd",+ description="Removes a Reddit post or comment as a moderator. Requires 'modposts' scope. Reddit scopes are account-wide, so this grants the ability across every subreddit you moderate, not only the one set here.",+ categories={BlockCategory.SOCIAL},+ disabled=reddit_disabled(),+ input_schema=RemoveRedditPostBlock.Input,+ output_schema=RemoveRedditPostBlock.Output,+ test_credentials=TEST_CREDENTIALS,+ test_input={+ "credentials": TEST_CREDENTIALS_INPUT,+ "post_id": "t3_abc123",+ "spam": False,+ },+ test_output=[+ ("post_id", "t3_abc123"),+ ("success", True),+ ],+ test_mock={"remove_post": lambda creds, post_id, spam, mod_note: True},+ is_sensitive_action=True,+ )++ @staticmethod+ def remove_post(+ creds: RedditCredentials,+ post_id: str,+ spam: bool,+ mod_note: str | None,+ ) -> bool:+ thing = _get_moderated_thing(creds, post_id)+ remove_kwargs: dict[str, Any] = {"spam": spam}+ if mod_note:+ remove_kwargs["mod_note"] = mod_note+ thing.mod.remove(**remove_kwargs)+ return True++ async def run(+ self, input_data: Input, *, credentials: RedditCredentials, **kwargs+ ) -> BlockOutput:+ success = self.remove_post(+ credentials,+ post_id=input_data.post_id,+ spam=input_data.spam,+ mod_note=input_data.mod_note,+ )+ yield "post_id", input_data.post_id+ yield "success", success+++class ApproveRedditPostBlock(Block):+ class Input(BlockSchemaInput):+ credentials: RedditCredentialsInput = RedditCredentialsField(+ required_scopes={MOD_POSTS_SCOPE}+ )+ post_id: str = SchemaField(+ description=f"Post or comment to approve. {THING_ID_DESCRIPTION}",+ )++ class Output(BlockSchemaOutput):+ post_id: str = SchemaField(description="ID of the approved post (pass-through)")+ success: bool = SchemaField(description="Whether the approval succeeded")++ def __init__(self):+ super().__init__(+ id="ae695fcf-e1bf-4900-b06c-3ae21d6edf70",+ description="Approves a Reddit post or comment from the mod queue. Requires 'modposts' scope. Reddit scopes are account-wide, so this grants the ability across every subreddit you moderate, not only the one set here.",+ categories={BlockCategory.SOCIAL},+ disabled=reddit_disabled(),+ input_schema=ApproveRedditPostBlock.Input,+ output_schema=ApproveRedditPostBlock.Output,+ test_credentials=TEST_CREDENTIALS,+ test_input={+ "credentials": TEST_CREDENTIALS_INPUT,+ "post_id": "t3_abc123",+ },+ test_output=[+ ("post_id", "t3_abc123"),+ ("success", True),+ ],+ test_mock={"approve_post": lambda creds, post_id: True},+ is_sensitive_action=True,+ )++ @staticmethod+ def approve_post(creds: RedditCredentials, post_id: str) -> bool:+ thing = _get_moderated_thing(creds, post_id)+ thing.mod.approve()+ return True++ async def run(+ self, input_data: Input, *, credentials: RedditCredentials, **kwargs+ ) -> BlockOutput:+ success = self.approve_post(credentials, post_id=input_data.post_id)+ yield "post_id", input_data.post_id+ yield "success", success+++class LockRedditPostBlock(Block):+ class Input(BlockSchemaInput):+ credentials: RedditCredentialsInput = RedditCredentialsField(+ required_scopes={MOD_POSTS_SCOPE}+ )+ post_id: str = SchemaField(+ description=f"Post or comment to lock or unlock. {THING_ID_DESCRIPTION}",+ )+ lock: bool = SchemaField(+ description="True to lock (disable comments/replies), False to unlock",+ default=True,+ )++ class Output(BlockSchemaOutput):+ post_id: str = SchemaField(description="ID of the post (pass-through)")+ locked: bool = SchemaField(description="Current lock state after the action")++ def __init__(self):+ super().__init__(+ id="1deaf67c-0407-457f-989d-323198073f74",+ description="Locks or unlocks a Reddit post or comment to prevent or allow replies. Requires 'modposts' scope. Reddit scopes are account-wide, so this grants the ability across every subreddit you moderate, not only the one set here.",+ categories={BlockCategory.SOCIAL},+ disabled=reddit_disabled(),+ input_schema=LockRedditPostBlock.Input,+ output_schema=LockRedditPostBlock.Output,+ test_credentials=TEST_CREDENTIALS,+ test_input={+ "credentials": TEST_CREDENTIALS_INPUT,+ "post_id": "t3_abc123",+ "lock": True,+ },+ test_output=[+ ("post_id", "t3_abc123"),+ ("locked", True),+ ],+ test_mock={"set_lock": lambda creds, post_id, lock: lock},+ is_sensitive_action=True,+ )++ @staticmethod+ def set_lock(creds: RedditCredentials, post_id: str, lock: bool) -> bool:+ thing = _get_moderated_thing(creds, post_id)+ if lock:+ thing.mod.lock()+ else:+ thing.mod.unlock()+ return lock++ async def run(+ self, input_data: Input, *, credentials: RedditCredentials, **kwargs+ ) -> BlockOutput:+ locked = self.set_lock(+ credentials,+ post_id=input_data.post_id,+ lock=input_data.lock,+ )+ yield "post_id", input_data.post_id+ yield "locked", locked+++class BanSubredditUserBlock(Block):+ class Input(BlockSchemaInput):+ credentials: RedditCredentialsInput = RedditCredentialsField(+ required_scopes={MOD_CONTRIBUTORS_SCOPE}+ )+ subreddit: str = SchemaField(+ description="Subreddit to ban the user from, excluding the /r/ prefix",+ )+ username: str = SchemaField(+ description="Reddit username to ban (without the u/ prefix)",+ )+ duration: int | None = SchemaField(+ description=(+ "Ban duration in days "+ f"(1-{BAN_MAX_DURATION_DAYS}, Reddit's cap for temporary bans). "+ "Leave blank for a permanent ban."+ ),+ default=None,+ ge=1,+ le=BAN_MAX_DURATION_DAYS,+ )+ reason: str = SchemaField(+ description="Internal moderator-only ban reason (max 100 chars). Use ban_message to explain the ban to the user.",+ default="Violation of subreddit rules",+ max_length=BAN_REASON_MAX_LENGTH,+ )+ mod_note: str | None = SchemaField(+ description="Internal moderator note (not shown to the user)",+ default=None,+ max_length=BAN_MOD_NOTE_MAX_LENGTH,+ )+ ban_message: str | None = SchemaField(+ description="Optional custom message sent to the user explaining the ban",+ default=None,+ max_length=BAN_MESSAGE_MAX_LENGTH,+ )++ class Output(BlockSchemaOutput):+ username: str = SchemaField(description="Banned username (pass-through)")+ subreddit: str = SchemaField(description="Subreddit (pass-through)")+ success: bool = SchemaField(description="Whether the ban was applied")+ permanent: bool = SchemaField(description="True if the ban is permanent")++ def __init__(self):+ super().__init__(+ id="428d56d4-52d0-47d9-8544-836d13d196c0",+ description="Bans a user from a subreddit. Requires 'modcontributors' scope. Reddit scopes are account-wide, so this grants the ability across every subreddit you moderate, not only the one set here.",+ categories={BlockCategory.SOCIAL},+ disabled=reddit_disabled(),+ input_schema=BanSubredditUserBlock.Input,+ output_schema=BanSubredditUserBlock.Output,+ test_credentials=TEST_CREDENTIALS,+ test_input={+ "credentials": TEST_CREDENTIALS_INPUT,+ "subreddit": "testsubreddit",+ "username": "spamuser123",+ "duration": 7,+ "reason": "Spam",+ },+ test_output=[+ ("username", "spamuser123"),+ ("subreddit", "testsubreddit"),+ ("success", True),+ ("permanent", False),+ ],+ test_mock={+ "ban_user": lambda creds, subreddit, username, duration, reason, mod_note, ban_message: True+ },+ is_sensitive_action=True,+ )++ @staticmethod+ def ban_user(+ creds: RedditCredentials,+ subreddit: str,+ username: str,+ duration: int | None,+ reason: str,+ mod_note: str | None,+ ban_message: str | None,+ ) -> bool:+ client = get_praw(creds)+ sub = client.subreddit(subreddit)+ ban_kwargs: dict[str, Any] = {"ban_reason": reason}+ if duration is not None:+ ban_kwargs["duration"] = duration+ if mod_note:+ ban_kwargs["note"] = mod_note+ if ban_message:+ ban_kwargs["ban_message"] = ban_message+ sub.banned.add(username, **ban_kwargs)+ return True++ async def run(+ self, input_data: Input, *, credentials: RedditCredentials, **kwargs+ ) -> BlockOutput:+ success = self.ban_user(+ credentials,+ subreddit=input_data.subreddit,+ username=input_data.username,+ duration=input_data.duration,+ reason=input_data.reason,+ mod_note=input_data.mod_note,+ ban_message=input_data.ban_message,+ )+ yield "username", input_data.username+ yield "subreddit", input_data.subreddit+ yield "success", success+ yield "permanent", input_data.duration is None+++class UnbanSubredditUserBlock(Block):+ class Input(BlockSchemaInput):+ credentials: RedditCredentialsInput = RedditCredentialsField(+ required_scopes={MOD_CONTRIBUTORS_SCOPE}+ )+ subreddit: str = SchemaField(+ description="Subreddit to unban the user from, excluding the /r/ prefix",+ )+ username: str = SchemaField(+ description="Reddit username to unban (without the u/ prefix)",+ )++ class Output(BlockSchemaOutput):+ username: str = SchemaField(description="Unbanned username (pass-through)")+ subreddit: str = SchemaField(description="Subreddit (pass-through)")+ success: bool = SchemaField(description="Whether the unban succeeded")++ def __init__(self):+ super().__init__(+ id="90979f47-605e-4478-a417-39da3d7184ef",+ description="Unbans a user from a subreddit. Requires 'modcontributors' scope. Reddit scopes are account-wide, so this grants the ability across every subreddit you moderate, not only the one set here.",+ categories={BlockCategory.SOCIAL},+ disabled=reddit_disabled(),+ input_schema=UnbanSubredditUserBlock.Input,+ output_schema=UnbanSubredditUserBlock.Output,+ test_credentials=TEST_CREDENTIALS,+ test_input={+ "credentials": TEST_CREDENTIALS_INPUT,+ "subreddit": "testsubreddit",+ "username": "rehabilitateduser",+ },+ test_output=[+ ("username", "rehabilitateduser"),+ ("subreddit", "testsubreddit"),+ ("success", True),+ ],+ test_mock={"unban_user": lambda creds, subreddit, username: True},+ is_sensitive_action=True,+ )++ @staticmethod+ def unban_user(creds: RedditCredentials, subreddit: str, username: str) -> bool:+ client = get_praw(creds)+ sub = client.subreddit(subreddit)+ sub.banned.remove(username)+ return True++ async def run(+ self, input_data: Input, *, credentials: RedditCredentials, **kwargs+ ) -> BlockOutput:+ success = self.unban_user(+ credentials,+ subreddit=input_data.subreddit,+ username=input_data.username,+ )+ yield "username", input_data.username+ yield "subreddit", input_data.subreddit+ yield "success", success+++class SendModMailBlock(Block):+ class Input(BlockSchemaInput):+ credentials: RedditCredentialsInput = RedditCredentialsField(+ required_scopes={MODMAIL_SCOPE}+ )+ subreddit: str = SchemaField(+ description="Subreddit to send modmail from, excluding the /r/ prefix",+ )+ to_username: str = SchemaField(+ description="Username to send the modmail to (without u/ prefix)",+ )+ subject: str = SchemaField(+ description="Subject line of the modmail message",+ max_length=MODMAIL_SUBJECT_MAX_LENGTH,+ )+ body: str = SchemaField(+ description="Body of the modmail message",+ max_length=MODMAIL_BODY_MAX_LENGTH,+ )++ class Output(BlockSchemaOutput):+ conversation_id: str = SchemaField(+ description="ID of the created modmail conversation"+ )+ success: bool = SchemaField(description="Whether the modmail was sent")++ def __init__(self):+ super().__init__(+ id="168b919c-0e06-471d-bd46-eb354ed3d278",+ description="Sends a modmail message from a subreddit to a user. Requires 'modmail' scope. Reddit scopes are account-wide, so this grants the ability across every subreddit you moderate, not only the one set here.",+ categories={BlockCategory.SOCIAL},+ disabled=reddit_disabled(),+ input_schema=SendModMailBlock.Input,+ output_schema=SendModMailBlock.Output,+ test_credentials=TEST_CREDENTIALS,+ test_input={+ "credentials": TEST_CREDENTIALS_INPUT,+ "subreddit": "testsubreddit",+ "to_username": "someuser",+ "subject": "Warning: Spam",+ "body": "Please stop posting promotional content.",+ },+ test_output=[+ ("conversation_id", "mock_conv_id"),+ ("success", True),+ ],+ test_mock={+ "send_modmail": lambda creds, subreddit, to_username, subject, body: "mock_conv_id"+ },+ is_sensitive_action=True,+ )++ @staticmethod+ def send_modmail(+ creds: RedditCredentials,+ subreddit: str,+ to_username: str,+ subject: str,+ body: str,+ ) -> str:+ client = get_praw(creds)+ sub = client.subreddit(subreddit)+ conversation = sub.modmail.create(+ subject=subject,+ body=body,+ recipient=to_username,+ )+ return conversation.id++ async def run(+ self, input_data: Input, *, credentials: RedditCredentials, **kwargs+ ) -> BlockOutput:+ conversation_id = self.send_modmail(+ credentials,+ subreddit=input_data.subreddit,+ to_username=input_data.to_username,+ subject=input_data.subject,+ body=input_data.body,+ )+ yield "conversation_id", conversation_id+ # Derived, not a literal: `success` means "Reddit came back with a+ # conversation", which is the only evidence we have that it landed.+ yield "success", bool(conversation_id)diff --git a/autogpt_platform/backend/backend/blocks/test/test_reddit_moderation.py b/autogpt_platform/backend/backend/blocks/test/test_reddit_moderation.pynew file mode 100644index 0000000000..8a3341efe2--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/test/test_reddit_moderation.py@@ -0,0 +1,671 @@+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest+from praw.models import Comment, Submission+from pydantic import ValidationError+from pydantic.fields import FieldInfo++from backend.blocks.reddit import (+ REDDIT_BASE_SCOPES,+ TEST_CREDENTIALS,+ TEST_CREDENTIALS_INPUT,+ RedditCredentialsField,+)+from backend.blocks.reddit_moderation import (+ BAN_MAX_DURATION_DAYS,+ MOD_QUEUE_MAX_LIMIT,+ ApproveRedditPostBlock,+ BanSubredditUserBlock,+ LockRedditPostBlock,+ ModQueueBlock,+ RemoveRedditPostBlock,+ SendModMailBlock,+ UnbanSubredditUserBlock,+ _get_moderated_thing,+ _get_thing_type,+)+++def _patch_praw(mocker) -> MagicMock:+ client = MagicMock()+ mocker.patch("backend.blocks.reddit_moderation.get_praw", return_value=client)+ return client+++def _mock_praw_client() -> MagicMock:+ client = MagicMock()+ client.config.kinds = {"comment": "t1", "submission": "t3"}+ return client+++ ("block_cls", "elevated_scope"),+ [+ (ModQueueBlock, "modposts"),+ (RemoveRedditPostBlock, "modposts"),+ (ApproveRedditPostBlock, "modposts"),+ (LockRedditPostBlock, "modposts"),+ (BanSubredditUserBlock, "modcontributors"),+ (UnbanSubredditUserBlock, "modcontributors"),+ (SendModMailBlock, "modmail"),+ ],+)+def test_moderation_blocks_declare_least_privilege_scopes(block_cls, elevated_scope):+ """+ Each moderation block asks for exactly one elevated scope on top of the+ baseline. The baseline must be included because+ ``BaseOAuthHandler.handle_default_scopes`` *replaces* ``DEFAULT_SCOPES`` when a+ non-empty scope list is requested — a block asking for only ``modposts`` would+ receive a token that cannot even call ``client.user.me()``.+ """+ field = block_cls().input_schema.model_fields["credentials"]+ extra = field.json_schema_extra+ assert isinstance(extra, dict)+ declared = set(extra["credentials_scopes"])++ assert declared == REDDIT_BASE_SCOPES | {elevated_scope}+ # Never request scopes no block consumes (e.g. modlog).+ assert "modlog" not in declared+++def test_explicit_empty_reddit_scopes_still_include_the_baseline():+ field = RedditCredentialsField(required_scopes=set())+ assert isinstance(field, FieldInfo)+ extra = field.json_schema_extra+ assert isinstance(extra, dict)++ assert set(extra["credentials_scopes"]) == REDDIT_BASE_SCOPES+++def test_default_reddit_scopes_remain_implicit_for_legacy_blocks():+ field = RedditCredentialsField()+ assert isinstance(field, FieldInfo)+ extra = field.json_schema_extra+ assert isinstance(extra, dict)++ # The OAuth handler fills in DEFAULT_SCOPES for an absent scope list. Keeping+ # this implicit avoids changing the credential contract of existing blocks.+ assert "credentials_scopes" not in extra+++ ("queued_item", "only", "expected"),+ [+ pytest.param(+ SimpleNamespace(+ id="abc123",+ fullname="t3_abc123",+ title="Queued title",+ author="queued-user",+ permalink="/r/test/comments/abc123/queued_title/",+ mod_reason_title="",+ ),+ "submissions",+ {+ "id": "t3_abc123",+ "type": "submission",+ "title": "Queued title",+ "author": "queued-user",+ "permalink": "/r/test/comments/abc123/queued_title/",+ "reason": "",+ },+ id="submission",+ ),+ pytest.param(+ # No `title`, no author, no mod reason: the comment defaults.+ SimpleNamespace(+ id="xyz789",+ fullname="t1_xyz789",+ author=None,+ permalink="/r/test/comments/abc123/comment/",+ mod_reason_title=None,+ ),+ "comments",+ {+ "id": "t1_xyz789",+ "type": "comment",+ "title": "[comment]",+ "author": "[deleted]",+ "permalink": "/r/test/comments/abc123/comment/",+ "reason": "",+ },+ id="comment",+ ),+ ],+)+def test_get_mod_queue_maps_listing_items(mocker, queued_item, only, expected):+ sub = MagicMock()+ sub.mod.modqueue.return_value = [queued_item]+ client = _patch_praw(mocker)+ client.subreddit.return_value = sub++ items = ModQueueBlock.get_mod_queue(+ TEST_CREDENTIALS,+ subreddit="test",+ limit=5,+ only=only,+ )++ sub.mod.modqueue.assert_called_once_with(limit=5, only=only)+ assert items == [expected]+++ ("queued_item", "expected_id", "expected_type"),+ [+ (+ Comment(+ _mock_praw_client(),+ _data={+ "id": "xyz789",+ "author": "queued-user",+ "permalink": "/r/test/comments/abc123/comment/xyz789/",+ "mod_reason_title": None,+ },+ ),+ "t1_xyz789",+ "comment",+ ),+ (+ Submission(+ _mock_praw_client(),+ _data={+ "id": "abc123",+ "author": "queued-user",+ "permalink": "/r/test/comments/abc123/queued_title/",+ "mod_reason_title": None,+ "title": "Queued title",+ },+ ),+ "t3_abc123",+ "submission",+ ),+ ],+)+def test_get_mod_queue_uses_hydrated_praw_fields_without_fetching(+ mocker, queued_item, expected_id, expected_type+):+ """Building an item must not cost an API call per queued thing (no N+1).++ Asserted against the praw client rather than against `_fetch`: praw marks a+ comment built from `_data` as `_fetched=True`, so a patched `_fetch` on the+ comment parameter can never fire and that assertion would be vacuous. Every+ lazy attribute access has to go through `_reddit`, so a `to_item` that starts+ reading a field the modqueue listing doesn't return shows up here — for the+ submission parameter, which praw leaves `_fetched=False`, it really does.+ """+ item_client = queued_item._reddit+ sub = MagicMock()+ sub.mod.modqueue.return_value = [queued_item]+ client = _patch_praw(mocker)+ client.subreddit.return_value = sub++ items = ModQueueBlock.get_mod_queue(+ TEST_CREDENTIALS,+ subreddit="test",+ limit=5,+ only=None,+ )++ assert items[0]["id"] == expected_id+ assert items[0]["type"] == expected_type+ assert item_client.method_calls == []+++def test_get_mod_queue_returns_empty_list_for_empty_queue(mocker):+ sub = MagicMock()+ sub.mod.modqueue.return_value = []+ client = _patch_praw(mocker)+ client.subreddit.return_value = sub++ assert (+ ModQueueBlock.get_mod_queue(+ TEST_CREDENTIALS, subreddit="test", limit=5, only=None+ )+ == []+ )+ sub.mod.modqueue.assert_called_once_with(limit=5)+++def test_get_moderated_thing_resolves_comments_and_submissions(mocker):+ client = _patch_praw(mocker)++ _get_moderated_thing(TEST_CREDENTIALS, "t1_xyz789")+ client.comment.assert_called_once_with(id="xyz789")+ client.submission.assert_not_called()++ client.reset_mock()+ _get_moderated_thing(TEST_CREDENTIALS, "t3_abc123")+ client.submission.assert_called_once_with(id="abc123")+ client.comment.assert_not_called()++[email protected]("thing_id", ["abc123", "t5_subreddit", "", "T1_xyz789"])+def test_get_moderated_thing_rejects_ambiguous_ids(mocker, thing_id):+ """A bare ID is a valid post ID *and* a valid comment ID — never guess."""+ client = _patch_praw(mocker)++ with pytest.raises(ValueError, match="Ambiguous Reddit thing ID"):+ _get_moderated_thing(TEST_CREDENTIALS, thing_id)++ client.comment.assert_not_called()+ client.submission.assert_not_called()+++def test_get_thing_type_rejects_unknown_prefixes():+ with pytest.raises(ValueError, match="Ambiguous Reddit thing ID"):+ _get_thing_type("t5_subreddit")+++async def test_mod_queue_run_fans_out_every_item_and_emits_one_batch(mocker):+ items = [+ {+ "id": "t3_first",+ "type": "submission",+ "title": "First",+ "author": "alice",+ "permalink": "/r/test/comments/first/",+ "reason": "",+ },+ {+ "id": "t1_second",+ "type": "comment",+ "title": "[comment]",+ "author": "bob",+ "permalink": "/r/test/comments/first/_/second/",+ "reason": "Rule 1",+ },+ ]+ block = ModQueueBlock()+ mocker.patch.object(block, "get_mod_queue", return_value=items)+ input_data = block.Input.model_validate(+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "subreddit": "test",+ "limit": 2,+ }+ )++ outputs = [+ output async for output in block.run(input_data, credentials=TEST_CREDENTIALS)+ ]++ # Pin the *complete* scalar sequence, not just the post_id pins: the block+ # description promises scalar outputs fan out once per queued item, and+ # asserting only a subset lets a dropped `yield` pass unnoticed.+ assert outputs == [+ ("post_id", "t3_first"),+ ("item_type", "submission"),+ ("post_title", "First"),+ ("author", "alice"),+ ("permalink", "/r/test/comments/first/"),+ ("reason", ""),+ ("post_id", "t1_second"),+ ("item_type", "comment"),+ ("post_title", "[comment]"),+ ("author", "bob"),+ ("permalink", "/r/test/comments/first/_/second/"),+ ("reason", "Rule 1"),+ ("items", items),+ ]+++ ("post_id", "kind", "bare_id", "spam", "mod_note", "expected_kwargs"),+ [+ pytest.param(+ "t1_xyz789",+ "comment",+ "xyz789",+ False,+ "Rule 3",+ {"spam": False, "mod_note": "Rule 3"},+ id="comment-with-mod-note",+ ),+ pytest.param(+ "t3_abc123",+ "submission",+ "abc123",+ True,+ None,+ {"spam": True},+ id="submission-without-mod-note",+ ),+ ],+)+def test_remove_post_targets_the_right_thing(+ mocker, post_id, kind, bare_id, spam, mod_note, expected_kwargs+):+ client = _patch_praw(mocker)+ target = MagicMock()+ getattr(client, kind).return_value = target++ result = RemoveRedditPostBlock.remove_post(+ TEST_CREDENTIALS,+ post_id=post_id,+ spam=spam,+ mod_note=mod_note,+ )++ assert result is True+ getattr(client, kind).assert_called_once_with(id=bare_id)+ target.mod.remove.assert_called_once_with(**expected_kwargs)+++def test_remove_post_rejects_bare_id_before_calling_reddit(mocker):+ client = _patch_praw(mocker)++ with pytest.raises(ValueError, match="Ambiguous Reddit thing ID"):+ RemoveRedditPostBlock.remove_post(+ TEST_CREDENTIALS, post_id="abc123", spam=False, mod_note=None+ )++ client.submission.assert_not_called()+ client.comment.assert_not_called()+++ ("post_id", "kind", "bare_id"),+ [+ pytest.param("t3_abc123", "submission", "abc123", id="submission"),+ pytest.param("t1_xyz789", "comment", "xyz789", id="comment"),+ ],+)+def test_approve_post_resolves_target_and_approves(mocker, post_id, kind, bare_id):+ client = _patch_praw(mocker)+ target = MagicMock()+ getattr(client, kind).return_value = target++ assert (+ ApproveRedditPostBlock.approve_post(TEST_CREDENTIALS, post_id=post_id) is True+ )++ getattr(client, kind).assert_called_once_with(id=bare_id)+ target.mod.approve.assert_called_once_with()+++ ("post_id", "kind", "bare_id", "lock", "called", "not_called"),+ [+ pytest.param(+ "t3_abc123", "submission", "abc123", True, "lock", "unlock", id="lock"+ ),+ pytest.param(+ "t1_xyz789", "comment", "xyz789", False, "unlock", "lock", id="unlock"+ ),+ ],+)+def test_set_lock_calls_the_matching_mod_action(+ mocker, post_id, kind, bare_id, lock, called, not_called+):+ client = _patch_praw(mocker)+ target = MagicMock()+ getattr(client, kind).return_value = target++ assert (+ LockRedditPostBlock.set_lock(TEST_CREDENTIALS, post_id=post_id, lock=lock)+ is lock+ )++ getattr(client, kind).assert_called_once_with(id=bare_id)+ getattr(target.mod, called).assert_called_once_with()+ getattr(target.mod, not_called).assert_not_called()+++def test_ban_user_passes_full_kwargs(mocker):+ subreddit = MagicMock()+ client = _patch_praw(mocker)+ client.subreddit.return_value = subreddit++ assert (+ BanSubredditUserBlock.ban_user(+ TEST_CREDENTIALS,+ subreddit="testsubreddit",+ username="spamuser123",+ duration=7,+ reason="Spam",+ mod_note="Third strike",+ ban_message="Please stop spamming.",+ )+ is True+ )++ client.subreddit.assert_called_once_with("testsubreddit")+ subreddit.banned.add.assert_called_once_with(+ "spamuser123",+ ban_reason="Spam",+ duration=7,+ note="Third strike",+ ban_message="Please stop spamming.",+ )+++def test_ban_user_permanent_ban_omits_duration(mocker):+ subreddit = MagicMock()+ client = _patch_praw(mocker)+ client.subreddit.return_value = subreddit++ BanSubredditUserBlock.ban_user(+ TEST_CREDENTIALS,+ subreddit="testsubreddit",+ username="spamuser123",+ duration=None,+ reason="Spam",+ mod_note=None,+ ban_message=None,+ )++ subreddit.banned.add.assert_called_once_with("spamuser123", ban_reason="Spam")+++def test_unban_user_calls_banned_remove(mocker):+ subreddit = MagicMock()+ client = _patch_praw(mocker)+ client.subreddit.return_value = subreddit++ assert (+ UnbanSubredditUserBlock.unban_user(+ TEST_CREDENTIALS, subreddit="testsubreddit", username="rehabilitateduser"+ )+ is True+ )++ client.subreddit.assert_called_once_with("testsubreddit")+ subreddit.banned.remove.assert_called_once_with("rehabilitateduser")+++def test_send_modmail_creates_conversation(mocker):+ subreddit = MagicMock()+ subreddit.modmail.create.return_value = SimpleNamespace(id="conv123")+ client = _patch_praw(mocker)+ client.subreddit.return_value = subreddit++ conversation_id = SendModMailBlock.send_modmail(+ TEST_CREDENTIALS,+ subreddit="testsubreddit",+ to_username="someuser",+ subject="Warning: Spam",+ body="Please stop posting promotional content.",+ )++ assert conversation_id == "conv123"+ client.subreddit.assert_called_once_with("testsubreddit")+ subreddit.modmail.create.assert_called_once_with(+ subject="Warning: Spam",+ body="Please stop posting promotional content.",+ recipient="someuser",+ )+++def _input(block_cls, **fields) -> None:+ """Validate a block's Input schema — raises ValidationError on bad values."""+ block_cls.Input.model_validate({"credentials": TEST_CREDENTIALS_INPUT, **fields})+++def test_mod_queue_limit_is_bounded():+ _input(ModQueueBlock, subreddit="test", limit=MOD_QUEUE_MAX_LIMIT)++ with pytest.raises(ValidationError):+ _input(ModQueueBlock, subreddit="test", limit=MOD_QUEUE_MAX_LIMIT + 1)++[email protected]("duration", [0, BAN_MAX_DURATION_DAYS + 1])+def test_ban_duration_is_bounded(duration):+ """Reddit caps temporary bans at 999 days; reject out-of-range up front."""+ _input(BanSubredditUserBlock, subreddit="test", username="u", duration=1)++ with pytest.raises(ValidationError):+ _input(BanSubredditUserBlock, subreddit="test", username="u", duration=duration)+++def test_moderator_free_text_inputs_are_length_bounded():+ with pytest.raises(ValidationError):+ _input(RemoveRedditPostBlock, post_id="t3_abc123", mod_note="x" * 251)++ with pytest.raises(ValidationError):+ _input(+ BanSubredditUserBlock,+ subreddit="test",+ username="u",+ ban_message="x" * 1001,+ )++ with pytest.raises(ValidationError):+ _input(+ BanSubredditUserBlock,+ subreddit="test",+ username="u",+ reason="x" * 101,+ )++ with pytest.raises(ValidationError):+ _input(+ SendModMailBlock,+ subreddit="test",+ to_username="someuser",+ subject="x" * 101,+ body="hello",+ )++ with pytest.raises(ValidationError):+ _input(+ SendModMailBlock,+ subreddit="test",+ to_username="someuser",+ subject="hello",+ body="x" * 10001,+ )+++# The human-in-the-loop gate for automated moderation. `data/graph.py` reads+# `block.is_sensitive_action` to decide whether a run needs approval, so a block+# silently losing the flag would start banning and removing without a prompt.+# Nothing else in the suite pins it.+ ("block_cls", "is_sensitive"),+ [+ (RemoveRedditPostBlock, True),+ (ApproveRedditPostBlock, True),+ (LockRedditPostBlock, True),+ (BanSubredditUserBlock, True),+ (UnbanSubredditUserBlock, True),+ (SendModMailBlock, True),+ # Read-only: the mod queue must NOT demand approval to be listed.+ (ModQueueBlock, False),+ ],+)+def test_state_changing_moderation_blocks_are_gated(block_cls, is_sensitive):+ assert block_cls().is_sensitive_action is is_sensitive+++async def test_ban_run_reports_permanent_when_duration_omitted(mocker):+ """A ban with no duration is permanent, and must say so.++ `test_input` always sets a duration, so the `duration=None` branch of the+ `permanent` output is otherwise unexercised: a moderator issuing a permanent+ ban could silently get `permanent: false`.+ """+ block = BanSubredditUserBlock()+ mocker.patch.object(block, "ban_user", return_value=True)+ input_data = block.Input.model_validate(+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "subreddit": "testsubreddit",+ "username": "spamuser123",+ "reason": "Spam",+ }+ )++ outputs = [+ output async for output in block.run(input_data, credentials=TEST_CREDENTIALS)+ ]++ assert input_data.duration is None+ assert ("permanent", True) in outputs+ assert ("success", True) in outputs+++async def test_ban_run_reports_temporary_when_duration_given(mocker):+ block = BanSubredditUserBlock()+ mocker.patch.object(block, "ban_user", return_value=True)+ input_data = block.Input.model_validate(+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "subreddit": "testsubreddit",+ "username": "spamuser123",+ "duration": 7,+ "reason": "Spam",+ }+ )++ outputs = [+ output async for output in block.run(input_data, credentials=TEST_CREDENTIALS)+ ]++ assert ("permanent", False) in outputs+++async def test_modmail_success_is_derived_from_conversation_id(mocker):+ """`success` must mean something: no conversation id, no success."""+ block = SendModMailBlock()+ mocker.patch.object(block, "send_modmail", return_value="")+ input_data = block.Input.model_validate(+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "subreddit": "testsubreddit",+ "to_username": "someuser",+ "subject": "Warning",+ "body": "Please stop.",+ }+ )++ outputs = [+ output async for output in block.run(input_data, credentials=TEST_CREDENTIALS)+ ]++ assert ("success", False) in outputs+++async def test_mod_queue_run_emits_only_the_empty_batch(mocker):+ """An empty queue yields no scalar pins at all, and exactly one ('items', [])."""+ block = ModQueueBlock()+ mocker.patch.object(block, "get_mod_queue", return_value=[])+ input_data = block.Input.model_validate(+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "subreddit": "test",+ "limit": 5,+ }+ )++ outputs = [+ output async for output in block.run(input_data, credentials=TEST_CREDENTIALS)+ ]++ assert outputs == [("items", [])]diff --git a/autogpt_platform/backend/backend/integrations/oauth/reddit.py b/autogpt_platform/backend/backend/integrations/oauth/reddit.pyindex 33ecc866d7..46c333f462 100644--- a/autogpt_platform/backend/backend/integrations/oauth/reddit.py+++ b/autogpt_platform/backend/backend/integrations/oauth/reddit.py@@ -13,6 +13,28 @@ from backend.util.settings import Settingssettings = Settings()+def _granted_scopes(raw_scope: object, requested_scopes: list[str]) -> list[str]:+ """+ Resolve the scopes Reddit actually granted from a token response.++ Parsing and the empty-response fallback are shared with every other handler+ via `parse_granted_scopes`. The one Reddit-specific bit is the wildcard `*`,+ which Reddit uses to mean "every scope this app may request" -- storing it+ verbatim would leave the credential with a scope no block can ever match.+ """+ granted = parse_granted_scopes(+ raw_scope if isinstance(raw_scope, str) else None, fallback=requested_scopes+ )+ if "*" in granted:+ return requested_scopes+ return granted+++def _union_scopes(existing: list[str], granted: list[str]) -> list[str]:+ """Existing scopes plus any newly granted ones, in a stable order."""+ return existing + [s for s in granted if s not in existing]++class RedditOAuthHandler(BaseOAuthHandler):"""Reddit OAuth 2.0 handler.@@ -28,6 +50,10 @@ class RedditOAuthHandler(BaseOAuthHandler):"""PROVIDER_NAME = ProviderName.REDDIT+ # Baseline scopes granted to every Reddit connection. Elevated moderator+ # scopes are NOT listed here on purpose: blocks that need them declare them+ # per-block via `RedditCredentialsField(required_scopes=...)`, so a user who+ # only posts or reads is never asked to grant ban/remove/modmail authority.DEFAULT_SCOPES: ClassVar[list[str]] = ["identity", # Get username, verify auth"read", # Access posts and comments@@ -110,7 +136,10 @@ class RedditOAuthHandler(BaseOAuthHandler):refresh_token=tokens.get("refresh_token"),access_token_expires_at=int(time.time()) + tokens.get("expires_in", 3600),refresh_token_expires_at=None, # Reddit refresh tokens don't expire- scopes=parse_granted_scopes(tokens.get("scope"), fallback=scopes),+ # Persist what Reddit granted, not what we asked for: a non-moderator+ # who authorizes a moderation block must not end up with a credential+ # that falsely claims mod scopes it never received.+ scopes=_granted_scopes(tokens.get("scope"), scopes),)async def _get_username(self, access_token: str) -> str:@@ -183,7 +212,16 @@ class RedditOAuthHandler(BaseOAuthHandler):refresh_token=refresh_token,access_token_expires_at=int(time.time()) + tokens.get("expires_in", 3600),refresh_token_expires_at=None,- scopes=credentials.scopes,+ # Union, never replace. The credentials store refuses an update whose+ # scopes aren't a superset of the stored ones (`credentials_store.py`,+ # `issuperset` guard), so persisting a narrower set here would make the+ # refreshed token unstorable and leave every later run re-failing on the+ # stale one. Reddit narrowing a refresh response is not a revocation, so+ # widening back to what's on record is the safe reading.+ scopes=_union_scopes(+ credentials.scopes,+ _granted_scopes(tokens.get("scope"), credentials.scopes),+ ),)async def revoke_tokens(self, credentials: OAuth2Credentials) -> bool:diff --git a/autogpt_platform/backend/backend/integrations/oauth/reddit_test.py b/autogpt_platform/backend/backend/integrations/oauth/reddit_test.pynew file mode 100644index 0000000000..4600523786--- /dev/null+++ b/autogpt_platform/backend/backend/integrations/oauth/reddit_test.py@@ -0,0 +1,286 @@+from unittest.mock import AsyncMock, MagicMock+from urllib.parse import parse_qs, urlparse++import pytest+from pydantic import SecretStr+from pytest_mock import MockerFixture++from backend.data.model import OAuth2Credentials+from backend.integrations.oauth.reddit import RedditOAuthHandler+from backend.integrations.providers import ProviderName+++def _handler() -> RedditOAuthHandler:+ return RedditOAuthHandler(+ client_id="test-client-id",+ client_secret="test-client-secret",+ redirect_uri="https://example.com/callback",+ )+++def _creds(scopes: list[str] | None = None) -> OAuth2Credentials:+ return OAuth2Credentials(+ provider=ProviderName.REDDIT,+ title=None,+ username="reddit-user",+ access_token=SecretStr("access-token-value"),+ refresh_token=SecretStr("refresh-token-value"),+ access_token_expires_at=None,+ refresh_token_expires_at=None,+ scopes=scopes or ["identity", "read", "modposts"],+ )+++MODERATION_SCOPES = {"modposts", "modcontributors", "modmail", "modlog"}+++def test_default_login_url_never_requests_moderation_scopes():+ """+ A plain Reddit connection (read/post workflows) must not be forced to grant+ ban/remove/modmail authority. Moderation scopes are opt-in per block via+ ``RedditCredentialsField(required_scopes=...)``.+ """+ url = _handler().get_login_url([], "state-token", None)++ query = parse_qs(urlparse(url).query)+ scopes = set(query["scope"][0].split())++ assert scopes == {+ "identity",+ "read",+ "submit",+ "edit",+ "history",+ "privatemessages",+ "flair",+ }+ assert not scopes & MODERATION_SCOPES+++def test_get_login_url_requests_block_declared_scopes():+ requested = sorted(set(RedditOAuthHandler.DEFAULT_SCOPES) | {"modposts"})++ url = _handler().get_login_url(requested, "state-token", None)++ query = parse_qs(urlparse(url).query)+ assert set(query["scope"][0].split()) == set(requested)+++def _mock_token_response(mocker: MockerFixture, tokens: dict) -> None:+ mock_response = MagicMock()+ mock_response.ok = True+ mock_response.json.return_value = tokens+ mocker.patch(+ "backend.integrations.oauth.reddit.Requests",+ return_value=MagicMock(post=AsyncMock(return_value=mock_response)),+ )+++def _handler_with_mocked_username(mocker: MockerFixture) -> RedditOAuthHandler:+ handler = _handler()+ mocker.patch.object(handler, "_get_username", AsyncMock(return_value="reddit-user"))+ return handler+++async def test_exchange_code_for_tokens_persists_granted_scopes(+ mocker: MockerFixture,+):+ """+ A non-moderator authorizing a moderation block gets a narrower grant than we+ asked for. Storing the *requested* scopes would make the credential claim mod+ authority it never received, turning a clear permission problem into an opaque+ 403 at block-run time.+ """+ _mock_token_response(+ mocker,+ {+ "access_token": "access-token-value",+ "refresh_token": "refresh-token-value",+ "expires_in": 3600,+ "scope": "identity read",+ },+ )++ creds = await _handler_with_mocked_username(mocker).exchange_code_for_tokens(+ code="auth-code",+ scopes=["identity", "read", "modposts"],+ code_verifier=None,+ )++ assert creds.scopes == ["identity", "read"]+++async def test_exchange_code_for_tokens_normalizes_comma_separated_scopes(+ mocker: MockerFixture,+):+ _mock_token_response(+ mocker,+ {+ "access_token": "access-token-value",+ "refresh_token": "refresh-token-value",+ "expires_in": 3600,+ "scope": "identity,read",+ },+ )++ creds = await _handler_with_mocked_username(mocker).exchange_code_for_tokens(+ code="auth-code",+ scopes=["identity", "read"],+ code_verifier=None,+ )++ assert creds.scopes == ["identity", "read"]+++async def test_exchange_code_for_tokens_normalizes_wildcard_scope(+ mocker: MockerFixture,+):+ """Reddit returns `*` to mean "everything this app may request"."""+ _mock_token_response(+ mocker,+ {+ "access_token": "access-token-value",+ "refresh_token": "refresh-token-value",+ "expires_in": 3600,+ "scope": "*",+ },+ )++ creds = await _handler_with_mocked_username(mocker).exchange_code_for_tokens(+ code="auth-code",+ scopes=["identity", "read", "modposts"],+ code_verifier=None,+ )++ assert creds.scopes == ["identity", "read", "modposts"]+++async def test_exchange_code_for_tokens_falls_back_when_scope_missing(+ mocker: MockerFixture,+):+ _mock_token_response(+ mocker,+ {+ "access_token": "access-token-value",+ "refresh_token": "refresh-token-value",+ "expires_in": 3600,+ },+ )++ creds = await _handler_with_mocked_username(mocker).exchange_code_for_tokens(+ code="auth-code",+ scopes=["identity", "read", "modposts"],+ code_verifier=None,+ )++ assert creds.scopes == ["identity", "read", "modposts"]+++async def test_refresh_tokens_never_narrows_stored_scopes(mocker: MockerFixture):+ """A narrowing refresh response must not shrink the stored scope set.++ `credentials_store.update_creds` rejects an update whose scopes aren't a+ superset of the stored ones, so narrowing here would make the refreshed+ token unstorable and every later run would re-fail on the stale token.+ """+ _mock_token_response(+ mocker,+ {+ "access_token": "new-access-token",+ "expires_in": 3600,+ "scope": "identity read",+ },+ )++ refreshed = await _handler_with_mocked_username(mocker)._refresh_tokens(_creds())++ assert set(refreshed.scopes).issuperset(_creds().scopes)+ assert refreshed.scopes == ["identity", "read", "modposts"]+ assert refreshed.refresh_token == SecretStr("refresh-token-value")+++async def test_refresh_tokens_picks_up_newly_granted_scopes(mocker: MockerFixture):+ """A widening refresh response adds the new scopes on top of the stored ones."""+ _mock_token_response(+ mocker,+ {+ "access_token": "new-access-token",+ "expires_in": 3600,+ "scope": "identity read modposts modmail",+ },+ )++ refreshed = await _handler_with_mocked_username(mocker)._refresh_tokens(_creds())++ assert refreshed.scopes == ["identity", "read", "modposts", "modmail"]+++async def test_refresh_tokens_keeps_existing_scopes_when_absent(+ mocker: MockerFixture,+):+ _mock_token_response(+ mocker,+ {+ "access_token": "new-access-token",+ "expires_in": 3600,+ },+ )++ refreshed = await _handler_with_mocked_username(mocker)._refresh_tokens(_creds())++ assert refreshed.scopes == ["identity", "read", "modposts"]+++async def test_exchange_code_for_tokens_falls_back_on_empty_scope_string(+ mocker: MockerFixture,+):+ """An empty `scope` string is as uninformative as an absent one."""+ _mock_token_response(+ mocker,+ {+ "access_token": "access-token-value",+ "refresh_token": "refresh-token-value",+ "expires_in": 3600,+ "scope": " ",+ },+ )++ creds = await _handler_with_mocked_username(mocker).exchange_code_for_tokens(+ code="auth-code",+ scopes=["identity", "read", "modposts"],+ code_verifier=None,+ )++ assert creds.scopes == ["identity", "read", "modposts"]+++async def test_exchange_code_for_tokens_records_scopes_beyond_those_requested(+ mocker: MockerFixture,+):+ """Reddit granting more than was asked for is recorded as granted, not trimmed."""+ _mock_token_response(+ mocker,+ {+ "access_token": "access-token-value",+ "refresh_token": "refresh-token-value",+ "expires_in": 3600,+ "scope": "identity read modposts modmail",+ },+ )++ creds = await _handler_with_mocked_username(mocker).exchange_code_for_tokens(+ code="auth-code",+ scopes=["identity", "read"],+ code_verifier=None,+ )++ assert creds.scopes == ["identity", "read", "modposts", "modmail"]diff --git a/docs/integrations/README.md b/docs/integrations/README.mdindex 9615d8acd4..550e6df32a 100644--- a/docs/integrations/README.md+++ b/docs/integrations/README.md@@ -340,6 +340,8 @@ Below is a comprehensive list of all available blocks, categorized by their prim| Block Name | Description ||------------|-------------|+| [Approve Reddit Post](block-integrations/misc.md#approve-reddit-post) | Approves a Reddit post or comment from the mod queue |+| [Ban Subreddit User](block-integrations/misc.md#ban-subreddit-user) | Bans a user from a subreddit || [Create Discord Thread](block-integrations/discord/bot_blocks.md#create-discord-thread) | Creates a new thread in a Discord channel || [Create Reddit Post](block-integrations/misc.md#create-reddit-post) | Create a new post on a subreddit || [Delete Reddit Comment](block-integrations/misc.md#delete-reddit-comment) | Delete a Reddit comment that you own |@@ -366,6 +368,8 @@ Below is a comprehensive list of all available blocks, categorized by their prim| [Get User Posts](block-integrations/misc.md#get-user-posts) | Fetch posts by a specific Reddit user || [Linkedin Person Lookup](block-integrations/enrichlayer/linkedin.md#linkedin-person-lookup) | Look up LinkedIn profiles by person information using Enrichlayer || [Linkedin Role Lookup](block-integrations/enrichlayer/linkedin.md#linkedin-role-lookup) | Look up LinkedIn profiles by role in a company using Enrichlayer |+| [Lock Reddit Post](block-integrations/misc.md#lock-reddit-post) | Locks or unlocks a Reddit post or comment to prevent or allow replies |+| [Mod Queue](block-integrations/misc.md#mod-queue) | Fetches the mod queue for a subreddit || [Post Reddit Comment](block-integrations/misc.md#post-reddit-comment) | This block posts a Reddit comment on a specified Reddit post || [Post To Bluesky](block-integrations/ayrshare/post_to_bluesky.md#post-to-bluesky) | Post to Bluesky using Ayrshare || [Post To Facebook](block-integrations/ayrshare/post_to_facebook.md#post-to-facebook) | Post to Facebook using Ayrshare |@@ -383,6 +387,7 @@ Below is a comprehensive list of all available blocks, categorized by their prim| [Publish To Medium](block-integrations/misc.md#publish-to-medium) | Publishes a post to Medium || [Read Discord Messages](block-integrations/discord/bot_blocks.md#read-discord-messages) | Reads new messages from a Discord channel using a bot token and triggers when a new message is posted || [Reddit Get My Posts](block-integrations/misc.md#reddit-get-my-posts) | Fetch posts created by the authenticated Reddit user (you) |+| [Remove Reddit Post](block-integrations/misc.md#remove-reddit-post) | Removes a Reddit post or comment as a moderator || [Reply To Discord Message](block-integrations/discord/bot_blocks.md#reply-to-discord-message) | Replies to a specific Discord message || [Reply To Reddit Comment](block-integrations/misc.md#reply-to-reddit-comment) | Reply to a specific Reddit comment || [Reply To Telegram Message](block-integrations/telegram/blocks.md#reply-to-telegram-message) | Reply to a specific message in a Telegram chat |@@ -391,6 +396,7 @@ Below is a comprehensive list of all available blocks, categorized by their prim| [Send Discord Embed](block-integrations/discord/bot_blocks.md#send-discord-embed) | Sends a rich embed message to a Discord channel || [Send Discord File](block-integrations/discord/bot_blocks.md#send-discord-file) | Sends a file attachment to a Discord channel || [Send Discord Message](block-integrations/discord/bot_blocks.md#send-discord-message) | Sends a message to a Discord channel using a bot token |+| [Send Mod Mail](block-integrations/misc.md#send-mod-mail) | Sends a modmail message from a subreddit to a user || [Send Reddit Message](block-integrations/misc.md#send-reddit-message) | Send a private message (DM) to a Reddit user || [Send Slack Message](block-integrations/slack/blocks.md#send-slack-message) | Send a text message to any Slack channel, DM, or thread || [Send Telegram Audio](block-integrations/telegram/blocks.md#send-telegram-audio) | Send an audio file to a Telegram chat |@@ -453,6 +459,7 @@ Below is a comprehensive list of all available blocks, categorized by their prim| [Twitter Unmute User](block-integrations/twitter/mutes.md#twitter-unmute-user) | This block unmutes a specified Twitter user || [Twitter Unpin List](block-integrations/twitter/pinned_lists.md#twitter-unpin-list) | This block allows the authenticated user to unpin a specified List || [Twitter Update List](block-integrations/twitter/manage_lists.md#twitter-update-list) | This block updates a specified Twitter List owned by the authenticated user |+| [Unban Subreddit User](block-integrations/misc.md#unban-subreddit-user) | Unbans a user from a subreddit |## Communicationdiff --git a/docs/integrations/block-integrations/misc.md b/docs/integrations/block-integrations/misc.mdindex c0e9900148..ccb227f29e 100644--- a/docs/integrations/block-integrations/misc.md+++ b/docs/integrations/block-integrations/misc.md@@ -38,6 +38,43 @@ Input and output schemas define the expected data structure for communication be---+## Approve Reddit Post++### What it is+Approves a Reddit post or comment from the mod queue. Requires 'modposts' scope. Reddit scopes are account-wide, so this grants the ability across every subreddit you moderate, not only the one set here.++### How it works+<!-- MANUAL: how_it_works -->+This block requires a prefixed Reddit thing ID — `t3_...` for a post or `t1_...` for a comment — and loads the matching PRAW object before calling the moderator `approve()` action with credentials that include the `modposts` scope. Bare IDs are rejected: posts and comments share an ID namespace, so an unprefixed ID could resolve to an unrelated object.++On success, the block returns the original `post_id` and `success=True`. `Mod Queue` emits prefixed IDs on its `post_id` output, so the two blocks chain directly without losing whether the item started as a comment or a submission.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| post_id | Post or comment to approve. Full Reddit thing ID, prefixed with 't3_' for a post (e.g. 't3_abc123') or 't1_' for a comment (e.g. 't1_xyz789'). Bare IDs are rejected: posts and comments share an ID namespace, so an unprefixed ID cannot be resolved safely. | str | Yes |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| post_id | ID of the approved post (pass-through) | str |+| success | Whether the approval succeeded | bool |++### Possible use case+<!-- MANUAL: use_case -->+**False Positive Cleanup**: Approve items from the mod queue after an external classifier determines they are safe.++**Appeal Handling**: Restore a previously filtered post or comment after a moderator reviews a user appeal.++**Hybrid Moderation**: Combine automated queue scoring with a final approval step for borderline content.+<!-- END MANUAL -->++---+## AutoPilot### What it is@@ -87,6 +124,50 @@ Tool and block identifiers provided in `tools` and `blocks` are validated at run---+## Ban Subreddit User++### What it is+Bans a user from a subreddit. Requires 'modcontributors' scope. Reddit scopes are account-wide, so this grants the ability across every subreddit you moderate, not only the one set here.++### How it works+<!-- MANUAL: how_it_works -->+The input schema bounds the optional `duration` to 1–999 days (Reddit's cap for temporary bans) and caps the internal `reason`, `mod_note`, and user-facing `ban_message` fields at Reddit's moderation limits, so invalid values are rejected before any API call is made. The block then calls `sub.banned.add(...)`, optionally including a temporary duration and a `ban_message`.++The outputs echo the target user and subreddit, plus `success` and a derived `permanent` flag so downstream steps can branch on temporary versus permanent bans. Use `reason` and `mod_note` for internal moderation context, and reserve `ban_message` for the explanation shown to the banned user.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| subreddit | Subreddit to ban the user from, excluding the /r/ prefix | str | Yes |+| username | Reddit username to ban (without the u/ prefix) | str | Yes |+| duration | Ban duration in days (1-999, Reddit's cap for temporary bans). Leave blank for a permanent ban. | int | No |+| reason | Internal moderator-only ban reason (max 100 chars). Use ban_message to explain the ban to the user. | str | No |+| mod_note | Internal moderator note (not shown to the user) | str | No |+| ban_message | Optional custom message sent to the user explaining the ban | str | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| username | Banned username (pass-through) | str |+| subreddit | Subreddit (pass-through) | str |+| success | Whether the ban was applied | bool |+| permanent | True if the ban is permanent | bool |++### Possible use case+<!-- MANUAL: use_case -->+**Escalation Workflow**: Ban repeat offenders automatically after multiple confirmed moderation violations.++**Temporary Cooldown**: Apply short bans during heated incidents while moderators review the situation.++**Policy Enforcement**: Pair user reporting or detection blocks with standardized ban actions and messaging.+<!-- END MANUAL -->++---+## Create Reddit Post### What it is@@ -739,6 +820,88 @@ The sandbox persists until its timeout expires or it's explicitly disposed. Use---+## Lock Reddit Post++### What it is+Locks or unlocks a Reddit post or comment to prevent or allow replies. Requires 'modposts' scope. Reddit scopes are account-wide, so this grants the ability across every subreddit you moderate, not only the one set here.++### How it works+<!-- MANUAL: how_it_works -->+This block resolves the target `post_id` to the correct Reddit object from its `t3_` (post) or `t1_` (comment) prefix, so both can be locked or unlocked from the same input field; bare, unprefixed IDs are rejected as ambiguous. It then calls `lock()` when `lock=True` or `unlock()` when `lock=False`, using moderator credentials with the `modposts` scope.++The block returns the original `post_id` plus the resulting `locked` state, which makes it useful in review pipelines where the moderation decision and final state need to be recorded explicitly.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| post_id | Post or comment to lock or unlock. Full Reddit thing ID, prefixed with 't3_' for a post (e.g. 't3_abc123') or 't1_' for a comment (e.g. 't1_xyz789'). Bare IDs are rejected: posts and comments share an ID namespace, so an unprefixed ID cannot be resolved safely. | str | Yes |+| lock | True to lock (disable comments/replies), False to unlock | bool | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| post_id | ID of the post (pass-through) | str |+| locked | Current lock state after the action | bool |++### Possible use case+<!-- MANUAL: use_case -->+**Thread Freeze**: Lock a post when discussion becomes abusive or starts attracting brigading.++**Post-Resolution Cleanup**: Unlock a thread again after moderators have resolved the incident and want to reopen discussion.++**Incident Playbooks**: Trigger lock or unlock actions automatically from moderation decision trees.+<!-- END MANUAL -->++---++## Mod Queue++### What it is+Fetches the mod queue for a subreddit. Scalar outputs fan out once per queued post or comment; items emits the full batch once. Requires moderator access.++### How it works+<!-- MANUAL: how_it_works -->+This block calls `sub.mod.modqueue(...)` for the target subreddit, forwarding the optional `only` filter and the `limit` value (bounded to 1–100 so a single run can't fan out into an unbounded chain of paginated Reddit calls). Each returned PRAW item is normalized into a predictable dictionary with a fullname ID, detected item type, title fallback for comments, author, permalink, and moderator reason.++The block emits every queue entry individually for fan-out workflows and also emits the full `items` list for batch processing. Because the `post_id` output keeps the Reddit fullname (`t1_...` or `t3_...`), downstream moderation blocks can safely act on comments and submissions without extra type checks.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| subreddit | Subreddit name, excluding the /r/ prefix | str | Yes |+| limit | Maximum number of items to fetch from the mod queue (1-100) | int | No |+| only | Filter to only submissions or only comments. Leave blank for both. | "submissions" \| "comments" | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| post_id | Full Reddit thing ID of a queued item, such as 't3_abc123' or 't1_xyz789' | str |+| item_type | Whether the queued item is a comment or submission | "comment" \| "submission" |+| post_title | Title of the queued item | str |+| author | Username of the author | str |+| permalink | Full Reddit permalink | str |+| reason | Mod queue reason (if any) | str |+| items | All queued items as a list. Emitted exactly once; an empty list signals that the queue was checked and had no items. | List[Dict[str, Any]] |++### Possible use case+<!-- MANUAL: use_case -->+**Queue Triage**: Pull the latest subreddit queue and route each item into approve, remove, or lock actions.++**Moderator Dashboards**: Feed queued items into summaries, alerts, or external review systems for human moderators.++**Policy Automation**: Filter only comments or only submissions when building specialized moderation pipelines.+<!-- END MANUAL -->++---+## Post Reddit Comment### What it is@@ -891,6 +1054,45 @@ This block uses the Reddit API via PRAW to fetch posts you've submitted to Reddi---+## Remove Reddit Post++### What it is+Removes a Reddit post or comment as a moderator. Requires 'modposts' scope. Reddit scopes are account-wide, so this grants the ability across every subreddit you moderate, not only the one set here.++### How it works+<!-- MANUAL: how_it_works -->+This block requires a prefixed Reddit thing ID (`t3_...` for a post, `t1_...` for a comment) and resolves it to the matching submission or comment before moderation; bare IDs are rejected because posts and comments share an ID namespace. It then calls `thing.mod.remove(...)`, forwarding the `spam` flag and the optional `mod_note`, which is capped at Reddit's 250-character moderator-note limit by the input schema.++The block returns the original `post_id` and a success flag so workflows can record or branch on the removal decision. Passing through the prefixed IDs emitted by `Mod Queue` lets the same flow moderate queued comments and submissions without extra conversion.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| post_id | Post or comment to remove. Full Reddit thing ID, prefixed with 't3_' for a post (e.g. 't3_abc123') or 't1_' for a comment (e.g. 't1_xyz789'). Bare IDs are rejected: posts and comments share an ID namespace, so an unprefixed ID cannot be resolved safely. | str | Yes |+| spam | Mark as spam (True) or just remove (False). Spam trains the filter. | bool | No |+| mod_note | Optional internal moderator note visible only to mods | str | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| post_id | ID of the removed post (pass-through) | str |+| success | Whether the removal succeeded | bool |++### Possible use case+<!-- MANUAL: use_case -->+**Spam Cleanup**: Remove obvious spam and optionally train Reddit's spam filter by marking it as spam.++**Comment Moderation**: Use fullnames from `Mod Queue` to remove problematic comments without additional lookup steps.++**Human-in-the-Loop Review**: Attach an internal moderator note when an automated rule removes borderline content.+<!-- END MANUAL -->++---+## Reply To Reddit Comment### What it is@@ -1045,6 +1247,46 @@ The block handles connection, authentication, and message delivery, returning a---+## Send Mod Mail++### What it is+Sends a modmail message from a subreddit to a user. Requires 'modmail' scope. Reddit scopes are account-wide, so this grants the ability across every subreddit you moderate, not only the one set here.++### How it works+<!-- MANUAL: how_it_works -->+This block opens the target subreddit and creates a modmail conversation via `sub.modmail.create(...)` using the provided recipient, subject, and body. Because it uses the subreddit modmail endpoint, the credential must include the `modmail` scope and moderator access to that community.++On success, the block returns the new conversation ID and `success=True`, which gives later steps a stable reference for logging or follow-up actions. Any Reddit API failure is surfaced through the standard `error` output.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| subreddit | Subreddit to send modmail from, excluding the /r/ prefix | str | Yes |+| to_username | Username to send the modmail to (without u/ prefix) | str | Yes |+| subject | Subject line of the modmail message | str | Yes |+| body | Body of the modmail message | str | Yes |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| conversation_id | ID of the created modmail conversation | str |+| success | Whether the modmail was sent | bool |++### Possible use case+<!-- MANUAL: use_case -->+**Appeal Responses**: Send official moderator replies when a user asks why content was removed or locked.++**Proactive Outreach**: Notify a user about rule issues before escalating to stronger moderation actions.++**Case Management**: Create modmail threads that can be referenced by later audit or follow-up steps.+<!-- END MANUAL -->++---+## Send Reddit Message### What it is@@ -1160,3 +1402,42 @@ The transcript text is returned as a single string, suitable for summarization,<!-- END MANUAL -->---++## Unban Subreddit User++### What it is+Unbans a user from a subreddit. Requires 'modcontributors' scope. Reddit scopes are account-wide, so this grants the ability across every subreddit you moderate, not only the one set here.++### How it works+<!-- MANUAL: how_it_works -->+This block opens the target subreddit with moderator credentials and calls `sub.banned.remove(username)` to remove the user from the community ban list. It requires the `modcontributors` scope, and on success it returns the `username`, `subreddit`, and `success=True` so the unban can be audited or chained into follow-up actions such as notifications.++Reddit is responsible for validating the username, subreddit, and moderator permissions. If the username is malformed, the subreddit is missing, or the credential does not have sufficient moderator access, the Reddit API error is surfaced through the block's standard `error` output. In practice, repeated unban attempts are typically safe to treat as idempotent workflow steps: if another moderator already removed the ban, the operation should be logged as a no-op for auditability, while transient API failures or rate limits should be retried with normal backoff before escalating to a human moderator.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| subreddit | Subreddit to unban the user from, excluding the /r/ prefix | str | Yes |+| username | Reddit username to unban (without the u/ prefix) | str | Yes |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| username | Unbanned username (pass-through) | str |+| subreddit | Subreddit (pass-through) | str |+| success | Whether the unban succeeded | bool |++### Possible use case+<!-- MANUAL: use_case -->+**Appeal Resolution**: Restore access after a moderator approves a user's ban appeal.++**Temporary Ban Expiry**: Pair scheduled workflows with unban actions when a manual review confirms the restriction should end.++**Moderator Remediation**: Correct mistaken bans and immediately hand the result to a notification step.+<!-- END MANUAL -->++---