Skip to content

Self-improving AI Employees for everyone

3.0 KB
Raw Blame
"""Twitter Receive — Wave 11.C migration (polling trigger).

Nothing polls Twitter for this node yet: it is not a
``PollingTriggerNode`` and its dispatcher (``_events.dispatch_twitter_event_received``)
has no caller, so a deployed one never fired and a canvas Run waited
forever. Until a poller exists, Start refuses it (``validate_graph``) and
a canvas Run answers with the reason (RFC-0005 Phase 0.8).
"""

from __future__ import annotations

from typing import Any, Dict, Literal, Optional

from pydantic import BaseModel, ConfigDict, Field

import time

from services.plugin import NodeContext, NodeUserError, Operation, TaskQueue, TriggerNode

from .._credentials import TwitterCredential

_UNAVAILABLE = (
    "Twitter Receive cannot run yet: nothing polls Twitter for it, so it would never fire. "
    "To act on new tweets, run Twitter Search from a Cron Scheduler."
)


class TwitterReceiveParams(BaseModel):
    trigger_type: Literal["mentions", "search", "timeline"] = Field(
        default="mentions",
    )
    search_query: str = Field(default="")
    user_id: str = Field(default="")
    filter_retweets: bool = Field(default=True)
    filter_replies: bool = Field(default=False)
    poll_interval: int = Field(default=60, ge=15, le=3600)

    model_config = ConfigDict(extra="ignore")


class TwitterReceiveOutput(BaseModel):
    tweet_id: Optional[str] = None
    text: Optional[str] = None
    author: Optional[str] = None

    model_config = ConfigDict(extra="allow")


class TwitterReceiveNode(TriggerNode):
    type = "twitterReceive"
    display_name = "Twitter Receive"
    subtitle = "Mentions / DMs"
    group = ("social", "trigger")
    description = "Trigger workflow on Twitter mentions, search results, or timeline updates (polling-based)"
    component_kind = "trigger"
    # Wave 11.I, milestone K: ``event_type`` ClassVar lets
    # ``event_waiter._auto_populate_from_plugins`` backfill
    # TRIGGER_REGISTRY without a hardcoded entry in event_waiter.
    event_type = "twitter_event_received"
    handles = ({"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},)
    credentials = (TwitterCredential,)
    task_queue = TaskQueue.TRIGGERS_POLL
    mode = "polling"
    default_poll_interval = 60

    Params = TwitterReceiveParams
    Output = TwitterReceiveOutput

    @classmethod
    def validate_graph(cls, node_id: str, graph: Dict[str, Any]) -> list[Dict[str, Any]]:
        return [{"code": "TWITTER_RECEIVE_UNAVAILABLE", "node_id": node_id, "message": _UNAVAILABLE}]

    async def execute(
        self,
        node_id: str,
        parameters: Dict[str, Any],
        context: NodeContext,
    ) -> Dict[str, Any]:
        error = NodeUserError(_UNAVAILABLE)
        return self._wrap_error(start_time=time.time(), error=str(error), error_type="NodeUserError", extra=error.as_dict())

    @Operation("wait")
    async def wait(self, ctx: NodeContext, params: TwitterReceiveParams) -> TwitterReceiveOutput:
        raise NotImplementedError("Polling trigger uses execute() override")