Skip to content

Instantly share code, notes, and snippets.

@bugb
Last active December 27, 2023 10:06
Show Gist options
  • Save bugb/9c8d43a965cab3ccf2f67ee7b1c972c0 to your computer and use it in GitHub Desktop.
Save bugb/9c8d43a965cab3ccf2f67ee7b1c972c0 to your computer and use it in GitHub Desktop.
How to list all public channels in a Slack workspace using API?

1. Set up a Slack App:

Go to the Slack App Management page. Click on "Create New App" and follow the instructions to set up your app.

2. Install App to Workspace:

After creating the app, install it to your workspace. Get OAuth Access Token: Once installed, you'll receive an OAuth access token. This token will be used to authenticate your requests.

3. Run the Python scripts:

import requests
import time

token = "YOUR_SLACK_APP_OAUTH_TOKEN"
url = "https://slack.com/api/conversations.list"

headers = {
    "Content-Type": "application/json; charset=utf-8",
    "Authorization": f"Bearer {token}"
}

params = {
    "limit": 1000,  # Adjust the limit based on your needs
    "type": "public_channel",
    "exclude_archived": True,
}

def get_all_chanels():
    c = set()
    while True:
        response = requests.post(url, headers=headers, params=params)
        data = response.json()
        while not data["ok"]:
            time.sleep(int(response.headers['Retry-After']) + 1)
            response = requests.post(url, headers=headers, params=params)
            data = response.json()
            if data["ok"]:
                break

        if "channels" not in data:
            break
        channels = data["channels"]
        for channel in channels:
            chn_item = (f"{channel['name']}", f"{channel['id']}")
            c.add(chn_item)

        # Check if there is another page
        if "response_metadata" in data and "next_cursor" in data["response_metadata"]:
            params["cursor"] = data["response_metadata"]["next_cursor"]
        else:
            break
    return c

c = get_all_chanels()
sort_c = sorted(c)
lines = [','.join(tup) for tup in sort_c]

print("Channel Name, Channel ID")
for line in lines:
    print(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment