LoginSignup
3
5

More than 3 years have passed since last update.

PythonでSlackにbotを作成する

Last updated at Posted at 2021-05-07

完成例

image.png

slack apiにアクセスしてアプリを作成

「Create a custom app」よりアプリを作成します。

image.png

インストールするSlackのワークスペースを選択します。

Bot用のスコープを追加してアプリをワークスペースにインストール

image.png

OAuth & Permissionsを選択します。

image.png

Add an OAuth を選択してchat:writeをスコープに追加します。

image.png

ワークスペースにインストールします。

bot(アプリ)をメッセージを投稿したいチャンネルに追加

image.png

botを追加したいチャンネルの詳細メニューのその他からインストールしたアプリを追加します。(ワークスペースにアプリをインストールすると表示されます。)

Pythonのコード

example.py
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError


def SendToSlackMessage(message):
    client = WebClient(token='your_token') 
    response=client.chat_postMessage(channel='your_channel', text=message)

SendToSlackMessage("Helloworld!")

slack_sdkをpipでインストールする必要があります。
your_tokenにはslack apiに記載されているOAuth Tokenを入力します。
your_channelにはブラウザからslackを立ち上げると識別できるチャンネルIDを入力します。

OAuth Token

image.png

チャンネルID

image.png

実行結果

image.png

3
5
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
3
5