LoginSignup
2
4

More than 3 years have passed since last update.

chat.postMessageを利用したpythonでのslack botの開発

Last updated at Posted at 2019-12-29

ひとつ前の記事でメンションに特定の文字列を返すbotを作成しました。
https://qiita.com/tokoroten_346/items/0aa9c04d5d3f2a956cd2

今回はbotにもう少し機能を持たせていきます。

ファイルの構造は前回同様こんな感じ

hello
 ├ hello.py              # botを起動するファイル
 ├ slackbot_settings.py  # botの設定を書くファイル(slackのトークンなど)。
 └─plugins
   └┬ __init__.py          # 空でいい…らしい 
    └ bot_module.py        # 今回はここに記述してbotの機能を足していく

早速bot_module.pyに記述してbotの返答を追加していきます。
まずは以下の機能を作ります。
・メンションの特定の単語に対する返答(respond_toを使用)
・チャンネル内の特定の単語に対する返答(listen_toを使用)

コードはこんな感じ

bot_module.py
from slackbot.bot import respond_to
from slackbot.bot import listen_to

# respond_toはメンションすると応答する
@respond_to('Hello')
def mention_function(message):
    #slackに応答を返す
    message.reply('World')

# listen_toはチャンネル内の単語に応答する
@listen_to('おはよう')
def lesten_function(message):
    #slackに応答を返す
   message.reply('ニホンゴワカリマセン')

@respond_toでメンションに対する応答を。
@listen_toでチャンネル内に対する応答を記述してます。

その他のコードは前回と同じ

hello.py
from slackbot.bot import Bot

def main():
    bot = Bot()
    bot.run()

if __name__ == "__main__":
    print("Hello bot")
    main()
slackbot_settings.py
# 先ほど取得したbotアカウントのトークンを指定する
API_TOKEN = "xxxx-xxxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxxxxxxx"

# このbotのデフォルトの返答を書く
DEFAULT_REPLY = "おはようございます"

# プラグインスクリプトを置いてあるサブディレクトリ名のリスト
PLUGINS = ['plugins']

このbotを実行すると以下のようになります。
botの返事追加.png

「Hello」のメンションに対しては「World」を、チャンネル内の「おはよう」には「ニホンゴワカリマセン」を、登録していないメンションには「返事がない…」を返します。
ちなみにメンションとチャンネル内の投稿が逆だとうまく反応してくれません。
botの返事エラー例.png

listen_toとrespond_toで返答が可能になったので次はchat.postMessageのapiを利用していきます。
https://api.slack.com/methods/chat.postMessage

bot_module.pyを下記のように変えていきます。

bot_module.py
from slackbot.bot import respond_to
from slackbot.bot import listen_to
import json
import requests

# respond_toはメンションすると応答する
@respond_to('Hello')
def mention_function(message):
    post_url = 'https://slack.com/api/chat.postMessage'
    token = 'xxxx-xxxxxxxxx…'  #Bot User OAuth Access Tokenを記述
    channel = 'xxxxxxx'        #チャンネルのURLの末尾についている文字列
    username = '挨拶bot'       # botの名前
    icon_emoji = ':ghost:'     # 表示アイコン(今回はゴーストにします)
    text       =  'おはよ~'    #slackに応答を返す

    #json形式で記述
    attachments = [{
        'text': text,
    }]

    payload = {
        'token': token,
        'channel': channel,
        'username': username,
        'icon_emoji': icon_emoji,
        'attachments': json.dumps(attachments)
    }

    res = requests.post(post_url, data=payload)
    print (res.status_code)

# listen_toはチャンネル内の単語に応答する
@listen_to('おはよう')
def lesten_function(message):
    #slackに応答を返す
   message.reply('ニホンゴワカリマセン')

これを実行すしslacktest君にHelloとメンションを送ると
ゴースト.png

アイコンがゴーストの挨拶bot君がおはよ~と返してくれます。
chat.postMessageを使うことでアイコンの変更やjsonでの記述が出来るようになりました。

2
4
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
4