チャンネルの数が異常に増えて,一度チャンネル一覧を出力したいと思ったのでそのまとめ.
以前はSlack APIを使用できるようにした.
参考資料
https://github.com/slackapi/python-slackclient
https://api.slack.com/methods/conversations.list
https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/
環境
MacOS Mojave 10.14.5
Python3.7
slackclient 2.0.1
準備
以前の手順を踏んでいるのが前提.
Appに以下のスコープを付与(conversations_listを使用するため).
- channels: read
- groups: read
- im: read
- mpim: read
使用する関数ごとにAppに与えるべきスコープの範囲が異なるので,必要に応じてslack公式のリファレンスから参照して設定すること.
まずはスラックチャンネルの一覧を取得する.
def get_channels(client):
channels = client.conversations_list(limit=1000)
if channels['ok']:
return channels['channels']
else:
assert channels['ok']
return None
JSON形式での保存
json_data = json.dumps(channels)
with open("channel_list.json", 'w') as fp:
json.dump(channels, fp)
CSV形式での保存
一度取得したチャンネルをDataFrame形式にしてからCSVへ変換
python
df = pd.DataFrame(channels, columns=channels[0].keys())
df.to_csv("channel_list.csv")
ソースコード
import os # 環境変数取得のため
import slack # SlackAPIの使用
import json # json形式で保存
import pandas as pd # csv形式で保存
# チャンネルの取得
def get_channels(client):
channels = client.conversations_list(limit=1000)
if channels['ok']:
return channels['channels']
else:
assert channels['ok']
return None
if __name__ == '__main__':
cli = slack.WebClient(token=os.environ['SLACK_API_TOKEN'])
channels = get_channels(cli)
json_data = json.dumps(channels)
with open("channel_list.json", 'w') as fp:
json.dump(channels, fp)
df = pd.DataFrame(channels, columns=channels[0].keys())
df.to_csv("channel_list.csv")