Search code examples
pythonibm-watsonwatsonwatson-conversation

How to pass response from external api to dialog in watson conversation?


I'm building a weather bot using watson conversation api.

Whenever a user sends 'what is the weather of '. I get back a response with intents and entities. Now I make a call to a weather api and get a response. How do I pass this weather response back to watson dialog to be displayed?

I think that I have to send the response through context object, but how do I make the call to conversation api to pass the response?

I'm using python api.


Solution

  • In this case, the API Referecence from IBM official document, show one example to how send message inside Watson Conversation Service.

    Check this example:

    import json
    from watson_developer_cloud import ConversationV1
    
    conversation = ConversationV1(
      username='{username}',
      password='{password}',
      version='2017-04-21'
    )
    
    # Replace with the context obtained from the initial request
    context = {}
    
    workspace_id = '25dfa8a0-0263-471b-8980-317e68c30488'
    
    response = conversation.message(
      workspace_id=workspace_id,
      message_input={'text': 'Turn on the lights'},
      context=context
    )
    
    print(json.dumps(response, indent=2))
    

    In this case, to send the message from user, you can use message_input, and to send message like Watson, you can use output. If your parameter is set to response, for example, you can use:

    #Get response from Watson Conversation
    responseFromWatson = conversation.message(
        workspace_id=WORKSPACE_ID,
        message_input={'text': command},
        context=context
    )
    

    See one official example code from IBM Developers:

    if intent == "schedule":
                response = "Here are your upcoming events: "
                attachments = calendarUsage(user, intent)
            elif intent == "free_time":
                response = calendarUsage(user, intent)
            else:
                response = responseFromWatson['output']['text'][0] //THIS SEND THE MESSAGE TO USER
    
        slack_client.api_call("chat.postMessage", as_user=True, channel=channel, text=response,
                          attachments=attachments)
    

    Use this to send:

    response = responseFromWatson['output']['text'][0];
     if intent == "timeWeather":
            response = "The Weather today is: " +yourReturnWeather
    

    Tutorial from IBM Developer for this project here.

    This example will integrate with Slack, but you can see one good example to did what you want in this project.

    See official documentation.