如何从android cilent连接到Microsoft bot框架

最后发布: 2016-06-13 07:20:01


问题

I created a simple android app which sends a message though JSON format using restfull jersey WS 我创建了一个简单的Android应用程序,它使用restfull jersey WS通过JSON格式发送消息

which URL should i enter in my app that connects the bot? 我应该在连接机器人的应用程序中输入哪个URL?

and how does that bot receive message and send back the response? 以及该机器人如何接收消息并发回响应?

As of now I am using bot emulator by Microsoft 截至目前,我正在使用微软的bot模拟器

Thanks in advance. 提前致谢。

botframework direct-line-botframework
回答

You can connect your android client with DirectLine Rest API, before that enble web chat in your bot dashboard. 您可以在机器人仪表板中进行网络聊天之前,将您的Android客户端与DirectLine Rest API连接起来。 Please refer documentation about direct line approach for Bot framework. 请参考有关Bot框架的直线方法的文档。

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. 您需要做的是使用https://directline.botframework.com/api/conversations作为您的终端并调用这些API,如文档中所示。

Example :- I just tried with ASP.MVC application. 示例: - 我刚刚尝试使用ASP.MVC应用程序。 I created a text box and button for submit message to bot. 我创建了一个文本框和按钮,用于向bot提交消息。

1.First enable direct link in your bot application. 1.首先在机器人应用程序中启用直接链接。 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. 2.以下代码示例向您展示如何将聊天应用程序或公司应用程序与使用bot框架工作构建的bot连接。

3.First you need to authorize your access to direct link API. 3.首先,您需要授权您访问直接链接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 - 4.如果您以前的回复成功,您可以开始一个新的对话模型 -

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. 如果您成功使用此响应,您将获得conversationId和令牌以启动消息传递。

5.Then pass your message to bot via following code, 然后通过以下代码将您的消息传递给bot,

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 现在您需要从BOT获取回复消息

6.To get the message from bot, 6.从机器人那里得到消息,

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. 在这里你得到一个消息集,这意味着你发送的消息和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. 使用这些API调用,您可以轻松地将任何自定义聊天应用程序与bot框架连接起来。 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. 谢谢你的机器人干杯。


回答

As mentioned in a previous answer, you will need to use the Direct Line API to communicate with your bot. 如前面的答案所述,您需要使用Direct Line API与机器人进行通信。 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. 为了能够使用Direct Line API,您需要注册机器人,将Direct Line配置为可以访问它的通道,并生成您将在通信期间使用的Direct Line密钥。 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. 您已经注册了机器人并配置了直线通道,通过Direct Line API与Bot进行对话有3个步骤。 For each step the URL will differ slightly. 对于每个步骤,URL略有不同。 Below is Android Java code that demonstrates the 3 steps and the URL required to accomplish each step. 下面是Android Java代码,演示了完成每个步骤所需的3个步骤和URL。

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. 生成的JSON将映射到Conversation类。

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. 现在我们已经建立了一个对话,下一步就是向bot发送消息。 Here's the Message class (Note: Not all the properties have been fully implemented to convert to/from JSON) 这是Message类(注意:并非所有属性都已完全实现以转换为/从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. 我们使用Conversation.conversationId创建POST消息的路径。

    // 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. 最后一步,我们将机器人的任何响应读入MessageSet类。

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. 我们在查询字符串上使用来自先前(如果有的话)消息交换的MessageSet.watermark,因此我们只得到对我们发送的当前消息的响应。

    // 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();
    }
}


回答

在这里,我使用Direct Line API编写了一个相同的工作演示 - https://blogs.msdn.microsoft.com/brijrajsingh/2017/01/10/android-sample-direct-line-api-microsoft-bot-framework/