Metadata-Version: 2.4
Name: outnoise
Version: 1.0.1
Summary: Official Python SDK for the Outnoise Developer
Keywords: outnoise,sdk,api,social
Classifier: Programming Language :: Python :: 3
Classifier: Intended Audience :: Developers
Classifier: Typing :: Typed
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Requires-Dist: httpx<1.0,>=0.24
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"

# outnoise-sdk

Official Python SDK for the **Outnoise Developer Platform** (formerly Chat X).

```python
from outnoise import Outnoise

client = Outnoise(api_key="YOUR_BOT_TOKEN")
print(client.users.me().username)
client.posts.create(content="Hello from Outnoise SDK!")
```

- Package name: `outnoise-sdk` · import name: `outnoise`
- Python 3.8+ · built on [httpx](https://www.python-httpx.org/) · synchronous **and** asynchronous clients
- Typed exceptions, automatic pagination, automatic rate-limit handling, mocked-HTTP test suite

---

## Installation

```bash
pip install outnoise-sdk
```

> The package is not published yet. Until it is, install it from this folder (see [Local development](#local-development)).

## Getting started

1. On Outnoise open the Developer Portal (`/developers`) and **create an application**.
2. In **Permissions** enable the scopes your code needs (for example `identify`, `posts.read`, `posts.write`).
3. Either create a **bot** (Bot tab → copy the bot token) or use **OAuth2** (OAuth2 tab → Client ID/Secret, add a redirect URL).
4. Install the SDK and make a request:

```python
import os
from outnoise import Outnoise

client = Outnoise(api_key=os.environ["OUTNOISE_API_KEY"])      # never hard-code credentials

me = client.users.me()                         # scope: identify
posts = client.posts.list(limit=10)            # scope: posts.read
post = client.posts.create(content="Hello from Outnoise SDK!")   # scope: posts.write
groups = client.groups.list(limit=10)          # scope: groups.read
analytics = client.analytics.overview()        # scope: analytics.read
```

Responses are dictionaries that also allow attribute access: `me.username` and `me["username"]` both work.

## Authentication

| You pass | Sent as | Acts as | Scopes |
|---|---|---|---|
| `api_key="…"` (bot token) | `Authorization: Bot …` | your application's bot account | every scope enabled for the application |
| `access_token="…"` (OAuth2) | `Authorization: Bearer …` | the user who authorized your app | the scopes that user approved |

```python
bot  = Outnoise(api_key="onbt_…")
user = Outnoise(access_token="onat_…")
```

Pass **either** one, not both. Both can also come from the environment:

| Variable | Meaning |
|---|---|
| `OUTNOISE_API_KEY` | bot token |
| `OUTNOISE_ACCESS_TOKEN` | OAuth2 access token |
| `OUTNOISE_BASE_URL` | API address, e.g. `http://127.0.0.1:8000/api/v1` |

```python
client = Outnoise()          # reads OUTNOISE_API_KEY / OUTNOISE_ACCESS_TOKEN / OUTNOISE_BASE_URL
```

### Getting an OAuth2 access token

Send the user to `https://<your-outnoise-host>/oauth2/authorize?client_id=APP_ID&response_type=code&redirect_uri=…&scope=identify%20posts.read&state=…`,
then exchange the returned `code` **on your server** (the client secret must never reach a browser):

```python
import httpx

tokens = httpx.post("https://<your-outnoise-host>/oauth2/token", data={
    "grant_type": "authorization_code", "code": code, "redirect_uri": "https://example.com/callback",
    "client_id": APP_ID, "client_secret": CLIENT_SECRET,
}).json()

client = Outnoise(access_token=tokens["access_token"])
```

Access tokens expire after 1 hour; renew with `grant_type=refresh_token`. Full details: `/developers/documentation/authentication`.

## Available resources

| Resource | Methods | Scope |
|---|---|---|
| `client.applications` | `me()` | – |
| `client.users` | `me()`, `get(username)` | `identify`, `profile.read` |
| `client.posts` | `list(limit, offset, author)`, `iter(...)`, `get(id)`, `create(content, visibility, images, feeling)` | `posts.read`, `posts.write` |
| `client.groups` | `list(limit, offset, mine)`, `iter(...)`, `get(id)` | `groups.read` |
| `client.events` | `list(limit, offset, include_past)`, `iter(...)` | `events.read` |
| `client.messages` | `list(user, limit, offset)`, `iter(user)`, `send(recipient, content)` | `messages.read`, `messages.write` |
| `client.analytics` | `overview(days=28)` | `analytics.read` |

Notes: `visibility` is `public`, `followers`, `unlisted` or `private`. Bots may only direct-message users who authorized the application or messaged the bot first. Methods raise `ValueError` for bad arguments before any request is made.

## Pagination

List methods return a `Page` (a normal list with paging info):

```python
page = client.posts.list(limit=10)
print(len(page), page.has_more, page.next_offset)
page2 = client.posts.list(limit=10, offset=page.next_offset)
```

or iterate over everything — pages are fetched lazily:

```python
for post in client.posts.iter(author="alice", page_size=50, max_items=200):
    print(post.content)
```

## Error handling

```python
from outnoise import (Outnoise, OutnoiseError, AuthenticationError, MissingScopeError, NotFoundError,
                      RateLimitError, APIConnectionError)

try:
    client.posts.create(content="hi")
except MissingScopeError as e:
    print("Enable these scopes:", e.required_scopes)
except AuthenticationError:
    print("Bad, expired or revoked credentials")
except RateLimitError as e:
    print("Slow down, retry in", e.retry_after, "seconds")
except NotFoundError:
    ...
except APIConnectionError:
    print("Could not reach Outnoise")
except OutnoiseError as e:      # catches everything from this package
    print(e)                    # e.g. "[400 content_too_long] Content too long (max 2500 characters)."
```

| Exception | When |
|---|---|
| `ConfigurationError` | missing/conflicting credentials, bad `base_url` |
| `APIConnectionError` / `APITimeoutError` | network failure / timeout |
| `InvalidRequestError` (400) | the API rejected the request |
| `AuthenticationError` (401) | invalid, expired or revoked token |
| `PermissionDeniedError` (403), `MissingScopeError` | not allowed / missing scope |
| `NotFoundError` (404) | unknown or invisible resource |
| `RateLimitError` (429) | rate limit exceeded (`.retry_after`) |
| `ServerError` (5xx) | server problem |

Every API error has `.status_code`, `.code`, `.message`, `.body` and `.headers`.

### Rate limits and retries

The API limits each token (reads 120/min, writes 30/min, messages 20/min). The SDK automatically:

- retries `429` responses after the `Retry-After` delay (also for `POST`, because a rate-limited request was not processed);
- retries `GET` requests on connection errors, timeouts and 502/503/504 with exponential backoff.

Control it with `Outnoise(max_retries=2, max_retry_wait=30)`; `max_retries=0` turns retrying off. If the server asks for a longer wait than `max_retry_wait`, `RateLimitError` is raised immediately.

## Async usage

```python
import asyncio
from outnoise import AsyncOutnoise

async def main():
    async with AsyncOutnoise(api_key="YOUR_BOT_TOKEN") as client:
        me = await client.users.me()
        post = await client.posts.create(content="Hello from async!")
        async for p in client.posts.iter(max_items=100):
            print(p.content)

asyncio.run(main())
```

`AsyncOutnoise` has the same resources and options; every call is awaited and `iter()` is used with `async for`.

## Configuration

```python
client = Outnoise(
    api_key="…",
    base_url="http://127.0.0.1:8000/api/v1",   # custom API address (local testing, staging)
    timeout=30,                                # seconds
    max_retries=2,
)
```

The built-in default address is the beta deployment (`https://beta-chatx.hostmybotprojects.net/api/v1`). Change `DEFAULT_BASE_URL` in `src/outnoise/_base.py`, or pass `base_url` / `OUTNOISE_BASE_URL`, when you use another host. You can also hand over your own `httpx.Client` / `httpx.AsyncClient` with `http_client=` (proxies, custom transports).

## Local development

Install in editable mode — no PyPI needed:

```bash
cd outnoise-sdk
python -m venv .venv && source .venv/bin/activate      # Windows: .venv\Scripts\activate
pip install -e ".[dev]"
```

Test it against your local Outnoise backend (use a **test** account/application, never production credentials):

```python
from outnoise import Outnoise
client = Outnoise(api_key="TEST_KEY", base_url="http://127.0.0.1:8000/api/v1")
print(client.users.me())
```

(`python app.py` in the Outnoise project serves on port 3002 by default, so the local URL is usually `http://127.0.0.1:3002/api/v1`.)

## Testing

```bash
pytest
```

The suite uses `httpx.MockTransport`, so it needs **no network and no credentials**. It covers authentication, request building, invalid credentials, API errors, pagination, rate limits, custom base URLs, every resource method and the async client.
`tests/test_live_backend.py` is an optional integration test that is skipped unless `OUTNOISE_TEST_BASE_URL` and `OUTNOISE_TEST_API_KEY` point at a local test backend.

## Security

- Keep bot tokens and client secrets in environment variables or a secrets manager — never in source control, browsers or mobile apps.
- Resetting a token or secret in the Developer Portal invalidates the old one immediately.
- Credentials are never included in exception messages or `repr()` output.
