Agentive
自動化ラボ

Slack × AI自動化 — Claude MCPでチーム業務を効率化

約5分で読めます

Slack × AI自動化

Slack MCPを使えば、Claude Codeから直接Slackを操作できる。日次レポートの自動投稿、メンション通知の自動応答、チャンネルサマリーの自動生成まで、チームコミュニケーションをAIで自動化する方法を解説する。

Slack MCPのセットアップ

MCPサーバーの追加

claude mcp add-json slack '{"type":"http","url":"https://mcp.slack.com/mcp"}'

この1行でClaude CodeがSlackに接続される。認証はOAuth2で行われ、初回接続時にブラウザでSlackワークスペースへのアクセスを許可する。

接続確認

claude -p "Slackの#generalチャンネルの最新5件のメッセージを取得して"

正常に接続されていれば、チャンネルのメッセージが返される。

日次レポートの自動投稿

Pythonスクリプトでの定期投稿

import anthropic
import json
import urllib.request
from datetime import datetime

client = anthropic.Anthropic()

def generate_daily_summary(data: dict) -> str:
    response = client.messages.create(
        model="claude-haiku-35-20241022",
        max_tokens=500,
        messages=[{
            "role": "user",
            "content": "以下のデータから日次サマリーを3行で作成:\n"
                       + json.dumps(data, ensure_ascii=False)
        }]
    )
    return response.content[0].text

def post_to_slack(webhook_url: str, summary: str):
    today = datetime.now().strftime("%Y-%m-%d")
    payload = json.dumps({
        "blocks": [
            {"type": "header",
             "text": {"type": "plain_text", "text": "Daily Report " + today}},
            {"type": "section",
             "text": {"type": "mrkdwn", "text": summary}}
        ]
    }).encode()
    req = urllib.request.Request(webhook_url, data=payload,
        headers={"Content-Type": "application/json"})
    urllib.request.urlopen(req)

Node.jsでのSlack Bot投稿

const { WebClient } = require("@slack/web-api");
const slack = new WebClient(process.env.SLACK_BOT_TOKEN);

async function postDailyReport(channel, reportData) {
  const today = new Date().toISOString().split("T")[0];
  await slack.chat.postMessage({
    channel: channel,
    blocks: [
      { type: "header",
        text: { type: "plain_text", text: "Daily Report " + today } },
      { type: "section",
        text: { type: "mrkdwn",
                text: "*PV*: " + reportData.pv
                    + "\n*New Users*: " + reportData.newUsers
                    + "\n*Revenue*: " + reportData.revenue } }
    ]
  });
}

メンション通知の自動応答

Slack Events APIでメンション検知

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route("/slack/events", methods=["POST"])
def handle_event():
    data = request.json
    if data.get("type") == "url_verification":
        return jsonify({"challenge": data["challenge"]})

    event = data.get("event", {})
    if event.get("type") == "app_mention":
        user_message = event["text"]
        channel = event["channel"]
        response_text = generate_ai_response(user_message)
        post_reply(channel, event["ts"], response_text)

    return jsonify({"ok": True})

def generate_ai_response(message: str) -> str:
    response = client.messages.create(
        model="claude-haiku-35-20241022",
        max_tokens=300,
        system="あなたはチームのAIアシスタントです。簡潔に回答してください。",
        messages=[{"role": "user", "content": message}]
    )
    return response.content[0].text

def post_reply(channel, thread_ts, text):
    payload = json.dumps({
        "channel": channel, "thread_ts": thread_ts, "text": text
    }).encode()
    req = urllib.request.Request(
        "https://slack.com/api/chat.postMessage",
        data=payload,
        headers={"Content-Type": "application/json",
                 "Authorization": "Bearer " + SLACK_BOT_TOKEN})
    urllib.request.urlopen(req)

チャンネルサマリーの自動生成

過去24時間のメッセージを要約

import time

def get_channel_messages(channel_id, hours=24):
    oldest = str(time.time() - hours * 3600)
    url = ("https://slack.com/api/conversations.history"
           + "?channel=" + channel_id + "&oldest=" + oldest)
    req = urllib.request.Request(url,
        headers={"Authorization": "Bearer " + SLACK_BOT_TOKEN})
    response = urllib.request.urlopen(req)
    data = json.loads(response.read())
    return [msg["text"] for msg in data.get("messages", [])]

def generate_channel_summary(channel_id):
    messages = get_channel_messages(channel_id)
    if not messages:
        return "過去24時間のメッセージはありません。"
    all_text = "\n".join(messages)
    response = client.messages.create(
        model="claude-haiku-35-20241022",
        max_tokens=500,
        messages=[{
            "role": "user",
            "content": ("以下のSlackメッセージを要約してください。\n"
                        "重要な決定事項とアクションアイテムを抽出:\n\n"
                        + all_text)
        }]
    )
    return response.content[0].text

ワークフロー自動化の実践パターン

パターン1: 承認フロー自動化

def create_approval_message(request_title, requester, details):
    return {
        "blocks": [
            {"type": "section",
             "text": {"type": "mrkdwn",
                      "text": "*承認リクエスト*\n" + request_title}},
            {"type": "section",
             "fields": [
                 {"type": "mrkdwn", "text": "*申請者:* " + requester},
                 {"type": "mrkdwn", "text": "*詳細:* " + details}
             ]},
            {"type": "actions",
             "elements": [
                 {"type": "button",
                  "text": {"type": "plain_text", "text": "承認"},
                  "style": "primary", "action_id": "approve"},
                 {"type": "button",
                  "text": {"type": "plain_text", "text": "却下"},
                  "style": "danger", "action_id": "reject"}
             ]}
        ]
    }

パターン2: 定期リマインダー

claude -p "毎週月曜9時に#teamチャンネルに週次目標確認のリマインダーを設定して"

Claude Code MCPの活用コマンド集

# チャンネル一覧取得
claude -p "参加しているSlackチャンネル一覧を表示して"

# メッセージ検索
claude -p "Slackで過去1週間のデプロイに関するメッセージを検索して"

# ファイル共有
claude -p "#devチャンネルにこのファイルを共有して: report.pdf"

# ステータス更新
claude -p "Slackのステータスをミーティング中に変更して"

関連記事

A

Agentive 編集部

AIエージェントを実際に使い倒す個人開発者。サイト制作の自動化を実践しながら、その知見を発信しています。