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

# リストとコミュニティ

Sorsa APIで、公開Xリストのメンバー、フォロワー、ツイートフィードを取得します。このページでは、APIリファレンスにあるコミュニティのリクエスト形式も説明します。新しいワークフローで使う前に、提供状況の注記を確認してください。

> **注：** 戦略的な背景、費用の計算、監視の全体像は、ブログの[X List APIガイド](https://api.sorsa.io/blog/x-lists-and-communities-api)を参照してください。

> **コミュニティの提供状況：** APIリファレンスにはコミュニティのエンドポイントが掲載されていますが、現在取得できるデータの確認が必要です。新しい仕組みを作る前に[サポートへ連絡](https://docs.sorsa.io/ja/support)し、利用できる操作と結果を確認してください。以下の例はインターフェースの説明であり、現在の稼働確認ではありません。

***

## リスト

Xリストは、最大5,000アカウントをまとめた公開の一覧です。2種類のユーザーが関わります。

* **メンバー：** 作成者がリストに追加したアカウント。
* **フォロワー（購読者）：** リストのタイムラインを読むためにフォローしたユーザー。

非公開リストにはAPIからアクセスできません。

| エンドポイント              | メソッド | 戻り値                     | ページサイズ |
| :------------------- | :--- | :---------------------- | :----- |
| `/v3/list-members`   | GET  | リスト内のアカウントのプロフィール       | 最大200  |
| `/v3/list-followers` | GET  | リストをフォローするアカウントのプロフィール  | 最大200  |
| `/v3/list-tweets`    | GET  | リストのメンバーの投稿をまとめた時系列フィード | 約20    |

リストIDはURL内の数値です。`https://x.com/i/lists/1234567890`ならIDは`1234567890`です。

> **ヒント：** 全アカウントにカード不要・有効期限なしの無料100リクエストがあり、中規模のリストを全体取得できます。[API Playground](https://api.sorsa.io/playground)ではコードなしで試せます。

### リストのメンバーを取得する

`GET /v3/list-members`

| パラメーター        | 型      | 必須  | 説明                    |
| :------------ | :----- | :-- | :-------------------- |
| `list_id`     | string | はい  | 数値のリストID。             |
| `next_cursor` | string | いいえ | 前のレスポンスのページネーションカーソル。 |

```bash theme={null}
curl "https://api.sorsa.io/v3/list-members?list_id=1234567890" \
  -H "ApiKey: YOUR_API_KEY"
```

```python theme={null}
import requests

API_KEY = "YOUR_API_KEY"
BASE = "https://api.sorsa.io/v3"
HEADERS = {"ApiKey": API_KEY}


def get_list_members(list_id, max_pages=50):
    members, cursor = [], None

    for _ in range(max_pages):
        params = {"list_id": list_id}
        if cursor:
            params["next_cursor"] = cursor

        r = requests.get(f"{BASE}/list-members", headers=HEADERS, params=params, timeout=30)
        r.raise_for_status()
        data = r.json()

        members.extend(data.get("users", []))
        cursor = data.get("next_cursor")
        if not cursor:
            break

    return members


members = get_list_members("1234567890")
for u in members[:5]:
    print(f"@{u['username']} ({u['followers_count']:,} followers)")
```

5,000メンバーのリスト全体は約25リクエストで取得できます。

### リストのフォロワーを取得する

`GET /v3/list-followers`

| パラメーター        | 型      | 必須  | 説明              |
| :------------ | :----- | :-- | :-------------- |
| `list_link`   | string | はい  | リストのURLまたは数値ID。 |
| `next_cursor` | string | いいえ | ページネーションカーソル。   |

パラメーター名に注意してください。`/list-followers`は`list_link`（URLまたはID）を使い、`/list-members`と`/list-tweets`は`list_id`（数値IDのみ）を使います。

```python theme={null}
def get_list_followers(list_link, max_pages=50):
    followers, cursor = [], None

    for _ in range(max_pages):
        params = {"list_link": list_link}
        if cursor:
            params["next_cursor"] = cursor

        r = requests.get(f"{BASE}/list-followers", headers=HEADERS, params=params, timeout=30)
        r.raise_for_status()
        data = r.json()

        followers.extend(data.get("users", []))
        cursor = data.get("next_cursor")
        if not cursor:
            break

    return followers


subs = get_list_followers("https://x.com/i/lists/1234567890")
print(f"{len(subs)} subscribers")
```

### リストのツイートを取得する

`GET /v3/list-tweets`

全メンバーの最近の投稿を1つの時系列フィードで返します。[リアルタイム監視](https://docs.sorsa.io/ja/real-time-monitoring)では、アカウントを個別に確認する代わりに、1リクエストでグループを追跡するために使います。

| パラメーター        | 型      | 必須  | 説明            |
| :------------ | :----- | :-- | :------------ |
| `list_id`     | string | はい  | 数値のリストID。     |
| `next_cursor` | string | いいえ | ページネーションカーソル。 |

```python theme={null}
def get_list_tweets(list_id, max_pages=10):
    tweets, cursor = [], None

    for _ in range(max_pages):
        params = {"list_id": list_id}
        if cursor:
            params["next_cursor"] = cursor

        r = requests.get(f"{BASE}/list-tweets", headers=HEADERS, params=params, timeout=30)
        r.raise_for_status()
        data = r.json()

        tweets.extend(data.get("tweets", []))
        cursor = data.get("next_cursor")
        if not cursor:
            break

    return tweets


feed = get_list_tweets("1234567890", max_pages=10)
for t in feed[:5]:
    print(f"@{t['user']['username']}: {t['full_text'][:80]}")
```

***

## コミュニティ

以下は、APIリファレンスのコミュニティ用リクエスト形式です。利用前に、上記の注記に従って提供状況を確認してください。

メンバーデータが利用できれば、参加情報はオーディエンスを探す手がかりになります。ただし参加だけでは最近の活動状況は分かりません。

| エンドポイント                       | メソッド | 戻り値               | ページサイズ |
| :---------------------------- | :--- | :---------------- | :----- |
| `/v3/community-members`       | POST | コミュニティのメンバープロフィール | 約20    |
| `/v3/community-tweets`        | POST | コミュニティ内のツイート      | 約20    |
| `/v3/community-search-tweets` | POST | コミュニティ内のキーワード検索   | 約20    |

コミュニティIDはURL内の数値です。`https://x.com/i/communities/1966045657589813686`ならIDは`1966045657589813686`です。

非公開コミュニティはAPIからアクセスできませんでした。

### コミュニティのメンバーを取得する

`POST /v3/community-members`

| パラメーター           | 型      | 必須  | 説明                 |
| :--------------- | :----- | :-- | :----------------- |
| `community_link` | string | はい  | コミュニティIDまたは完全なURL。 |
| `next_cursor`    | string | いいえ | ページネーションカーソル。      |

簡略プロフィール（ID、ユーザー名、表示名、アバター、認証状態、非公開状態）を返します。

```python theme={null}
def get_community_members(community_link, max_pages=20):
    members, cursor = [], None

    for _ in range(max_pages):
        body = {"community_link": community_link}
        if cursor:
            body["next_cursor"] = cursor

        r = requests.post(
            f"{BASE}/community-members",
            headers={**HEADERS, "Content-Type": "application/json"},
            json=body,
            timeout=30,
        )
        r.raise_for_status()
        data = r.json()

        members.extend(data.get("users", []))
        cursor = data.get("next_cursor")
        if not cursor:
            break

    return members
```

### コミュニティのツイートを取得する

`POST /v3/community-tweets`

| パラメーター         | 型      | 必須  | 説明                               |
| :------------- | :----- | :-- | :------------------------------- |
| `community_id` | string | はい  | 数値のコミュニティID。                     |
| `order`        | string | いいえ | `"latest"`（デフォルト）または`"popular"`。 |
| `next_cursor`  | string | いいえ | ページネーションカーソル。                    |

```python theme={null}
def get_community_tweets(community_id, order="latest", max_pages=10):
    tweets, cursor = [], None

    for _ in range(max_pages):
        body = {"community_id": community_id, "order": order}
        if cursor:
            body["next_cursor"] = cursor

        r = requests.post(
            f"{BASE}/community-tweets",
            headers={**HEADERS, "Content-Type": "application/json"},
            json=body,
            timeout=30,
        )
        r.raise_for_status()
        data = r.json()

        tweets.extend(data.get("tweets", []))
        cursor = data.get("next_cursor")
        if not cursor:
            break

    return tweets
```

### コミュニティ内のツイートを検索する

`POST /v3/community-search-tweets`

| パラメーター           | 型      | 必須  | 説明                          |
| :--------------- | :----- | :-- | :-------------------------- |
| `community_link` | string | はい  | コミュニティIDまたは完全なURL。          |
| `query`          | string | いいえ | 検索キーワード。省略するとコミュニティ全体のフィード。 |
| `order`          | string | いいえ | `"popular"`または`"latest"`。   |
| `next_cursor`    | string | いいえ | ページネーションカーソル。               |

```python theme={null}
def search_community_tweets(community_link, query, order="popular", max_pages=5):
    tweets, cursor = [], None

    for _ in range(max_pages):
        body = {"community_link": community_link, "query": query, "order": order}
        if cursor:
            body["next_cursor"] = cursor

        r = requests.post(
            f"{BASE}/community-search-tweets",
            headers={**HEADERS, "Content-Type": "application/json"},
            json=body,
            timeout=30,
        )
        r.raise_for_status()
        data = r.json()

        tweets.extend(data.get("tweets", []))
        cursor = data.get("next_cursor")
        if not cursor:
            break

    return tweets
```

全メンバーをページネーションで取得せず、個別の参加確認だけを行う場合は、専用の[`/check-community-member`](https://docs.sorsa.io/ja/api-reference/verification/check-community-membership)を使ってください。

***

## CSVに出力する

上記のリスト用エンドポイントのユーザー・ツイートフィードは、1つのヘルパーで出力できます。ユーザーの例：

```python theme={null}
import csv

def export_users_to_csv(users, path):
    fields = ["id", "username", "display_name", "description",
              "followers_count", "tweets_count", "verified", "location"]

    with open(path, "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=fields)
        writer.writeheader()
        for u in users:
            writer.writerow({
                "id": u.get("id", ""),
                "username": u.get("username", ""),
                "display_name": u.get("display_name", ""),
                "description": (u.get("description") or "").replace("\n", " "),
                "followers_count": u.get("followers_count", 0),
                "tweets_count": u.get("tweets_count", 0),
                "verified": u.get("verified", False),
                "location": u.get("location", ""),
            })


export_users_to_csv(get_list_members("1234567890"), "members.csv")
```

`/list-members`と`/list-followers`は`users`にプロフィールを返します。`/list-tweets`は`tweets`にツイートを返し、投稿者は`user`に入ります。任意のプロフィール項目は空の場合があります。ツイートを出力するときは、`{"username": tweet["user"]["username"]}`のように、ネストを明示的に平坦化してください。CSV出力処理は`user.username`のようなドット区切り名を自動で解釈しません。

***

## 関連ガイド

* [X List APIガイド](https://api.sorsa.io/blog/x-lists-and-communities-api)：戦略、費用の計算、活用例
* [リアルタイム監視](https://docs.sorsa.io/ja/real-time-monitoring)：`/list-tweets`の定期取得
* [ターゲット層の発見](https://docs.sorsa.io/ja/target-audiences-Discovery)：リストを使ったオーディエンス調査
* [マーケティングキャンペーンの確認](https://docs.sorsa.io/ja/Marketing-Campaign-Verification)：メンバー資格の確認
* [API利用の最適化](https://docs.sorsa.io/ja/optimizing-api-usage)：バッチ処理とレート制限対応
