LoginSignup
6
7

More than 5 years have passed since last update.

Pythonで個人Slack用のbotを作る

Last updated at Posted at 2018-04-21

なんでもやってくれる秘書兼イマジナリーコンパニオンのSlack botをPythonで作っていきます。
今回は仮想環境&slackbotのインストールまで。

開発環境を作る

virtualenvは導入済

# python3仮想環境を作成
$ virtualenv -p python3 env

# 仮想環境を有効化
$ source env/bin/activate

slackbotをインストール

定番の https://github.com/lins05/slackbot を利用します。

# lins05/slackbotをインストール
(env)$ pip install slackbot

Slack BotのAPIトークンとDEFAULT_REPLYを設定

Botはあらかじめ作成しておく。
API Tokenは管理 > カスタムインテグレート > Botsから。

slackbot_settings.py
# APIキー
API_TOKEN = "<your-api-token>"

# デフォルトの返答
DEFAULT_REPLY = "Sorry but I didn't understand you"

run.pyを作成

run.py
from slackbot.bot import Bot
def main():
    bot = Bot()
    bot.run()

if __name__ == "__main__":
    main()

動くかテスト

run.pyを走らせる

(env)$ python run.py

Slackで話しかけてDEFAULT_REPLYが返ってくれば成功
(※自分のテンション上げるために有名なおじいさんを使っていますが気になさらず。)
slackbot1.png

プラグイン用のディレクトリを作る

slackbot_settings.pyで指定したファイルをプラグインとして読み込むことができます。
今後の基本的な機能の実装はpluginsディレクトリ下でパッケージして追加していく予定です。

# プラグインディレクトリを作成
$ mkdir plugins

# ディレクトリをパッケージ化
$ touch plugins/__init__.py

slackbot_settings.pyにプラグインディレクトリを指定

slackbot_settings.py
PLUGINS = [
    'plugins',
]

参考URL

6
7
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
6
7