2
4

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 5 years have passed since last update.

docomoの知識Q&A APIで賢いslackbotを作ってみる(後編)

Last updated at Posted at 2018-03-07

この記事は,docomoの知識Q&A APIで賢いslackbotを作ってみる(前編)の続きです.
前回はコンソール上で動かしていたシステムを,slack上に導入し賢いbot化しました.

完成したものは全体は,github上で公開しているので,こちらもを参考に,.
https://github.com/sey323/shitsumonkun

slackbotのインストールと設定

slackbot周りの設定はこちらこちらのような先人の方々の知恵をお借りしました.
ありがたや.

$ sudo pip3 install slackbot

リンクを参考にした,ファイル構成は以下の通り.前回作成したdocomo_dialogue.pyplugins下に移動させた.

./shitumonkun
| - plugins
|     | - __init__.py
|     | - my_mention.py
|     ` - docomo_dialogue.py
| - config.json
| - run.py
` _ slackbot_setting.py

設定ファイルの作成

apiなどを直接プログラムに打ち込むのは面倒なので,config.jsonに記述し,それらを書くプログラムで読み込むようにした.config_default.jsonがあるので,そちら参考に.

config.json
{
    "email":"@",
    "slack_bot":{
        "api_key":"APIキー"
    },
    "docomo":{
        "api_key":"APIキー",
      }
}

前回作成したdocomo_dialogue.pyにもconfig.jsonから読み込むように追記.

./plugins/docomo_dialogue.py
~~~ 省略 ~~~
    '''
    config.jsonからAPIキーの取得
    '''
    def get_api_param( self  , _filename ):
        json = self.load_json( _filename )
        data = json["docomo"]
        self._token = data['api_key']

    '''
    jsonファイルの読み込み
    '''
    def load_json( self ,  _filename):
            f = open( _filename )
            json_data = json.load( f )

            f.close()
            return json_data

~~~ 省略 ~~~

slackbot_setting.pyでAPIキーをconfig.jsonから取得するように変更.

./slackbot_setting.py
# coding: utf-8
import json
'''
jsonファイルの読み込み用
'''
def load_json( _filename):
        f = open( _filename )
        json_data = json.load( f )

        f.close()
        return json_data


json = load_json( 'config.json' )
# botアカウントのトークンを指定
API_TOKEN = json['slack_bot']['api_key']
# このbot宛のメッセージで、どの応答にも当てはまらない場合の応答文字列
DEFAULT_REPLY = "なんだこいつ"

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

初期設定

./run.py
# coding: utf-8

from slackbot.bot import Bot

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

if __name__ == "__main__":
    print('start slackbot')
    main()

メンションの設定

今回は@slackbotまたは,ダイレクトメッセージでslackbotに話しかけた内容を,全てdocomoAPIに投げるようにする.

./plugins/my_mention.py
# coding: utf-8
import sys ,os
sys.path.append( os.pardir )

from slackbot.bot import respond_to     # @botname: で反応するデコーダ
from slackbot.bot import default_reply

from plugins.docomo_dialogue import DdialogueDriver

# @respond_to('string')     bot宛のメッセージ
#                           stringは正規表現が可能 「r'string'」

ddialogue = DdialogueDriver()

@default_reply()
def question_talk( message ):
    text = message.body['text']
    ddialogue.listen( text )
    # 表示
    message.reply( "%s" % ddialogue.speak())

実行

コンソール上でrun.pyを実行すると,slackbotが開始される.

$ python3 run.py

実行結果はこんなかんじ
スクリーンショット 2018-03-07 12.21.26.png

dr-strage君がslackbotです.
わからない時は,「わかりませんでした」と表示され,答えられる時は上位5つまでの検索候補のURLを返してくれます.
明日の天気がわからないのに,世界最強の人間は答えてくれるんですね笑.

参考

Pythonを使ったSlackBotの作成方法
PythonのslackbotライブラリでSlackボットを作る

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?