LoginSignup
11
7

More than 5 years have passed since last update.

Python3でdocomoの自然対話:雑談apiを動かす

Last updated at Posted at 2018-06-11

docomoの自動応答botをPython3で動かしてみようとトライしたらサンプルソースコードを見つけられなかったというか全て動かなかったので書いた。

docomo自然対話(雑談対話)

docomo Developer supportが提供する自然対話api。少し使う分には無料。

雑談対話APIの特徴

・ユーザの何気ない一言にバリエーション豊富な応答を返す、コンピュータと雑談を楽しむことができる機能です。雑談対話APIはユーザのどんな発話に対しても必ず応答します。
・対話における話題と文脈を認識し、大規模発話データから応答文を選択し発話します。

docomo Developer support : API 自然対話(雑談対話)

コード書く前にやること

docomo Developer supportのアカウント登録
 法人情報など、ほぼ何も登録しないミニマムなアカウントでも可能。
新規API利用申請
 利用開始は本日から。
 雑談対話のapiにチェックがついていさえすれば良い。
 
API申請が済んだらマイページに行き、Apikeyをコピーしてくる。

雑談対話する

2回目以降の実行は52-54行目をコメントアウトし、1回目で得られたappIdを55行目記載すると情報が引き継がれる。

# -*- coding: utf-8 -*-

import requests
import json
from _datetime import datetime

# your APIKEY
KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

# リクエストクエリ
endpoint = 'https://api.apigw.smt.docomo.ne.jp/naturalChatting/v1/dialogue?APIKEY=REGISTER_KEY'
url = endpoint.replace('REGISTER_KEY', KEY)


# user registration
def register():
    r_endpoint = 'https://api.apigw.smt.docomo.ne.jp/naturalChatting/v1/registration?APIKEY=REGISTER_KEY'
    r_url = r_endpoint.replace('REGISTER_KEY', KEY)
    r_headers = {'Content-type': 'application/json'}
    pay = {
        "botId": "Chatting",
        "appKind": "Smart Phone"
    }
    r = requests.post(r_url, data=json.dumps(pay), headers=r_headers)
    appId = r.json()['appId']
    return appId


def reply(appId, utt_content):
    headers = {'Content-type': 'application/json;charset=UTF-8'}
    payload = {
        "language": "ja-JP",
        "botId": "Chatting",
        "appId": appId,
        "voiceText": utt_content,
        "appRecvTime": "2018-06-11 22:44:22",  # 仮置き。これで動いてしまう。
        "appSendTime": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }
    # Transmission
    r = requests.post(url, data=json.dumps(payload), headers=headers)
    data = r.json()
    # rec_time = data['serverSendTime']
    response = data['systemText']['expression']

    print("response: %s" % response)
    return response



if __name__ == "__main__":
    # appIdを取得した2回目以降、コメントアウトして55行目に記載
    appId = register()
    print(appId)
    # appId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    while True:
        utt_content = input('>>')
        reply(appId, utt_content)

キャプチャ.PNG

おわりに

32行目以下の内容がサーバーに送られるjsonファイルの中身になる。
機能別リファレンスにある属性を追加して記載できる。

docomoの方でアップデートがあったんじゃないだろうか。たぶん。
2018年6月11日現在これで動く。

参考

uepon日々の備忘録

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