Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Docomoの雑談対話APIを使ってチャットできるスクリプト (Python 3)
# https://ja.stackoverflow.com/q/37648/19110
import sys
import urllib.request
import json
import os
APP_URL = 'https://api.apigw.smt.docomo.ne.jp/dialogue/v1/dialogue'
class DocomoChat(object):
def __init__(self, api_key):
api_key = os.environ.get('DOCOMO_DIALOGUE_API_KEY', api_key)
super(DocomoChat, self).__init__()
self.api_url = APP_URL + ('?APIKEY=%s' % api_key)
self.context, self.mode = None, None
def __send_message(self, input_message = '', custom_dict = None):
req_data = {'utt': input_message}
if self.context:
req_data['context'] = self.context
if self.mode:
req_data['mode'] = self.mode
if custom_dict:
req_data.update(custom_dict)
request = urllib.request.Request(self.api_url,
data = json.dumps(req_data).encode('utf-8'))
request.add_header('Content-Type', 'application/json')
try:
response = urllib.request.urlopen(request)
except Exception as e:
print(e)
sys.exit()
return response
def __process_response(self, response):
resp_json = json.load(response)
self.context = resp_json['context']
self.mode = resp_json['mode']
return resp_json['utt']
def send_and_get(self, input_message):
response = self.__send_message(input_message)
received_message = self.__process_response(response)
return received_message
def set_name(self, name, yomi):
response = self.__send_message(custom_dict = {'nickname': name, 'nickname_y': yomi})
received_message = self.__process_response(response)
return received_message
def main():
chat = DocomoChat('your-api-key')
resp = chat.set_name('あなたのニックネーム', 'ニックネームのヨミガナ')
print('相手  : %s' % resp)
message = ''
while message != 'バイバイ':
message = input('あなた : ')
resp = chat.send_and_get(message)
print('相手  : %s' % resp)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.