LoginSignup
22
35

More than 5 years have passed since last update.

変数名や関数名に困った時に役立つSlackbotを作った

Last updated at Posted at 2017-10-27

つくったもの

codic "翻訳したい言葉"をSlackで発言すると翻訳してくれるbotを
PythonのSlackbotライブラリとcodicAPIを使用して作成した。
スクリーンショット 2017-10-22 18.26.32.png

Slackbotライブラリ

Slackbotライブラリの使い方は下記を参考にした。
PythonのslackbotライブラリでSlackボットを作る
PythonでSlackbotを作る(1)

codic

codicは、プログラマー・システムエンジニアのためのネーミングツール
スクリーンショット 2017-10-22 18.03.27.png

ユーザー登録をするとフリープランでも100/hリクエストを下限とするAPIが公開されているので、こちらを利用する。
スクリーンショット 2017-10-22 18.31.33.png
またエディタやIDEのプラグインも用意されている。
(わざわざbotに翻訳してもらわなくてもプラグインを利用すればいい)
スクリーンショット 2017-10-22 18.21.23.png

実装

codicのアクセストークンを取得する

ユーザー登録後、プロフィールからアクセストークンの取得ができる。
こちらのページからAPIのステータスも確認可能。
token.png

コード

codic_translate.py
# -*- coding: utf-8 -*-
from slackbot.bot import listen_to
import requests

@listen_to(r'^codic\s+\S.*')
def codic_translate(message):
    text = message.body['text']
    temp, word = text.split(None, 1)
    codicURL = 'https://api.codic.jp/v1/engine/translate.json?text={}&casing=lower+underscore'.format(word)
    headers = {
    'Authorization': 'codicのアクセストークン',
    }
    r = requests.get(codicURL,headers=headers)
    codic_response = r.json()
    message.send('"' + word + '"をcodicで翻訳すると')
    message.send(codic_response[0]['translated_text'])

"翻訳したい言葉"をSlackの発言から受け取る

listen_to(r'^codic\s+\S.*')
def codic_translate(message):
    text = message.body['text']
    temp, word = text.split(None, 1)

codic "翻訳したい言葉"という形式の発言があった場合に、
"翻訳したい言葉"をwordに代入する

codicAPIから翻訳を受け取る

    codicURL = 'https://api.codic.jp/v1/engine/translate.json?text={}&casing=lower+underscore'.format(word)
    headers = {
    'Authorization': 'codicのアクセストークン',
    }
    r = requests.get(codicURL,headers=headers)

codicAPIのtextとしてwordを投げると翻訳を受け取ることができる。
casingでcamel,pascal,lower underscore,upper underscore, hyphenを選択することも可能

    codic_response = r.json()
    message.send('"' + word + '"をcodicで翻訳すると')
    message.send(codic_response[0]['translated_text'])

Slack上で翻訳を発言する。

22
35
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
22
35