how to connect to Microsoft bot framework from and

2019-01-19 22:38发布

问题:

I created a simple android app which sends a message though JSON format using restfull jersey WS

which URL should i enter in my app that connects the bot?

and how does that bot receive message and send back the response?

As of now I am using bot emulator by Microsoft

Thanks in advance.

回答1:

You can connect your android client with DirectLine Rest API, before that enble web chat in your bot dashboard. Please refer documentation about direct line approach for Bot framework.

What you have to do is use https://directline.botframework.com/api/conversations as your endpoint and call those API as shown in the documentation.

Example :- I just tried with ASP.MVC application. I created a text box and button for submit message to bot.

1.First enable direct link in your bot application. Then remember that secret.

2.Following code sample shows you how to connect your chat app or your company app with bot you built using bot frame work.

3.First you need to authorize your access to direct link API.

client = new HttpClient();
client.BaseAddress = new Uri("https://directline.botframework.com/api/conversations/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("BotConnector", "[Your Secret Key Here]");

response = await client.GetAsync("/api/tokens/");

if (response.IsSuccessStatusCode)

4.If you are success with previous response you can start a new Conversation Model -

public class Conversation { 
public string conversationId { get; set; } 
public string token { get; set; } 
public string eTag { get; set; } 
}

Code inside controller -

var conversation = new Conversation();
 response = await client.PostAsJsonAsync("/api/conversations/",conversation);
 if (response.IsSuccessStatusCode)

If you success with this response you will get conversationId and a token to start messaging.

5.Then pass your message to bot via following code,

Conversation ConversationInfo = response.Content.ReadAsAsync(typeof(Conversation)).Result as Conversation; string conversationUrl = ConversationInfo.conversationId+"/messages/"; Message msg = new Message() { text = message }; response = await client.PostAsJsonAsync(conversationUrl,msg); if (response.IsSuccessStatusCode)

If you get a success response, that means you have already sent your message to the bot. Now you need to get the reply message from BOT

6.To get the message from bot,

response = await client.GetAsync(conversationUrl); if (response.IsSuccessStatusCode){ MessageSet BotMessage = response.Content.ReadAsAsync(typeof(MessageSet)).Result as MessageSet; ViewBag.Messages = BotMessage; IsReplyReceived = true; }

Here you get a Message set, That means the message you sent and the reply from the Bot. You can now display it in your chat window.

Message Model -

public class MessageSet
{
    public Message[] messages { get; set; }
    public string watermark { get; set; }
    public string eTag { get; set; }
}

public class Message
{
    public string id { get; set; }
    public string conversationId { get; set; }
    public DateTime created { get; set; }
    public string from { get; set; }
    public string text { get; set; }
    public string channelData { get; set; }
    public string[] images { get; set; }
    public Attachment[] attachments { get; set; }
    public string eTag { get; set; }
}

public class Attachment
{
    public string url { get; set; }
    public string contentType { get; set; }
}

Using those API calls you can easily connect any of your custom chat applications with bot framework. Below is the full code inside one method for you to get idea about how you can archive your goal.

 private async Task<bool> PostMessage(string message)
    {
        bool IsReplyReceived = false;

        client = new HttpClient();
        client.BaseAddress = new Uri("https://directline.botframework.com/api/conversations/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("BotConnector", "[Your Secret Code Here]");
        response = await client.GetAsync("/api/tokens/");
        if (response.IsSuccessStatusCode)
        {
            var conversation = new Conversation();
            response = await client.PostAsJsonAsync("/api/conversations/", conversation);
            if (response.IsSuccessStatusCode)
            {
                Conversation ConversationInfo = response.Content.ReadAsAsync(typeof(Conversation)).Result as Conversation;
                string conversationUrl = ConversationInfo.conversationId+"/messages/";
                Message msg = new Message() { text = message };
                response = await client.PostAsJsonAsync(conversationUrl,msg);
                if (response.IsSuccessStatusCode)
                {
                    response = await client.GetAsync(conversationUrl);
                    if (response.IsSuccessStatusCode)
                    {
                        MessageSet BotMessage = response.Content.ReadAsAsync(typeof(MessageSet)).Result as MessageSet;
                        ViewBag.Messages = BotMessage;
                        IsReplyReceived = true;
                    }
                }
            }

        }
        return IsReplyReceived;
    }

Thanks Cheers with your bot.



回答2:

As mentioned in a previous answer, you will need to use the Direct Line API to communicate with your bot. To be able to use the Direct Line API you need to register your bot, configure Direct Line as a channel that can access it, and generate a Direct Line secret key that you will use during communications. This is all covered in the Getting Started with the Connector tutorial.

One you have the bot registered and the Direct Line channel configured, there are 3 steps to having a conversation with a Bot through the Direct Line API. For each step the URL will differ slightly. Below is Android Java code that demonstrates the 3 steps and the URL required to accomplish each step.

The first step is to establish a conversation with your bot.

    // Step 1: Establish a conversation with your bot
    String secretCode = "[YOUR SECRET CODE HERE]";
    Conversation conversation = null;

    URL directLineUrl = new URL("https://directline.botframework.com/api/conversations/");
    HttpsURLConnection directLineConnection = (HttpsURLConnection) directLineUrl.openConnection();
    directLineConnection.setRequestMethod("POST"); // for some reason this has to be a post, even though we're really doing a get.
    directLineConnection.addRequestProperty("Authorization", "BotConnector " + secretCode);
    directLineConnection.setRequestProperty("Content-Type", "application/json");
    directLineConnection.setDoOutput(true);
    directLineConnection.setDoInput(true);

    if (directLineConnection.getResponseCode() == 200) {
        // Read the Conversation JSON
        InputStream in = new BufferedInputStream(directLineConnection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        conversation = new Conversation(result.toString());
    }

    directLineConnection.disconnect();

The resulting JSON will map into a Conversation class.

public class Conversation {
    public Conversation() {}

    public Conversation(String jsonString) throws JSONException {
        this(new JSONObject(jsonString));
    }

    public Conversation(JSONObject json) throws JSONException {
        if (json.isNull("conversationId") == false) {
            conversationId = json.getString("conversationId");
        }

        if (json.isNull("eTag") == false) {
            eTag = json.getString("eTag");
        }

        if (json.isNull("token") == false) {
            token = json.getString("token");
        }
    }

    public String conversationId = null;
    public String eTag = null;
    public String token = null;
}

Now we have established a conversation, the next step is to send the bot a message. Here's the Message class (Note: Not all the properties have been fully implemented to convert to/from JSON)

public class Message {
    public Message() {}

    public Message(String jsonString) throws JSONException {
        this(new JSONObject(jsonString));
    }

    public Message(JSONObject json) throws JSONException {
        if(json.isNull("id") == false) {
            this.id = json.getString("id");
        }

        if(json.isNull("conversationId") == false) {
            this.conversationId = json.getString("conversationId");
        }

        if(json.isNull("created") == false) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            try {
                this.created = dateFormat.parse(json.getString("created"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if(json.isNull("from") == false) {
            this.from = json.getString("from");
        }

        if(json.isNull("text") == false) {
            this.text = json.getString("text");
        }

        if(json.isNull("eTag") == false) {
            this.eTag = json.getString("eTag");
        }

        // TODO: Implement channelData, images, and attachments
    }


    public String id = null;
    public String conversationId = null;
    public Date created = null;
    public String from = null;
    public String text = null;
    public Object channelData = null;
    public List<String> images = null;
    public List<Attachment> attachments = null;
    public String eTag = null;

    public String toJSON() {
        String jsonString = "";

        try {
            JSONObject json = new JSONObject();
            json.put("id", this.id);
            json.put("conversationId", this.conversationId);
            if(this.created != null) {
                json.put("created", this.created.toString());
            }

            json.put("from", this.from);
            json.put("text", this.text);
            json.put("eTag", this.eTag);

            // channelData, images, and attachments are never encoded to JSON by this object.

            jsonString = json.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return jsonString;
    }
}

We use the Conversation.conversationId to create the path to POST the Message to.

    // Step 2: Post Message to bot
    String botUrl = "https://directline.botframework.com/api/conversations/" + conversation.conversationId + "/messages/";

    Message message = new Message();
    message.text = "[SOME TEXT TO SEND TO YOUR BOT]";

    boolean messageSent = false;
    URL messageUrl = new URL(botUrl);
    HttpsURLConnection messageConnection = (HttpsURLConnection) messageUrl.openConnection();
    messageConnection.setRequestMethod("POST");
    messageConnection.addRequestProperty("Authorization", "BotConnector " + secretCode);
    messageConnection.setRequestProperty("Content-Type", "application/json");
    messageConnection.setDoOutput(true);
    messageConnection.setDoInput(true);

    // Send message to bot through direct line connection
    DataOutputStream outputStream = new DataOutputStream(messageConnection.getOutputStream());
    outputStream.writeBytes(message.toJSON());
    outputStream.flush();
    outputStream.close();

    if (messageConnection.getResponseCode() == 204) {
        messageSent = true;
    }

    messageConnection.disconnect();

And for the final step, we read any responses from the bot into a MessageSet class.

public class MessageSet {
    public MessageSet() {}

    public MessageSet(String jsonString) throws JSONException {
        this(new JSONObject(jsonString));
    }

    public MessageSet(JSONObject json) throws JSONException {
        if (json.isNull("watermark") == false) {
            this.watermark = json.getString("watermark");
        }

        if (json.isNull("eTag") == false) {
            this.eTag = json.getString("eTag");
        }

        if (json.isNull("messages") == false) {
            JSONArray array = json.getJSONArray("messages");

            if (array.length() > 0) {
                this.messages = new ArrayList<Message>();

                for (int i = 0; i < array.length(); ++i) {
                    this.messages.add(new Message(array.getJSONObject(i)));
                }
            }
        }
    }

    public List<Message> messages;
    public String watermark;
    public String eTag;
}

We use MessageSet.watermark, from the previous (if any) Message exchange, on the query string so we only get the response to the current Message we sent.

    // Step 3: Read the bot response into MessageSet
    MessageSet messageSet = null;

    String messageSetPath = botUrl;
    if (lastWatermark.isEmpty() == false) {
        messageSetPath += "?watermark=" + lastWatermark;
    }

    URL messageSetUrl = new URL(messageSetPath);
    HttpsURLConnection messageSetConnection = (HttpsURLConnection) messageSetUrl.openConnection();
    messageSetConnection.addRequestProperty("Authorization", "BotConnector " + secretCode);
    messageSetConnection.setRequestProperty("Content-Type", "application/json");
    messageSetConnection.setDoOutput(true);
    messageSetConnection.setDoInput(true);

    if (messageSetConnection.getResponseCode() == 200) {
        InputStream in = new BufferedInputStream(messageSetConnection.getInputStream());

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        messageSet = new MessageSet(result.toString());
        lastWatermark = messageSet.watermark;
    }

    messageSetConnection.disconnect();

Below is the full code in one method to see how it all ties together.

private String lastWatermark = "";

public void DirectLineExample() throws IOException, JSONException {

    // Step 1: Establish a conversation with your bot
    String secretCode = "[YOUR SECRET CODE HERE]";
    Conversation conversation = null;

    URL directLineUrl = new URL("https://directline.botframework.com/api/conversations/");
    HttpsURLConnection directLineConnection = (HttpsURLConnection) directLineUrl.openConnection();
    directLineConnection.setRequestMethod("POST"); // for some reason this has to be a post, even though we're really doing a get.
    directLineConnection.addRequestProperty("Authorization", "BotConnector " + secretCode);
    directLineConnection.setRequestProperty("Content-Type", "application/json");
    directLineConnection.setDoOutput(true);
    directLineConnection.setDoInput(true);

    if (directLineConnection.getResponseCode() == 200) {
        // Read the Conversation JSON
        InputStream in = new BufferedInputStream(directLineConnection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        conversation = new Conversation(result.toString());
    }

    directLineConnection.disconnect();

    // Step 2: Post Message to bot
    String botUrl = "https://directline.botframework.com/api/conversations/" + conversation.conversationId + "/messages/";

    Message message = new Message();
    message.text = "[SOME TEXT TO SEND TO YOUR BOT]";

    boolean messageSent = false;
    URL messageUrl = new URL(botUrl);
    HttpsURLConnection messageConnection = (HttpsURLConnection) messageUrl.openConnection();
    messageConnection.setRequestMethod("POST");
    messageConnection.addRequestProperty("Authorization", "BotConnector " + secretCode);
    messageConnection.setRequestProperty("Content-Type", "application/json");
    messageConnection.setDoOutput(true);
    messageConnection.setDoInput(true);

    // Send message to bot through direct line connection
    DataOutputStream outputStream = new DataOutputStream(messageConnection.getOutputStream());
    outputStream.writeBytes(message.toJSON());
    outputStream.flush();
    outputStream.close();

    if (messageConnection.getResponseCode() == 204) {
        messageSent = true;
    }

    messageConnection.disconnect();

    if (messageSent) {
        // Step 3: Read the bot response into MessageSet
        MessageSet messageSet = null;

        String messageSetPath = botUrl;
        if (lastWatermark.isEmpty() == false) {
            messageSetPath += "?watermark=" + lastWatermark;
        }

        URL messageSetUrl = new URL(messageSetPath);
        HttpsURLConnection messageSetConnection = (HttpsURLConnection) messageSetUrl.openConnection();
        messageSetConnection.addRequestProperty("Authorization", "BotConnector " + secretCode);
        messageSetConnection.setRequestProperty("Content-Type", "application/json");
        messageSetConnection.setDoOutput(true);
        messageSetConnection.setDoInput(true);

        if (messageSetConnection.getResponseCode() == 200) {
            InputStream in = new BufferedInputStream(messageSetConnection.getInputStream());

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            messageSet = new MessageSet(result.toString());
            lastWatermark = messageSet.watermark;
        }

        messageSetConnection.disconnect();
    }
}


回答3:

Here I wrote a working demo for the same using Direct Line API - https://blogs.msdn.microsoft.com/brijrajsingh/2017/01/10/android-sample-direct-line-api-microsoft-bot-framework/