2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

プライベートチャンネルを含む、Slackのチャンネルをテキストファイルにするツールを作ってみた。

Last updated at Posted at 2023-04-28

Slackのチャンネルをテキストファイルとして出力出来たら、データを保存したり、分析できて、便利なのにと思っていました。

そこで、プライベートチャンネルを含む、Slack botがいる全てのチャンネルの全ての投稿をチャンネル名のテキストファイルを作成して、保存するツールを作成してみました。

このツールは、処理もすぐ終わり、実行中にする必要もないので、今回はGoogle colabで使用出来る方法を記載します。

手順は以下です。
⒈Slack APIのダッシュボードで botを作成して、スコープを設定してBot User OAuth Tokenを取得する
⒉テキスト化するチャンネルに botを入れてプログラムを実行する

⒈Slack APIのダッシュボードで botを作成して、スコープを設定してBot User OAuth Tokenを取得する

まず、 botのアプリを作成します。
テキスト化したいチャンネルのあるワークスペースにログインしてから、Slack APIのダッシュボードにアクセスして、ページの上の方にある緑の「Create New App」のボタンを押します。
開いたメニューで、from scratchの方を選択します。アプリ名は好きな名前、ワークスペースはテキスト化したいチャンネルのあるワークスペースにして、Create Appを押します。

アプリが出来たら、左のメニューからOAuth & Permissionsを押します。
OAuth & Permissionsのページが開いたら、Bot Token Scopesのところまで下にスクロールして、以下のスコープを設定します。

必要なスコープ
channels:read,groups:read,mpim:read,im:read
channels:history,groups:history,mpim:history,im:history

スコープを設定したら、上にスクロールして、OAuth Tokens for Your Workspaceからアプリをワークスペースにインストールします。
アプリをインストールしたら、OAuth Tokens for Your Workspaceの欄にBot User OAuth Tokenが生成されるので、こちらをコピーしてメモします。

これで、Slack APIのダッシュボードで botを作成して、スコープを設定してBot User OAuth Tokenを取得する、は完了です!

⒉テキスト化するチャンネルに botを入れてプログラムを実行する

まず、先程作成した botをSlackのテキスト化したいチャンネルに入れてください。

次にGoogle colabを開き、新規ノートブックを作成します。

新規ノートブックを開いたらGoogle colabからGoogle ドライブにアクセスして、ファイルを保存出来るように以下の操作を行います。

ファイルを開く
写真の赤枠のマークを押す。
ECEC3A64-9001-4920-BBB8-BB2D6042E2F0.jpeg

Googleドライブをマウントする
写真の赤枠のマークを押す。メニューが開いたら、ドライブに接続を押す。
75EE7CC2-6328-4BFC-99DB-EE8025D72621.jpeg

ここまで出来たら、コードを入れていきます。

まず、Slack sdkをインストールします。

!pip install slack-sdk

次に以下のコードに保存先のディレクトリと先程取得したBot User OAuth Tokenを入れます。保存先のディレクトリが存在しない場合、指定したパスにディレクトリが作成されます。
因みにGoogleドライブのパス指定は、「/content/drive/MyDrive/フォルダ名」という風になります。写真のようにフォルダの横の縦3つの点のマークを押してパスを確認することも出来ます。
1AE99D8B-6C72-49D0-B57A-FFEBD97B73AA.jpeg

import os
import json
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

# 保存先ディレクトリを指定
output_directory = "path/to/your/output_directory"

# Slack APIトークンを取得
SLACK_API_TOKEN = "SLACK_API_TOKEN"  # Slack botのトークンを入れる
client = WebClient(token=SLACK_API_TOKEN)

# 保存先ディレクトリが存在しない場合は作成
os.makedirs(output_directory, exist_ok=True)

def fetch_all_messages(channel_id):
    messages = []
    cursor = None

    while True:
        try:
            response = client.conversations_history(channel=channel_id, cursor=cursor)
            messages.extend(response["messages"])
            cursor = response.get("response_metadata", {}).get("next_cursor")

            if not cursor:
                break

        except SlackApiError as e:
            print(f"Error getting conversation history: {e}")
            break

    return messages

# 普通のチャンネルからダウンロード
try:
    # チームのチャンネル一覧を取得する
    response = client.conversations_list()

    # 各チャンネルの投稿を保存するためのファイルを作成する
    for channel in response["channels"]:
        channel_name = channel["name"]
        channel_id = channel["id"]
        file_name = f"{output_directory}/{channel_name}.txt"

        # チャンネルの投稿を取得し、ファイルに書き込む
        messages = fetch_all_messages(channel_id)

        # 投稿内容を保存するためのファイルを開く
        with open(f"{output_directory}/{channel_name}.txt", "w", encoding="utf-8") as f:
            for message in messages:
                # メッセージがテキストであれば、そのテキストをファイルに書き込む
                if "text" in message:
                    f.write(message["text"] + "\n")

except SlackApiError as e:
    print("Error getting conversation list: {}".format(e))

# プライベートチャネルからダウンロード
try:
    # プライベートチャンネルのリストを取得
    response = client.conversations_list(types="private_channel")
    private_channels = response["channels"]

    for channel in private_channels:
        # 各チャンネルの情報
        channel_id = channel["id"]
        channel_name = channel["name"]

        # チャンネルの投稿を取得
        messages = fetch_all_messages(channel_id)

        # テキストファイルに書き込む
        with open(f"{output_directory}/{channel_name}.txt", "w", encoding="utf-8") as f:
                for message in messages:
                    if "text" in message:
                        f.write(f"{message['text']}\n")

except SlackApiError as e:
    print(f"Error fetching private channels: {e}")

以上が完了したら全てのセルを実行します。
Google colab側では、 作成したbotがいないチャンネルの情報は取れませんでしたよ、と出力されて、
Googleドライブの指定したフォルダに普通のチャンネルの全てのテキストファイルが作成されて、
作成したbotのいる全てのチャンネルのテキストファイルにはチャンネルの投稿が記載されていたら成功です!

最後に

初めて仕事にも使えそうなアプリを作成しました。
こういうのも楽しいですね。
また何か作ってみます。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?