本文整理匯總了Python中apiai.ApiAI方法的典型用法代碼示例。如果您正苦於以下問題:Python apiai.ApiAI方法的具體用法?Python apiai.ApiAI怎麽用?Python apiai.ApiAI使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類apiai
的用法示例。
在下文中一共展示了apiai.ApiAI方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: apiai_reply
# 需要導入模塊: import apiai [as 別名]
# 或者: from apiai import ApiAI [as 別名]
def apiai_reply(msg_content, user_id):
print("try APIAI reply...")
ai = apiai.ApiAI(APIAI_TOKEN)
request = ai.text_request()
request.lang = 'zh-CN'
request.session_id = user_id
request.query = msg_content
response = request.getresponse()
s = json.loads(response.read().decode('utf-8'))
if s['result']['action'] == 'input.unknown':
raise Exception('api.ai cannot reply this message')
if s['status']['code'] == 200:
print("use APIAI reply")
print('return code: ' + str(s['status']['code']))
return s['result']['fulfillment']['speech']
示例2: chatbot
# 需要導入模塊: import apiai [as 別名]
# 或者: from apiai import ApiAI [as 別名]
def chatbot(arg):
CLIENT_ACCESS_TOKEN = 'f1f4bd11d9b84401aa53684d6f8833d0'
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
request = ai.text_request()
request.lang = 'en' # optional, default value equal 'en'
request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"
request.query = arg
response = request.getresponse()
rope = str(response.read())
rope = rope[rope.index("speech")+10:]
rope = rope[0:rope.index("\"")]
print rope
say(rope)
示例3: apiai_text_request
# 需要導入模塊: import apiai [as 別名]
# 或者: from apiai import ApiAI [as 別名]
def apiai_text_request(sess_id, text):
access_token = os.environ.get('APIAI_API_ACCESS_TOKEN')
assert access_token is not None
api = apiai.ApiAI(access_token)
request = api.text_request()
request.lang = 'en'
request.session_id = sess_id
request.query = text
res = request.getresponse()
return json.loads(res.read())
#
# Note:
# To test API.AI, You need to build an Pizza Agent by importing
# chabi/chabi/tests/prjs/apiai/PizzaAgent.zip. Then copy client access
# token of the Agent and set APIAI_API_ACCESS_TOKEN environment
# variable before run pytest
#
# $ APIAI_API_ACCESS_TOKEN=CLIENT-ACCESS-TOKEN py.test -k\
# >test_apiai
#
示例4: test_apiai_webhook
# 需要導入模塊: import apiai [as 別名]
# 或者: from apiai import ApiAI [as 別名]
def test_apiai_webhook(sess):
"""API.AI App test."""
access_token = os.environ.get('APIAI_API_ACCESS_TOKEN')
assert access_token is not None
class EventHandler(EventHandlerBase):
def handle_action(self, data):
return dict(result=data['foo'])
app = Flask(__name__)
ApiAI(app, access_token)
EventHandler(app)
app.config['TESTING'] = True
with app.test_client() as c:
r = c.get('/apiai')
assert '200 OK' == r.status
data = dict(foo=123)
with app.test_client() as c:
r = c.post('/apiai', headers={'Content-Type': 'application/json'},
data=json.dumps(data))
assert '200 OK' == r.status
assert 'result' in r.data.decode('utf8')
示例5: deliver
# 需要導入模塊: import apiai [as 別名]
# 或者: from apiai import ApiAI [as 別名]
def deliver(query):
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
request = ai.text_request()
request.lang = 'en' # optional, default value equal 'en'
request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"
request.query = query
response = request.getresponse()
j = json.loads(response.read())
s = j["result"]["parameters"]
res = "food:" + s["food"] + ", " + " address:" + s["address"]
return res
示例6: get_bot_result
# 需要導入模塊: import apiai [as 別名]
# 或者: from apiai import ApiAI [as 別名]
def get_bot_result(message_content: str, config: Dict[str, str], sender_id: str) -> str:
if message_content.strip() == '' or message_content.strip() == 'help':
return config['bot_info']
ai = apiai.ApiAI(config['key'])
try:
request = ai.text_request()
request.session_id = sender_id
request.query = message_content
response = request.getresponse()
res_str = response.read().decode('utf8', 'ignore')
res_json = json.loads(res_str)
if res_json['status']['errorType'] != 'success' and 'result' not in res_json.keys():
return 'Error {}: {}.'.format(res_json['status']['code'], res_json['status']['errorDetails'])
if res_json['result']['fulfillment']['speech'] == '':
if 'alternateResult' in res_json.keys():
if res_json['alternateResult']['fulfillment']['speech'] != '':
return res_json['alternateResult']['fulfillment']['speech']
return 'Error. No result.'
return res_json['result']['fulfillment']['speech']
except Exception as e:
logging.exception(str(e))
return 'Error. {}.'.format(str(e))
示例7: main
# 需要導入模塊: import apiai [as 別名]
# 或者: from apiai import ApiAI [as 別名]
def main(query,sessionid):
ai = apiai.ApiAI('13537e5537c543b78b713852b76ff0f3 ')
request = ai.text_request()
request.lang = 'en' # optional, default value equal 'en'
request.session_id = sessionid
request.query = query
response = request.getresponse()
response=json.loads(response.read())
print(response)
send_message(sessionid, response['result']['fulfillment']['speech'])
示例8: __init__
# 需要導入模塊: import apiai [as 別名]
# 或者: from apiai import ApiAI [as 別名]
def __init__(self, slack_clients, msg_writer, intent_handler):
self.clients = slack_clients
self.msg_writer = msg_writer
self.intent_handler = intent_handler
self.api_ai = apiai.ApiAI(API_ACCESS_TOKEN)
self.sessions = {}
self.tasks = [] # For mult-message spanning tasks
self.local_intent = None
示例9: __init__
# 需要導入模塊: import apiai [as 別名]
# 或者: from apiai import ApiAI [as 別名]
def __init__(self):
self.ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
示例10: __init__
# 需要導入模塊: import apiai [as 別名]
# 或者: from apiai import ApiAI [as 別名]
def __init__(self, token):
"""
Initializees the DialogFlow API
:param token: the client access token for the agent
"""
self.ai = apiai.ApiAI(token)
self.speech = ""
self.response = ""
self.action = ""
self.parameters = ""
self.actionincomplete = ""
示例11: __init__
# 需要導入模塊: import apiai [as 別名]
# 或者: from apiai import ApiAI [as 別名]
def __init__(self,model,config, actions, ozz_guid, redis_db, mongo):
self.redis_db = redis_db
self.mongo = mongo
with open(actions,"r") as jsonFile:
self.actions = json.load(jsonFile)
if ozz_guid != "":
if ozz_guid[:4] == 'api_':
self.nlu = None
self.api = apiai.ApiAI(ozz_guid[4:])
else:
self.nlu = OzzParser(ozz_guid)
else:
self.nlu = None
print("HTTP endpoint - /api/messages/http")
示例12: fetch_from_apiai
# 需要導入模塊: import apiai [as 別名]
# 或者: from apiai import ApiAI [as 別名]
def fetch_from_apiai(message):
just_text = (
message.text
.replace('@%s' % bot._user_name, '')
.replace('<@%s>' % bot._user_id, '')
)
ai = apiai.ApiAI(API_AI_KEY)
log.info('Requesting action from api.ai...')
request = ai.text_request()
request.query = just_text
response = json.loads(request.getresponse().read())
result = response.get('result', {})
action = result.get('action', {})
log.info('Got action %s' % action)
function = bot._function_map.get(action)
log.info('Got function %s' % function)
if function:
log.info('Invoking...')
# import pdb; pdb.set_trace()
result = yield function(message)
log.info('Function returned %s' % result)
示例13: __init__
# 需要導入模塊: import apiai [as 別名]
# 或者: from apiai import ApiAI [as 別名]
def __init__(self):
super(APINLP, self).__init__()
from credentials import APIAI_ACCESS_TOKEN_DEVELOPER
self.apiai = apiai.ApiAI(APIAI_ACCESS_TOKEN_DEVELOPER)
示例14: __init__
# 需要導入模塊: import apiai [as 別名]
# 或者: from apiai import ApiAI [as 別名]
def __init__(self, app, access_token):
"""Init ApiAI Instance.
Args:
app: Flask app instance.
access_token: API.AI client access token.
"""
super(ApiAI, self).__init__(app, blueprint)
self.ai = api_ai.ApiAI(access_token)
示例15: handle
# 需要導入模塊: import apiai [as 別名]
# 或者: from apiai import ApiAI [as 別名]
def handle(msg):
global look_obj
content_type, chat_type, chat_id = telepot.glance(msg)
print(content_type, chat_type, chat_id)
#if content_type == 'text':
#bot.sendMessage(chat_id, msg['text'])
msg_txt=msg['text']
words=msg_txt.split(' ')
#print(words[-1])
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
request = ai.text_request()
request.query = msg_txt
response = request.getresponse()
reply = response.read()
reply = reply.decode("utf-8")
parsed_json = json.loads(reply)
action = parsed_json['result']['action']
parameters = parsed_json['result']['parameters']
response = parsed_json['result']['fulfillment']['speech']
#return parameters, action, response
print(action)
print(parameters['object'])
if action=='go_to':
look_obj=str(parameters['object'])
print(look_obj)
bot.sendMessage(chat_id, ("I'll look for a " + str(parameters['object']) + "!") )
#TOKEN = sys.argv[1] # get token from command-line