> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cowboy.inc/llms.txt
> Use this file to discover all available pages before exploring further.

# Bring existing code

> Turn a script or service you already have into an actor you can sell, by sorting each part into the actor, runner jobs and secrets

By the end of this page, you'll know where each part of an existing script or service goes on Cowboy, and you'll have seen a cron script turned into an actor that does the same job on its own.

Most of your logic carries over as it is. What changes is the edges: how the code is started, how it reaches the network, where it keeps its keys, and where it stores what it learns.

## Where each part goes

An actor holds the rules and the records, and it runs the same way on every machine that checks it. That's why it can't reach the network, read the clock or open a file itself. A **runner**, a machine that does work for actors, makes those calls for it and hands back the answer.

| In your code | On Cowboy |
| - | - |
| A cron job, a loop or a timer | A schedule in the actor, with `@every` or `runtime.schedule_after` |
| A request to a web API | A runner job, `await runner.http(...)` |
| A call to a model | A runner job, `await runner.llm(...)` |
| An API key in an environment variable or `.env` | The secret store, marked with `runner.secret(...)` |
| A database table or a JSON file | The actor's state, which is public, or a private volume |
| A config file | State, set by an owner-only handler |
| A function that answers requests | A handler |
| Heavy computation, or a library like pandas | An off-chain function |
| A server that must stay up at a URL | A workload |

[Where your code runs](https://docs.cowboy.inc/build/where-your-code-runs.md) explains the last two.

## Before: a cron script

Here's a typical starting point. Once an hour, cron runs a script that reads a key from the environment, asks an API for an account's follower count, and appends it to a file:

```python theme={"system"}
import json
import os
import time

import requests

API_KEY = os.environ["EXAMPLE_API_KEY"]
ACCOUNT = "cowboy"


def main() -> None:
    reply = requests.get(
        "https://api.example.com/v1/accounts/" + ACCOUNT,
        headers={"Authorization": "Bearer " + API_KEY},
        timeout=30,
    )
    reply.raise_for_status()
    with open("counts.json") as f:
        counts = json.load(f)
    counts.append({"followers": reply.json()["followers"], "at": time.time()})
    with open("counts.json", "w") as f:
        json.dump(counts[-100:], f)


if __name__ == "__main__":
    main()
```

It needs a machine that stays on, a crontab entry, and the key on that machine. Sorted with the table above:

* cron becomes `@every(HOUR)`
* `requests.get` becomes `runner.http`
* `os.environ["EXAMPLE_API_KEY"]` becomes `runner.secret("EXAMPLE_API_KEY", ...)`
* `counts.json` becomes the actor's state
* `ACCOUNT` becomes state too, set by a handler only the owner can call

## After: an actor

Create a project next to your code with `cowboy init follower_tracker`, and replace `actors/follower_tracker/main.py` with:

```python theme={"system"}
from cowboy_sdk import HOUR, OWNER, Actor, JobFailed, callable_by, every, public, runner, runtime

ACCOUNT_URL = "https://api.example.com/v1/accounts/"
MAX_COUNTS = 100


class TrackerActor(Actor):
    @public
    def init(self, payload: bytes | None = None) -> None:
        self.storage["account"] = None
        self.storage["counts"] = []

    @callable_by(OWNER)
    def track(self, account: object) -> None:
        if not isinstance(account, str) or not account.isalnum():
            raise ValueError("send an account name")
        self.storage["account"] = account
        self.storage["counts"] = []
        every.start(self.check)

    @every(HOUR)
    @runner.continuation(timeout=HOUR)
    async def check(self) -> None:
        try:
            reply = await runner.http(
                url=ACCOUNT_URL + self.storage["account"],
                method="GET",
                headers={
                    "Authorization": runner.secret("EXAMPLE_API_KEY", prefix="Bearer ")
                },
            )
        except JobFailed:
            return
        if not isinstance(reply.data, dict) or "followers" not in reply.data:
            return
        counts = self.storage["counts"]
        counts.append({"followers": reply.data["followers"], "at_ms": runtime.get_timestamp_ms()})
        self.storage["counts"] = counts[-MAX_COUNTS:]

    @public
    def counts(self, _payload: object) -> object:
        return self.storage["counts"]
```

The logic is the same. What moved:

* **Starting it.** `track` sets the account and starts the hourly schedule. After that, `check` runs every hour with nothing on your side, and the actor pays for each run from its balance.
* **The request.** `await runner.http(...)` hands the request to a runner, and `check` picks up from the same line when the answer arrives. The time comes from `runtime.get_timestamp_ms()`, not `time.time()`.
* **The key.** It's in the secret store, and the job carries only `"Bearer "` and the key's name ([Call an API with a key](https://docs.cowboy.inc/sell/call-an-api-with-a-secret.md)).
* **The file.** `counts` lives in the actor's state, which anyone can read and anyone can query through the `counts` handler. Keep private data in a private volume instead ([An actor's files](https://docs.cowboy.inc/build/sdk/files.md)).

Some code carries over only after a change. A handler can't loop over `await`s, so a script that calls an API once per item either makes one call that returns them all, or handles one item per run. And code that depends on randomness or the current time has to get them from the SDK ([What actor code can and can't do](https://docs.cowboy.inc/build/sdk/determinism.md)).

## Test it the same way

Your old tests probably mocked `requests`. On Cowboy, a test plays the API's part: it moves time forward, sees the job the actor sent, and answers it. Replace `tests/test_follower_tracker.py` with:

```python theme={"system"}
from cowboy_sdk import codec, mock_host
from cowboy_sdk.testing import SimulatedChain

from actors.follower_tracker import main


def test_hourly_check_records_followers() -> None:
    actor = main.TrackerActor()
    chain = SimulatedChain(actor)
    mock_host.seed_actor_owner(mock_host.context()["sender"])
    chain.call(actor.init)
    chain.call(actor.track, codec.encode("cowboy"))
    assert chain.jobs() == []
    chain.advance_block(3600)
    job = chain.jobs()[-1]["payload"]["kwargs"]
    assert job["url"] == main.ACCOUNT_URL + "cowboy"
    assert [slot["key"] for slot in job["secret_slots"]] == ["EXAMPLE_API_KEY"]
    chain.reply({"followers": 42})
    counts = codec.decode(chain.call(actor.counts))
    assert [c["followers"] for c in counts] == [42]
```

```bash theme={"system"}
cowboy test
```

```text Output theme={"system"}
============================== 1 passed in 0.11s ===============================
```

`chain.advance_block(3600)` moves time forward an hour, about one second a block, so the schedule fires once.

## Then ship it

From here, it's the same path as any actor: deploy it with the API's host in its manifest, add the key, then package and submit it. The [walkthrough](https://docs.cowboy.inc/sell/social-metrics-walkthrough.md#6-deploy-it-with-web-access) shows each step.

## Next

* [Walkthrough: sell a social metrics product](https://docs.cowboy.inc/sell/social-metrics-walkthrough.md)
* [Call an API with a key](https://docs.cowboy.inc/sell/call-an-api-with-a-secret.md)
* [Where your code runs](https://docs.cowboy.inc/build/where-your-code-runs.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.