GAミント至上主義

Web Monomaniacal Developer.

pythonのslackbotを使ってJSONを整形するボットを作る

新しく入ってきた人にPythonでSlack上の会話を翻訳するbotを作るにあたり、まずは自分でも作ってみた。

yfp5521.hatenablog.com


使ったライブラリはこれ。普通にpipで入れられてすぐ使える。
GitHub - lins05/slackbot: A chat bot for Slack (https://slack.com).


もう一つGoogle Cloud Natural Language APIの結果を返す動作確認用のボットも作ったけど、ぐちゃぐちゃなので公開しづらい。



下記をjson.pyとして、slackbotのインストール時に作ったpluginsに置く。

# coding: utf-8
from slackbot.bot import respond_to     # @botname: で反応するデコーダ
# from slackbot.bot import listen_to      # チャネル内発言で反応するデコーダ
# from slackbot.bot import default_reply    # 該当する応答がない場合に反応するデコーダ
import json
import logging
logger = logging.getLogger(__name__)


@respond_to('^[\{\[].*[\}\]]$')
def json_listen_func(message):
    json_text = message._body.get("text")
    logger.debug(json_text)
    try:
        json_obj = json.loads(json_text)
    except Exception as e:
        logger.debug(e)
    else:
        text = json.dumps(json_obj,
                          ensure_ascii=False,
                          indent=2,
                          sort_keys=True)
        users = message._client.users
        attachments = [{"text": text,
                        "author_name": users.get(message._body["user"], "none"),
                        
        message.reply_webapi("",
                             attachments=attachments,
                             as_user=True,
                             in_thread=False)

slackbot_settings.pyは下記のような感じ。

# coding: utf-8
# botアカウントのトークンを指定
API_TOKEN = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# このbot宛のメッセージで、どの応答にも当てはまらない場合の応答文字列
DEFAULT_REPLY = "ルームに招待してくれたら自然言語解析、ダイレクトメッセージでJSONの変換ができるよ"

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

ERRORS_TO = "uyamazak"

DEBUG = True

ざっくりと条件として、@respond_toで最初と最後が{}、[]だけのときに反応するようにしている。

どっかのサーバーで動かすと下記のようになる

f:id:uyamazak:20170912135633p:plain

よくデータをBigQueryにJSONでぶち込んでるけど、その中身をさっと確認したいとき、今まではWEBサービスをググって使ってたけどslackでもできるようになった。